+<#
+ setup-windows-no-uac.ps1
+ Non-elevated portion of the Windows provisioning. Invoked by setup-windows.bat
+ after its winget installs, or run directly from an ordinary (NOT elevated)
+ prompt:
+
+ powershell -NoProfile -ExecutionPolicy Bypass -File .\setup-windows-no-uac.ps1
+
+ Run it non-elevated on purpose. Every step here writes per-user state - the
+ HKCU PATH and the global .gitconfig under $env:USERPROFILE - so running it
+ elevated would configure the *administrator's* profile instead of yours.
+
+ What this installs / configures:
+ - WinMerge on the user PATH
+ - BinSkim (binary hardening analyzer) in %LOCALAPPDATA%\Programs\BinSkim,
+ on the user PATH
+ - Global git identity, and core.sshCommand pointed at the Windows OpenSSH
+ client so git shares the Windows ssh-agent
+
+ FILL IN $GitUserName / $GitUserEmail below before the first run.
+
+ Steps are independent: one failing warns and the rest still run. The exit code
+ is 1 if any step failed, 0 otherwise.
+#>
+
+[CmdletBinding()]
+param(
+ # Skip individual steps. Note that `powershell -File` cannot pass more than
+ # one value to an array parameter (neither comma- nor space-separated), so
+ # for several, dot-call the script or use -Command:
+ # .\setup-windows-no-uac.ps1 -Skip BinSkim,GitConfig
+ # powershell -File .\setup-windows-no-uac.ps1 -Skip BinSkim
+ [ValidateSet('WinMerge', 'BinSkim', 'GitConfig')]
+ [string[]] $Skip = @()
+)
+
+$ErrorActionPreference = 'Stop'
+
+# --- Global git identity: FILL THESE IN BEFORE RUNNING ---
+# Left empty, Set-GlobalGitConfig skips the identity and says so, rather than
+# stamping a placeholder onto your commits. Leaving them empty is a legitimate
+# choice - it keeps your identity per-repository. core.sshCommand is set either
+# way, so the ssh side works regardless.
+$GitUserName = '' # e.g. 'Ada Lovelace'
+$GitUserEmail = '' # e.g. 'ada@example.com'
+
+# BinSkim's win-x64 build, from the NuGet flat container.
+$BinSkimPackage = 'microsoft.codeanalysis.binskim'
+$BinSkimDir = Join-Path $env:LOCALAPPDATA 'Programs\BinSkim'
+
+function Write-Step([string]$Msg) {
+ Write-Host "`n==> $Msg" -ForegroundColor Cyan
+}
+
+function Add-ToUserPath([string]$Dir) {
+ # HKCU PATH, not the process PATH: this must outlive the script. Idempotent,
+ # and re-applied on every run so an entry lost to an unrelated PATH edit is
+ # repaired without re-doing the install that put it there.
+ $user = [Environment]::GetEnvironmentVariable('Path', 'User')
+ if (-not $user) { $user = '' }
+ if (($user -split ';') -contains $Dir) {
+ Write-Host " $Dir already in user PATH."
+ return
+ }
+ $new = if ($user.Trim()) { $user.TrimEnd(';') + ';' + $Dir } else { $Dir }
+ [Environment]::SetEnvironmentVariable('Path', $new, 'User')
+ Write-Host " Added $Dir to user PATH (restart your shell to pick it up)."
+}
+
+function Add-WinMergeToUserPath {
+ Write-Step 'WinMerge on the user PATH'
+ $candidates = @(
+ (Join-Path $env:ProgramFiles 'WinMerge'),
+ (Join-Path ${env:ProgramFiles(x86)} 'WinMerge'),
+ (Join-Path $env:LOCALAPPDATA 'Programs\WinMerge')
+ )
+ $dir = $candidates |
+ Where-Object { Test-Path (Join-Path $_ 'WinMergeU.exe') } |
+ Select-Object -First 1
+ if (-not $dir) {
+ Write-Warning 'WinMerge not found; user PATH unchanged.'
+ return
+ }
+ Add-ToUserPath $dir
+}
+
+function Install-BinSkim {
+ # BinSkim checks the exact mitigations the native project enables in
+ # CMakeLists.txt (CFG/XFG, CET, ASLR/HighEntropyVA, DEP, /GS, stack cookies,
+ # DEPENDENTLOADFLAG, ...). The NuGet package ships a self-contained win-x64
+ # build, so this needs no .NET SDK/runtime: the .nupkg is a zip - extract the
+ # win-x64 tool folder and put it on the PATH. After restarting the shell:
+ # binskim analyze path\to\your.exe
+ #
+ # VERSION CHECK FIRST. The .nupkg is a large download (well over 100 MB), so
+ # ask NuGet what the newest stable version is BEFORE fetching anything, and
+ # skip the download entirely when the installed copy already matches.
+ # Re-provisioning an up-to-date box should not pay for it.
+ #
+ # The installed version is recorded in nupkg-version.txt next to the tool.
+ # For a copy installed before that marker existed, fall back to BinSkim.exe's
+ # own ProductVersion; either way the marker is (re)written once we know the
+ # version, so the fallback runs at most once per install. The
+ # flat-container URL pins the exact version we checked,
+ # unlike the v2 /package/<id> endpoint, which just redirects to whatever is
+ # newest at the moment of the request.
+ Write-Step 'BinSkim'
+ [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
+
+ $exe = Join-Path $BinSkimDir 'BinSkim.exe'
+ $marker = Join-Path $BinSkimDir 'nupkg-version.txt'
+
+ $have = $null
+ if (Test-Path $exe) {
+ if (Test-Path $marker) {
+ $have = (Get-Content $marker -Raw).Trim()
+ } else {
+ $pv = (Get-Item $exe).VersionInfo.ProductVersion
+ # NuGet versions carry no build metadata; ProductVersion may ("1.2.3+sha").
+ if ($pv) { $have = $pv.Split('+')[0].Trim() }
+ }
+ }
+
+ $latest = $null
+ try {
+ $index = Invoke-RestMethod -UseBasicParsing `
+ -Uri "https://api.nuget.org/v3-flatcontainer/$BinSkimPackage/index.json"
+ # Versions come back oldest-first; '-' marks a prerelease.
+ $latest = $index.versions | Where-Object { $_ -notmatch '-' } | Select-Object -Last 1
+ } catch {
+ Write-Warning "BinSkim version check failed: $($_.Exception.Message)"
+ }
+
+ if (-not $latest) {
+ if (-not $have) {
+ Write-Warning 'BinSkim not installed and NuGet unreachable; skipping.'
+ return
+ }
+ Write-Host " BinSkim $have kept (could not reach NuGet to check for a newer one)."
+ } elseif ($have -and ($have -eq $latest -or $have -eq "$latest.0")) {
+ Write-Host " BinSkim $have is already the newest stable release; skipping download."
+ # Records what the ProductVersion fallback just worked out, so the next
+ # run reads the marker instead of re-deriving it.
+ Set-Content -Path $marker -Value $latest -Encoding ascii
+ } else {
+ if ($have) {
+ Write-Host " BinSkim $have -> $latest; downloading."
+ } else {
+ Write-Host " BinSkim $latest; downloading."
+ }
+ $tmp = Join-Path $env:TEMP ('binskim_' + [guid]::NewGuid().ToString('N'))
+ New-Item -ItemType Directory -Force -Path $tmp | Out-Null
+ try {
+ $zip = Join-Path $tmp 'binskim.zip'
+ Invoke-WebRequest -UseBasicParsing -OutFile $zip `
+ -Uri "https://api.nuget.org/v3-flatcontainer/$BinSkimPackage/$latest/$BinSkimPackage.$latest.nupkg"
+ Expand-Archive -Path $zip -DestinationPath $tmp -Force
+
+ $src = Get-ChildItem -Path $tmp -Recurse -Filter 'BinSkim.exe' |
+ Where-Object { $_.FullName -match 'win-x64' } |
+ Sort-Object FullName | Select-Object -Last 1
+ if (-not $src) { throw 'BinSkim.exe (win-x64) not found in package.' }
+
+ # Replace wholesale rather than merging over the old tree, so files
+ # dropped between releases don't linger.
+ if (Test-Path $BinSkimDir) { Remove-Item -Recurse -Force $BinSkimDir }
+ New-Item -ItemType Directory -Force -Path $BinSkimDir | Out-Null
+ Copy-Item -Path (Join-Path $src.Directory.FullName '*') `
+ -Destination $BinSkimDir -Recurse -Force
+ # Written last: the marker must only claim a version that fully landed.
+ Set-Content -Path $marker -Value $latest -Encoding ascii
+ Write-Host " BinSkim $latest installed to $BinSkimDir"
+ } finally {
+ Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue
+ }
+ }
+
+ Add-ToUserPath $BinSkimDir
+}
+
+function Get-GitPath {
+ # winget installed Git moments ago, but this process inherited its PATH
+ # before that happened, so Get-Command can miss it on a first run. Prefer a
+ # git already on PATH, then the usual install roots.
+ $onPath = Get-Command git.exe -ErrorAction SilentlyContinue
+ if ($onPath) { return $onPath.Source }
+ $roots = @(
+ (Join-Path $env:ProgramFiles 'Git\cmd\git.exe'),
+ (Join-Path ${env:ProgramFiles(x86)} 'Git\cmd\git.exe'),
+ (Join-Path $env:LOCALAPPDATA 'Programs\Git\cmd\git.exe')
+ )
+ return $roots | Where-Object { Test-Path $_ } | Select-Object -First 1
+}
+
+function Set-GlobalGitConfig {
+ Write-Step 'Global git config'
+ $git = Get-GitPath
+ if (-not $git) {
+ Write-Warning 'git.exe not found; skipping global git config.'
+ return
+ }
+ Write-Host " using $git"
+
+ if (-not $GitUserName -or -not $GitUserEmail) {
+ Write-Host ' Identity not configured; leaving user.name / user.email alone.' -ForegroundColor Yellow
+ Write-Host ' Fill in $GitUserName / $GitUserEmail at the top of this script, or set' -ForegroundColor Yellow
+ Write-Host ' your identity per-repository.' -ForegroundColor Yellow
+ } else {
+ & $git config --global user.name $GitUserName
+ & $git config --global user.email $GitUserEmail
+ Write-Host " identity: $GitUserName <$GitUserEmail>"
+ }
+
+ # --- Make git use the Windows OpenSSH client ---
+ # Git for Windows ships its own MSYS2 ssh.exe and prefers it, and that client
+ # cannot reach the Windows ssh-agent service that the elevated half enables:
+ # Win32-OpenSSH publishes the agent on a named pipe the MSYS2 build does not
+ # speak. So keys added with `ssh-add` from PowerShell stay invisible to git,
+ # and a push falls back to hunting for a key file and prompting for its
+ # passphrase. Pointing core.sshCommand at the in-box ssh.exe gives git the
+ # same client, the same agent, and the same %USERPROFILE%\.ssh\config as
+ # `ssh` from an ordinary shell.
+ $winSsh = Join-Path $env:WINDIR 'System32\OpenSSH\ssh.exe'
+ if (-not (Test-Path $winSsh)) {
+ Write-Warning "No Windows OpenSSH client at $winSsh. Add the 'OpenSSH Client' optional feature and re-run; until then git uses its own bundled ssh.exe, which cannot see keys held by the Windows ssh-agent service."
+ return
+ }
+ # Forward slashes on purpose: git parses core.sshCommand with shell quoting
+ # rules, in which a backslash is an escape character.
+ $value = $winSsh -replace '\\', '/'
+ & $git config --global core.sshCommand $value
+ Write-Host " core.sshCommand: $value"
+}
+
+# ---------------------------------------------------------------------------
+# Main
+# ---------------------------------------------------------------------------
+if (([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(
+ [Security.Principal.WindowsBuiltInRole]::Administrator)) {
+ Write-Warning 'Running elevated. The user PATH and .gitconfig changes below will apply to the administrator profile, not yours.'
+}
+
+$steps = [ordered]@{
+ WinMerge = { Add-WinMergeToUserPath }
+ BinSkim = { Install-BinSkim }
+ GitConfig = { Set-GlobalGitConfig }
+}
+
+$failed = @()
+foreach ($name in $steps.Keys) {
+ if ($Skip -contains $name) {
+ Write-Host "`n==> $name (skipped)" -ForegroundColor DarkGray
+ continue
+ }
+ try {
+ & $steps[$name]
+ } catch {
+ # One broken step must not cost the others. Collect and report at the end.
+ Write-Warning "$name failed: $($_.Exception.Message)"
+ $failed += $name
+ }
+}
+
+if ($failed) {
+ Write-Host "`n[setup-windows-no-uac] FAILED: $($failed -join ', ')" -ForegroundColor Red
+ exit 1
+}
+Write-Host "`n[setup-windows-no-uac] All steps completed." -ForegroundColor Green
+exit 0