# squirrelscan Windows installer # Usage: iwr -useb https://install.squirrelscan.com/install.ps1 | iex # Or: iwr -useb https://raw.githubusercontent.com/squirrelscan/squirrelscan/main/install.ps1 | iex # # Environment variables: # SQUIRREL_VERSION - Pin to specific version (e.g., v0.0.15) # SQUIRREL_CHANNEL - Release channel: stable or beta (default: stable) # SQUIRREL_NO_MODIFY_PATH - Never edit the user PATH; print instructions # instead. Any value but empty, 0 or false enables it. # SQUIRREL_FORCE_MIRROR - Skip github.com and download from # install.squirrelscan.com (for networks that block # GitHub). Any value but empty, 0 or false enables it. $ErrorActionPreference = "Stop" # Windows PowerShell 5.1 can otherwise negotiate with its legacy protocol # defaults. Add TLS 1.2 without replacing newer protocols such as TLS 1.3. [Net.ServicePointManager]::SecurityProtocol = ` [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 $Repo = "squirrelscan/squirrelscan" $CertIdentity = "https://github.com/squirrelscan/squirrelscan/.github/workflows/release.yml@refs/heads/main" $Platform = "windows-x64" # Pinned release signing keys (squirrelscan/repo#5032), rendered from # release-keys.json. A release is accepted when EITHER a pinned, non-revoked key # signed it OR its GitHub attestation verifies; from $ReleaseFirstSignedVersion # up, nothing else is accepted. Both slots empty means the signature path is off. # BEGIN GENERATED RELEASE KEYS (scripts/sync-install-header.ts, from release-keys.json; do not edit) $ReleaseKeyCurrentId = '3d10cf3775665622' $ReleaseKeyCurrentPem = '-----BEGIN PUBLIC KEY----- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEN8K5cMpCjrfRAEv94Fiic1a65ED6 wzfEsN/5YD0EUAJrlIL76/L4KPU+L6/Oloiua4UYWu9bK5YFBvKQpsn7FQ== -----END PUBLIC KEY-----' $ReleaseKeyNextId = '' $ReleaseKeyNextPem = '' $ReleaseKeysRevoked = '' $ReleaseFirstSignedVersion = '0.0.190-beta.1' # END GENERATED RELEASE KEYS function Write-Log { param($Message) Write-Host "==> " -ForegroundColor Green -NoNewline; Write-Host $Message } function Write-Info { param($Message) Write-Host ":: " -ForegroundColor Blue -NoNewline; Write-Host $Message } function Write-Warn { param($Message) Write-Host "Warning: " -ForegroundColor Yellow -NoNewline; Write-Host $Message } function Write-Err { param([string]$Message, [string]$Output = "", [int]$ExitCode = 1) Write-Host "Error: " -ForegroundColor Red -NoNewline Write-Host $Message # $Output is the failing command's own stdout/stderr, when we captured it. Send-ErrorReport -Step $script:CurrentStep -ExitCode $ExitCode -Line "$Message" -Output $Output exit 1 } # --- Failure reporting ------------------------------------------------- # On failure, fire a tiny anonymous report to the installer worker (→ Sentry) # so we can see when installs break in the field. Opt-out: DO_NOT_TRACK=1 or NO_TELEMETRY (any # non-empty value, mirroring install.sh and apps/cli/src/self/telemetry.ts). # Fire-and-forget: never blocks or fails the install; carries only coarse # context (os/arch/step/exit code), never paths/env/hostname/secrets. #1013 # v2 adds `error_output` — the tail of the failing command's own output (#1538). # v3 adds `version` (the release being installed). $InstallerReportVersion = "3" # The release being installed, bare ("0.0.73"); set once known, empty before. $script:ReleaseVersion = "" $ErrorEndpoint = if ($env:SQUIRREL_ERROR_ENDPOINT) { $env:SQUIRREL_ERROR_ENDPOINT } else { "https://install.squirrelscan.com/error" } # Release metadata (latest version per channel) — R2-backed, no rate limits. $ReleasesEndpoint = if ($env:SQUIRREL_RELEASES_ENDPOINT) { $env:SQUIRREL_RELEASES_ENDPOINT } else { "https://install.squirrelscan.com/releases" } # Release assets, mirrored through our own origin. A GitHub release-asset URL # redirects to githubusercontent.com (objects.* historically, release-assets.* # today), which some networks cannot reach: the metadata fetch above succeeds # and the binary download then fails on every retry, forever (#2064). Every # asset therefore has two sources. $DownloadEndpoint = if ($env:SQUIRREL_DOWNLOAD_ENDPOINT) { $env:SQUIRREL_DOWNLOAD_ENDPOINT } else { "https://install.squirrelscan.com/dl" } $ErrorLineMax = 200 $ErrorOutputMax = 1000 $script:CurrentStep = "init" $script:PathSetup = "" $script:LastCapturedExitCode = 0 # Where `squirrel self install` puts the binary on Windows. Hoisted to script # scope because the download-failure guidance names it too, not only the PATH # check at the end of Main. # # Guarded: Join-Path throws on a null Path, and at script scope with # $ErrorActionPreference = "Stop" that would kill the installer on line one, # before the banner, in any environment that has no LOCALAPPDATA (a service or # stripped-env invocation). This value is only ever printed, so naming the # variable symbolically is a better answer than dying. $script:InstallBinDir = if ($env:LOCALAPPDATA) { Join-Path $env:LOCALAPPDATA "squirrel\bin" } else { "%LOCALAPPDATA%\squirrel\bin" } # Make an arbitrary string safe to put in a report: reduce to printable ASCII # (control chars AND non-ASCII -> space) so truncation can't split a # surrogate/multibyte char and no ANSI escape reaches the JSON, scrub the home # path -> '~' so no local path leaks, then hard-truncate. Command output keeps # its TAIL (-KeepTail) because that's where the error is; a one-line message # keeps its head. The worker re-clamps and redacts too. function Get-ScrubbedText { param([string]$Text, [int]$MaxLength = 200, [switch]$KeepTail) if (-not $Text) { return "" } $scrubbed = $Text -replace '[^\x20-\x7E]', ' ' if ($env:USERPROFILE) { $scrubbed = $scrubbed.Replace($env:USERPROFILE, "~") } if ($HOME) { $scrubbed = $scrubbed.Replace($HOME, "~") } if ($scrubbed.Length -gt $MaxLength) { if ($KeepTail) { $scrubbed = $scrubbed.Substring($scrubbed.Length - $MaxLength) } else { $scrubbed = $scrubbed.Substring(0, $MaxLength) } } return $scrubbed } # Run a native command, echoing its output live AND returning it as one string. # `2>&1` merges the command's stderr into the pipeline; under # $ErrorActionPreference = "Stop" anything a native command writes to stderr # would otherwise become a terminating NativeCommandError, so drop to # "Continue" for the duration and restore afterwards. The exit code lands in # $script:LastCapturedExitCode. function Invoke-CapturedCommand { param([string]$FilePath, [string[]]$Arguments = @()) $previous = $ErrorActionPreference $ErrorActionPreference = "Continue" try { $lines = & $FilePath @Arguments 2>&1 | ForEach-Object { $text = if ($_ -is [System.Management.Automation.ErrorRecord]) { $_.ToString() } else { "$_" } Write-Host $text $text } $script:LastCapturedExitCode = $LASTEXITCODE } finally { $ErrorActionPreference = $previous } return ($lines -join "`n") } function Send-ErrorReport { param([string]$Step, [int]$ExitCode = 1, [string]$Line = "", [string]$Output = "") # Presence disables reporting, including an explicitly empty value. if (Test-Path Env:NO_TELEMETRY) { return } # DO_NOT_TRACK=1 or true also opts out (mirrors the CLI). if ($env:DO_NOT_TRACK -in @("1", "true", "True", "TRUE")) { return } try { $scrubbed = Get-ScrubbedText -Text $Line -MaxLength $ErrorLineMax # The tail of the failing command's own stdout/stderr. Without it a # self_install failure carried an exit code and nothing else (#1538). $scrubbedOutput = Get-ScrubbedText -Text $Output -MaxLength $ErrorOutputMax -KeepTail $arch = switch ($env:PROCESSOR_ARCHITECTURE) { "AMD64" { "x64" } "ARM64" { "arm64" } default { "$($env:PROCESSOR_ARCHITECTURE)" } } $channel = if ($env:SQUIRREL_CHANNEL) { $env:SQUIRREL_CHANNEL } else { "stable" } $payload = @{ script = "ps1" script_version = $InstallerReportVersion channel = $channel os = "windows" arch = $arch step = $Step exit_code = $ExitCode error_line = $scrubbed error_output = $scrubbedOutput } # Omitted rather than empty when the failure came before a version was # known; the worker treats an absent field as "unknown". if ($script:ReleaseVersion) { $payload["version"] = $script:ReleaseVersion } $payload = $payload | ConvertTo-Json -Compress # Fire-and-forget: run the POST in a background job so it never blocks # the installer. Not awaited; the 3s timeout inside is the backstop and # failures are swallowed. Start-Job -ScriptBlock { param($Uri, $Body) try { Invoke-RestMethod -Uri $Uri -Method Post -Body $Body ` -ContentType "application/json" -TimeoutSec 3 | Out-Null } catch {} } -ArgumentList $ErrorEndpoint, $payload | Out-Null } catch { # Reporting must never surface or fail the install. } } # --- Banner ------------------------------------------------------------ # The pixel squirrel + wordmark the CLI prints (apps/cli/src/cli/brand.ts), # pre-rendered because nothing but PowerShell exists at iwr|iex time. # BEGIN GENERATED HEADER (scripts/sync-install-header.ts, from apps/cli/src/cli/brand.ts; do not edit) $BannerArtColor = @' ▀▀ ▀▀ ▀▀▄ ▀▀ ▀▀▀▀ squirrelscan ▀▀ ▀▀▀▀▀▀▀▀▀▀ The website QA tool for your coding agent ▀▀▀▀▀▀▀▀ ▄▀ ▀▀▀▀▀▀ ▀▀ ▀▀ ▀▀ '@ $BannerArtPlain = @' ██ ██ ██▄ ██ ███▀ squirrelscan ██ ██████████ The website QA tool for your coding agent ████████ ▄█ ██████ ▀▀ ██ ██ '@ $BannerTextFallback = @' squirrelscan The website QA tool for your coding agent '@ # END GENERATED HEADER # Half-block glyphs need a UTF-8 console to render correctly; the classic # Windows console defaults to codepage 437/850 unless configured otherwise. function Test-Utf8Console { try { return [Console]::OutputEncoding.CodePage -eq 65001 } catch { return $false } } function Test-ColorSupported { if ($env:NO_COLOR) { return $false } try { if ([Console]::IsOutputRedirected) { return $false } } catch { return $false } # A non-redirected console isn't enough -- it also needs to actually # process raw ANSI/VT escapes, or the truecolor codes print literally. # Windows Terminal and PowerShell 7+ do this by default; classic # Windows PowerShell 5.1 in conhost.exe often doesn't (codex review, # #1029), so only opt in for hosts known to handle it. if ($env:WT_SESSION -or $env:TERM_PROGRAM) { return $true } return $PSVersionTable.PSVersion.Major -ge 7 } function Show-Banner { Write-Host "" if (-not (Test-Utf8Console)) { Write-Host $BannerTextFallback } elseif (Test-ColorSupported) { Write-Host $BannerArtColor } else { Write-Host $BannerArtPlain } Write-Host "" } # --- Release asset download (two sources) ------------------------------ # GitHub is the origin and always has every asset, so it is tried first; the # mirror at $DownloadEndpoint proxies the same bytes through Cloudflare, which # reaches GitHub even when the client cannot. The manifest's sha256 is verified # over whatever comes back either way, so a second source adds no trust. # # A mirror that answers 404 is treated as "nothing here", which is also what a # worker deployed before the route existed answers: the script degrades to the # GitHub failure it would have reported anyway rather than breaking. $script:DownloadUrlGitHub = "" $script:DownloadUrlMirror = "" $script:DownloadSource = "" # Opt-in flag semantics, matching the CLI's SQUIRREL_NO_UPDATE: empty, 0 and # false are off, anything else is on. Presence semantics would make a stray # empty SQUIRREL_FORCE_MIRROR silently reroute every install. function Test-ForceMirror { $value = "$($env:SQUIRREL_FORCE_MIRROR)".Trim().ToLowerInvariant() return -not ($value -eq "" -or $value -eq "0" -or $value -eq "false") } # Keep these installer metadata guards aligned with the validation in # apps/cli/src/self/paths.ts. Installer versions may carry the tag's `v`. function Test-ReleaseVersion { param([string]$Value) return $Value -cmatch '^v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?\z' } function Test-ReleaseFilename { param([string]$Value) return $Value -cmatch '^[A-Za-z0-9][A-Za-z0-9._-]*\z' } function Test-Sha256 { param([string]$Value) return $Value -cmatch '^[0-9a-fA-F]{64}\z' } # The two sources for one asset, in the order to try them, as (host, url) # pairs. Also records both URLs for the failure report. function Get-DownloadSources { param([string]$Version, [string]$Asset) if (-not (Test-ReleaseVersion $Version)) { Write-Err "Invalid release version in metadata" } if (-not (Test-ReleaseFilename $Asset)) { Write-Err "Invalid release asset filename in metadata" } $script:DownloadUrlGitHub = "https://github.com/$Repo/releases/download/$Version/$Asset" $script:DownloadUrlMirror = "$DownloadEndpoint/$Version/$Asset" $script:DownloadSource = "" $sources = @() if (Test-ForceMirror) { Write-Info "SQUIRREL_FORCE_MIRROR is set, skipping github.com" } else { $sources += ,@("github.com", $script:DownloadUrlGitHub) } $sources += ,@("install.squirrelscan.com", $script:DownloadUrlMirror) return ,$sources } # Invoke-WebRequest -OutFile leaves a partial file behind when a transfer dies # mid-stream, and the next source would then be asked to overwrite it. Delete a # failed attempt so only a completed download is ever handed back. function Get-ReleaseAsset { param( [string]$Version, [string]$Asset, [string]$OutFile, [string]$Label ) $sources = Get-DownloadSources -Version $Version -Asset $Asset for ($i = 0; $i -lt $sources.Count; $i++) { try { Invoke-WebRequest -Uri $sources[$i][1] -OutFile $OutFile -TimeoutSec 120 -UseBasicParsing $script:DownloadSource = $sources[$i][0] return $true } catch { if (Test-Path $OutFile) { Remove-Item -Path $OutFile -Force -ErrorAction SilentlyContinue } if ($i -lt ($sources.Count - 1)) { Write-Warn "$($sources[$i][0]) could not serve the $Label, trying $($sources[$i + 1][0])..." } } } return $false } # A 200 is not the same as the file we asked for. A captive portal, a proxy # error page, or a bucket that answers every path with its index all return HTML # with a 200, and Invoke-RestMethod hands that back as a string rather than # throwing. Content that is not a manifest means this SOURCE failed, so the # mirror still gets its turn. function Test-ManifestShape { param($Manifest) if ($null -eq $Manifest) { return $false } # A string is what Invoke-RestMethod returns for an HTML or plain-text body; # a real manifest comes back as an object with these two members. if ($Manifest -is [string]) { return $false } if (-not $Manifest.PSObject.Properties.Match('binaries').Count) { return $false } if (-not $Manifest.PSObject.Properties.Match('version').Count) { return $false } # `binaries` has to be a map, not merely present: `{"binaries":"unavailable"}` # would otherwise be accepted, the mirror would never be tried, and the user # would get "No binary for platform" from a source that plainly failed. $binaries = $Manifest.binaries if ($null -eq $binaries) { return $false } return ($binaries -is [System.Management.Automation.PSCustomObject]) -or ($binaries -is [hashtable]) } # Same two sources for a small JSON asset. Returns the parsed object, or $null # when both sources failed or neither served a usable one. function Get-ReleaseAssetJson { param([string]$Version, [string]$Asset, [string]$Label) $sources = Get-DownloadSources -Version $Version -Asset $Asset for ($i = 0; $i -lt $sources.Count; $i++) { $failure = "" try { $parsed = Invoke-RestMethod -Uri $sources[$i][1] -TimeoutSec 30 if (Test-ManifestShape $parsed) { $script:DownloadSource = $sources[$i][0] return $parsed } $failure = "$($sources[$i][0]) returned something that is not a $Label" } catch { $failure = "$($sources[$i][0]) could not serve the $Label" } if ($i -lt ($sources.Count - 1)) { Write-Warn "$failure, trying $($sources[$i + 1][0])..." } else { Write-Warn $failure } } return $null } # Reduce a URL to scheme, host and path before it is printed or reported. # SQUIRREL_DOWNLOAD_ENDPOINT is user-supplied and every part of it that can hold # a secret has to go: it can sit in the userinfo before the host, in the query # after the path, or in the fragment. The report scrubber strips home paths and # clamps length; it knows nothing about URL structure, so anything left here # reaches the reporting endpoint verbatim. Scheme, host and path are all a reader needs to tell which host was # tried, which is the whole point of carrying the URL at all. # Order is load-bearing, and getting it wrong leaks. `[^/@]*@` happily crosses a # `?`, so run against `https://host?token=user@secret/path` the userinfo rule ate # `host?token=user@` and promoted the token's value to the host: the secret # survived, in the report and on screen. Cut the query and fragment off first, # then strip userinfo from what is left, and bound that pattern so it cannot # cross a delimiter even if the order is ever changed back. function Get-RedactedUrl { param([string]$Url) $trimmed = [regex]::Replace($Url, '[?#].*$', '') return [regex]::Replace($trimmed, '^([a-zA-Z][a-zA-Z0-9+.-]*://)[^/?#@]*@', '$1') } # Single-quote a value for a copy-paste recipe. A literal apostrophe ends the # string in PowerShell and is escaped by doubling it: O'Brien -> 'O''Brien'. function Get-SingleQuoted { param([string]$Value) return "'" + $Value.Replace("'", "''") + "'" } # The report line and the user-facing guidance for a download that ran out of # sources. Write-Err carries the first to Sentry (clamped to $ErrorLineMax, # which two full URLs would blow past) and prints it; the URLs themselves ride # along in error_output, which has room for them. # # The line names the hosts AND the way out, because it is the one line that # reaches both the user's console and the Sentry issue; the guidance below it is # local only. function Get-DownloadFailureLine { param([string]$Label) if (Test-ForceMirror) { return "Failed to download the $Label from install.squirrelscan.com (SQUIRREL_FORCE_MIRROR is set, github.com was skipped)" } return "Failed to download the $Label from github.com and install.squirrelscan.com (retry with SQUIRREL_FORCE_MIRROR=1 to skip github.com)" } # Skipped is not failed: with SQUIRREL_FORCE_MIRROR set we never asked GitHub, # and a report claiming we did would send whoever reads it after the wrong host. function Get-DownloadFailureOutput { $github = Get-RedactedUrl $script:DownloadUrlGitHub $mirror = Get-RedactedUrl $script:DownloadUrlMirror $githubLine = if (Test-ForceMirror) { "skipped $github (SQUIRREL_FORCE_MIRROR)" } else { "tried $github (failed)" } return "$githubLine`ntried $mirror (failed)" } # `Kind` is `binary` or `manifest`: only the binary has a by-hand recipe worth # printing, because only the binary is the thing the user ultimately needs on # disk. function Show-DownloadFailureGuidance { param([string]$Asset, [string]$Kind) Write-Host " Tried:" if (Test-ForceMirror) { Write-Host " github.com skipped (SQUIRREL_FORCE_MIRROR is set)" } else { Write-Host " github.com $(Get-RedactedUrl $script:DownloadUrlGitHub)" } Write-Host " install.squirrelscan.com $(Get-RedactedUrl $script:DownloadUrlMirror)" Write-Host "" if (-not (Test-ForceMirror)) { Write-Host " If github.com is blocked on this network, skip it and retry:" Write-Host " `$env:SQUIRREL_FORCE_MIRROR='1'; iwr -useb https://install.squirrelscan.com/install.ps1 | iex" Write-Host "" } if ($Kind -eq "binary") { Write-Host " If both hosts are blocked, download $Asset on a machine that can" Write-Host " reach one of them, copy it here, then:" # The bin directory does not exist until the first successful install, # and Move-Item does not create it. Both paths are quoted through # Get-SingleQuoted: a profile under C:\Users\O'Brien would otherwise # print a command that will not parse. Write-Host " New-Item -ItemType Directory -Force -Path $(Get-SingleQuoted $script:InstallBinDir) | Out-Null" # Concatenated, not Join-Path: this is a display string, and Join-Path # resolves drives (it rejects a C:\ path anywhere that drive does not # exist, which is every non-Windows host the contract checks run on). Write-Host " Move-Item $(Get-SingleQuoted $Asset) $(Get-SingleQuoted "$($script:InstallBinDir)\squirrel.exe")" } else { Write-Host " If both hosts are blocked, this machine cannot reach anywhere the" Write-Host " release is published. Allowlist github.com or install.squirrelscan.com," Write-Host " or install from a network that already reaches one of them." } } function Get-LatestVersion { param([string]$Channel = "stable") $script:CurrentStep = "fetch_releases" Write-Info "Fetching releases (channel: $Channel)..." # Primary: install.squirrelscan.com/releases/{channel} — R2-backed release # metadata with no rate limits. Fallback: the GitHub API, which anonymous # clients share at 60 req/hr per IP — corporate NAT/VPN/CI egress hits 403s. try { $meta = Invoke-RestMethod -Uri "$ReleasesEndpoint/$Channel" -Headers @{"User-Agent"="squirrelscan-installer"} -TimeoutSec 15 if ($meta.version) { # Manifest versions are bare ("0.0.73"); release tags carry the v prefix. return "v" + ($meta.version -replace '^v', '') } } catch { Write-Warn "Release metadata endpoint unavailable, falling back to GitHub API..." } try { $releases = Invoke-RestMethod -Uri "https://api.github.com/repos/$Repo/releases" -Headers @{"User-Agent"="squirrelscan-installer"} -TimeoutSec 30 } catch { Write-Err "Failed to fetch releases: $_" } if (-not $releases -or $releases.Count -eq 0) { Write-Err "No releases found. Check: https://github.com/$Repo/releases" } if ($Channel -eq "stable") { $release = $releases | Where-Object { -not $_.prerelease } | Select-Object -First 1 } else { $release = $releases | Select-Object -First 1 } if (-not $release) { Write-Err "No releases found for channel '$Channel'" } return $release.tag_name } function Get-Manifest { param([string]$Version) $script:CurrentStep = "download_manifest" Write-Log "Downloading manifest..." $manifest = Get-ReleaseAssetJson -Version $Version -Asset "manifest.json" -Label "manifest" if ($null -eq $manifest) { Show-DownloadFailureGuidance -Asset "manifest.json" -Kind "manifest" Write-Err (Get-DownloadFailureLine "manifest") -Output (Get-DownloadFailureOutput) } return $manifest } # Provenance check (#169), the same policy as install.sh. The sha256 comes from # a manifest served next to the binary, so it cannot tell a compromised origin # from a good one. GitHub artifact attestations are signed in the release # workflow and checked against Sigstore and GitHub, which is not our origin. # gh usable, attestation matches -> continue # gh usable, attestation mismatch -> hard failure, nothing is installed # gh absent, too old, or logged out -> visible warning, sha256 alone decides # `gh attestation verify` needs an authenticated gh, so a gh that is installed # but not logged in counts as absent, never as a pass. $GhName is a seam for # the tests; callers use the default. # Runs gh with a deadline so a hung gh cannot hang the install. Returns # @{ Code; Output; TimedOut }. Start-Process with redirected output files, then # WaitForExit(ms) and Kill. $env:SQUIRREL_TEST_GH_TIMEOUT_SECS replaces every # deadline and exists only as a test seam. function Invoke-GhBounded { param([string]$GhName, [string[]]$GhArgs, [int]$TimeoutSec) if ($env:SQUIRREL_TEST_GH_TIMEOUT_SECS) { $TimeoutSec = [int]$env:SQUIRREL_TEST_GH_TIMEOUT_SECS } $exe = (Get-Command $GhName -ErrorAction SilentlyContinue | Select-Object -First 1).Source $outFile = [System.IO.Path]::GetTempFileName() $errFile = [System.IO.Path]::GetTempFileName() $previousNotifier = $env:GH_NO_UPDATE_NOTIFIER $previousPrompt = $env:GH_PROMPT_DISABLED $env:GH_NO_UPDATE_NOTIFIER = "1" $env:GH_PROMPT_DISABLED = "1" try { $quoted = @($GhArgs | ForEach-Object { if ($_ -match '[\s"]') { '"' + ($_ -replace '"', '\"') + '"' } else { $_ } }) $proc = Start-Process -FilePath $exe -ArgumentList $quoted -PassThru -NoNewWindow ` -RedirectStandardOutput $outFile -RedirectStandardError $errFile $null = $proc.Handle # keeps the handle so ExitCode is readable after exit $timedOut = $false if (-not $proc.WaitForExit($TimeoutSec * 1000)) { $timedOut = $true try { $proc.Kill($true) } catch { try { $proc.Kill() } catch { } } $null = $proc.WaitForExit(5000) } else { $proc.WaitForExit() # flush the redirected streams } $text = ((Get-Content $outFile -Raw -ErrorAction SilentlyContinue), (Get-Content $errFile -Raw -ErrorAction SilentlyContinue)) -join "`n" $code = if ($timedOut) { -1 } else { $proc.ExitCode } return @{ Code = $code; Output = $text.Trim(); TimedOut = $timedOut } } finally { $env:GH_NO_UPDATE_NOTIFIER = $previousNotifier $env:GH_PROMPT_DISABLED = $previousPrompt Remove-Item $outFile, $errFile -Force -ErrorAction SilentlyContinue } } function Test-ReleaseAttestation { param([string]$Path, [string]$GhName = "gh") $script:CurrentStep = "verify_attestation" if (-not (Get-Command $GhName -ErrorAction SilentlyContinue)) { Skip-Attestation "gh is not installed" "GitHub CLI (gh) not found: skipping the release provenance check, relying on the sha256 checksum only.`n Install gh and run 'gh auth login' to verify installs against the GitHub attestation." return } $help = Invoke-GhBounded -GhName $GhName -GhArgs @("attestation", "verify", "--help") -TimeoutSec 15 if ($help.TimedOut) { Skip-Attestation "gh attestation verify --help timed out" "gh attestation verify --help timed out after 15s: skipping the release provenance check, relying on the sha256 checksum only." return } if ($help.Code -ne 0) { Skip-Attestation "this gh is too old for 'gh attestation verify'" "This gh is too old for 'gh attestation verify': skipping the release provenance check, relying on the sha256 checksum only." return } $auth = Invoke-GhBounded -GhName $GhName -GhArgs @("auth", "status", "--hostname", "github.com") -TimeoutSec 15 if ($auth.TimedOut) { Skip-Attestation "gh auth status timed out" "gh auth status timed out after 15s: skipping the release provenance check, relying on the sha256 checksum only." return } if ($auth.Code -ne 0) { Skip-Attestation "gh is not logged in" "gh is not logged in: skipping the release provenance check, relying on the sha256 checksum only.`n Run 'gh auth login' to enable it." return } Write-Log "Verifying release attestation..." $verify = Invoke-GhBounded -GhName $GhName -GhArgs @("attestation", "verify", $Path, "--repo", $Repo, "--cert-identity", $CertIdentity, "--deny-self-hosted-runners") -TimeoutSec 120 if ($verify.TimedOut) { Write-Err "gh attestation verify timed out after 120s, nothing was installed." -Output $verify.Output } if ($verify.Code -ne 0) { $tail = (($verify.Output -split "`n") | Select-Object -Last 10) -join "`n" Write-Host $tail $noSig = if ($script:SigPinned) { "`n The release carries no squirrelscan release-key signature either." } else { "" } Write-Err "Attestation verification failed: this binary was not built by the $Repo release workflow.$noSig`n Nothing was installed. Do not run it." -Output $tail } Write-Info "Attestation verified: built by $Repo" } # Signed era (squirrelscan/repo#5032), the same rule as install.sh. From # $ReleaseFirstSignedVersion up, a release is accepted ONLY on a valid # pinned-key signature or a valid GitHub attestation: sha256 alone is a hard # failure, with or without gh. The era comes from the version being installed # (the resolved target), never from a manifest field. Unset means no era. $script:SignedEra = $false $script:SignedEraVersion = "" $script:SigNote = "" $script:SigPinned = $false # Numeric identifiers compared as digit strings, so nothing overflows. function Compare-DigitString { param([string]$A, [string]$B) $A = $A.TrimStart('0'); $B = $B.TrimStart('0') if ($A.Length -ne $B.Length) { return [Math]::Sign($A.Length - $B.Length) } return [Math]::Sign([string]::CompareOrdinal($A, $B)) } # Semver precedence of two versions that satisfy Test-ReleaseVersion: -1, 0 or 1. # A leading v and +build are ignored; a prerelease sorts below its release. function Compare-ReleaseVersion { param([string]$A, [string]$B) $pa = ($A -replace '^v', '' -split '\+')[0] $pb = ($B -replace '^v', '' -split '\+')[0] $ca, $ra = $pa -split '-', 2 $cb, $rb = $pb -split '-', 2 $na = $ca -split '\.' $nb = $cb -split '\.' for ($i = 0; $i -lt 3; $i++) { $c = Compare-DigitString $na[$i] $nb[$i] if ($c -ne 0) { return $c } } if (-not $ra -and -not $rb) { return 0 } if (-not $ra) { return 1 } if (-not $rb) { return -1 } $ia = $ra -split '\.' $ib = $rb -split '\.' for ($i = 0; $i -lt [Math]::Max($ia.Count, $ib.Count); $i++) { if ($i -ge $ia.Count) { return -1 } if ($i -ge $ib.Count) { return 1 } $xn = $ia[$i] -cmatch '^[0-9]+$' $yn = $ib[$i] -cmatch '^[0-9]+$' if ($xn -and $yn) { $c = Compare-DigitString $ia[$i] $ib[$i] if ($c -ne 0) { return $c } } elseif ($xn) { return -1 } elseif ($yn) { return 1 } elseif ($ia[$i] -cne $ib[$i]) { return [Math]::Sign([string]::CompareOrdinal($ia[$i], $ib[$i])) } } return 0 } # True when $Version is at or after $FirstSigned (default: the generated one). # A version that does not parse counts as signed-era, never as a way out. function Test-SignedEra { param([string]$Version, [string]$FirstSigned = $ReleaseFirstSignedVersion) if (-not $FirstSigned) { return $false } if (-not (Test-ReleaseVersion $Version)) { return $true } return (Compare-ReleaseVersion $Version $FirstSigned) -ge 0 } function Stop-SignedEra { param([string]$What) Write-Err "Cannot verify squirrel $($script:SignedEraVersion -replace '^v', ''): $What.`n This version is only installed with a valid release-key signature or GitHub attestation; the sha256 checksum alone is not accepted.`n Nothing was installed.`n To install by hand, download the binary and its .sig and check them with openssl dgst -sha256 -verify:`n https://docs.squirrelscan.com/install#verifying-a-release" } # gh cannot check the attestation. Before the signed era that is a warning and # the sha256 decides; in it, it is a hard failure. function Skip-Attestation { param([string]$Reason, [string]$Message) if ($script:SignedEra) { $note = if ($script:SigNote) { $script:SigNote } else { "no signature was checked" } Stop-SignedEra "$note, and the GitHub attestation could not be checked ($Reason)" } Write-Warn $Message } # --- ECDSA P-256 verify (the .sig files are DER, from openssl dgst -sha256 -sign) --- # PowerShell 7 (.NET Core 3+) builds an ECDsa from the SPKI's point and verifies DER directly. # Windows PowerShell 5.1 (.NET Framework 4.x) has neither, so it goes through # ECDsaCng with an EccPublicBlob built from the SPKI's raw point and a raw r||s # signature. The helpers below are plain byte work, shared and unit-tested. function ConvertFrom-PemPublicKey { param([string]$Pem) $m = [regex]::Match(($Pem -replace "`r`n", "`n"), '^-----BEGIN PUBLIC KEY-----\n([A-Za-z0-9+/=\n]+)\n-----END PUBLIC KEY-----\n?\z') if (-not $m.Success) { return $null } try { return [Convert]::FromBase64String(($m.Groups[1].Value -replace "`n", "")) } catch { return $null } } # The 91-byte SPKI of a P-256 key: this 26-byte header, then 04 || X || Y. $script:P256SpkiHeader = [byte[]](0x30,0x59,0x30,0x13,0x06,0x07,0x2A,0x86,0x48,0xCE,0x3D,0x02,0x01,0x06,0x08,0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x07,0x03,0x42,0x00) # X || Y (64 bytes) from a P-256 SPKI, or $null when it is not one. function Get-SpkiPoint { param([byte[]]$Spki) if ($null -eq $Spki -or $Spki.Length -ne 91) { return $null } for ($i = 0; $i -lt 26; $i++) { if ($Spki[$i] -ne $script:P256SpkiHeader[$i]) { return $null } } if ($Spki[26] -ne 4) { return $null } return [byte[]]($Spki[27..90]) } # BCRYPT_ECCKEY_BLOB: magic ECS1 (0x31534345, ECDSA P-256 public), key length 32, X || Y. function New-EccPublicBlob { param([byte[]]$Point) $blob = New-Object byte[] 72 [BitConverter]::GetBytes([uint32]0x31534345).CopyTo($blob, 0) [BitConverter]::GetBytes([uint32]32).CopyTo($blob, 4) [Array]::Copy($Point, 0, $blob, 8, 64) return ,$blob } # DER SEQUENCE { INTEGER r, INTEGER s } to 64 bytes r || s, each left-padded to # 32. Strict: anything that is not minimal DER for P-256 returns $null. function ConvertFrom-DerSignature { param([byte[]]$Der) if ($null -eq $Der -or $Der.Length -lt 8 -or $Der.Length -gt 72) { return $null } if ($Der[0] -ne 0x30 -or $Der[1] -gt 0x7F -or $Der[1] -ne $Der.Length - 2) { return $null } $raw = New-Object byte[] 64 $pos = 2 for ($part = 0; $part -lt 2; $part++) { if ($pos + 2 -gt $Der.Length -or $Der[$pos] -ne 0x02) { return $null } $len = $Der[$pos + 1] $pos += 2 if ($len -lt 1 -or $len -gt 33 -or $pos + $len -gt $Der.Length) { return $null } $start = $pos $pos += $len if ($Der[$start] -band 0x80) { return $null } if ($len -gt 1 -and $Der[$start] -eq 0 -and -not ($Der[$start + 1] -band 0x80)) { return $null } if ($Der[$start] -eq 0) { $start++; $len-- } if ($len -gt 32) { return $null } [Array]::Copy($Der, $start, $raw, $part * 32 + (32 - $len), $len) } if ($pos -ne $Der.Length) { return $null } return ,$raw } # $true only for a valid signature of $Data by the key in $Pem. Any failure is $false. function Test-EcdsaP256Signature { param([string]$Pem, [byte[]]$Data, [byte[]]$DerSignature) try { $spki = ConvertFrom-PemPublicKey $Pem $point = Get-SpkiPoint $spki if ($null -eq $point) { return $false } if ('System.Security.Cryptography.DSASignatureFormat' -as [type]) { # ImportSubjectPublicKeyInfo takes a ReadOnlySpan, which PowerShell cannot # pass, so the already-checked point goes in as ECParameters. $q = [System.Security.Cryptography.ECPoint]::new() $q.X = [byte[]]$point[0..31] $q.Y = [byte[]]$point[32..63] $params = [System.Security.Cryptography.ECParameters]::new() $params.Curve = [System.Security.Cryptography.ECCurve]::CreateFromFriendlyName("nistP256") $params.Q = $q $ecdsa = [System.Security.Cryptography.ECDsa]::Create($params) try { return $ecdsa.VerifyData($Data, $DerSignature, [System.Security.Cryptography.HashAlgorithmName]::SHA256, [System.Security.Cryptography.DSASignatureFormat]::Rfc3279DerSequence) } finally { $ecdsa.Dispose() } } $raw = ConvertFrom-DerSignature $DerSignature if ($null -eq $raw) { return $false } $cngKey = [System.Security.Cryptography.CngKey]::Import((New-EccPublicBlob $point), [System.Security.Cryptography.CngKeyBlobFormat]::EccPublicBlob) $cng = New-Object System.Security.Cryptography.ECDsaCng($cngKey) try { $cng.HashAlgorithm = [System.Security.Cryptography.CngAlgorithm]::Sha256 return $cng.VerifyData($Data, $raw) } finally { $cng.Dispose(); $cngKey.Dispose() } } catch { return $false } } function Test-ReleaseKeysPinned { return [bool]($ReleaseKeyCurrentPem -or $ReleaseKeyNextPem) } # The PEM of the pinned slot with this id, or $null. function Get-ReleaseKeyPem { param([string]$Id) if ($ReleaseKeyCurrentPem -and $Id -ceq $ReleaseKeyCurrentId) { return $ReleaseKeyCurrentPem } if ($ReleaseKeyNextPem -and $Id -ceq $ReleaseKeyNextId) { return $ReleaseKeyNextPem } return $null } # One quiet fetch of a small file as bytes. A missing .sig is normal for an # attested release. $null when absent, unreachable or larger than $MaxBytes. function Get-ReleaseFileBytes { param([string]$Url, [int]$MaxBytes) $tmp = [System.IO.Path]::GetTempFileName() try { Invoke-WebRequest -Uri $Url -OutFile $tmp -TimeoutSec 30 -UseBasicParsing $bytes = [System.IO.File]::ReadAllBytes($tmp) if ($bytes.Length -eq 0 -or $bytes.Length -gt $MaxBytes) { return $null } return ,$bytes } catch { return $null } finally { Remove-Item $tmp -Force -ErrorAction SilentlyContinue } } function Stop-SignatureFailed { param([string]$Why) Write-Err "Release signature verification failed: $Why.`n Nothing was installed. Do not run it." } # Returns $true when a pinned key signed both manifest.json and the binary, and # $false when the release carries no signature (or the check cannot run), so the # attestation decides. Anything else is a hard failure, attestation or not: an # unpinned or revoked key, a signature that does not verify, a signed manifest # for another version, or only one of the two .sig files. function Test-ReleaseSignature { param([string]$Version, [string]$Filename, [string]$BinaryPath) $script:CurrentStep = "verify_signature" $script:SigPinned = Test-ReleaseKeysPinned if (-not $script:SigPinned) { $script:SigNote = "no release key is pinned"; return $false } $binaryUrl = if ($script:DownloadSource -eq "github.com") { $script:DownloadUrlGitHub } else { $script:DownloadUrlMirror } $base = $binaryUrl.Substring(0, $binaryUrl.Length - $Filename.Length) $manifestBytes = Get-ReleaseFileBytes "${base}manifest.json" 1048576 $manifestSig = Get-ReleaseFileBytes "${base}manifest.json.sig" 1024 $assetSig = Get-ReleaseFileBytes "${binaryUrl}.sig" 1024 if (-not $manifestSig -and -not $assetSig) { $script:SigNote = "the release has no .sig files"; return $false } if (-not $manifestSig) { Stop-SignatureFailed "manifest.json.sig is missing" } if (-not $assetSig) { Stop-SignatureFailed "$Filename.sig is missing" } if (-not $manifestBytes) { Stop-SignatureFailed "manifest.json could not be fetched to check it" } try { $signed = [System.Text.Encoding]::UTF8.GetString($manifestBytes) | ConvertFrom-Json } catch { Stop-SignatureFailed "manifest.json is not valid JSON" } $keyId = "$($signed.signing_key_id)" if ($keyId -cnotmatch '^[0-9a-f]{16}\z') { Stop-SignatureFailed "manifest.json names no signing key id" } if (($ReleaseKeysRevoked -split ' ') -ccontains $keyId) { Stop-SignatureFailed "it is signed with revoked key $keyId" } $pem = Get-ReleaseKeyPem $keyId if (-not $pem) { Stop-SignatureFailed "it is signed with key $keyId, which this installer does not pin" } Write-Log "Verifying release signature..." if (-not (Test-EcdsaP256Signature -Pem $pem -Data $manifestBytes -DerSignature $manifestSig)) { Stop-SignatureFailed "manifest.json is not signed by key $keyId" } # A signed manifest replayed under another version's URL is a downgrade. if (("$($signed.version)" -replace '^v', '') -cne ($Version -replace '^v', '')) { Stop-SignatureFailed "the signed manifest is for version '$($signed.version)', not $Version" } if (-not (Test-EcdsaP256Signature -Pem $pem -Data ([System.IO.File]::ReadAllBytes($BinaryPath)) -DerSignature $assetSig)) { Stop-SignatureFailed "$Filename is not signed by key $keyId" } Write-Info "Release signature verified: signed by squirrelscan release key $keyId" return $true } # Provenance after the sha256 check: a pinned-key signature, else the # attestation. In the signed era neither skipping nor sha256 alone is an option. function Test-ReleaseProvenance { param([string]$Version, [string]$Filename, [string]$BinaryPath, [string]$GhName = "gh") $script:SignedEraVersion = $Version $script:SignedEra = Test-SignedEra $Version $script:SigNote = "" if (-not (Test-ReleaseSignature -Version $Version -Filename $Filename -BinaryPath $BinaryPath)) { Test-ReleaseAttestation -Path $BinaryPath -GhName $GhName } } function Install-Squirrel { param( [string]$Version, [object]$Manifest ) $binary = $Manifest.binaries.$Platform if (-not $binary) { Write-Err "No binary for platform: $Platform`n See: https://github.com/$Repo/releases/tag/$Version" } $filename = $binary.filename $expectedHash = $binary.sha256 if (-not (Test-ReleaseFilename $filename)) { Write-Err "Invalid release asset filename in metadata" } if (-not (Test-Sha256 $expectedHash)) { Write-Err "Invalid SHA256 in release manifest" } $expectedHash = $expectedHash.ToLowerInvariant() # Create temp directory $tempDir = Join-Path $env:TEMP "squirrel-install-$(Get-Random)" New-Item -ItemType Directory -Path $tempDir -Force | Out-Null try { $binaryPath = Join-Path $tempDir "squirrel.exe" $script:CurrentStep = "download_binary" Write-Log "Downloading squirrel $Version..." if (-not (Get-ReleaseAsset -Version $Version -Asset $filename -OutFile $binaryPath -Label "binary")) { Show-DownloadFailureGuidance -Asset $filename -Kind "binary" Write-Err (Get-DownloadFailureLine "binary") -Output (Get-DownloadFailureOutput) } # Only when the mirror answered. The GitHub path is the one almost every # install takes, and its output stays byte-identical to before this change. if ($script:DownloadSource -ne "github.com") { Write-Info "Downloaded from $($script:DownloadSource)" } # Verify checksum $script:CurrentStep = "verify_checksum" Write-Log "Verifying checksum..." $actualHash = (Get-FileHash -Path $binaryPath -Algorithm SHA256).Hash.ToLowerInvariant() if ($actualHash -cne $expectedHash) { Write-Err "Checksum mismatch!`n Expected: $expectedHash`n Actual: $actualHash" } Write-Info "Checksum verified: $($expectedHash.Substring(0, 16))..." Test-ReleaseProvenance -Version $Version -Filename $filename -BinaryPath $binaryPath # Run self install. Its output is echoed live AND captured, so a failure # reports what the binary actually said instead of a bare exit code # (#1538) — the tail rides along on the error report. $script:CurrentStep = "self_install" Write-Log "Running self install..." $selfInstallOutput = Invoke-CapturedCommand -FilePath $binaryPath -Arguments @("self", "install") $selfInstallExit = $script:LastCapturedExitCode if ($selfInstallExit -ne 0) { Write-Err "Self install failed with exit code $selfInstallExit" ` -Output $selfInstallOutput -ExitCode $selfInstallExit } } finally { # Cleanup if (Test-Path $tempDir) { Remove-Item -Path $tempDir -Recurse -Force -ErrorAction SilentlyContinue } } } # Same flag semantics as the shell installer: empty, 0 and false are off. function Test-NoModifyPath { $v = "$env:SQUIRREL_NO_MODIFY_PATH".Trim().ToLowerInvariant() return ($v -ne "" -and $v -ne "0" -and $v -ne "false") } function Test-CiEnvironment { $v = "$env:CI".Trim().ToLowerInvariant() return ($v -ne "" -and $v -ne "0" -and $v -ne "false") } # True when $Dir is one of the ';'-separated entries of $PathValue. function Test-PathHasDir { param([string]$PathValue, [string]$Dir) foreach ($entry in ("$PathValue" -split ";")) { # A User Path entry can hold %VARS% (REG_EXPAND_SZ); compare it expanded. $expanded = [Environment]::ExpandEnvironmentVariables($entry) if ($expanded.TrimEnd("\") -ieq $Dir.TrimEnd("\")) { return $true } } return $false } # The User Path exactly as stored, %VARS% unexpanded ("" when unset). function Get-RawUserPath { try { $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey("Environment") if (-not $key) { return "" } try { return [string]$key.GetValue("Path", "", [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) } finally { $key.Close() } } catch { # No registry (non-Windows PowerShell): the expanded value is the best there is. return [string][Environment]::GetEnvironmentVariable("Path", "User") } } # Put $BinDir on the User-scope Path (never Machine) and on this session's # $env:Path. Returns the outcome stamped for `squirrel self install`: # on_path | added | opted_out | ci | failed function Set-UserPath { param([string]$BinDir) # The raw, unexpanded value: expanding it and writing it back would # flatten any %VARS% entries the user keeps in their Path. $userPath = Get-RawUserPath if (Test-PathHasDir $userPath $BinDir) { # Already persisted; make sure this session sees it too. if (-not (Test-PathHasDir $env:Path $BinDir)) { $env:Path = ("$env:Path".TrimEnd(";") + ";" + $BinDir) } return "on_path" } # On this session's Path only: nothing to persist, and none of our business. if (Test-PathHasDir $env:Path $BinDir) { return "on_path" } if (Test-NoModifyPath) { return "opted_out" } if (Test-CiEnvironment) { if ($env:GITHUB_PATH) { try { Add-Content -Path $env:GITHUB_PATH -Value $BinDir -ErrorAction Stop } catch { return "failed" } } return "ci" } # A symbolic %LOCALAPPDATA% fallback (no such variable) is not a real path. if ($BinDir -like "*%*") { return "failed" } try { $newPath = if ($userPath) { $userPath.TrimEnd(";") + ";" + $BinDir } else { $BinDir } if ($newPath -like "*%*") { # SetEnvironmentVariable would rewrite the value as REG_SZ and stop # %VARS% entries expanding. Write REG_EXPAND_SZ, then set and clear a # throwaway variable so Windows broadcasts WM_SETTINGCHANGE and new # terminals see the Path. # A null $key throws below and the catch reports "failed". $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey("Environment", $true) try { $key.SetValue("Path", $newPath, [Microsoft.Win32.RegistryValueKind]::ExpandString) } finally { $key.Close() } [Environment]::SetEnvironmentVariable("SQUIRREL_PATH_NOTIFY", "1", "User") [Environment]::SetEnvironmentVariable("SQUIRREL_PATH_NOTIFY", $null, "User") } else { [Environment]::SetEnvironmentVariable("Path", $newPath, "User") } $env:Path = ("$env:Path".TrimEnd(";") + ";" + $BinDir) return "added" } catch { return "failed" } } function Show-Epilogue { # Get-started epilogue: lead with the first audit, then `squirrel setup` # (sign-in, agent skills, defaults), which also ends by offering an audit. param([string]$Version, [string]$BinDir = "", [string]$PathSetup = "") Write-Host "" Write-Host "squirrel $Version installed" -ForegroundColor Green Write-Host "" if ($PathSetup -in @("opted_out", "ci", "failed") -and $BinDir) { # This session cannot find squirrel: name a command that works now. Write-Host "squirrel is not on your PATH yet. Run your first audit right now:" Write-Host "" Write-Host " & '$($BinDir.Replace("'", "''"))\squirrel.exe' audit https://your-site.com" } else { Write-Host "Run your first audit (crawls the site, scores it, lists exact fixes):" Write-Host "" Write-Host " squirrel audit https://your-site.com" } Write-Host "" Write-Host "Then set up sign-in, agent skills and defaults: squirrel setup" Write-Host "Docs: https://docs.squirrelscan.com" Write-Host "" } function Main { Show-Banner Write-Log "Installing squirrel..." $channel = if ($env:SQUIRREL_CHANNEL) { $env:SQUIRREL_CHANNEL } else { "stable" } # Get version if ($env:SQUIRREL_VERSION) { $version = $env:SQUIRREL_VERSION $script:ReleaseVersion = $version -replace '^v', '' Write-Log "Installing pinned version: $version" } else { $version = Get-LatestVersion -Channel $channel if (-not $version) { if ($channel -eq "stable") { Write-Err "No stable releases found. Try:`n `$env:SQUIRREL_CHANNEL='beta'; iwr -useb ... | iex" } else { Write-Err "No releases found for channel '$channel'" } } $script:ReleaseVersion = $version -replace '^v', '' Write-Log "Latest version: $version (channel: $channel)" } # Put the bin dir on PATH before self install, which hands the outcome to # the CLI's one-time install registration (path_setup). $binDir = $script:InstallBinDir $script:PathSetup = Set-UserPath -BinDir $binDir $env:SQUIRREL_PATH_SETUP = $script:PathSetup # Get manifest and install $manifest = Get-Manifest -Version $version Install-Squirrel -Version $version -Manifest $manifest if ($script:PathSetup -eq "added") { Write-Info "Added $binDir to your user PATH. New terminals pick it up." } Show-Epilogue -Version $version -BinDir $binDir -PathSetup $script:PathSetup if ($script:PathSetup -in @("opted_out", "failed", "ci")) { Write-Host "" Write-Warn "$binDir is not in your PATH" Write-Host "" # Detect shell/terminal $shell = if ($env:WT_SESSION) { "Windows Terminal" } elseif ($env:TERM_PROGRAM -eq "vscode") { "VS Code" } else { "PowerShell" } Write-Host "To add permanently, run:" Write-Host "" Write-Host " [Environment]::SetEnvironmentVariable('Path', [Environment]::GetEnvironmentVariable('Path', 'User') + ';$binDir', 'User')" Write-Host "" Write-Host "Then restart your terminal ($shell)." Write-Host "" Write-Host "Or add to session temporarily:" Write-Host "" Write-Host " `$env:Path += ';$binDir'" Write-Host "" Write-Host "After updating PATH, verify with: squirrel self doctor" } Write-Host "" exit 0 } try { Main } catch { # A terminating error that didn't route through Write-Err (e.g. an # unexpected cmdlet failure under $ErrorActionPreference = "Stop"). Send-ErrorReport -Step $script:CurrentStep -ExitCode 1 -Line "$($_.Exception.Message)" Write-Host "Error: $($_.Exception.Message)" -ForegroundColor Red exit 1 }