<# Hoody CLI installer (Windows PowerShell) — GitHub-native. Windows sibling of install.sh; identical trust chain. Resolves the latest release (npm registry first, then GitHub), downloads the native binary + its signed checksum manifest, verifies the minisign (Ed25519) signature BEFORE the SHA-256 hash, and installs hoody.exe into %USERPROFILE%\.hoody\bin. No admin. Trust model (identical to install.sh): * SHA256SUMS.minisig (offline Ed25519 key) is the authenticity anchor, verified FIRST — a stolen GitHub credential could rewrite a binary AND its checksum, but it cannot forge the signature. * The minisign VERIFIER is bootstrapped from the Release and its SHA-256 is PINNED here, checked before it verifies anything. * The signed trusted_comment must name the resolved version (anti-replay). Portability: every network fetch goes through one System.Net.Http.HttpClient with auto-redirect DISABLED and manual, HTTPS-asserted redirect following, so TLS + redirect behavior is identical on Windows PowerShell 5.1 (.NET Framework) and PowerShell 7 (.NET) — no https->http downgrade on either, and the release 302 is read from a typed Uri instead of version-divergent cmdlet internals. Invocation: `iwr https://install./install.ps1 -UseBasicParsing | iex`. Because `iex` runs in the CALLER's scope, the whole body runs inside an invoked scriptblock `& { ... }`, so StrictMode / $ErrorActionPreference / helper functions are scoped to it and never leak into the user's session, and every failure prints one friendly line rather than `exit` (which would close the user's console) or a raw stack. #> [CmdletBinding()] param() & { Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' $ProgressPreference = 'SilentlyContinue' # PS 5.1: the progress bar cripples large downloads # --- Pinned trust anchors ------------------------------------------------- $PinnedPubkey = 'RWRpngXprNcILzU05dVs9Bkws5tS4KqPkg2FVm7vnS1sowCpg42ax3Ek' $Repo = 'HoodyNetwork/hoody-sdk' $VerifierSha = '5535be9e4e123831ebe6ef324aafe9dde507015c176191f9e20c3ad60567f9e1' $IsCore = $PSVersionTable.PSVersion.Major -ge 6 $origSpm = $null # captured/mutated inside the outer try below, restored in its finally function Fail([string]$m) { throw "hoody install: $m" } function Step([string]$m) { Write-Host "-> $m" -ForegroundColor White } function Ok([string]$m) { Write-Host "OK $m" -ForegroundColor Green } function Get-Sha256([string]$Path) { return (Get-FileHash -Algorithm SHA256 -LiteralPath $Path).Hash.ToLowerInvariant() } # Canonical SemVer (semver.org grammar): MAJOR.MINOR.PATCH with no leading # zeros, optional dot-separated -prerelease, optional +build. Matches # install.sh's is_semver. Gates the resolved version before it enters a URL. # Uses [0-9] (NOT \d, which .NET expands to Unicode decimal digits) and \A..\z # absolute anchors via -cmatch (NOT ^..$, which would accept a trailing LF). function Test-SemVer([string]$v) { return $v -cmatch '\A(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-((0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)(\.(0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*))*))?(\+([0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*))?\z' } # Split a semver into numeric core parts + prerelease string (build metadata # dropped). function Get-SemVerParts([string]$v) { $noBuild = ($v -split '\+', 2)[0] $dash = $noBuild.IndexOf('-') if ($dash -ge 0) { return @{ Core = $noBuild.Substring(0, $dash).Split('.'); Pre = $noBuild.Substring($dash + 1) } } return @{ Core = $noBuild.Split('.'); Pre = '' } } # Compare two non-negative integer STRINGS without overflow: strip leading # zeros, then compare by length, then lexically. Returns -1/0/1. function Compare-NumStr([string]$x, [string]$y) { $x = $x.TrimStart('0'); if ($x -eq '') { $x = '0' } $y = $y.TrimStart('0'); if ($y -eq '') { $y = '0' } if ($x.Length -lt $y.Length) { return -1 } if ($x.Length -gt $y.Length) { return 1 } $c = [string]::CompareOrdinal($x, $y) if ($c -lt 0) { return -1 }; if ($c -gt 0) { return 1 }; return 0 } # Full SemVer precedence (spec sec.11): numeric core, then prerelease — a # release outranks a prerelease, numeric identifiers compare numerically and # rank below alphanumeric, more identifiers outrank fewer. Returns -1/0/1. # This is what makes a beta -> stable of the same core (1.0.0-beta.3 -> 1.0.0) # read as an UPGRADE, not a downgrade; a core-only compare would miss it. # Numeric comparison is string-based (Compare-NumStr) so it never overflows. function Compare-SemVer([string]$a, [string]$b) { $pa = Get-SemVerParts $a; $pb = Get-SemVerParts $b for ($i = 0; $i -lt 3; $i++) { $c = Compare-NumStr $pa.Core[$i] $pb.Core[$i] if ($c -ne 0) { return $c } } if ($pa.Pre -eq '' -and $pb.Pre -eq '') { return 0 } if ($pa.Pre -eq '') { return 1 } # release > prerelease if ($pb.Pre -eq '') { return -1 } $ia = $pa.Pre.Split('.'); $ib = $pb.Pre.Split('.') $n = [Math]::Max($ia.Length, $ib.Length) for ($i = 0; $i -lt $n; $i++) { if ($i -ge $ia.Length) { return -1 } # fewer identifiers rank lower if ($i -ge $ib.Length) { return 1 } $x = $ia[$i]; $y = $ib[$i] $xn = $x -match '^[0-9]+$'; $yn = $y -match '^[0-9]+$' if ($xn -and $yn) { $c = Compare-NumStr $x $y; if ($c -ne 0) { return $c } } elseif ($xn) { return -1 } # numeric < alphanumeric elseif ($yn) { return 1 } else { $c = [string]::CompareOrdinal($x, $y) if ($c -lt 0) { return -1 }; if ($c -gt 0) { return 1 } } } return 0 } # Run a native command with the error preference relaxed so a stderr line does # not become a terminating error before we can read $LASTEXITCODE (a PS 5.1 # gotcha). Callers still gate on $LASTEXITCODE. function Invoke-Native([scriptblock]$Block) { $old = $ErrorActionPreference $ErrorActionPreference = 'Continue' try { & $Block } finally { $ErrorActionPreference = $old } } # --- HTTPS transport (one code path for both PowerShell lineages) --------- function New-HoodyHttpClient([int]$TimeoutSec) { $h = [System.Net.Http.HttpClientHandler]::new() $h.AllowAutoRedirect = $false # we follow manually, asserting https each hop $c = [System.Net.Http.HttpClient]::new($h, $true) $c.Timeout = [TimeSpan]::FromSeconds($TimeoutSec) $c.DefaultRequestHeaders.UserAgent.ParseAdd('hoody-install') return $c } # GET, following up to $MaxRedir redirects, each hop asserted https. Returns # the final HttpResponseMessage (caller disposes). Throws on a non-https hop, # too many redirects, or a transport error. Uses ResponseContentRead so the # client's Timeout bounds the WHOLE transfer (headers AND body) — a server # that sends headers then stalls the body cannot hang the installer. (The # (Stream, CancellationToken) CopyToAsync overload does not exist on .NET # Framework 4.x, so this is the portable way to time-bound the body.) function Get-HttpsResponse($Client, [string]$Url, [int]$MaxRedir = 6) { $cur = $Url for ($i = 0; $i -le $MaxRedir; $i++) { if ($cur -notmatch '^https://') { throw "refusing non-HTTPS URL in redirect chain: $cur" } $resp = $Client.GetAsync($cur, [System.Net.Http.HttpCompletionOption]::ResponseContentRead).GetAwaiter().GetResult() $code = [int]$resp.StatusCode if ($code -ge 300 -and $code -lt 400) { $next = $resp.Headers.Location $resp.Dispose() if (-not $next) { throw "redirect without Location from $cur" } if (-not $next.IsAbsoluteUri) { $next = [System.Uri]::new([System.Uri]$cur, $next) } $cur = $next.AbsoluteUri continue } return $resp } throw "too many redirects for $Url" } # Read the Location of the FIRST response without following it (for the # releases/latest 302), resolving a relative Location against the request URI. # Any failure yields $null -> caller degrades cleanly. function Get-RedirectLocation($Client, [string]$Url) { if ($Url -notmatch '^https://') { return $null } try { $resp = $Client.GetAsync($Url, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead).GetAwaiter().GetResult() try { $loc = $resp.Headers.Location if (-not $loc) { return $null } if (-not $loc.IsAbsoluteUri) { $loc = [System.Uri]::new([System.Uri]$Url, $loc) } return $loc.AbsoluteUri } finally { $resp.Dispose() } } catch { return $null } } function Save-Https($Client, [string]$Url, [string]$Out, [string]$What) { try { $resp = Get-HttpsResponse $Client $Url } catch { Fail "could not download $What ($Url)." } try { if (-not $resp.IsSuccessStatusCode) { Fail "could not download $What — HTTP $([int]$resp.StatusCode) ($Url)." } $fs = [System.IO.File]::Create($Out) try { $resp.Content.CopyToAsync($fs).GetAwaiter().GetResult() | Out-Null } finally { $fs.Dispose() } } finally { $resp.Dispose() } } function Read-HttpsString($Client, [string]$Url) { try { $resp = Get-HttpsResponse $Client $Url } catch { return $null } try { if (-not $resp.IsSuccessStatusCode) { return $null } return $resp.Content.ReadAsStringAsync().GetAwaiter().GetResult() } finally { $resp.Dispose() } } # --- Platform (Windows x86_64; ARM64 runs it under emulation) ------------- $Os = 'windows'; $Arch = 'x86_64' $BinaryName = "hoody-$Os-$Arch.exe" $VerifierName = "minisign-$Os-$Arch.exe" Write-Host "" Write-Host " Hoody CLI installer" -ForegroundColor Cyan Write-Host "" $Tmp = $null; $Staged = $null; $client = $null try { # TLS 1.2 for Windows PowerShell 5.1 (its HttpClientHandler honors the # process-wide ServicePointManager); PS 7 negotiates >= 1.2 by default and # ignores it. Done inside THIS try so the finally always restores it — an # `iwr | iex` caller's session must not be left with a mutated static. try { $origSpm = [Net.ServicePointManager]::SecurityProtocol [Net.ServicePointManager]::SecurityProtocol = $origSpm -bor [Net.SecurityProtocolType]::Tls12 } catch {} if (-not $IsCore) { try { Add-Type -AssemblyName System.Net.Http } catch {} } $client = New-HoodyHttpClient 600 try { # --- Resolve latest version (npm first, then GitHub) ------------------ # npm-first is what makes the beta -> stable switch just work: it reads the # `latest` dist-tag, exactly like `npm i -g hoody-sdk@latest`, so whatever # is published (a prerelease today, a stable tag later) resolves here. Step "Resolving latest release" $Version = '' if ($env:HOODY_VERSION) { $Version = ($env:HOODY_VERSION -replace '^v', '') } else { $json = Read-HttpsString $client 'https://registry.npmjs.org/hoody-sdk/latest' if ($json) { try { $doc = $json | ConvertFrom-Json if ($doc.PSObject.Properties['version']) { $Version = ([string]$doc.version).Trim() } } catch { $Version = '' } } if (-not (Test-SemVer $Version)) { $loc = Get-RedirectLocation $client "https://github.com/$Repo/releases/latest" if ($loc -and ($loc -match "^https://github\.com/$([regex]::Escape($Repo))/releases/tag/(.+)$")) { $cand = ($Matches[1] -replace '^v', '') if (Test-SemVer $cand) { $Version = $cand } } } } if (-not (Test-SemVer $Version)) { Fail "could not resolve the latest version from npm or GitHub (got: '$Version'). Set HOODY_VERSION=X.Y.Z." } $Tag = "v$Version" Ok "latest is $Tag" # --- Anti-rollback (best-effort; fails open on unparseable, like sh) --- if (-not $env:HOODY_ALLOW_DOWNGRADE) { if (Get-Command hoody -ErrorAction SilentlyContinue) { $inst = '' try { $inst = ((Invoke-Native { & hoody --version 2>&1 } | Out-String) -split "`n" | Select-Object -First 1).Trim() -replace '^v', '' } catch { $inst = '' } if ((Test-SemVer $inst) -and ((Compare-SemVer $inst $Version) -gt 0)) { Fail "refusing to downgrade: installed $inst is newer than resolved $Version. Set HOODY_ALLOW_DOWNGRADE=1 to override." } } } $Rel = "https://github.com/$Repo/releases/download/$Tag" $Tmp = Join-Path ([System.IO.Path]::GetTempPath()) ("hoody-install-" + [System.IO.Path]::GetRandomFileName()) New-Item -ItemType Directory -Path $Tmp -Force | Out-Null # --- Bootstrap + pin the verifier ------------------------------------- Step "Fetching verifier" $VerifierPath = Join-Path $Tmp 'minisign.exe' Save-Https $client "$Rel/$VerifierName" $VerifierPath 'the minisign verifier' $gotV = Get-Sha256 $VerifierPath if ($gotV -cne $VerifierSha) { Fail "verifier hash mismatch — refusing to use it (expected $VerifierSha, got $gotV)." } Ok "verifier pinned" # --- Download + verify the signed manifest ---------------------------- Step "Verifying release signature" $SumsPath = Join-Path $Tmp 'SHA256SUMS' $SigPath = Join-Path $Tmp 'SHA256SUMS.minisig' Save-Https $client "$Rel/SHA256SUMS" $SumsPath 'SHA256SUMS' Save-Https $client "$Rel/SHA256SUMS.minisig" $SigPath 'SHA256SUMS.minisig (this release is not signed; refusing)' # -V -Q: verify, quiet. minisign exits nonzero on any mismatch. Native # exit codes survive Out-Null and are unaffected by the error preference. $null = Invoke-Native { & $VerifierPath -V -Q -P $PinnedPubkey -m $SumsPath -x $SigPath 2>&1 } if ($LASTEXITCODE -ne 0) { Fail "SIGNATURE VERIFICATION FAILED — SHA256SUMS is not authentic. Aborting." } # Bind the signature to THIS version via the signed trusted_comment. The # second run (no -Q) prints `Trusted comment: ` on stdout, as install.sh # parses it. Case-EXACT match; trim only the CR/LF that Out-String adds. $vout = Invoke-Native { & $VerifierPath -V -P $PinnedPubkey -m $SumsPath -x $SigPath 2>$null } | Out-String $tc = ($vout -split "`n" | Where-Object { $_ -match '^Trusted comment: ' } | ForEach-Object { $_ -replace '^Trusted comment: ', '' } | Select-Object -First 1) if (-not $tc) { Fail "could not read the signature's trusted comment." } $tc = $tc.TrimEnd([char]13, [char]10) if ($tc -cne "hoody bin version=$Version") { Fail "signature trusted_comment '$tc' does not match version $Version — refusing." } Ok "signature verified ($tc)" # --- Download + hash-check the binary --------------------------------- Step "Downloading $BinaryName" $BinPath = Join-Path $Tmp $BinaryName Save-Https $client "$Rel/$BinaryName" $BinPath $BinaryName # Require EXACTLY ONE canonical line (64-hex + separator + exact filename). # Count RAW matching lines — no dedupe — so duplicates are rejected too. # SHA256SUMS is already signature-verified; this just makes the parse # unambiguous rather than first-match. $rawMatches = @(Get-Content -LiteralPath $SumsPath | Where-Object { $_ -match "^[0-9a-fA-F]{64}\s+\*?$([regex]::Escape($BinaryName))$" }) if ($rawMatches.Count -ne 1) { Fail "$BinaryName does not have exactly one checksum line in SHA256SUMS (found $($rawMatches.Count))." } $want = (($rawMatches[0] -split '\s+')[0]).ToLowerInvariant() $got = Get-Sha256 $BinPath if ($got -cne $want) { Fail "binary hash mismatch (expected $want, got $got) — corrupt or tampered." } Ok "hash verified" # --- Install ---------------------------------------------------------- Step "Installing" $InstallDir = if ($env:HOODY_INSTALL_DIR) { $env:HOODY_INSTALL_DIR } else { Join-Path $env:USERPROFILE '.hoody\bin' } New-Item -ItemType Directory -Path $InstallDir -Force | Out-Null $Dest = Join-Path $InstallDir 'hoody.exe' if (Test-Path -LiteralPath $Dest -PathType Container) { Fail "$Dest is a directory — refusing to install over it." } # Stage in the same dir, then move over the target. A RUNNING hoody.exe # can't be deleted (so Move-Item -Force, which deletes-then-moves, fails) # but it CAN be renamed aside — so on a lock, move the old one out of the # way first, then retry, best-effort cleaning up. $Staged = Join-Path $InstallDir ('.hoody-' + [System.IO.Path]::GetRandomFileName() + '.exe') Copy-Item -LiteralPath $BinPath -Destination $Staged -Force try { Move-Item -LiteralPath $Staged -Destination $Dest -Force } catch { $old = "$Dest.old-" + [System.IO.Path]::GetRandomFileName() try { Move-Item -LiteralPath $Dest -Destination $old -Force } catch { Fail "hoody.exe is in use and could not be replaced — close it and re-run." } try { Move-Item -LiteralPath $Staged -Destination $Dest -Force } catch { # Try to restore the previous executable; report accurately whether it # succeeded — never claim it was kept if the restore also failed. $restored = $false try { Move-Item -LiteralPath $old -Destination $Dest -Force; $restored = $true } catch {} if ($restored) { Fail "could not install into $InstallDir (previous hoody.exe restored)." } else { Fail "install FAILED and the previous hoody.exe could not be restored — it is saved at: $old" } } Remove-Item -LiteralPath $old -Force -ErrorAction SilentlyContinue } $Staged = $null if (-not (Test-Path -LiteralPath $Dest -PathType Leaf)) { Fail "install verification failed — $Dest is missing after the move." } Ok "installed hoody $Version -> $Dest" # --- Next steps ------------------------------------------------------- Write-Host "" if (($env:PATH -split ';') -contains $InstallDir) { Write-Host " Run 'hoody --help' to get started." -ForegroundColor DarkGray } else { Write-Host " $InstallDir is not on your PATH. Add it (current user):" -ForegroundColor DarkGray Write-Host " [Environment]::SetEnvironmentVariable('PATH', `"$InstallDir;`$([Environment]::GetEnvironmentVariable('PATH','User'))`", 'User')" -ForegroundColor DarkGray Write-Host " Then open a new terminal." -ForegroundColor DarkGray } Write-Host "" } catch { Write-Host "" Write-Host " $($_.Exception.Message)" -ForegroundColor Red Write-Host "" } finally { if ($Staged) { Remove-Item -LiteralPath $Staged -Force -ErrorAction SilentlyContinue } if ($Tmp) { Remove-Item -Recurse -Force -LiteralPath $Tmp -ErrorAction SilentlyContinue } } } catch { # Transport/assembly construction failures land here (before the inner try). Write-Host "" Write-Host " $($_.Exception.Message)" -ForegroundColor Red Write-Host "" } finally { if ($client) { $client.Dispose() } if ($null -ne $origSpm) { try { [Net.ServicePointManager]::SecurityProtocol = $origSpm } catch {} } } }