From 9c6fe0888566f1568ddec7fb8e1bf944966f3f9e Mon Sep 17 00:00:00 2001 From: rebuildup Date: Mon, 23 Nov 2026 20:17:12 +0900 Subject: [PATCH] fix(windows): fail closed on Tailscale status and converge the User PATH (#174) - setup-tailscale.ps1 decodes `tailscale status --json` / `serve status` as UTF-8 and refuses node registration when the backend state cannot be determined, instead of treating parse failure as "not running" and re-registering an enrolled node. - verify.ps1 decodes Tailscale output the same way, accepts both the WinGet MSI and MSIX shapes of Microsoft.PowerShell 7, and checks the User PATH for the legacy .cargo\bin entry and the mise shims entry. - New platforms/windows-11/user-path.ps1 converges HKCU Path: removes the legacy rustup proxy entry by exact expanded match, guarantees the mise shims entry, backs up the raw value, and restores via -Restore. bootstrap.ps1 and converge.ps1 both invoke it; ADR-0021 gains an addendum and the README documents the new boundary. - ci.yml gains a regression step covering the fail-closed ordering, UTF-8 handling, MSIX acceptance, and user-path.ps1 plan/apply/ restore round-trip on the ephemeral runner. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .github/workflows/ci.yml | 82 ++++++++++++ bootstrap.ps1 | 10 ++ docs/adr/ADR-0021.md | 6 +- platforms/windows-11/README.md | 21 +++ platforms/windows-11/converge.ps1 | 23 ++++ platforms/windows-11/setup-tailscale.ps1 | 79 +++++++++-- platforms/windows-11/user-path.ps1 | 161 +++++++++++++++++++++++ platforms/windows-11/verify.ps1 | 109 +++++++++++++-- 8 files changed, 468 insertions(+), 23 deletions(-) create mode 100644 platforms/windows-11/user-path.ps1 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bc75ab57..34113b70 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -668,6 +668,88 @@ jobs: throw 'mise-path-ownership.ps1 must print duplicate owners before the plan-only exit.' } + - name: Validate Tailscale fail-closed and User PATH convergence + shell: pwsh + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + + # setup-tailscale.ps1 must fail closed when `tailscale status --json` + # cannot be parsed: the old code treated parse failure as "not + # running" and fell into `tailscale up --auth-key`, re-registering an + # already-enrolled node. And both scripts must decode the native JSON + # as UTF-8, because Windows PowerShell 5.1 uses the OEM code page and + # mojibake breaks ConvertFrom-Json on Japanese Windows. + $setup = Get-Content -LiteralPath ./platforms/windows-11/setup-tailscale.ps1 -Raw + foreach ($needle in 'Invoke-Utf8Native', 'Get-TailscaleStatus', 'UTF8', 'fail closed') { + if (-not $setup.Contains($needle)) { throw "setup-tailscale.ps1 is missing: $needle" } + } + $statusCall = $setup.IndexOf('$status = Get-TailscaleStatus') + $nullGuard = $setup.IndexOf('refusing to touch node registration') + $register = $setup.IndexOf("'up'") + if ($statusCall -lt 0 -or $nullGuard -lt 0 -or $register -lt 0) { + throw 'setup-tailscale.ps1 must read status through Get-TailscaleStatus and guard registration behind the fail-closed check.' + } + if (-not ($statusCall -lt $nullGuard -and $nullGuard -lt $register)) { + throw 'setup-tailscale.ps1 must throw on unknown status BEFORE reaching tailscale up.' + } + + $verify = Get-Content -LiteralPath ./platforms/windows-11/verify.ps1 -Raw + foreach ($needle in 'Invoke-NativeUtf8', 'Microsoft.PowerShell', 'user-path.ps1', 'legacy .cargo\bin') { + if (-not $verify.Contains($needle)) { throw "verify.ps1 is missing: $needle" } + } + + # user-path.ps1 edits HKCU\Environment\Path. Plan mode must be + # read-only; -Apply must back up the unexpanded value first and write + # through the registry with the original value kind preserved. + $up = './platforms/windows-11/user-path.ps1' + $tokens = $null; $parseErrors = $null + [void][System.Management.Automation.Language.Parser]::ParseFile((Resolve-Path $up).Path, [ref]$tokens, [ref]$parseErrors) + if ($parseErrors.Count -gt 0) { throw "user-path.ps1 does not parse: $($parseErrors[0].Message)" } + $upText = Get-Content -LiteralPath $up -Raw + foreach ($needle in 'param(', '[switch]$Apply', '[string]$Restore', 'HKCU', 'user-path-backup', 'DoNotExpandEnvironmentNames', '.cargo\bin', 'mise\shims') { + if (-not $upText.Contains($needle)) { throw "user-path.ps1 is missing: $needle" } + } + $backupIndex = $upText.IndexOf('user-path-backup') + $setValueIndex = $upText.IndexOf("SetValue('Path'") + if ($backupIndex -lt 0 -or $setValueIndex -lt 0 -or $setValueIndex -lt $backupIndex) { + throw 'user-path.ps1 must save the previous User PATH before writing it.' + } + + # Plan mode on the CI runner must not write. + $userKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false) + try { $before = $userKey.GetValue('Path', '', 'DoNotExpandEnvironmentNames') } finally { $userKey.Close() } + & $up *>&1 | Out-Null + if ($LASTEXITCODE -ne 0) { throw "user-path.ps1 plan mode exited $LASTEXITCODE" } + $userKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false) + try { $after = $userKey.GetValue('Path', '', 'DoNotExpandEnvironmentNames') } finally { $userKey.Close() } + if ($before -ne $after) { throw 'user-path.ps1 changed the User PATH without -Apply.' } + + # -Apply on the ephemeral runner must converge and be restorable: + # apply, confirm a second plan reports converged, restore the backup, + # confirm the original value is back. + $applyOut = (& $up -Apply *>&1 | Out-String) + if ($LASTEXITCODE -ne 0) { throw "user-path.ps1 -Apply exited $LASTEXITCODE`n$applyOut" } + $backupLine = [regex]::Match($applyOut, 'backup\s+(\S+\.txt)') + if (-not $backupLine.Success) { throw "user-path.ps1 -Apply printed no backup path`n$applyOut" } + $backupFile = $backupLine.Groups[1].Value + $converged = (& $up *>&1 | Out-String) + if ($converged -notmatch 'already converged') { throw "user-path.ps1 did not converge after -Apply`n$converged" } + & $up -Restore $backupFile *>&1 | Out-Null + if ($LASTEXITCODE -ne 0) { throw "user-path.ps1 -Restore exited $LASTEXITCODE" } + $userKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false) + try { $restored = $userKey.GetValue('Path', '', 'DoNotExpandEnvironmentNames') } finally { $userKey.Close() } + if ($restored -ne $before) { throw 'user-path.ps1 -Restore did not put the original User PATH back.' } + + # bootstrap.ps1 and converge.ps1 must both reach the same script so a + # fresh install and the hourly converge stay on one code path. + $bootstrap = Get-Content -LiteralPath ./bootstrap.ps1 -Raw + if (-not $bootstrap.Contains('user-path.ps1')) { throw 'bootstrap.ps1 must invoke user-path.ps1.' } + $converge = Get-Content -LiteralPath ./platforms/windows-11/converge.ps1 -Raw + if (-not $converge.Contains('user-path.ps1') -or -not $converge.Contains("Invoke-Step 'user-path'")) { + throw 'converge.ps1 must run user-path.ps1 as a named step.' + } + - name: Validate converge survives a step error and always reports shell: pwsh run: | diff --git a/bootstrap.ps1 b/bootstrap.ps1 index 7aa01dd5..f6dd0bc0 100644 --- a/bootstrap.ps1 +++ b/bootstrap.ps1 @@ -222,6 +222,16 @@ finally { Install-NotionMsix Install-StoreApps +# User PATH convergence (ADR-0021): drop the legacy .cargo\bin rustup proxy +# entry and guarantee the mise shims entry. HKCU only with a backup; a failure +# must not stop bootstrap — verify.ps1 reports the resulting state. +try { + & (Join-Path $applyDir 'platforms\windows-11\user-path.ps1') -Apply +} +catch { + Write-Warning "User PATH convergence failed: $($_.Exception.Message)" +} + # Rex is in public beta and its Windows server still requires tester # enrollment, so a failed install or `rex server install --user` must not stop # the rest of the machine bootstrap. platforms/windows-11/verify.ps1 reports diff --git a/docs/adr/ADR-0021.md b/docs/adr/ADR-0021.md index d508af6d..bb5446fa 100644 --- a/docs/adr/ADR-0021.md +++ b/docs/adr/ADR-0021.md @@ -83,7 +83,11 @@ orphan shim は上の「Rust CLI は mise の cargo backend で宣言する」 - mise 管理のツールは、`mise activate` された shell で mise が先頭に差し込む install dir / shim で解決される。activation が無い経路 (Scheduled Task / IDE / GUI / `pwsh -NoProfile`) では、registry PATH 上の同名 binary が勝つ。 - registry (User/Machine) PATH には mise shim dir だけを mise 由来の最小集合として置く。`%USERPROFILE%\.cargoin` のような mise の data dir 外の Rust home は registry PATH に置かない。 -- 同名の重複 (Program Files / npm global / bun / chocolatey) は、その管理者が自己更新する GUI・vendor 経路を壊しうるため、自動では削除しない。`verify.ps1` は非 activation 経路で mise 外に解決されるものを WARN として列挙する。 +- 同名の重複 (Program Files / npm global / bun / chocolatey) は、その管理者が自己更新する GUI・vendor 経路を壊しうるため、自動では削除しない。`verify.ps1` は Tool ownership で非 activation 経路の mise 外解決を FAIL として報告し、`mise-path-ownership.ps1` が Machine PATH の冗長 entry を除去する。 + +## Addendum (#174, 2026-11-23): User PATH の収束は user-path.ps1 が担う + +「`%USERPROFILE%\.cargo\bin` は User PATH から外す」の実施手段として `platforms/windows-11/user-path.ps1` を追加した。HKCU の User PATH だけを対象に、展開後の完全一致で legacy `.cargo\bin` entry を除去し、`%LOCALAPPDATA%\mise\shims` の存在を保証する。既定は plan のみで、`-Apply` は書き込み前に生値を state dir へ backup し、`-Restore` で復元できる。`bootstrap.ps1` と `converge.ps1` の双方から呼ばれ、`verify.ps1` は未収束を FAIL として報告する。 ## Consequences diff --git a/platforms/windows-11/README.md b/platforms/windows-11/README.md index da7d57cd..0fb29f93 100644 --- a/platforms/windows-11/README.md +++ b/platforms/windows-11/README.md @@ -131,6 +131,8 @@ pwsh -NoProfile -File platforms/windows-11/powershell-path.ps1 -Apply # 管理 並び順だけを変更し、PATH entry も PowerShell 本体も削除しない。変更前の PATH は `%LOCALAPPDATA%\pc-setup` に保存する。 +`winget:Microsoft.PowerShell` は MSI と MSIX のどちらの package も同じ正本として導入されうる。MSIX の場合 `pwsh` は `%LOCALAPPDATA%\Microsoft\WindowsApps\Microsoft.PowerShell__x64__\pwsh.exe` の per-user 実行エイリアスに解決される。`verify.ps1` は MSI path・MSIX `InstallLocation`・実行エイリアスのいずれにも一致すれば正本として受理する。 + ### Herdr 実機の Herdr は GitHub backend (`github:herdrdev/herdr`、aqua registry より新しい)。Windows だけこの宣言を `mise.global.toml` に置き、Linux/macOS は従来の registry entry のまま。`mise.global.lock` には Windows の GitHub backend entry を追加している。 @@ -180,6 +182,10 @@ infisical login --domain=https://secrets.rebuildup.dev setup script は Infisical から OAuth secret を runtime injectionし、未接続の host だけを persistent / preauthorized node として登録する。既に Tailscale backend が `Running` の host は既存 node identity を維持し、再登録しない。 +`tailscale status --json` の出力は UTF-8 で decode する。Windows PowerShell 5.1 が console の OEM code page で decode すると、日本語 Windows では Health 文字列が文字化けして `ConvertFrom-Json` が失敗するため、status / serve の呼び出しは一時的に UTF-8 へ切り替えて実行する。 + +status が取得・parse できない場合は **fail closed** とし、node 登録 (`tailscale up --auth-key`) へ進まない。状態不明を「未接続」と誤認して既存 node を再登録する経路はない。`BackendState` が判明して `Running` 以外 (`NeedsLogin` / `Stopped` など) の場合だけ登録処理へ進む。 + その後 Tailscale Serve を idempotent に収束させるため、WSL 側の SSH endpoint は従来どおり Windows localhost にだけ bind したままでよい。LAN interfaceへ `2222` / `2223` を直接公開しない。 詳細な authority / recovery boundary は [ADR-0011](../../docs/adr/ADR-0011.md) を参照。 @@ -306,6 +312,21 @@ pwsh -NoProfile -File platforms/windows-11/mise-path-ownership.ps1 -Restore +``` + +- 変更するのは **User PATH (HKCU) のみ**。展開後の完全一致で `.cargo\bin` entry を除去し、mise shims entry が無ければ末尾へ追加する。並び順は変えず、他の entry・ファイル・ディレクトリは触らない。 +- Machine PATH は `mise-path-ownership.ps1` の担当であり、この script は触らない。 +- 書き込み前に展開前の生値を `%LOCALAPPDATA%\pc-setup\user-path-backup\user-path-.txt` に保存する。registry の値 kind (REG_SZ / REG_EXPAND_SZ) は保持する。 +- `bootstrap.ps1` と `converge.ps1` の両方から呼ばれ、再実行は冪等。`verify.ps1` は `.cargo\bin` 残存と shims entry 欠落を FAIL として報告する。 + ### 宣言済みツールの実行確認 `verify.ps1` は `Get-Command` による**解決**だけでなく、宣言済みツールを**実際に起動**して確認する。存在確認では検出できない破損があるため。 diff --git a/platforms/windows-11/converge.ps1 b/platforms/windows-11/converge.ps1 index 04ffe2b9..0f5bb5d9 100644 --- a/platforms/windows-11/converge.ps1 +++ b/platforms/windows-11/converge.ps1 @@ -205,6 +205,28 @@ function Invoke-MiseApply { } } +# Converges the per-user PATH (ADR-0021): drops the legacy .cargo\bin rustup +# proxy entry and guarantees the mise shims entry. HKCU only, exact-match +# removal, backup before write — user-path.ps1 is idempotent by design. +function Invoke-UserPath { + if (-not $script:DeployOk) { + Add-Step 'user-path' 'skipped' 'deploy checkout not converged in this run' + return + } + $userPath = Join-Path (Join-Path (Join-Path $DeployDir 'platforms') 'windows-11') 'user-path.ps1' + if (-not (Test-Path -LiteralPath $userPath)) { + Add-Step 'user-path' 'skipped' 'no user-path.ps1 in the deploy checkout' + return + } + & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $userPath -Apply *>&1 | ForEach-Object { Write-Log ([string]$_) } + $code = $LASTEXITCODE + if ($code -eq 0) { + Add-Step 'user-path' 'ok' 'User PATH converged' + } else { + Add-Step 'user-path' 'error' ('user-path.ps1 -Apply exited ' + $code + '; see ' + $script:LogFile) + } +} + # Derived from current state, not from a previous run: dsh is pending when # `npm:@deepseek-ai/dsh` is installed on this machine but the deployed # mise.global.toml does not declare it (it exists only in an unmerged PR; ADR-0016). @@ -531,6 +553,7 @@ function Invoke-Main { Invoke-Step 'deploy-sync' { Sync-Deploy } Invoke-Step 'mise-apply' { Invoke-MiseApply } + Invoke-Step 'user-path' { Invoke-UserPath } Invoke-Step 'dsh-declaration' { Test-DshDeclaration } Invoke-Step 'dotfiles-sync' { Invoke-DotfilesSync } Invoke-Step 'devices-sync' { Sync-Devices } diff --git a/platforms/windows-11/setup-tailscale.ps1 b/platforms/windows-11/setup-tailscale.ps1 index 14556cf6..910ae827 100644 --- a/platforms/windows-11/setup-tailscale.ps1 +++ b/platforms/windows-11/setup-tailscale.ps1 @@ -40,6 +40,58 @@ function Invoke-Checked { } } +# `tailscale status --json` emits UTF-8. Windows PowerShell 5.1 on a Japanese +# (or any non-UTF-8) console decodes native output with the OEM code page, so +# the Health strings arrive as mojibake and ConvertFrom-Json fails on +# 'Path 'Health[0]''. Decode as UTF-8 for the duration of the call and restore +# the previous encoding afterwards; a failure to set it must not stop the +# script, because the parse below still fails closed on bad output. +function Invoke-Utf8Native { + param( + [Parameter(Mandatory)][string]$Command, + [Parameter(Mandatory)][string[]]$Arguments + ) + + $previousEncoding = $null + try { + $previousEncoding = [Console]::OutputEncoding + [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 + } + catch { } + + try { + $output = @(& $Command @Arguments 2>$null) + $exitCode = $LASTEXITCODE + } + finally { + if ($null -ne $previousEncoding) { + try { [Console]::OutputEncoding = $previousEncoding } catch { } + } + } + + return [pscustomobject]@{ Output = $output; ExitCode = $exitCode } +} + +# Returns the parsed `tailscale status --json` object, or $null when the state +# cannot be determined. Callers MUST treat $null as "unknown" and fail closed: +# an unparseable status once fell through to the `tailscale up --auth-key` +# path and re-registered a node that was already enrolled. +function Get-TailscaleStatus { + param([Parameter(Mandatory)]$TailscaleCommand) + + $result = Invoke-Utf8Native -Command $TailscaleCommand -Arguments @('status', '--json') + if ($result.ExitCode -ne 0 -or $result.Output.Count -eq 0) { + return $null + } + + try { + return (($result.Output -join [Environment]::NewLine) | ConvertFrom-Json) + } + catch { + return $null + } +} + if ([System.Environment]::OSVersion.Platform -ne [System.PlatformID]::Win32NT) { throw 'This setup targets Windows.' } @@ -107,18 +159,18 @@ if ([string]::IsNullOrWhiteSpace($oauthSecret)) { throw "Required Infisical secret is not injected: $secretName" } -$status = $null -$statusOutput = @(& $tailscale status --json 2>$null) -if ($LASTEXITCODE -eq 0 -and $statusOutput.Count -gt 0) { - try { - $status = ($statusOutput -join [Environment]::NewLine) | ConvertFrom-Json - } - catch { - $status = $null - } +$status = Get-TailscaleStatus -TailscaleCommand $tailscale + +if ($null -eq $status -or $null -eq $status.BackendState) { + # Fail closed: the backend state is unknown, so this script cannot tell a + # fresh machine (NeedsLogin) from an already-enrolled node whose status + # output failed to decode. Re-registering here once replaced a healthy + # node identity; refuse instead and let the operator re-run once the + # status command works. + throw 'tailscale status --json is unavailable or unparseable; refusing to touch node registration (fail closed). Re-run after Tailscale is responsive.' } -if (-not $status -or $status.BackendState -ne 'Running') { +if ($status.BackendState -ne 'Running') { Write-Host 'Registering Windows host with Tailscale' $authKey = "${oauthSecret}?$($config.Tailscale.AuthKeyParameters)" try { @@ -147,9 +199,10 @@ foreach ($mapping in $config.Tailscale.Serve) { ) -Description "Tailscale Serve $($mapping.ListenPort)" } -$serveStatus = @(& $tailscale serve status 2>$null) -join [Environment]::NewLine -if ($LASTEXITCODE -ne 0) { - throw "Tailscale Serve status failed with exit code $LASTEXITCODE" +$serveResult = Invoke-Utf8Native -Command $tailscale -Arguments @('serve', 'status') +$serveStatus = ($serveResult.Output -join [Environment]::NewLine) +if ($serveResult.ExitCode -ne 0) { + throw "Tailscale Serve status failed with exit code $($serveResult.ExitCode)" } foreach ($mapping in $config.Tailscale.Serve) { diff --git a/platforms/windows-11/user-path.ps1 b/platforms/windows-11/user-path.ps1 new file mode 100644 index 00000000..c098d9a8 --- /dev/null +++ b/platforms/windows-11/user-path.ps1 @@ -0,0 +1,161 @@ +# Converges the per-user PATH for the mise-managed Windows baseline. +# +# user-path.ps1 plan: report what would change, change nothing +# user-path.ps1 -Apply write the User PATH (no elevation needed) +# user-path.ps1 -Restore put a saved User PATH back +# +# Why this exists +# ADR-0021 makes mise the single owner of Rust on Windows: rustup's home and +# Cargo home live under the mise data dir, and the legacy +# %USERPROFILE%\.cargo\bin entry must not stay on the registry User PATH — +# on a real machine it sat at the head of User PATH and resolved rustc/cargo +# to the legacy rustup proxies in shells that do not activate mise. mise's +# own shims entry (%LOCALAPPDATA%\mise\shims) is the only mise-sourced entry +# the registry PATH is supposed to carry. +# +# What it changes +# Only the *User* PATH (HKCU), and only by exact expanded-path match: +# - removes every entry that expands to \.cargo\bin +# - appends %LOCALAPPDATA%\mise\shims when it is absent +# Nothing is reordered, no other entry is touched, and no file or +# directory is deleted. Removing the PATH entry leaves the legacy +# directory in place; the proxies simply stop winning resolution. +# +# Safety +# The unexpanded User PATH is saved to +# \user-path-backup\user-path-.txt before any write, +# and -Restore reads exactly that file back. +[CmdletBinding()] +param( + [switch]$Apply, + [string]$Restore, + [string]$StateDir = '' +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +. (Join-Path $PSScriptRoot 'app-detection.ps1') + +$userKeyPath = 'HKCU:\Environment' + +# Legacy Rust proxy home. ADR-0021 keeps the directory itself (inert once +# RUSTUP_HOME/CARGO_HOME point into the mise data dir); only its PATH +# presence is the defect. +$legacyCargoBin = Join-Path $env:USERPROFILE '.cargo\bin' + +$miseShimEntry = '%LOCALAPPDATA%\mise\shims' + +function Split-PathValue { + param([string]$Value) + # Same rule as mise-path-ownership.ps1: empty entries are not meaningful + # and are never introduced. The comma operator keeps an empty result an + # empty array instead of $null. + return , @($Value -split ';' | Where-Object { $_ -and $_.Trim() }) +} + +function Test-LegacyCargoEntry { + param([Parameter(Mandatory)][string]$Entry) + $expanded = [Environment]::ExpandEnvironmentVariables($Entry).Trim().TrimEnd('\') + return ($expanded.Equals($legacyCargoBin.TrimEnd('\'), [StringComparison]::OrdinalIgnoreCase)) +} + +function Test-MiseShimEntry { + param([Parameter(Mandatory)][string]$Entry) + $expanded = [Environment]::ExpandEnvironmentVariables($Entry).Trim().TrimEnd('\') + $expected = [Environment]::ExpandEnvironmentVariables($miseShimEntry).TrimEnd('\') + return ($expanded.Equals($expected, [StringComparison]::OrdinalIgnoreCase)) +} + +if (-not $StateDir) { + $StateDir = Join-Path (Get-PcSetupStateDir) 'user-path-backup' +} + +function Get-UserPathRaw { + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false) + try { + $value = $key.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) + $kind = $key.GetValueKind('Path') + if ($kind -eq [Microsoft.Win32.RegistryValueKind]::Unknown) { + # PATH normally exists as REG_EXPAND_SZ; a missing value kind means + # the value itself is absent, so write it back expandable. + $kind = [Microsoft.Win32.RegistryValueKind]::ExpandString + } + } + finally { $key.Close() } + return [pscustomobject]@{ Value = $value; Kind = $kind } +} + +function Set-UserPathRaw { + param([string]$Value, [Microsoft.Win32.RegistryValueKind]$Kind) + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true) + try { $key.SetValue('Path', $Value, $Kind) } finally { $key.Close() } +} + +if ($Restore) { + if (-not (Test-Path -LiteralPath $Restore)) { throw "restore file not found: $Restore" } + $saved = (Get-Content -LiteralPath $Restore -Raw).TrimEnd("`r", "`n") + $current = Get-UserPathRaw + New-Item -ItemType Directory -Force -Path $StateDir | Out-Null + $pre = Join-Path $StateDir ("user-path-{0}.txt" -f (Get-Date -Format 'yyyyMMdd-HHmmss')) + Set-Content -LiteralPath $pre -Value $current.Value -Encoding utf8 -NoNewline + Set-UserPathRaw -Value $saved -Kind $current.Kind + Write-Host "restored User PATH from $Restore" + Write-Host "previous value saved to $pre" + exit 0 +} + +$current = Get-UserPathRaw +$entries = Split-PathValue -Value $current.Value +$removals = @($entries | Where-Object { Test-LegacyCargoEntry -Entry $_ }) +$shimPresent = @($entries | Where-Object { Test-MiseShimEntry -Entry $_ }).Count -gt 0 + +Write-Host "User PATH entries: $($entries.Count)" +foreach ($entry in $removals) { + Write-Host (" remove {0} (expands to {1}; legacy rustup proxy home, ADR-0021)" -f $entry, $legacyCargoBin) +} +if ($removals.Count -eq 0) { + Write-Host ' (no legacy .cargo\bin entry)' +} +if ($shimPresent) { + Write-Host " keep $miseShimEntry (already present)" +} +else { + Write-Host " add $miseShimEntry (mise shims; appended, order of existing entries unchanged)" +} + +if (-not $Apply) { + $changes = $removals.Count + $(if ($shimPresent) { 0 } else { 1 }) + if ($changes -eq 0) { + Write-Host 'ok User PATH already converged' + } + else { + Write-Host "plan only; re-run with -Apply to change $changes entr$(if ($changes -eq 1) { 'y' } else { 'ies' })." + } + exit 0 +} + +$kept = @($entries | Where-Object { -not (Test-LegacyCargoEntry -Entry $_) }) +if (-not $shimPresent) { $kept += $miseShimEntry } +$newValue = ($kept -join ';') + +if ($newValue -eq $current.Value) { + Write-Host 'ok User PATH already converged' + exit 0 +} + +New-Item -ItemType Directory -Force -Path $StateDir | Out-Null +$backup = Join-Path $StateDir ("user-path-{0}.txt" -f (Get-Date -Format 'yyyyMMdd-HHmmss')) +Set-Content -LiteralPath $backup -Value $current.Value -Encoding utf8 -NoNewline +Write-Host "backup $backup" +Write-Host "restore pwsh -NoProfile -File $PSCommandPath -Restore `"$backup`"" + +Set-UserPathRaw -Value $newValue -Kind $current.Kind +# Broadcast the change so new processes pick it up; existing shells keep +# their snapshot (same rule as mise-path-ownership.ps1). +[Environment]::SetEnvironmentVariable('PC_SETUP_PATH_TOUCH', '1', 'User') +[Environment]::SetEnvironmentVariable('PC_SETUP_PATH_TOUCH', $null, 'User') + +Write-Host ('applied; removed {0} entr{1}, mise shims {2}. Open a new shell.' -f ` + $removals.Count, $(if ($removals.Count -eq 1) { 'y' } else { 'ies' }), ` + $(if ($shimPresent) { 'already present' } else { 'added' })) diff --git a/platforms/windows-11/verify.ps1 b/platforms/windows-11/verify.ps1 index 5dc8db3b..d042aeea 100644 --- a/platforms/windows-11/verify.ps1 +++ b/platforms/windows-11/verify.ps1 @@ -60,6 +60,36 @@ function Resolve-TailscaleCommand { return $null } +# `tailscale status --json` is UTF-8. Windows PowerShell 5.1 decodes native +# output with the console OEM code page, so on a Japanese Windows the Health +# strings arrive as mojibake and ConvertFrom-Json fails even though the JSON +# is valid. Decode as UTF-8 for the call and restore the previous encoding. +function Invoke-NativeUtf8 { + param( + [Parameter(Mandatory)]$Command, + [Parameter(Mandatory)][string[]]$Arguments + ) + + $previousEncoding = $null + try { + $previousEncoding = [Console]::OutputEncoding + [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 + } + catch { } + + try { + $output = @(& $Command @Arguments 2>$null) + $exitCode = $LASTEXITCODE + } + finally { + if ($null -ne $previousEncoding) { + try { [Console]::OutputEncoding = $previousEncoding } catch { } + } + } + + return [pscustomobject]@{ Output = $output; ExitCode = $exitCode } +} + if ([System.Environment]::OSVersion.Platform -ne [System.PlatformID]::Win32NT) { throw 'This verification targets Windows.' } Write-Host "pc-setup Windows 11 verification`n" @@ -276,14 +306,42 @@ else { Write-Host "`nPowerShell (WinGet-managed Microsoft.PowerShell is canonical)" $pwshCommand = Get-Command pwsh -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 $pwshX64 = Join-Path $env:ProgramFiles 'PowerShell\7\pwsh.exe' -if (-not (Test-Path -LiteralPath $pwshX64)) { - Write-Fail "PowerShell 7 x64 not found at $pwshX64" +# winget:Microsoft.PowerShell installs either the MSI (Program Files) or the +# MSIX package; both are the same canonical PowerShell 7. The MSIX resolves +# through the per-user app execution alias +# (%LOCALAPPDATA%\Microsoft\WindowsApps\Microsoft.PowerShell__x64__\pwsh.exe) +# and its InstallLocation under WindowsApps, so accept every shape the package +# can produce instead of requiring the MSI path only. +$pwshCanonicalPaths = New-Object System.Collections.Generic.List[string] +if (Test-Path -LiteralPath $pwshX64) { $pwshCanonicalPaths.Add($pwshX64) } +foreach ($pwshPackage in @(Get-AppxPackage -Name 'Microsoft.PowerShell' -ErrorAction SilentlyContinue)) { + if ($pwshPackage.InstallLocation) { + $candidate = Join-Path $pwshPackage.InstallLocation 'pwsh.exe' + if (Test-Path -LiteralPath $candidate) { $pwshCanonicalPaths.Add($candidate) } + } } -elseif ($pwshCommand -and ($pwshCommand.Source -ne $pwshX64)) { - Write-WarnLocal "pwsh resolves to $($pwshCommand.Source), not the x64 install. Nothing was removed; run platforms/windows-11/powershell-path.ps1 (plan) and -Apply from an elevated shell, or call $pwshX64 explicitly." +$pwshResolved = if ($pwshCommand) { [string]$pwshCommand.Source } else { $null } +$pwshIsCanonical = $false +if ($pwshResolved) { + foreach ($candidate in $pwshCanonicalPaths) { + if ($pwshResolved.Equals($candidate, [StringComparison]::OrdinalIgnoreCase)) { $pwshIsCanonical = $true; break } + } + if (-not $pwshIsCanonical -and $pwshResolved -match '\\Microsoft\.PowerShell_[^\\]+\\pwsh\.exe$') { + # Per-user execution-alias path of an installed MSIX package. + $pwshIsCanonical = $true + } +} +if ($pwshCanonicalPaths.Count -eq 0) { + Write-Fail "PowerShell 7 not found (neither the MSI at $pwshX64 nor a Microsoft.PowerShell MSIX package)" +} +elseif (-not $pwshResolved) { + Write-Fail 'pwsh does not resolve on PATH' +} +elseif (-not $pwshIsCanonical) { + Write-WarnLocal "pwsh resolves to $pwshResolved, not a canonical PowerShell 7 install ($($pwshCanonicalPaths -join ', ')). Nothing was removed; run platforms/windows-11/powershell-path.ps1 (plan) and -Apply from an elevated shell, or call a canonical pwsh.exe explicitly." } else { - Write-Ok "pwsh -> $pwshX64" + Write-Ok "pwsh -> $pwshResolved" } Write-Host "`nRust (mise manages Rust on Windows; rustup runs underneath)" @@ -332,6 +390,37 @@ else { } } +Write-Host "`nUser PATH (ADR-0021: mise shims only, no legacy Rust proxy home)" +# Read the unexpanded registry value so %USERPROFILE% / %LOCALAPPDATA% style +# entries compare correctly; [Environment]::GetEnvironmentVariable('Path','User') +# would already be expanded and could hide a literal-vs-expanded difference. +$userPathKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false) +try { + $userPathValue = $userPathKey.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) +} +finally { $userPathKey.Close() } +$userPathEntries = @($userPathValue -split ';' | Where-Object { $_ -and $_.Trim() }) +$legacyCargoBin = (Join-Path $env:USERPROFILE '.cargo\bin').TrimEnd('\') +$legacyEntries = @($userPathEntries | Where-Object { + ([Environment]::ExpandEnvironmentVariables($_).Trim().TrimEnd('\')) -ieq $legacyCargoBin +}) +$miseShimExpected = [Environment]::ExpandEnvironmentVariables('%LOCALAPPDATA%\mise\shims').TrimEnd('\') +$shimEntries = @($userPathEntries | Where-Object { + ([Environment]::ExpandEnvironmentVariables($_).Trim().TrimEnd('\')) -ieq $miseShimExpected +}) +if ($legacyEntries.Count -gt 0) { + Write-Fail "User PATH still resolves rustc/cargo through the legacy rustup proxy home: $($legacyEntries -join ', '); run platforms/windows-11/user-path.ps1 -Apply" +} +else { + Write-Ok 'User PATH has no legacy .cargo\bin entry' +} +if ($shimEntries.Count -gt 0) { + Write-Ok "User PATH carries the mise shims entry ($($shimEntries -join ', '))" +} +else { + Write-Fail "User PATH has no mise shims entry ($miseShimExpected); run platforms/windows-11/user-path.ps1 -Apply" +} + Write-Host "`nTailscale / WSL SSH" $tailscaleConfig = Import-PowerShellDataFile -LiteralPath (Join-Path $ScriptDir 'tailscale.psd1') $tailscale = Resolve-TailscaleCommand @@ -342,8 +431,9 @@ else { Write-Ok 'Tailscale command available' $tailscaleVerdict = 'manual' - $statusOutput = @(& $tailscale status --json 2>$null) - if ($LASTEXITCODE -ne 0 -or $statusOutput.Count -eq 0) { + $statusResult = Invoke-NativeUtf8 -Command $tailscale -Arguments @('status', '--json') + $statusOutput = $statusResult.Output + if ($statusResult.ExitCode -ne 0 -or $statusOutput.Count -eq 0) { Write-Fail 'Tailscale status unavailable' } else { @@ -364,8 +454,9 @@ else { } } - $serveStatus = @(& $tailscale serve status 2>$null) -join [Environment]::NewLine - if ($LASTEXITCODE -ne 0) { + $serveResult = Invoke-NativeUtf8 -Command $tailscale -Arguments @('serve', 'status') + $serveStatus = ($serveResult.Output -join [Environment]::NewLine) + if ($serveResult.ExitCode -ne 0) { if ($tailscaleVerdict -eq 'ok') { Write-Fail 'Tailscale Serve status unavailable' } else { Write-WarnLocal 'Tailscale Serve status unavailable (backend is not Running; pending manual step)' } } else {