diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index b7ea6f60b..d3392ecd3 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -276,6 +276,15 @@ jobs: run: | & ./scripts/build_verify_windows_installer.ps1 -OutputDir dist -InstallerOutput installer-output if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + # One opt-in exact-SHA FAT: genuine published alpha.4 -> alpha.5 -> + # alpha.4 rollback, always on a disposable GitHub Windows runner. + # Never executed by ordinary PR/push, never on a user's workstation. + - name: Prove two authentic historical Inno releases upgrade and roll back + if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} + shell: pwsh + run: | + & ./scripts/test_two_genuine_inno_releases_windows.ps1 + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - uses: actions/upload-artifact@v4 if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} with: diff --git a/docs/ADR_SMART_AUTO_UPDATER_20261109.md b/docs/ADR_SMART_AUTO_UPDATER_20261109.md new file mode 100644 index 000000000..ef337e146 --- /dev/null +++ b/docs/ADR_SMART_AUTO_UPDATER_20261109.md @@ -0,0 +1,69 @@ +# ArSonMix Windows Smart Auto Update — M1 design and safety contract (2026-11-09) + +## Scope and status +Implementation branch: `feature/smart-auto-updater-safe-20261109`. Windows x64 **per-user Inno-installed** ArSonMix only. No portable/Windows service, no Linux/macOS auto-install. This is not stable/hardware-qualified until exact-source Windows MSVC/Inno/real desktop tests pass. **Older installations must first receive one installer containing `ArSonMixAutoUpdate.ps1`; no code can remotely update an installed old binary without a bootstrapping updater.** + +## User workflow (no new GUI, no interruption to live mixing) +1. JUCE native launches the installed updater as an independent hidden PowerShell process after constructing the approved mixer GUI. The audio callback never opens a URL, parses JSON, reads files, waits for the network or invokes a child process. +2. The worker holds one named mutex per user, checks no more than once per six hours, and fetches official `api.github.com/repos/masarray/arsonmix/releases` metadata. The installed `BUILD_PROVENANCE.json.sourceCommit` MUST match a currently published, valid older release. No development/portable/unknown source is upgraded. +3. Strict SemVer including alpha/beta/rc ordering prevents downgrade. A stable installation does not automatically opt into prereleases. Only unique, published Windows Inno **EXE** assets with a valid immutable tag, 40-hex commit, expected exact GitHub download URL, GitHub asset digest, `INSTALLER_PROVENANCE.json` and `SHA256SUMS.txt` qualify. +4. Stage both the replacement installer and the currently published rollback installer in per-user LocalAppData; independently verify size, SHA-256, per-release checksums and provenance source commit. Limit download sizes and HTTPS redirect hosts. No network failure may break normal mixer startup or operation. Apply checks the release API once more to reject revoked releases; if offline on normal close, the update is deferred. +5. During a normal shutdown, start a second short-lived supervisor and wait briefly for the original mixer process to **exit naturally**. No updater-driven `WM_CLOSE`, `SetEvent`, force kill or automatic device arm. If a new mixer instance is open, defer instead of interrupting a new session. The new Inno `/ARSONMIXAUTOUPDATE` mode runs a read-only, exact-EXE-path `-ProbeOnly` preflight (including unreadable-process fail-close), checks the running-mixer mutex and exclusive file access, and **never signals shutdown or WM_CLOSE**. Manual installation retains its normal graceful shutdown path. +6. Run the existing per-user Inno installer silently with the explicit fail-closed automatic-update mode. Silent Inno does not autostart GUI; the updater itself starts exactly one application. The new JUCE GUI acknowledges rendering readiness with a random GUID-scoped `GUI_READY` marker, and the worker checks installed source SHA plus a still-alive process. On success clean staged binaries and retain only small metadata/status. +7. A failed version is locally blocked from repeated automatic retries. Silent setup exceeding its bounded process wait is left untouched: **no second installer, relaunch or rollback** may start while the first could still be replacing files. GUI launch exceptions become explicit health failure so the previous verified installer can be considered for rollback. If startup fails and **no new mixer is running**, recover by running the previously verified original installer; restore the previous source identity and relaunch. If the failed new GUI is still alive/hung, fail closed rather than destroying live edits. + +## Why installation on normal exit? +Automatic shutdown while a singer performs is not an acceptable live mixer contract. Silence on the meter is not proof that performance is finished. Staging while running and applying only on normal exit guarantees the updater never deliberately interrupts the monitoring path. The checker exits immediately after staging, so no resident PowerShell process occupies memory during an ongoing mix. Normal shutdown starts a second worker to apply only the previously staged update; a user who never closes the app does not receive the update. The update may relaunch the GUI after a user intentionally quits. This is a documented tradeoff, not a promise of zero disruption. + +## Integrity and trust boundary +The update trusts HTTPS to the official GitHub API, immutable release source identity and GitHub-provided asset SHA256 digests, corroborated with the release's checksum/provenance assets. This guards against stale Pages catalogs, corrupted downloads, arbitrary third-party URLs and accidental version reversal. It is **not** a replacement for Authenticode publisher signing or a separately signed update manifest; an attacker controlling the repository's release publisher may control all those metadata values. Before stable/default-on auto-updates for general users, require an approved code-signing identity and an authenticated/pinned signing key, plus credential-rotation and revocation procedures. Do not claim that the alpha preview is signed. + +## Update lifecycle, operational safety +- Mutex `Local\\ArSonMix.AutoUpdater.v1` serializes the short-lived check/apply workers; existing `SetupMutex` serializes Inno. State is atomically replaced and may record `staged`, `installing`, `health-failed`, `rolled-back` and `idle`. Failure details are in `%LOCALAPPDATA%\\ArSonMix\\Updates\\last-result.txt`. +- Fail closed on unknown installed source, invalid provenance, untrusted URL, missing/duplicate assets, download overrun/short read/SHA mismatch, ZIP-only release, offline service, current app still active or installer lock. The worker uses a below-normal process priority; Windows sign-out/shutdown does not start a fresh installation. Private `.smix`, Studio data and user VSTs are never deleted by the updater. +- This worker downloads Inno EXE directly, not a ZIP: ZIP is for the public browser download and is irrelevant to the installer orchestration path. +- Mark healthy only after a real native GUI-ready event, not merely a successful silent installer return. A device/ASIO acoustic test remains separate from this updater health marker. +- Rollback remains best effort if Windows/antivirus blocks both old and new installers. A previously published rollback installer may predate `/ARSONMIXAUTOUPDATE`; the supervisor still checks no running ArSonMix before invoking it, but exact cross-version desktop rollback race tests remain mandatory prior to stable release. A running, non-responsive GUI is left intact instead of force-killed. Never promise mathematically impossible “no crash”. +- Updater is disabled on portable packages (script absent or `portable_mode.txt`). Unsupported operating systems are never offered Windows installers. + +## Acceptance tests / release gates +- Cheap `tests/windows_installer_contract_test.mjs` ensures packaging, safe process isolation, and no forced termination. Windows `scripts/test_inno_graceful_update_windows.ps1` exercises `-PolicySelfTest` (SemVer, untrusted URL, duplicate release artifact, tampered/short/missing 2MiB staged EXE), graceful/legacy/hung upgrade fixtures, **automatic-mode refusal while the mixer is running without WM_CLOSE**, and **automatic-mode installation after normal exit**. +- Exact-head Windows MSVC compile + all relevant CTest, native startup readiness marker, real Inno update/uninstall, source identity and private Studio retention; test intermittent networks, wrong hashes, smaller/larger response, same version, downgrade, repeated launches, hung app and rollback from startup crash on Windows (not all covered by existing fixture). +- No automatic stable release until code signing/pinned publisher identity and a real end-to-end M2 rollback/health FAT with two **genuine** ArSonMix installers. Existing synthetic WinForms/Inno smoke cannot certify real ASIO audio or startup health under actual WebView2 hardware. + +## Non-goals +No second GUI, updater UI banner/card, silent audio-device remap, DSP changes, Windows service, forced termination, system-wide install, scheduled task, repeated background CI or cross-platform pretend-updater. + +## M2 self-repair and interrupted update recovery +- A published Windows installation with verifiable exeSha256 and guiExeBytes is repaired only when its executable mismatches those expected bytes. The independently hashed current-release installer is staged and reapplied after normal exit. This is a non-destructive repair of packaged program files, not a broad uninstall or deletion of private Studio/.smix, custom VST3 or unknown directories. +- An interrupted install on next startup is reconciled to previous-retained, candidate-unverified or unknown-installation using installed source SHA. The failed release is blocked from endless retries; unknown source fails closed. These states do not certify audio or WebView health. +- Corrupt updater-owned state is quarantined without touching user data. Network failure retries no more than every 20 minutes; successfully fetched release lists are cached six hours. Complete staged transactions are retained across app reopens until the normal-exit update process. +- Cleanup removes only named vendor installer/checksum/provenance files. No recursive stage deletion. Failure of a same-version repair blocks repeated attempts; it does not uninstall or erase a session. +- A mixer executable that cannot start cannot repair itself: independent, publisher-signed bootstrap/recovery remains a required future release gate. + +## Bounded automatic error recovery +- A completed Inno installer that exits nonzero but leaves the old source intact gets one more attempt on the next normal app exit, after a 30-minute cooldown. The counter persists in updater metadata; two failures block that candidate. An installer timeout, partial version replacement, failed GUI health, or revoked release does not qualify for this retry. +- Only the old installed app can be relaunched after a non-destructive installer rejection. The updater never uninstalls or resets Studio/.smix to work around device, driver or VST issues. + +## Same-version Inno repair FAT +- The Windows Inno fixture creates an isolated artificial installation, intentionally truncates only its synthetic ArSonMix.exe, reruns Inno in unattended auto-update mode, and requires the original SHA-256 executable hash and private Studio sentinel to survive. This proves vendor-program-file repair mechanics; a real JUCE/WebView + ASIO failure scenario still needs a two-version desktop test. + +## M3 standalone recovery when the main application cannot launch +- The installed Start Menu includes Repair ArSonMix. This independent action validates the source commit against a published official GitHub Release, verifies the installer source/digest/checksums and installs vendor program files in place, without deleting any private .smix, Studio or user VST. The repaired app then launches and acknowledges GUI readiness. +- Automatic updates still reject an absent EXE. Only an explicitly invoked recovery uses the two no-close flags ARSONMIXAUTOUPDATE and ARSONMIXRECOVERY. An exact-image process probe and file lock checks refuse interruption of a running mixer. +- An abandoned worker mutex may be reclaimed when the prior process crashes. Unknown installed source or absent provenance must fail closed and direct the user to the official installer. No audio callback work, OS service or scheduled task. +- Windows Inno FAT creates a synthetic missing EXE, verifies ordinary auto-update refuses it, then tests explicit recovery restoring identical SHA while retaining private session sentinels. Code-signing and actual JUCE/ASIO end-to-end recovery remain separate release requirements. + +## Exact-image install, repair and rollback health +After install/repair/rollback, success requires the installed sourceCommit, exeSha256 and guiExeBytes to agree with on-disk ArSonMix.exe bytes. GUI_READY without matching image identity is insufficient. Deterministic Windows fixture tests reject unchanged source metadata with a tampered binary. Two real published releases exist, but interactive WebView and physical ASIO audio remain separate gates. + +## Genuine two-release installer qualification +- Opt-in Windows FAT now downloads two **already-published authentic** installer assets (v0.5.0-alpha.4 / v0.5.0-alpha.5), confirms official GitHub digest, source-commit provenance and SHA256SUMS, installs alpha.4 into a disposable runner directory, upgrades to alpha.5 and rolls back to alpha.4, validating installed PE SHA and private .smix plus install-local user sentinel after every step. It is gated to explicit package_fat dispatch on temporary GitHub Windows runners; ordinary PR/branch work never downloads historical packages. This verifies historical Inno compatibility, not live WebView2-ready startup or physical ASIO sound, which remain separately qualified. + +## Rollback asset identity safety +The post-close supervisor rechecks the **previous** published release as well as the **candidate** via GitHub. The staged rollback filename, SHA256, size, tag and original source commit must all agree with current published release metadata before any installer starts. If the published rollback artifact is missing, altered or withdrawn, the update is deferred with the current mixer intact. + +## Codex review P1 fixes — release parsing and startup health +- Windows PowerShell 5.1 `Invoke-RestMethod` returns JSON arrays as an array-valued pipeline object; wrapping its result in `@(...)` nests the releases. All three REST fetch sites now assign directly so stable/pre-release discovery, standalone recovery and revocation checks iterate individual releases. +- WebView2 timeout triggers stage 3 only to dismiss the splash and show an error. The GUID-scoped GUI_READY marker now requires **stage == 2**, not the stage>=2 dismissal branch, eliminating success claims for a failed browser. +- An incomplete installer/checksum/provenance download sets `staging-retry` with empty lastCheckUtc before network transfer, preserving the 20-minute retry rather than applying the six-hour successful-check throttle. diff --git a/installer/ArSonMix.iss b/installer/ArSonMix.iss index 351c88d69..4365336e3 100644 --- a/installer/ArSonMix.iss +++ b/installer/ArSonMix.iss @@ -45,12 +45,17 @@ RestartApplications=no ; The shutdown helper is EMBEDDED TEMPORARILY in Setup, never installed. ; It handles installed legacy builds that do not implement the new event. Source: "ArSonMixUpdateShutdown.ps1"; Flags: dontcopy +; The updater runs outside JUCE, never in the realtime audio callback. +Source: "ArSonMixAutoUpdate.ps1"; DestDir: "{app}"; Flags: ignoreversion Source: "{#SourceRoot}\verified-gui.exe"; DestDir: "{app}"; DestName: "ArSonMix.exe"; Flags: ignoreversion Source: "{#SourceRoot}\BUILD_PROVENANCE.json"; DestDir: "{app}"; Flags: ignoreversion Source: "{#SourceRoot}\README.md"; DestDir: "{app}"; Flags: ignoreversion Source: "{#SourceRoot}\FactoryFX\*"; DestDir: "{app}\FactoryFX"; Flags: ignoreversion recursesubdirs createallsubdirs skipifsourcedoesntexist [Icons] Name: "{autoprograms}\ArSonMix"; Filename: "{app}\ArSonMix.exe"; WorkingDir: "{app}" +; User-facing fallback when the main EXE cannot even open. The helper +; authenticates the published current release and repairs in place. +Name: "{autoprograms}\Repair ArSonMix"; Filename: "{sys}\WindowsPowerShell\v1.0\powershell.exe"; Parameters: "-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File ""{app}\ArSonMixAutoUpdate.ps1"" -RecoveryMode"; WorkingDir: "{app}" ; Do not create a second copy of an already running mixer. Restart Manager ; preflight closes the prior verified app before [Files]; [Run] launches exactly ; one new executable only after a successful interactive install/update. @@ -94,6 +99,34 @@ begin CloseWinHandle(H); end; +{ An automatic update must never close a new live-mixing session. + Manual/interactive setup retains the existing graceful-close workflow. } +function IsArSonMixAutoUpdate: Boolean; +var + I: Integer; +begin + Result := False; + for I := 1 to ParamCount do + if CompareText(ParamStr(I), '/ARSONMIXAUTOUPDATE') = 0 then + begin + Result := True; + Exit; + end; +end; + +function IsArSonMixRecovery: Boolean; +var + I: Integer; +begin + Result := False; + for I := 1 to ParamCount do + if CompareText(ParamStr(I), '/ARSONMIXRECOVERY') = 0 then + begin + Result := True; + Exit; + end; +end; + function PrepareToInstall(var NeedsRestart: Boolean): String; var Target, HelperPath, PowerShellExe, Params: string; @@ -102,6 +135,46 @@ var begin Result := ''; Target := ExpandConstant('{app}\ArSonMix.exe'); + if IsArSonMixAutoUpdate then + begin + { Never send InstallShutdown, CloseMainWindow or WM_CLOSE in auto mode. + Exact-path ProbeOnly + locked-PE preflight is strictly fail-closed. } + if not FileExists(Target) and not IsArSonMixRecovery then + begin + Result := 'Automatic update requires an existing ArSonMix installation.'; + Exit; + end; + { The recovery flag is allowed only with automatic (no-close) mode. + An absent EXE is permitted, but the same exact-image running-process + probe and exclusive-image checks are still mandatory. } + if CheckForMutexes('Local\ArSonMix.MixerRunning.v1') then + begin + Result := 'ArSonMix is running; automatic update deferred to a later normal exit.'; + Exit; + end; + ExtractTemporaryFile('ArSonMixUpdateShutdown.ps1'); + HelperPath := ExpandConstant('{tmp}\ArSonMixUpdateShutdown.ps1'); + PowerShellExe := ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'); + Params := '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File ' + + AddQuotes(HelperPath) + ' -TargetPath ' + AddQuotes(Target) + + ' -ProbeOnly'; + ExitCode := -1; + if not Exec(PowerShellExe, Params, '', SW_HIDE, + ewWaitUntilTerminated, ExitCode) then + begin + Result := 'Unable to verify that no ArSonMix session is active. No files replaced.'; + Exit; + end; + if ExitCode <> 0 then + begin + Log('Automatic update refused: active/unknown process, probe exit=' + IntToStr(ExitCode)); + Result := 'ArSonMix session is active or cannot be verified. Automatic update deferred; no files replaced.'; + Exit; + end; + if not InstalledExeReplaceable(Target) then + Result := 'ArSonMix.exe is occupied; automatic update deferred without closing a live session.'; + Exit; + end; if not FileExists(Target) then Exit; { first install: there is no existing exe to close } diff --git a/installer/ArSonMixAutoUpdate.ps1 b/installer/ArSonMixAutoUpdate.ps1 new file mode 100644 index 000000000..4e955c33c --- /dev/null +++ b/installer/ArSonMixAutoUpdate.ps1 @@ -0,0 +1,817 @@ +# SPDX-License-Identifier: AGPL-3.0-only +# ArSonMix automatic update supervisor. Installed next to ArSonMix.exe by Inno. +# Independent of JUCE/audio callback; starts from an installed GUI only. +# Downloads while the host is active; applies ONLY after normal host exit. +param([ValidateRange(0,2147483647)][int]$OwnerProcessId=0, + [switch]$PolicySelfTest, + [switch]$ApplyStaged, + [switch]$RecoveryMode) +Set-StrictMode -Version Latest +$ErrorActionPreference='Stop' +[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12 + +$repo='masarray/arsonmix' +$api='https://api.github.com/repos/masarray/arsonmix/releases?per_page=100' +$exe=[IO.Path]::GetFullPath((Join-Path $PSScriptRoot 'ArSonMix.exe')) +$provenance=Join-Path $PSScriptRoot 'BUILD_PROVENANCE.json' +$local=$env:LOCALAPPDATA +if([string]::IsNullOrWhiteSpace($local)){exit 0} +$root=Join-Path $local 'ArSonMix\Updates' +$statePath=Join-Path $root 'state.json' +$logPath=Join-Path $root 'last-result.txt' +$mutex=$null +$locked=$false +# Network, hashing and installer orchestration must yield CPU to live ASIO. +try { [Diagnostics.Process]::GetCurrentProcess().PriorityClass = + [Diagnostics.ProcessPriorityClass]::BelowNormal } catch { } + +function Log-Result([string]$message) { + try { + [IO.Directory]::CreateDirectory($root) | Out-Null + [IO.File]::WriteAllText($logPath,([DateTime]::UtcNow.ToString('o')+' '+$message),[Text.Encoding]::UTF8) + } catch { } # Observability must never break the mixer. +} +function Fail([string]$reason) { + Log-Result ('FAIL_CLOSED '+$reason) + throw $reason +} +function Read-Json([string]$path) { + return (Get-Content -LiteralPath $path -Raw -Encoding UTF8 | ConvertFrom-Json) +} +function Write-State([object]$value) { + $temp=$statePath+'.new' + $json=ConvertTo-Json -InputObject $value -Depth 8 -Compress + [IO.File]::WriteAllText($temp,$json,[Text.Encoding]::UTF8) + if(Test-Path -LiteralPath $statePath -PathType Leaf) { + [IO.File]::Replace($temp,$statePath,$null) + } else { [IO.File]::Move($temp,$statePath) } +} +function Version-Key([string]$tag) { + $m=[regex]::Match($tag,'^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-(alpha|beta|rc)\.(0|[1-9][0-9]*))?$') + if(-not $m.Success){return $null} + try { + $base=[version]::new([int]$m.Groups[1].Value,[int]$m.Groups[2].Value,[int]$m.Groups[3].Value) + $rank=switch($m.Groups[4].Value) { 'alpha' {0} 'beta' {1} 'rc' {2} default {3} } + $n=if($m.Groups[5].Success){[int]$m.Groups[5].Value}else{0} + return [pscustomobject]@{ Tag=$tag; Base=$base; Rank=$rank; Number=$n } + } catch {return $null} +} +function Compare-Version([object]$a,[object]$b) { + $base=$a.Base.CompareTo($b.Base) + if($base -ne 0){return $base} + if($a.Rank -ne $b.Rank){return [Math]::Sign($a.Rank-$b.Rank)} + return [Math]::Sign($a.Number-$b.Number) +} +function Find-Asset([object]$release,[string]$name,[int64]$minBytes) { + $items=@($release.assets | Where-Object { + $_.name -ceq $name -and $_.state -ceq 'uploaded' -and + $_.size -is [ValueType] -and [int64]$_.size -ge $minBytes -and + [string]$_.digest -cmatch '^sha256:[a-f0-9]{64}$' -and + $_.browser_download_url -ceq ("https://github.com/$repo/releases/download/$($release.tag_name)/$name") + }) + if($items.Count -ne 1){return $null} + return $items[0] +} +function Approved-Installer([object]$release) { + if($null -eq $release -or $release.draft -or + [string]$release.target_commitish -cnotmatch '^[a-f0-9]{40}$' -or + -not (Version-Key ([string]$release.tag_name)) -or + [string]::IsNullOrWhiteSpace([string]$release.published_at)){return $null} + $tag=[string]$release.tag_name + if($null -eq (Find-Asset $release 'INSTALLER_PROVENANCE.json' 1) -or + $null -eq (Find-Asset $release 'SHA256SUMS.txt' 1)){return $null} + return (Find-Asset $release "ArSonMix-$tag-Windows-x64-Setup.exe" 2097152) +} +function Download-Verified([object]$asset,[string]$destination) { + $expectedHash=([string]$asset.digest).Substring(7) + $expectedBytes=[int64]$asset.size + if($expectedBytes -gt 209715200){Fail 'Asset exceeds 200MiB hard limit'} + if(Test-Path -LiteralPath $destination -PathType Leaf) { + $existing=Get-Item -LiteralPath $destination + if($existing.Length -eq $expectedBytes -and + (Get-FileHash -LiteralPath $destination -Algorithm SHA256).Hash.ToLowerInvariant() -ceq $expectedHash) { + return + } + Remove-Item -LiteralPath $destination -Force + } + $parent=[IO.Path]::GetDirectoryName($destination) + [IO.Directory]::CreateDirectory($parent) | Out-Null + $part=$destination+'.partial' + if(Test-Path -LiteralPath $part){Remove-Item -LiteralPath $part -Force} + $request=[Net.HttpWebRequest]::Create([string]$asset.browser_download_url) + $request.Timeout=30000 + $request.ReadWriteTimeout=30000 + $request.UserAgent='ArSonMix-SmartUpdater/1' + $request.AllowAutoRedirect=$true + $request.MaximumAutomaticRedirections=5 + $response=$null + $streamIn=$null + $streamOut=$null + try { + $response=$request.GetResponse() + $uri=$response.ResponseUri + if($uri.Scheme -cne 'https' -or + @('github.com','release-assets.githubusercontent.com','objects.githubusercontent.com') -cnotcontains $uri.DnsSafeHost) { + Fail 'Unexpected download redirect destination' + } + if($response.ContentLength -gt $expectedBytes){Fail 'Oversize release response'} + $streamIn=$response.GetResponseStream() + $streamOut=[IO.File]::Open($part,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::None) + $buffer=New-Object byte[] 65536 + [int64]$total=0 + while(($read=$streamIn.Read($buffer,0,$buffer.Length)) -gt 0) { + $total+=$read + if($total -gt $expectedBytes){Fail 'Response larger than release metadata'} + $streamOut.Write($buffer,0,$read) + } + $streamOut.Flush($true) + $streamOut.Dispose();$streamOut=$null + if($total -ne $expectedBytes){Fail 'Incomplete release download'} + $hash=(Get-FileHash -LiteralPath $part -Algorithm SHA256).Hash.ToLowerInvariant() + if($hash -cne $expectedHash){Fail 'Release SHA256 mismatch'} + [IO.File]::Move($part,$destination) + } finally { + if($null -ne $streamOut){$streamOut.Dispose()} + if($null -ne $streamIn){$streamIn.Dispose()} + if($null -ne $response){$response.Dispose()} + if(Test-Path -LiteralPath $part){Remove-Item -LiteralPath $part -Force -ErrorAction SilentlyContinue} + } +} +function Download-Release-Verified([object]$release,[object]$installer,[string]$destination) { + $tag=[string]$release.tag_name + $prefix=[IO.Path]::GetDirectoryName($destination) + $sum=Find-Asset $release 'SHA256SUMS.txt' 1 + $provenanceAsset=Find-Asset $release 'INSTALLER_PROVENANCE.json' 1 + if($null -eq $sum -or $null -eq $provenanceAsset){Fail 'Missing attested release metadata'} + # Use per-tag metadata paths; never allow the second release to reuse + # the first release's hashes, even if tags share the same base version. + $sumPath=Join-Path $prefix ('SHA256SUMS-'+$tag+'.txt') + $proofPath=Join-Path $prefix ('INSTALLER_PROVENANCE-'+$tag+'.json') + Download-Verified $sum $sumPath + Download-Verified $provenanceAsset $proofPath + $proof=Read-Json $proofPath + $hash=([string]$installer.digest).Substring(7) + if($proof.sourceCommit -cne $release.target_commitish -or + $proof.installerSha256 -cne $hash) {Fail 'Installer provenance does not match published source/digest'} + $line=$hash+' '+[string]$installer.name + $matches=@(Get-Content -LiteralPath $sumPath -Encoding ASCII | + Where-Object {$_ -ceq $line}) + if($matches.Count -ne 1){Fail 'SHA256SUMS does not attest exactly one chosen installer'} + Download-Verified $installer $destination +} +function Test-StagedAsset([string]$path,[object]$asset) { + try { + if($null -eq $asset -or $asset.digest -cnotmatch '^sha256:[a-f0-9]{64}$' -or + [long]$asset.size -lt 2097152 -or [long]$asset.size -gt 209715200 -or + -not (Test-Path -LiteralPath $path -PathType Leaf)) {return $false} + $file=Get-Item -LiteralPath $path + if($file.Length -ne [long]$asset.size){return $false} + return (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant() -ceq + ([string]$asset.digest).Substring(7) + } catch {return $false} +} + +function Should-RetryInstaller([int]$attempts,[bool]$success,[bool]$oldRemains) { + # Only a completed, nonzero-exit installer is eligible. A timeout + # throws and must not spawn a second installer while the first runs. + return (-not $success -and $oldRemains -and $attempts -ge 1 -and $attempts -lt 2) +} +function Get-InstalledImageStatus([object]$build) { + try { + $hash=[string]$build.exeSha256 + $bytes=[int64]$build.guiExeBytes + if($hash -cnotmatch '^[a-f0-9]{64}$' -or $bytes -lt 1048576 -or $bytes -gt 209715200){return 'unknown'} + if((Get-Item -LiteralPath $exe -ErrorAction Stop).Length -ne $bytes){return 'damaged'} + if((Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant() -cne $hash){return 'damaged'} + return 'healthy' + } catch {return 'unknown'} +} +function Test-InstalledRelease([string]$expectedSha) { + try { + if($expectedSha -cnotmatch '^[a-f0-9]{40}$'){return $false} + $manifest=Read-Json $provenance + return ([string]$manifest.sourceCommit -ceq $expectedSha -and + (Get-InstalledImageStatus $manifest) -ceq 'healthy') + } catch {return $false} +} +function Classify-InterruptedTransaction([string]$phase,[string]$actual,[string]$previous,[string]$candidate) { + if(@('installing','installer-failed','health-failed') -cnotcontains $phase){return ''} + if($previous -cmatch '^[a-f0-9]{40}$' -and $actual -ceq $previous){return 'previous-retained'} + if($candidate -cmatch '^[a-f0-9]{40}$' -and $actual -ceq $candidate){return 'candidate-unverified'} + return 'unknown-installation' +} + +function Test-CompleteStagedTransaction([object]$transaction) { + try { + if($transaction.phase -cne 'staged' -or + $null -eq (Version-Key ([string]$transaction.candidateTag)) -or + $null -eq (Version-Key ([string]$transaction.previousTag))){return $false} + $newName="ArSonMix-$($transaction.candidateTag)-Windows-x64-Setup.exe" + $oldName="ArSonMix-$($transaction.previousTag)-Windows-x64-Setup.exe" + if($transaction.newAsset.name -cne $newName -or + $transaction.previousAsset.name -cne $oldName){return $false} + $folder=Join-Path $root 'stage' + return ((Test-StagedAsset (Join-Path $folder $newName) $transaction.newAsset) -and + (Test-StagedAsset (Join-Path $folder $oldName) $transaction.previousAsset)) + } catch {return $false} +} + +function Clear-StagedVendorFiles([object]$transaction) { + # Never recursively delete a directory or touch private Studio/.smix. + $folder=Join-Path $root 'stage' + foreach($tag in @([string]$transaction.previousTag,[string]$transaction.candidateTag)) { + if($null -eq (Version-Key $tag)){continue} + foreach($name in @("ArSonMix-$tag-Windows-x64-Setup.exe","SHA256SUMS-$tag.txt", + "INSTALLER_PROVENANCE-$tag.json")) { + Remove-Item -LiteralPath (Join-Path $folder $name) -Force -ErrorAction SilentlyContinue + } + } +} + +function Owns-Exe([int]$processId) { + try { + $process=[Diagnostics.Process]::GetProcessById($processId) + try { + return [string]::Equals([IO.Path]::GetFullPath($process.MainModule.FileName), + $exe,[StringComparison]::OrdinalIgnoreCase) + } finally {$process.Dispose()} + } catch {return $false} +} + +function Test-NoActiveMixer { + foreach($process in [Diagnostics.Process]::GetProcessesByName('ArSonMix')) { + try { + if([string]::Equals([IO.Path]::GetFullPath($process.MainModule.FileName), + $exe,[StringComparison]::OrdinalIgnoreCase)){return $false} + } catch {return $false} # Unreadable image identity cannot authorize file replacement. + finally {$process.Dispose()} + } + return $true +} +function Show-RecoveryFailure([string]$reason) { + Log-Result ('RECOVERY_FAILED '+$reason) + try { + Add-Type -AssemblyName System.Windows.Forms -ErrorAction Stop + $nl=[Environment]::NewLine + [Windows.Forms.MessageBox]::Show( + "ArSonMix could not repair itself safely."+$nl+$nl+ + "Your Studio sessions and plugins were not deleted."+$nl+$nl+ + "Use the official ArSonMix installer if this continues."+$nl+$nl+ + "Reason: "+$reason, + 'ArSonMix - Safe Recovery', + [Windows.Forms.MessageBoxButtons]::OK, + [Windows.Forms.MessageBoxIcon]::Information) | Out-Null + } catch { } +} +function Restore-InstalledRelease([string]$sourceSha) { + if(-not (Test-NoActiveMixer)){throw 'Another ArSonMix session is still active'} + # A separately invoked recovery shortcut works when EXE is missing. + # Match current SHA against GitHub's actual published release rather + # than trusting local update state as installation authority. + $headers=@{Accept='application/vnd.github+json';'User-Agent'='ArSonMix-SmartUpdater/1'; + 'X-GitHub-Api-Version'='2022-11-28'} + $releases=Invoke-RestMethod -Uri $api -Headers $headers -TimeoutSec 25 + $sourceRelease=$null + foreach($release in $releases) { + if([string]$release.target_commitish -ceq $sourceSha -and + $null -ne (Approved-Installer $release)) { + if($null -eq $sourceRelease) { + $sourceRelease=$release + } else { + $candidateVersion=Version-Key ([string]$release.tag_name) + $chosenVersion=Version-Key ([string]$sourceRelease.tag_name) + if((Compare-Version $candidateVersion $chosenVersion) -gt 0) { + $sourceRelease=$release + } + } + } + } + if($null -eq $sourceRelease){throw 'No published, verified release matches this installation'} + $asset=Approved-Installer $sourceRelease + $destination=Join-Path (Join-Path $root 'stage') ([string]$asset.name) + Download-Release-Verified $sourceRelease $asset $destination + if(-not (Test-StagedAsset $destination $asset)){throw 'Recovery installer SHA check failed'} + if(-not (Test-NoActiveMixer)){throw 'An active mixer appeared during repair'} + # Missing-EXE mode is NOT normal auto-update and never closes a mixer. + if(-not (Run-Installer $destination -AllowMissingExeRecovery)){ + throw 'Verified recovery installer was not accepted by Windows' + } + if(-not (Test-InstalledRelease $sourceSha)){ + throw 'Repair did not restore exact authenticated EXE and source manifest' + } + if(-not (Launch-WithHealth $sourceSha)){ + throw 'Repaired application did not pass the GUI startup check' + } + Log-Result ('RECOVERY_HEALTHY '+$sourceRelease.tag_name) + # Keep verified installer cached for next recovery; no Studio cleanup. +} + +function Run-Installer([string]$file,[switch]$AllowMissingExeRecovery) { + # Inno performs exact-path process shutdown and EXE replacement preflight. + # Its silent [Run] is disabled: only this supervisor relaunches once. + if(-not (Test-Path -LiteralPath $file -PathType Leaf)){return $false} + $info=New-Object Diagnostics.ProcessStartInfo + $info.FileName=$file + $info.Arguments='/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /CURRENTUSER /NOCLOSEAPPLICATIONS /ARSONMIXAUTOUPDATE /DIR="'+$PSScriptRoot+'"' + if($AllowMissingExeRecovery){$info.Arguments+=' /ARSONMIXRECOVERY'} + $info.UseShellExecute=$false + $info.CreateNoWindow=$true + $process=[Diagnostics.Process]::Start($info) + if($null -eq $process){return $false} + try { + if(-not $process.WaitForExit(120000)){ + # This Inno process is still able to replace program files. + # Never start another GUI or a rollback installer concurrently. + Fail 'Installer is still running after timeout; no relaunch or rollback' + } + return $process.ExitCode -eq 0 + } finally {$process.Dispose()} +} +function Launch-WithHealth([string]$expectedSha) { + $token=[guid]::NewGuid().ToString('D') + $healthDir=Join-Path $root 'health' + [IO.Directory]::CreateDirectory($healthDir) | Out-Null + $marker=Join-Path $healthDir ($token+'.ready') + $info=New-Object Diagnostics.ProcessStartInfo + $info.FileName=$exe + $info.WorkingDirectory=$PSScriptRoot + $info.UseShellExecute=$false + $info.EnvironmentVariables['ARSONMIX_UPDATE_PROBE']=$token + try {$process=[Diagnostics.Process]::Start($info)} + catch {Log-Result 'UPDATED_EXE_FAILED_TO_START';return $false} + if($null -eq $process){return $false} + try { + $deadline=[DateTime]::UtcNow.AddSeconds(75) + do { + if($process.HasExited){return $false} + if(Test-Path -LiteralPath $marker -PathType Leaf) { + if((Get-Content -LiteralPath $marker -Raw).Trim() -ceq 'GUI_READY' -and + (Test-InstalledRelease $expectedSha)) { + Start-Sleep -Seconds 2 + $process.Refresh() + return (-not $process.HasExited) + } + return $false + } + Start-Sleep -Milliseconds 500 + } while([DateTime]::UtcNow -lt $deadline) + # Never terminate a hung GUI to roll back: leave it for manual recovery. + return $false + } finally { + $process.Dispose() + Remove-Item -LiteralPath $marker -Force -ErrorAction SilentlyContinue + } +} + +if($PolicySelfTest) { + # Deterministic offline policy fixtures; no host process, network, + # installer, audio device or file mutation is permitted by this mode. + $alpha=Version-Key 'v0.5.0-alpha.5' + $next=Version-Key 'v0.5.0-alpha.6' + $stable=Version-Key 'v0.5.0' + if($null -eq $alpha -or $null -ne (Version-Key 'v0.5.0-alpha.5/evil') -or + (Compare-Version $next $alpha) -le 0 -or + (Compare-Version $stable $next) -le 0 -or + (Compare-Version (Version-Key 'v1.0.0') $stable) -le 0) { + throw 'Updater SemVer policy failed' + } + $tag='v0.5.0-alpha.6' + $sha='a'*64 + $asset=[pscustomobject]@{name="ArSonMix-$tag-Windows-x64-Setup.exe"; + size=3000000;state='uploaded';digest="sha256:$sha"; + browser_download_url="https://github.com/$repo/releases/download/$tag/ArSonMix-$tag-Windows-x64-Setup.exe"} + $sum=[pscustomobject]@{name='SHA256SUMS.txt';size=250;state='uploaded'; + digest="sha256:$sha";browser_download_url="https://github.com/$repo/releases/download/$tag/SHA256SUMS.txt"} + $proof=[pscustomobject]@{name='INSTALLER_PROVENANCE.json';size=500; + state='uploaded';digest="sha256:$sha"; + browser_download_url="https://github.com/$repo/releases/download/$tag/INSTALLER_PROVENANCE.json"} + $release=[pscustomobject]@{tag_name=$tag;draft=$false; + published_at='2026-11-09T00:00:00Z';target_commitish=('f'*40); + assets=@($asset,$sum,$proof)} + if($null -eq (Approved-Installer $release)){throw 'Valid release rejected'} + $asset.browser_download_url='https://attacker.example/update.exe' + if($null -ne (Approved-Installer $release)){throw 'Untrusted asset origin accepted'} + $asset.browser_download_url="https://github.com/$repo/releases/download/$tag/$($asset.name)" + $release.assets=@($asset,$asset,$sum,$proof) + if($null -ne (Approved-Installer $release)){throw 'Duplicate installer accepted'} + # Positive and negative staged binary integrity tests. These execute + # under synthetic TEMP; never use or modify the installed program. + $tmp=Join-Path ([IO.Path]::GetTempPath()) ('ArSonMix-Updater-Policy-'+[guid]::NewGuid().ToString('N')) + try { + [IO.Directory]::CreateDirectory($tmp) | Out-Null + $fixturePath=Join-Path $tmp 'test-installer.exe' + [IO.File]::WriteAllBytes($fixturePath,(New-Object byte[] 2097152)) + $goodHash=(Get-FileHash -LiteralPath $fixturePath -Algorithm SHA256).Hash.ToLowerInvariant() + $fixtureAsset=[pscustomobject]@{digest=('sha256:'+$goodHash);size=2097152} + if(-not (Test-StagedAsset $fixturePath $fixtureAsset)) {throw 'Valid staged EXE rejected'} + $fixtureAsset.digest='sha256:'+('0'*64) + if(Test-StagedAsset $fixturePath $fixtureAsset){throw 'Tampered staged EXE accepted'} + $fixtureAsset.digest='sha256:'+$goodHash + $fixtureAsset.size=2097153 + if(Test-StagedAsset $fixturePath $fixtureAsset){throw 'Short staged EXE accepted'} + $fixtureAsset.size=2097152 + $priorExe=$exe + try { + $exe=$fixturePath + $validBuild=[pscustomobject]@{exeSha256=$goodHash;guiExeBytes=2097152} + if((Get-InstalledImageStatus $validBuild) -cne 'healthy'){throw 'Healthy image rejected'} + $savedProvenance=$provenance + try { + $provenance=Join-Path $tmp 'BUILD_PROVENANCE.json' + $sampleSha='1'*40 + [IO.File]::WriteAllText($provenance,( + @{sourceCommit=$sampleSha;exeSha256=$goodHash;guiExeBytes=2097152} | + ConvertTo-Json -Compress),[Text.Encoding]::UTF8) + if(-not (Test-InstalledRelease $sampleSha)){throw 'Authentic installed image rejected'} + if(Test-InstalledRelease ('2'*40)){throw 'Incorrect source accepted'} + [IO.File]::WriteAllText($provenance,( + @{sourceCommit=$sampleSha;exeSha256=('0'*64);guiExeBytes=2097152} | + ConvertTo-Json -Compress),[Text.Encoding]::UTF8) + if(Test-InstalledRelease $sampleSha){throw 'Same source with changed EXE accepted'} + } finally {$provenance=$savedProvenance} + + $validBuild.exeSha256='0'*64 + if((Get-InstalledImageStatus $validBuild) -cne 'damaged'){throw 'Tampered image not detected'} + $validBuild.exeSha256=$goodHash + $validBuild.guiExeBytes=2097153 + if((Get-InstalledImageStatus $validBuild) -cne 'damaged'){throw 'Truncated image not detected'} + $validBuild.guiExeBytes=0 + if((Get-InstalledImageStatus $validBuild) -cne 'unknown'){throw 'Unknown manifest not fenced'} + if((Classify-InterruptedTransaction 'installing' ('1'*40) ('1'*40) ('2'*40)) -cne 'previous-retained'){ + throw 'Old EXE recovery not classified' + } + if((Classify-InterruptedTransaction 'installing' ('2'*40) ('1'*40) ('2'*40)) -cne 'candidate-unverified'){ + throw 'Candidate recovery not classified' + } + } finally {$exe=$priorExe} + [IO.File]::Delete($fixturePath) + if(Test-StagedAsset $fixturePath $fixtureAsset){throw 'Missing staged EXE accepted'} + } finally { + if(Test-Path -LiteralPath $tmp){Remove-Item -LiteralPath $tmp -Recurse -Force} + } + # Offline stage reuse must require BOTH full-size byte-verified EXEs. + $previousRoot=$root + try { + $root=$tmp + $stageDir=Join-Path $root 'stage' + [IO.Directory]::CreateDirectory($stageDir) | Out-Null + $tag='v0.5.0-alpha.6' + $stageFile=Join-Path $stageDir "ArSonMix-$tag-Windows-x64-Setup.exe" + [IO.File]::WriteAllBytes($stageFile,(New-Object byte[] 2097152)) + $hash=(Get-FileHash -LiteralPath $stageFile -Algorithm SHA256).Hash.ToLowerInvariant() + $stored=[pscustomobject]@{name="ArSonMix-$tag-Windows-x64-Setup.exe";size=2097152;digest="sha256:$hash"} + $transaction=[pscustomobject]@{phase='staged';candidateTag=$tag;previousTag=$tag; + newAsset=$stored;previousAsset=$stored} + if(-not (Test-CompleteStagedTransaction $transaction)){throw 'Verified stage not reused'} + $stored.digest='sha256:'+('0'*64) + if(Test-CompleteStagedTransaction $transaction){throw 'Corrupted staged transaction reused'} + } finally {$root=$previousRoot} + if(-not (Should-RetryInstaller 1 $false $true)){throw 'First transient retry rejected'} + if(Should-RetryInstaller 2 $false $true){throw 'Repeated installer retry accepted'} + if(Should-RetryInstaller 1 $false $false){throw 'Missing old version retried'} + if(Should-RetryInstaller 1 $true $true){throw 'Successful install retried'} + Write-Output 'ARSONMIX_UPDATER_EXACT_IMAGE_POLICY_PASS' + Write-Output 'ARSONMIX_UPDATER_RETRY_POLICY_PASS' + Write-Output 'ARSONMIX_UPDATER_CACHE_AND_RECOVERY_PASS' + + Write-Output 'ARSONMIX_UPDATER_SELF_REPAIR_POLICY_PASS' + Write-Output 'ARSONMIX_UPDATER_STAGED_INTEGRITY_PASS' + Write-Output 'ARSONMIX_UPDATER_POLICY_PASS' + exit 0 +} + +try { + if($RecoveryMode -and -not (Test-Path -LiteralPath $provenance -PathType Leaf)) { + Show-RecoveryFailure 'Installation version metadata is missing' + exit 0 + } + if(-not (Test-Path -LiteralPath $provenance -PathType Leaf) -or + (-not $RecoveryMode -and -not (Test-Path -LiteralPath $exe -PathType Leaf)) -or + (-not $ApplyStaged -and -not $RecoveryMode -and -not (Owns-Exe $OwnerProcessId))) {exit 0} + # No update worker from portable builds, different installation roots, + # arbitrary scripts outside {app}, or second ArSonMix updater instance. + if(Test-Path -LiteralPath (Join-Path $PSScriptRoot 'portable_mode.txt')){exit 0} + $mutex=[Threading.Mutex]::new($false,'Local\ArSonMix.AutoUpdater.v1') + try { + $locked=$mutex.WaitOne($(if($ApplyStaged -or $RecoveryMode){60000}else{0})) + } catch [Threading.AbandonedMutexException] { + # Previous worker was killed. WaitOne owns the mutex despite throwing. + $locked=$true + Log-Result 'ABANDONED_MUTEX_RECLAIMED' + } + if(-not $locked){exit 0} + [IO.Directory]::CreateDirectory($root) | Out-Null + $file=Read-Json $provenance + $installedSha=[string]$file.sourceCommit + if($installedSha -cnotmatch '^[a-f0-9]{40}$'){ + if($RecoveryMode){Show-RecoveryFailure 'Installed source identity is invalid'} + exit 0 + } + $state=[pscustomobject]@{lastCheckUtc='';lastAttemptUtc='';blockedTag='';lastInstalledTag='';phase='idle';operation='upgrade';installAttempts=0;retryAfterUtc=''; + candidateTag='';candidateSha='';previousSha='';previousTag=''; + newAsset=$null;previousAsset=$null} + if(Test-Path -LiteralPath $statePath -PathType Leaf) { + try { + $read=Read-Json $statePath + if($null -eq $read -or $null -eq $read.PSObject.Properties['phase']){throw 'Invalid updater state'} + } catch { + # Quarantine only the updater's own metadata, never user files. + $quarantine=$statePath+'.invalid.'+[guid]::NewGuid().ToString('N') + [IO.File]::Move($statePath,$quarantine) + Log-Result 'INVALID_UPDATER_STATE_QUARANTINED' + $read=$null + } + foreach($key in @('lastCheckUtc','lastAttemptUtc','blockedTag','lastInstalledTag','phase','operation','installAttempts','retryAfterUtc','candidateTag','candidateSha','previousSha','previousTag','newAsset','previousAsset')) { + if($null -ne $read -and $read.PSObject.Properties.Name -contains $key){$state.$key=$read.$key} + } + } + if($RecoveryMode) { + # Explicit Repair always verifies and reapplies the published + # application files. EXE may be intact while FactoryFX or packaged + # WebView resources are missing. No uninstall or user-data deletion. + try {Restore-InstalledRelease $installedSha} + catch {Show-RecoveryFailure $_.Exception.Message} + exit 0 + } + $recovery=Classify-InterruptedTransaction ([string]$state.phase) $installedSha ([string]$state.previousSha) ([string]$state.candidateSha) + if($recovery) { + if($state.candidateTag){$state.blockedTag=$state.candidateTag} + $state.phase=$recovery + Write-State $state + Log-Result ('RECOVERED_TRANSACTION_STATUS '+$recovery) + if($recovery -ceq 'unknown-installation'){exit 0} + } + if(-not $ApplyStaged) { + # A staged transaction stays staged across app opens. Installation + # always rechecks publication/revocation before touching any files. + if($state.phase -ceq 'staged' -and $state.previousSha -ceq $installedSha){ + if(Test-CompleteStagedTransaction $state){ + Log-Result 'STAGED_READY_FOR_NORMAL_EXIT' + exit 0 + } + # Incomplete/altered cached installers must be downloaded afresh. + # Never attempt an installer solely because metadata says "staged". + $state.phase='staging-retry' + $state.lastCheckUtc='' + $state.lastAttemptUtc='' + Write-State $state + Log-Result 'STAGED_CACHE_INVALID_REDOWNLOAD' + } + if($state.phase -ceq 'idle' -and $state.candidateTag -and + $state.lastInstalledTag -ceq $state.candidateTag) { + Clear-StagedVendorFiles $state + } + $imageStatus=Get-InstalledImageStatus $file + $now=[DateTime]::UtcNow + $attempt=[DateTime]::MinValue + if($state.lastAttemptUtc -and [DateTime]::TryParse([string]$state.lastAttemptUtc,[ref]$attempt) -and + $now -ge $attempt.ToUniversalTime() -and + $now.Subtract($attempt.ToUniversalTime()).TotalMinutes -lt 20){exit 0} + $checked=[DateTime]::MinValue + if($imageStatus -cne 'damaged' -and $state.lastCheckUtc -and + [DateTime]::TryParse([string]$state.lastCheckUtc,[ref]$checked) -and + $now -ge $checked.ToUniversalTime() -and + $now.Subtract($checked.ToUniversalTime()).TotalHours -lt 6){exit 0} + $state.lastAttemptUtc=$now.ToString('o') + Write-State $state + $headers=@{Accept='application/vnd.github+json';'User-Agent'='ArSonMix-SmartUpdater/1'; + 'X-GitHub-Api-Version'='2022-11-28'} + $releases=Invoke-RestMethod -Uri $api -Headers $headers -TimeoutSec 25 + $state.lastCheckUtc=[DateTime]::UtcNow.ToString('o') + Write-State $state + $current=$null + foreach($release in $releases) { + if([string]$release.target_commitish -ceq $installedSha -and + $null -ne (Approved-Installer $release)) { + if($null -eq $current -or (Compare-Version (Version-Key $release.tag_name) (Version-Key $current.tag_name)) -gt 0) { + $current=$release + } + } + } + if($null -eq $current){Log-Result 'NO_MATCHING_PUBLISHED_BASELINE';exit 0} + $new=$null + foreach($release in $releases) { + if($null -eq (Approved-Installer $release)){continue} + if(-not $current.prerelease -and $release.prerelease){continue} + if((Compare-Version (Version-Key $release.tag_name) (Version-Key $current.tag_name)) -le 0){continue} + if($null -eq $new -or (Compare-Version (Version-Key $release.tag_name) (Version-Key $new.tag_name)) -gt 0) { + $new=$release + } + } + $operation='upgrade' + if($null -eq $new) { + if($imageStatus -cne 'damaged'){Log-Result 'UP_TO_DATE';exit 0} + # Repair only a cryptographically proven EXE mismatch. Use the + # same verified Inno release in place; never uninstall user data. + $new=$current + $operation='repair' + Log-Result 'STAGING_VERIFIED_SAME_VERSION_REPAIR' + } + if($state.blockedTag -ceq $new.tag_name){Log-Result 'PREVIOUS_FAILURE_BLOCKED';exit 0} + $oldAsset=Approved-Installer $current + $newAsset=Approved-Installer $new + $stage=Join-Path $root 'stage' + $oldPath=Join-Path $stage ([string]$oldAsset.name) + $newPath=Join-Path $stage ([string]$newAsset.name) + # Release-list retrieval succeeded, but the transaction is NOT checked + # until both release packages/checksums have passed verification. + # On network/metadata failure here, retry after lastAttemptUtc's + # 20-minute backoff, not the six-hour successful-check cooldown. + $state.phase='staging-retry' + $state.lastCheckUtc='' + Write-State $state + Download-Release-Verified $new $newAsset $newPath + # Rollback must be possible offline. Do not begin update without a + # byte-verified previous installer. + Download-Release-Verified $current $oldAsset $oldPath + $state.phase='staged' + $state.lastCheckUtc=[DateTime]::UtcNow.ToString('o') + $state.operation=$operation + $state.installAttempts=0 + $state.retryAfterUtc='' + $state.candidateTag=[string]$new.tag_name + $state.candidateSha=[string]$new.target_commitish + $state.previousTag=[string]$current.tag_name + $state.previousSha=$installedSha + $state.newAsset=[pscustomobject]@{name=$newAsset.name;digest=$newAsset.digest;size=$newAsset.size} + $state.previousAsset=[pscustomobject]@{name=$oldAsset.name;digest=$oldAsset.digest;size=$oldAsset.size} + Write-State $state + Log-Result ('STAGED '+$new.tag_name+' WAITING_FOR_NORMAL_EXIT') + exit 0 # Checker ends here. Never keep PowerShell resident during mixing. + } + # Post-close supervisor: no resident updater during live audio. + if($state.phase -cne 'staged' -or $state.previousSha -cne $installedSha){exit 0} + if($state.operation -cnotin @('upgrade','repair')){Fail 'Unknown update operation'} + if($state.operation -ceq 'repair' -and $state.candidateSha -cne $installedSha){ + Fail 'Repair must use the installed release' + } + $retryAt=[DateTime]::MinValue + if($state.retryAfterUtc -and + [DateTime]::TryParse([string]$state.retryAfterUtc,[ref]$retryAt) -and + [DateTime]::UtcNow -lt $retryAt.ToUniversalTime()){ + Log-Result 'INSTALLER_RETRY_DEFERRED_COOLDOWN' + exit 0 + } + if($state.candidateSha -cnotmatch '^[a-f0-9]{40}$' -or + $null -eq (Version-Key ([string]$state.candidateTag)) -or + $null -eq (Version-Key ([string]$state.previousTag)) -or + $state.blockedTag -ceq $state.candidateTag) {Fail 'Invalid persisted update transaction'} + $newName='ArSonMix-'+$state.candidateTag+'-Windows-x64-Setup.exe' + $oldName='ArSonMix-'+$state.previousTag+'-Windows-x64-Setup.exe' + if($state.newAsset.name -cne $newName -or + $state.previousAsset.name -cne $oldName) {Fail 'Unsafe staged installer identity'} + $stage=Join-Path $root 'stage' + $newPath=Join-Path $stage $newName + $oldPath=Join-Path $stage $oldName + # Validate both independently. Do not build nested arrays here: + # PowerShell 5.1 pipeline unrolling can flatten the pair boundaries. + if(-not (Test-StagedAsset $newPath $state.newAsset) -or + -not (Test-StagedAsset $oldPath $state.previousAsset)) { + Fail 'Offline staged install/rollback bytes not verified' + } + # Re-query public release to reject a revoked or replaced candidate. + # No network is needed *during* live audio; if offline on close, defer. + $headers=@{Accept='application/vnd.github+json';'User-Agent'='ArSonMix-SmartUpdater/1'; + 'X-GitHub-Api-Version'='2022-11-28'} + $liveReleases=Invoke-RestMethod -Uri $api -Headers $headers -TimeoutSec 25 + $approved=$null + $approvedOld=$null + foreach($release in $liveReleases) { + if($release.tag_name -ceq $state.candidateTag -and + $release.target_commitish -ceq $state.candidateSha) { + $approved=Approved-Installer $release + } + if($release.tag_name -ceq $state.previousTag -and + $release.target_commitish -ceq $state.previousSha) { + $approvedOld=Approved-Installer $release + } + } + if($null -eq $approvedOld -or + $approvedOld.name -cne $state.previousAsset.name -or + $approvedOld.digest -cne $state.previousAsset.digest -or + [long]$approvedOld.size -ne [long]$state.previousAsset.size) { + # The rollback package is mandatory. Fail closed if its published + # source/asset identity was withdrawn or the local cache was altered. + # Do not install a newer version without an authentic way back. + Log-Result 'ROLLBACK_RELEASE_UNAVAILABLE_UPDATE_DEFERRED' + exit 0 + } + if($null -eq $approved -or $approved.digest -cne $state.newAsset.digest -or + [long]$approved.size -ne [long]$state.newAsset.size){ + # A withdrawn release must not be retried on every shutdown. + # Permit another newly published, attested release on next startup. + $state.blockedTag=$state.candidateTag + $state.phase='revoked' + $state.lastCheckUtc='' + $state.lastAttemptUtc='' + Write-State $state + Log-Result 'RELEASE_REVOKED_UPDATE_DEFERRED' + exit 0 + } + $new=[pscustomobject]@{tag_name=$state.candidateTag;target_commitish=$state.candidateSha} + $oldAsset=$state.previousAsset + $newAsset=$state.newAsset + # Never send shutdown event or WM_CLOSE from the updater itself. + # A live singer/session cannot be interrupted by release publication. + try { + $hostProcess=[Diagnostics.Process]::GetProcessById($OwnerProcessId) + try { + if(-not $hostProcess.WaitForExit(120000)) {exit 0} # bounded normal exit + } finally {$hostProcess.Dispose()} + } catch { } # Host already exited. + # Inno is the only authority allowed to close/replace its own installed EXE. + # If a new mixer instance is running, defer; do not hijack its session. + foreach($process in [Diagnostics.Process]::GetProcessesByName('ArSonMix')) { + try { + if([string]::Equals([IO.Path]::GetFullPath($process.MainModule.FileName),$exe, + [StringComparison]::OrdinalIgnoreCase)){Log-Result 'DEFER_NEW_SESSION';exit 0} + } catch {Log-Result 'DEFER_UNKNOWN_PROCESS';exit 0} + finally {$process.Dispose()} + } + if((Read-Json $provenance).sourceCommit -cne $installedSha) {Log-Result 'DEFER_VERSION_CHANGED';exit 0} + $state.phase='installing' + $state.installAttempts=[int]$state.installAttempts+1 + Write-State $state + $upgradeOK=Run-Installer $newPath + $actualSha='' + try {$actualSha=[string](Read-Json $provenance).sourceCommit} catch {} + if($upgradeOK -and (Test-InstalledRelease ([string]$new.target_commitish)) -and + (Launch-WithHealth ([string]$new.target_commitish))) { + $state.lastInstalledTag=$new.tag_name + $state.phase='idle' + $state.retryAfterUtc='' + $state.installAttempts=0 + $state.blockedTag='' + Write-State $state + Log-Result ($(if($state.operation -ceq 'repair'){'REPAIRED '}else{'HEALTHY '})+$new.tag_name) + Clear-StagedVendorFiles $state + exit 0 + } + # A transient, completed Inno rejection can retry ONCE on a later + # normal exit. Timeout/exception never qualifies for a second installer. + $oldRemains=($actualSha -ceq $installedSha) -and (Test-Path -LiteralPath $exe -PathType Leaf) + if(Should-RetryInstaller ([int]$state.installAttempts) ([bool]$upgradeOK) ([bool]$oldRemains)) { + $state.phase='staged' + $state.retryAfterUtc=[DateTime]::UtcNow.AddMinutes(30).ToString('o') + Write-State $state + Log-Result ('INSTALLER_TRANSIENT_FAILURE_RETRY_NEXT_EXIT '+$new.tag_name) + try {[Diagnostics.Process]::Start($exe) | Out-Null} catch { + Log-Result 'PREVIOUS_EXE_RELAUNCH_FAILED' + } + exit 0 + } + # An installer failure leaves the previous app intact or may be partial. + # If the known-good source is still installed, relaunch it once. + # Never silently retry the failing release on every startup. + # If the new GUI still runs but did not acknowledge readiness, NEVER + # kill it or overwrite its image. Block this release pending inspection. + $state.blockedTag=$new.tag_name + $state.phase=if($upgradeOK){'health-failed'}else{'installer-failed'} + Write-State $state + if($actualSha -ceq $installedSha) { + Log-Result ('INSTALLER_FAILED_PREVIOUS_VERSION_RETAINED '+$new.tag_name) + [Diagnostics.Process]::Start($exe) | Out-Null + exit 0 + } + foreach($process in [Diagnostics.Process]::GetProcessesByName('ArSonMix')) { + try { + if([string]::Equals([IO.Path]::GetFullPath($process.MainModule.FileName),$exe, + [StringComparison]::OrdinalIgnoreCase)) {Log-Result 'HEALTH_FAILED_NEW_GUI_STILL_OPEN';exit 0} + } catch {Log-Result 'HEALTH_FAILED_PROCESS_UNKNOWN';exit 0} + finally {$process.Dispose()} + } + if($state.operation -ceq 'repair') { + # Another copy of the same installer cannot act as rollback. + Log-Result ('REPAIR_HEALTH_FAILED_BLOCKED '+$new.tag_name) + exit 0 + } + # Roll back by running the previously authenticated Inno installer, + # not by copying arbitrary stale binaries over an installed application. + if(Run-Installer $oldPath) { + if(Test-InstalledRelease $installedSha) { + $state.phase='rolled-back' + Write-State $state + Log-Result ('ROLLED_BACK '+$new.tag_name) + [Diagnostics.Process]::Start($exe) | Out-Null + exit 0 + } + } + Fail 'Health failed and verified rollback installer did not restore old source' + } catch { + # An interrupted/crashed updater must never repeatedly apply the same + # candidate. Inno itself is fail-closed; a later normal app launch remains + # usable even if the updater encountered an unexpected exception. + try { + if((Get-Variable -Name state -ErrorAction SilentlyContinue) -and + (Get-Variable -Name new -ErrorAction SilentlyContinue) -and + $null -ne $new -and $state.phase -ceq 'installing') { + $state.blockedTag=$new.tag_name + $state.phase='installer-failed' + Write-State $state + } + } catch { } + Log-Result ('FAIL_CLOSED '+$_.Exception.Message) +} finally { + if($locked -and $null -ne $mutex){$mutex.ReleaseMutex()} + if($null -ne $mutex){$mutex.Dispose()} +} diff --git a/installer/ArSonMixUpdateShutdown.ps1 b/installer/ArSonMixUpdateShutdown.ps1 index b6f3faf14..952bca952 100644 --- a/installer/ArSonMixUpdateShutdown.ps1 +++ b/installer/ArSonMixUpdateShutdown.ps1 @@ -5,7 +5,8 @@ # the EXACT ArSonMix.exe path being replaced. Other ArSonMix copies are safe. param( [Parameter(Mandatory=$true)][string]$TargetPath, - [ValidateRange(1,90)][int]$WaitSeconds=25 + [ValidateRange(1,90)][int]$WaitSeconds=25, + [switch]$ProbeOnly ) Set-StrictMode -Version Latest $ErrorActionPreference='Stop' @@ -15,6 +16,7 @@ try { if($name -ne 'ArSonMix'){exit 30} # Start with the native .NET process list, no taskkill, broad WM_CLOSE # broadcasts, WMI process termination, or process-name-only shutdown. + $script:unknownIdentity=$false function Get-TargetProcesses { $found=@() foreach($process in [System.Diagnostics.Process]::GetProcessesByName('ArSonMix')) { @@ -32,12 +34,20 @@ try { } catch { # Windows may restrict MainModule even for a readable name. # Do not guess identity and NEVER close by process name only. + if($ProbeOnly){$script:unknownIdentity=$true} $process.Dispose() } } return @($found) } $matches=@(Get-TargetProcesses) + if($ProbeOnly) { + $count=$matches.Count + foreach($process in $matches){$process.Dispose()} + if($script:unknownIdentity){exit 22} + if($count -ne 0){exit 21} + exit 0 + } if($matches.Count -eq 0){exit 0} # Some JUCE versions have an ownerless top-level HWND; CloseMainWindow # alone reports false. Match HWND -> PID before posting WM_CLOSE. diff --git a/scripts/test_inno_graceful_update_windows.ps1 b/scripts/test_inno_graceful_update_windows.ps1 index 831bddb11..dff028a53 100644 --- a/scripts/test_inno_graceful_update_windows.ps1 +++ b/scripts/test_inno_graceful_update_windows.ps1 @@ -2,6 +2,20 @@ # Fast Windows Inno/Restart Manager smoke, independent of JUCE. # The staged .exe is a test-only WinForms window, NOT a product release. Set-StrictMode -Version Latest +# Offline functional policy gate for the actual shipped updater script. +# This mode never reads an install, touches a live process or calls the network. +$updaterPolicy=Join-Path (Resolve-Path .).Path "installer/ArSonMixAutoUpdate.ps1" +$policyOutput=& "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -File $updaterPolicy -OwnerProcessId 1 -PolicySelfTest +if($LASTEXITCODE -ne 0 -or $policyOutput -notcontains 'ARSONMIX_UPDATER_POLICY_PASS' -or + $policyOutput -notcontains 'ARSONMIX_UPDATER_EXACT_IMAGE_POLICY_PASS' -or + $policyOutput -notcontains 'ARSONMIX_UPDATER_CACHE_AND_RECOVERY_PASS' -or + $policyOutput -notcontains 'ARSONMIX_UPDATER_RETRY_POLICY_PASS' -or + $policyOutput -notcontains 'ARSONMIX_UPDATER_SELF_REPAIR_POLICY_PASS' -or + $policyOutput -notcontains 'ARSONMIX_UPDATER_STAGED_INTEGRITY_PASS'){ + throw "Smart updater offline version/origin/duplicate-asset policy failed: $policyOutput" +} +Write-Host "ARSONMIX_UPDATER_POLICY_PASS" + $ErrorActionPreference="Stop" $root=(Resolve-Path .).Path $work=Join-Path $env:RUNNER_TEMP ("arsonmix-inno-smoke-"+[guid]::NewGuid().ToString("N")) @@ -96,6 +110,64 @@ try { Write-Host "INNO_LEGACY_NO_HANDSHAKE_UPGRADE_PASS: exact exe process requested WM_CLOSE before replacement" $fixtureProcess.Dispose();$fixtureProcess=$null + # Automatic update MUST NOT close even a healthy existing mixer. + # Legacy and native-style active processes both fail before [Files]. + Remove-Item -LiteralPath $ready,$closed -Force -ErrorAction SilentlyContinue + $fixtureProcess=Start-Process -FilePath $installedExe -ArgumentList @( + ('"' + $ready + '"'),('"' + $closed + '"'),"legacy") -PassThru + for($i=0;$i -lt 75 -and -not (Test-Path -LiteralPath $ready);$i++){ + $fixtureProcess.Refresh() + if($fixtureProcess.HasExited){break} + Start-Sleep -Milliseconds 200 + } + Assert-Condition (Test-Path -LiteralPath $ready) "Auto-update active-session fixture not ready" + $autoAttempt=Start-Process -FilePath $setup -ArgumentList ($setupArgs + @('/ARSONMIXAUTOUPDATE')) -Wait -PassThru + $fixtureProcess.Refresh() + Assert-Condition ($autoAttempt.ExitCode -ne 0 -and -not $fixtureProcess.HasExited) "Auto updater closed/overwrote an active mixer" + Assert-Condition (-not (Test-Path -LiteralPath $closed)) "Auto updater unexpectedly sent WM_CLOSE" + Assert-Condition ((Get-FileHash -LiteralPath $installedExe -Algorithm SHA256).Hash -eq $fixtureHash) "Auto updater modified a locked executable" + Assert-Condition ((Test-Path -LiteralPath $userFile) -and (Test-Path -LiteralPath $privateSentinel)) "Auto updater damaged user data" + Write-Host "INNO_AUTO_UPDATE_LIVE_SESSION_PRESERVED_PASS: no WM_CLOSE, EXE untouched, Studio retained" + # Close ONLY this test fixture through the pre-existing exact-path + # graceful GUI helper. This is test teardown after proving that the + # automatic mode itself NEVER requested WM_CLOSE. + $helper=Join-Path $root "installer/ArSonMixUpdateShutdown.ps1" + & "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -NonInteractive -File $helper -TargetPath $installedExe -WaitSeconds 10 + Assert-Condition ($LASTEXITCODE -eq 0 -and $fixtureProcess.WaitForExit(10000)) "Auto-update test fixture did not close normally" + $fixtureProcess.Dispose();$fixtureProcess=$null + # A stopped ArSonMix should be eligible for auto update without a + # manual dialog, WM_CLOSE, replacement errors or stale-process bias. + $autoSuccess=Start-Process -FilePath $setup -ArgumentList ($setupArgs + @('/ARSONMIXAUTOUPDATE')) -Wait -PassThru + Assert-Condition ($autoSuccess.ExitCode -eq 0) "Automatic update rejected an exited ArSonMix installation" + Assert-Condition ((Get-FileHash -LiteralPath $installedExe -Algorithm SHA256).Hash -eq $fixtureHash) "Auto-install changed expected product bytes" + Assert-Condition ((Test-Path -LiteralPath $userFile) -and (Test-Path -LiteralPath $privateSentinel)) "Auto-install erased user data" + Write-Host "INNO_AUTO_UPDATE_AFTER_NORMAL_EXIT_PASS: silent setup, correct EXE, user data intact" + + # Test-only synthetic corruption: byte-level repair of vendor-owned EXE. + # Never run this on a user installation or private Studio content. + [IO.File]::WriteAllBytes($installedExe,(New-Object byte[] 4096)) + Assert-Condition ((Get-FileHash -LiteralPath $installedExe -Algorithm SHA256).Hash -ne $fixtureHash) "Corrupt fixture unexpectedly matched original binary" + $repair=Start-Process -FilePath $setup -ArgumentList ($setupArgs + @('/ARSONMIXAUTOUPDATE')) -Wait -PassThru + Assert-Condition ($repair.ExitCode -eq 0) "Automatic same-version repair installer failed" + Assert-Condition ((Get-FileHash -LiteralPath $installedExe -Algorithm SHA256).Hash -eq $fixtureHash) "Same-version repair did not restore verified EXE" + Assert-Condition ((Test-Path -LiteralPath $userFile) -and (Test-Path -LiteralPath $privateSentinel)) "Same-version repair erased Studio or install-local user files" + Write-Host "INNO_AUTO_REPAIR_CORRUPT_EXE_PASS: exact verified EXE restored, private Studio and user files retained" + + # Recovery when app EXE cannot start. This is a test-only isolated + # installation. User program files must never be deliberately deleted. + Remove-Item -LiteralPath $installedExe -Force + Assert-Condition (-not (Test-Path -LiteralPath $installedExe)) "Could not remove synthetic EXE" + $ordinary=Start-Process -FilePath $setup -ArgumentList ($setupArgs + @('/ARSONMIXAUTOUPDATE')) -Wait -PassThru + Assert-Condition ($ordinary.ExitCode -ne 0) "Ordinary auto-update accepted a missing program EXE" + Assert-Condition (-not (Test-Path -LiteralPath $installedExe)) "Normal auto-update restored EXE without explicit recovery" + $repaired=Start-Process -FilePath $setup -ArgumentList ($setupArgs + @('/ARSONMIXAUTOUPDATE','/ARSONMIXRECOVERY')) -Wait -PassThru + Assert-Condition ($repaired.ExitCode -eq 0) "Missing EXE recovery installer failed" + Assert-Condition ((Get-FileHash -LiteralPath $installedExe -Algorithm SHA256).Hash -eq $fixtureHash) "Missing EXE recovery did not restore exact SHA" + Assert-Condition ((Test-Path -LiteralPath $userFile) -and (Test-Path -LiteralPath $privateSentinel)) "Missing EXE recovery erased user data" + Write-Host "INNO_MISSING_EXE_RECOVERY_PASS: exact EXE recovered, app and Studio retained" + + + # Busy/hung GUI: it REFUSES WM_CLOSE and has no newer handshake. # Upgrade must fail before [Files], leave old EXE and Studio untouched. Remove-Item -LiteralPath $ready,$closed -Force -ErrorAction SilentlyContinue diff --git a/scripts/test_two_genuine_inno_releases_windows.ps1 b/scripts/test_two_genuine_inno_releases_windows.ps1 new file mode 100644 index 000000000..3a194e0e2 --- /dev/null +++ b/scripts/test_two_genuine_inno_releases_windows.ps1 @@ -0,0 +1,121 @@ +# SPDX-License-Identifier: AGPL-3.0-only +# Opt-in FAT ONLY: two genuine historical ArSonMix releases, update, +# rollback, user-data retention. Not used by the low-cost PR smoke path. +# This requires a disposable GitHub Windows runner, NEVER a user PC. +param() +Set-StrictMode -Version Latest +$ErrorActionPreference='Stop' +if($env:GITHUB_ACTIONS -cne 'true' -or + $env:RUNNER_OS -cne 'Windows' -or + [string]::IsNullOrWhiteSpace($env:RUNNER_TEMP)) { + throw 'REAL_RELEASE_FAT_REQUIRES_DISPOSABLE_GITHUB_WINDOWS_RUNNER' +} +[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12 +$repo='masarray/arsonmix' +$matrix=@( + @{tag='v0.5.0-alpha.4';sha='7447d82e84a52e583c7e4c30b9a7bbcded1abd11'}, + @{tag='v0.5.0-alpha.5';sha='d7cf109ad1d45f0666431ce748d72572dd49facc'} +) +$root=Join-Path $env:RUNNER_TEMP ('arsonmix-genuine-upgrade-'+[guid]::NewGuid().ToString('N')) +$packages=Join-Path $root 'packages' +$install=Join-Path $root 'installed' +$studio=Join-Path $root 'private-Studio' +[IO.Directory]::CreateDirectory($packages) | Out-Null +[IO.Directory]::CreateDirectory($install) | Out-Null +[IO.Directory]::CreateDirectory($studio) | Out-Null +$sentinel=Join-Path $studio 'proof-user-session.smix' +$installSentinel=Join-Path $install 'USER_PRESERVE_ME.txt' +[IO.File]::WriteAllText($sentinel,'real-release-upgrade-and-rollback') +[IO.File]::WriteAllText($installSentinel,'first-party-unrecognized-user-file') +function Assert-True([bool]$ok,[string]$message) { + if(-not $ok){throw $message} +} +function Release-Asset([object]$release,[string]$name) { + $found=@($release.assets | Where-Object { + $_.name -ceq $name -and $_.state -ceq 'uploaded' -and + $_.digest -cmatch '^sha256:[a-f0-9]{64}$' -and + $_.browser_download_url -ceq ("https://github.com/$repo/releases/download/$($release.tag_name)/$name") + }) + Assert-True ($found.Count -eq 1) "Published release lacks a unique verified $name" + return $found[0] +} +function Fetch-Verified([object]$asset,[string]$destination) { + $size=[int64]$asset.size + Assert-True ($size -ge 1 -and $size -le 209715200) "Unsafe published artifact size" + $url=[uri]$asset.browser_download_url + Assert-True ($url.Scheme -ceq 'https' -and $url.Host -ceq 'github.com') "Unexpected source hostname" + Invoke-WebRequest -Uri $url -OutFile $destination -TimeoutSec 180 -MaximumRedirection 5 + Assert-True ((Get-Item -LiteralPath $destination).Length -eq $size) "Downloaded asset truncated" + $hash=(Get-FileHash -LiteralPath $destination -Algorithm SHA256).Hash.ToLowerInvariant() + Assert-True ($hash -ceq ([string]$asset.digest).Substring(7)) "Downloaded asset SHA256 mismatch" +} +function Run-Silent([string]$installer,[string]$label) { + Assert-True (Test-Path -LiteralPath $installer) "Missing $label installer" + $arguments=@('/VERYSILENT','/SUPPRESSMSGBOXES','/NORESTART','/CURRENTUSER', + '/NOCLOSEAPPLICATIONS',('/DIR="'+$install+'"')) + $p=Start-Process -FilePath $installer -ArgumentList $arguments -Wait -PassThru + try { + Assert-True ($p.ExitCode -eq 0) "$label installation failed with $($p.ExitCode)" + } finally {$p.Dispose()} +} +function Verify-Installed([string]$sha,[string]$label) { + $exe=Join-Path $install 'ArSonMix.exe' + $manifest=Join-Path $install 'BUILD_PROVENANCE.json' + Assert-True ((Test-Path -LiteralPath $exe) -and (Test-Path -LiteralPath $manifest)) "$label missing native PE/manifest" + $proof=Get-Content -LiteralPath $manifest -Raw | ConvertFrom-Json + Assert-True ($proof.sourceCommit -ceq $sha) "$label wrong installed source commit" + Assert-True ([string]$proof.exeSha256 -cmatch '^[a-f0-9]{64}$') "$label invalid EXE digest" + Assert-True ((Get-Item -LiteralPath $exe).Length -eq [int64]$proof.guiExeBytes) "$label EXE size mismatch" + Assert-True ((Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant() -ceq $proof.exeSha256) "$label EXE hash mismatch" + Assert-True ((Get-Content -LiteralPath $sentinel -Raw) -ceq 'real-release-upgrade-and-rollback') "$label private .smix changed" + Assert-True ((Get-Content -LiteralPath $installSentinel -Raw) -ceq 'first-party-unrecognized-user-file') "$label install-local user file deleted" +} +$downloaded=@() +try { + foreach($item in $matrix) { + $tag=$item.tag + $uri="https://api.github.com/repos/$repo/releases/tags/$tag" + $release=Invoke-RestMethod -Uri $uri -Headers @{'User-Agent'='ArSonMix-GenuineFAT/1';Accept='application/vnd.github+json'} -TimeoutSec 45 + Assert-True (-not $release.draft -and $release.tag_name -ceq $tag -and + $release.target_commitish -ceq $item.sha) "Unexpected historical published release identity" + $name="ArSonMix-$tag-Windows-x64-Setup.exe" + $installerAsset=Release-Asset $release $name + $proofAsset=Release-Asset $release 'INSTALLER_PROVENANCE.json' + $sumAsset=Release-Asset $release 'SHA256SUMS.txt' + $dir=Join-Path $packages $tag + [IO.Directory]::CreateDirectory($dir) | Out-Null + $installer=Join-Path $dir $name + $proofFile=Join-Path $dir 'INSTALLER_PROVENANCE.json' + $sums=Join-Path $dir 'SHA256SUMS.txt' + Fetch-Verified $proofAsset $proofFile + Fetch-Verified $sumAsset $sums + $proof=Get-Content -LiteralPath $proofFile -Raw | ConvertFrom-Json + $digest=([string]$installerAsset.digest).Substring(7) + Assert-True ($proof.sourceCommit -ceq $item.sha -and + $proof.installerSha256 -ceq $digest) "Release installer provenance disagrees with official SHA" + $line=$digest+' '+$name + Assert-True (@(Get-Content -LiteralPath $sums | Where-Object {$_ -ceq $line}).Count -eq 1) "Published release SHA256SUMS mismatch" + Fetch-Verified $installerAsset $installer + $downloaded+=@{sha=$item.sha;tag=$tag;installer=$installer} + } + Run-Silent $downloaded[0].installer 'alpha.4 initial' + Verify-Installed $downloaded[0].sha 'alpha.4 initial' + Write-Host 'GENUINE_RELEASE_BASELINE_PASS' + Run-Silent $downloaded[1].installer 'alpha.5 upgrade' + Verify-Installed $downloaded[1].sha 'alpha.5 upgrade' + Write-Host 'GENUINE_RELEASE_UPGRADE_PASS' + Run-Silent $downloaded[0].installer 'alpha.4 rollback' + Verify-Installed $downloaded[0].sha 'alpha.4 rollback' + Write-Host 'GENUINE_RELEASE_ROLLBACK_PASS' +} finally { + $uninstall=Join-Path $install 'unins000.exe' + if(Test-Path -LiteralPath $uninstall) { + try { + $p=Start-Process -FilePath $uninstall -ArgumentList @('/VERYSILENT','/SUPPRESSMSGBOXES','/NORESTART') -PassThru -Wait + if($p){$p.Dispose()} + } catch {Write-Warning 'FAT fixture uninstall failed; GitHub runner remains disposable'} + } + # This is a unique RUNNER_TEMP directory created by this script, + # never the real installation or any ArSonMix user profile. + if(Test-Path -LiteralPath $root){Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction SilentlyContinue} +} diff --git a/src/Main.cpp b/src/Main.cpp index d6391cc08..9f25c832e 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -5206,9 +5206,34 @@ class ConsoleApp final : public juce::JUCEApplication, private juce::Timer if (stage >= 2) { splash_.reset(); // no overlay over live mixer after engine init +#if defined(_WIN32) + // A real JUCE/WebView ready acknowledgement, not simply + // "EXE launched". The outside supervisor uses it to decide + // whether an update may be retained or requires rollback. + const auto probe = juce::SystemStats::getEnvironmentVariable + ("ARSONMIX_UPDATE_PROBE", {}); + const auto localAppData = juce::SystemStats::getEnvironmentVariable + ("LOCALAPPDATA", {}); + if (stage == 2 && probe.length() == 36 + && juce::Uuid (probe).toDashedString() == probe + && localAppData.isNotEmpty()) + { + const auto healthDir = juce::File (localAppData) + .getChildFile ("ArSonMix").getChildFile ("Updates") + .getChildFile ("health"); + if (healthDir.createDirectory().wasOk()) + healthDir.getChildFile (probe + ".ready") + .replaceWithText ("GUI_READY"); + } +#endif + + if (window_) window_->toFront (true); } }); +#if defined(_WIN32) + launchSmartUpdater (false); +#endif // Opaque cover exactly matches the large HWND, not a small 740×420 // card leaving white WebView2 edges exposed during first paint. if (splash_ && window_) @@ -5223,6 +5248,16 @@ class ConsoleApp final : public juce::JUCEApplication, private juce::Timer window_.reset(); splash_.reset(); #if defined(_WIN32) + // All session persistence has completed. Only a normal user exit can + // apply an already downloaded update. Inno-initiated shutdown must + // not launch a competing installer. + const bool innoIsClosing = installerShutdownEvent_ != nullptr + && ::WaitForSingleObject (installerShutdownEvent_, 0) == WAIT_OBJECT_0; + // Avoid starting setup while Windows is signing out/shutting down: + // Windows may terminate installer midway through file replacement. + // A staged transaction remains available on the next normal exit. + if (!innoIsClosing && ::GetSystemMetrics (SM_SHUTTINGDOWN) == 0) + launchSmartUpdater (true); if (installerShutdownEvent_ != nullptr) { ::CloseHandle (installerShutdownEvent_); @@ -5236,6 +5271,40 @@ class ConsoleApp final : public juce::JUCEApplication, private juce::Timer #endif } private: +#if defined(_WIN32) + void launchSmartUpdater (bool applyStaged) + { + // Windows per-user installation only: independent updater process. + // On normal exit, apply only a previously prepared transaction. + // No audio callback, router or plugin operation. + const auto installedExe = juce::File::getSpecialLocation (juce::File::currentExecutableFile); + const auto installDir = installedExe.getParentDirectory(); + const auto updaterScript = installDir.getChildFile ("ArSonMixAutoUpdate.ps1"); + const auto provenance = installDir.getChildFile ("BUILD_PROVENANCE.json"); + const auto systemFolder = juce::File::getSpecialLocation (juce::File::windowsSystemDirectory); + const auto powerShell = systemFolder.getChildFile ("WindowsPowerShell") + .getChildFile ("v1.0") + .getChildFile ("powershell.exe"); + if (installedExe.getFileName().equalsIgnoreCase ("ArSonMix.exe") + && updaterScript.existsAsFile() && provenance.existsAsFile() + && powerShell.existsAsFile() + && !installDir.getChildFile ("portable_mode.txt").exists()) + { + juce::StringArray command { powerShell.getFullPathName(), + "-NoLogo", "-NoProfile", "-NonInteractive", + "-ExecutionPolicy", "Bypass", "-WindowStyle", "Hidden", + "-File", updaterScript.getFullPathName(), + "-OwnerProcessId", juce::String (static_cast (::GetCurrentProcessId())) }; + if (applyStaged) + command.add ("-ApplyStaged"); + juce::ChildProcess supervisor; + // The supervisor is detached from the mixing lifecycle. If it + // cannot start, the GUI still operates normally; updates are + // optional and never a reason to lose the live session. + supervisor.start (command, 0); + } + } +#endif bool startupAttempted_ = false; #if defined(_WIN32) HANDLE updateRunningMutex_ = nullptr; diff --git a/tests/ci_workflow_efficiency_test.mjs b/tests/ci_workflow_efficiency_test.mjs index 51227772d..5ae592431 100644 --- a/tests/ci_workflow_efficiency_test.mjs +++ b/tests/ci_workflow_efficiency_test.mjs @@ -163,7 +163,8 @@ test('Windows realtime CTest is explicit for PR milestones; packaging requires d assert.match(native,/^ windows-build:[\s\S]*?needs: quick\n/m); assert.match(native,/github\.event_name != 'pull_request'/); const fatOnly = [...native.matchAll(/^ if: .*inputs\.package_fat == true.*$/gm)].length; - assert.equal(fatOnly,7,'Portable FAT and Inno installer build/verify/upload all require deliberate manual opt-in'); + assert.equal(fatOnly,8,'Portable FAT, genuine release rollback, and Inno build/verify/upload require deliberate manual opt-in'); + assert.match(native,/scripts\/test_two_genuine_inno_releases_windows\.ps1/); assert.match(native,/FAT_EXACT_PR_HEAD_CHECKOUT/); assert.match(native,/ctest --test-dir build -C Release --output-on-failure/); assert.ok(native.indexOf('scripts/verify_native_windows_artifact.ps1 -OutputDir dist') < diff --git a/tests/windows_installer_contract_test.mjs b/tests/windows_installer_contract_test.mjs index 7ba654b07..20128d27c 100644 --- a/tests/windows_installer_contract_test.mjs +++ b/tests/windows_installer_contract_test.mjs @@ -112,3 +112,210 @@ test('installer packaging is gated by the exact SHA FAT verifier', () => { assert.match(ci, /ArSonMix-Windows-Installer-Preview/); assert.match(ci, /tests\/windows_installer_contract_test\.mjs/); }); + + +test('Smart Auto Updater uses an independent process and strict release gates', () => { + const updater = read('installer/ArSonMixAutoUpdate.ps1'); + const native = read('src/Main.cpp'); + assert.match(iss, /^Source: "ArSonMixAutoUpdate\.ps1"; DestDir: "\{app\}"; Flags: ignoreversion$/m); + assert.match(native, /getChildFile \("ArSonMixAutoUpdate\.ps1"\)/); + assert.match(native, /juce::ChildProcess supervisor/); + assert.match(native, /ARSONMIX_UPDATE_PROBE/); + assert.match(native, /GUI_READY/); + // JUCE 8.0.15 Uuid::toString() is un-dashed; PS .NET Guid.ToString("D") is dashed. + assert.match(native, /juce::Uuid \(probe\)\.toDashedString\(\) == probe/); + assert.doesNotMatch(native, /juce::Uuid \(probe\)\.toString\(\) == probe/); + assert.match(updater, /api\.github\.com\/repos\/masarray\/arsonmix\/releases\?per_page=100/); + assert.match(updater, /Download-Release-Verified/); + assert.match(updater, /INSTALLER_PROVENANCE\.json/); + assert.match(updater, /SHA256SUMS\.txt/); + assert.match(updater, /Get-FileHash -LiteralPath \$part -Algorithm SHA256/); + assert.match(updater, /WaitForExit\(120000\)/); + assert.match(native, /launchSmartUpdater \(true\)/); + assert.match(native, /launchSmartUpdater \(false\)/); + assert.match(updater, /\[switch\]\$ApplyStaged/); + assert.match(updater, /exit 0 # Checker ends here/); + assert.match(updater, /DEFER_NEW_SESSION/); + assert.match(updater, /Local\\ArSonMix\.AutoUpdater\.v1/); + assert.match(updater, /PREVIOUS_FAILURE_BLOCKED/); + assert.match(updater, /ROLLED_BACK/); + assert.match(updater, /Never terminate a hung GUI/); + assert.match(updater, /ARSONMIX_UPDATER_POLICY_PASS/); + assert.match(isolatedSmoke, /ARSONMIX_UPDATER_POLICY_PASS/); + assert.doesNotMatch(updater, /\b(?:taskkill|Stop-Process|TerminateProcess)\b/); + assert.doesNotMatch(updater, /ArSonMix\.InstallShutdown\.v1|SetEvent\(/); +}); + + +test('automatic Inno update never closes a newly active mixer', () => { + assert.match(iss, /function IsArSonMixAutoUpdate: Boolean;/); + assert.match(iss, /CompareText\(ParamStr\(I\), '\/ARSONMIXAUTOUPDATE'\)/); + assert.match(iss, /if IsArSonMixAutoUpdate then/); + assert.match(iss, /-ProbeOnly/); + assert.match(iss, /automatic update deferred/i); + assert.match(legacyShutdown, /\[switch\]\$ProbeOnly/); + assert.match(legacyShutdown, /if\(\$ProbeOnly\) \{/); + assert.match(legacyShutdown, /if\(\$count -ne 0\)\{exit 21\}/); + assert.match(read('installer/ArSonMixAutoUpdate.ps1'), /\/ARSONMIXAUTOUPDATE/); + assert.match(isolatedSmoke, /INNO_AUTO_UPDATE_LIVE_SESSION_PRESERVED_PASS/); +}); + + +test('auto updater cannot race a still-running installer or Windows shutdown', () => { + const updater = read('installer/ArSonMixAutoUpdate.ps1'); + const native = read('src/Main.cpp'); + assert.match(updater, /PriorityClass\s*=\s*\n\s*\[Diagnostics\.ProcessPriorityClass\]::BelowNormal/); + assert.match(updater, /Installer is still running after timeout; no relaunch or rollback/); + assert.match(updater, /UPDATED_EXE_FAILED_TO_START/); + assert.match(native, /GetSystemMetrics \(SM_SHUTTINGDOWN\) == 0/); +}); + +test('Windows updater executes byte-level offline stage integrity fixtures', () => { + const updater = read('installer/ArSonMixAutoUpdate.ps1'); + const smoke = read('scripts/test_inno_graceful_update_windows.ps1'); + assert.match(updater, /function Test-StagedAsset\(/); + assert.match(updater, /Test-StagedAsset \$newPath \$state\.newAsset/); + assert.match(updater, /Test-StagedAsset \$oldPath \$state\.previousAsset/); + assert.doesNotMatch(updater, /foreach\(\$pair in @\(@\(/); + assert.match(updater, /Tampered staged EXE accepted/); + assert.match(updater, /Short staged EXE accepted/); + assert.match(updater, /Missing staged EXE accepted/); + assert.match(updater, /ARSONMIX_UPDATER_STAGED_INTEGRITY_PASS/); + assert.match(smoke, /ARSONMIX_UPDATER_STAGED_INTEGRITY_PASS/); +}); + +test('updater recovers after crash and offers only verified same-version repair', () => { + const s = read('installer/ArSonMixAutoUpdate.ps1'); + for (const rule of [ + 'Get-InstalledImageStatus', 'exeSha256', 'guiExeBytes', + 'Classify-InterruptedTransaction', 'previous-retained', + 'candidate-unverified', 'INVALID_UPDATER_STATE_QUARANTINED', + "operation='repair'", 'STAGING_VERIFIED_SAME_VERSION_REPAIR', + 'Clear-StagedVendorFiles', 'ARSONMIX_UPDATER_SELF_REPAIR_POLICY_PASS', + 'TotalMinutes -lt 20', 'TotalHours -lt 6' + ]) assert.ok(s.includes(rule), rule); + assert.doesNotMatch(s, /Remove-Item -LiteralPath \$stage -Recurse/); + assert.doesNotMatch(s, /\bunins000\.exe\b/); +}); + +test('cached installers are byte-verified and revoked releases cannot loop indefinitely', () => { + const ps = read('installer/ArSonMixAutoUpdate.ps1'); + const smoke = read('scripts/test_inno_graceful_update_windows.ps1'); + for (const marker of [ + 'Test-CompleteStagedTransaction', 'STAGED_CACHE_INVALID_REDOWNLOAD', + 'STAGED_READY_FOR_NORMAL_EXIT', 'RELEASE_REVOKED_UPDATE_DEFERRED', + 'ARSONMIX_UPDATER_CACHE_AND_RECOVERY_PASS' + ]) assert.ok(ps.includes(marker), marker); + assert.match(smoke, /ARSONMIX_UPDATER_CACHE_AND_RECOVERY_PASS/); +}); + +test('transient Inno failure allows one delayed retry, never a reinstall loop', () => { + const ps = read('installer/ArSonMixAutoUpdate.ps1'); + const smoke = read('scripts/test_inno_graceful_update_windows.ps1'); + for (const x of ['Should-RetryInstaller','installAttempts','retryAfterUtc','AddMinutes(30)', + 'INSTALLER_RETRY_DEFERRED_COOLDOWN','INSTALLER_TRANSIENT_FAILURE_RETRY_NEXT_EXIT', + 'ARSONMIX_UPDATER_RETRY_POLICY_PASS']) assert.ok(ps.includes(x), x); + assert.match(smoke,/ARSONMIX_UPDATER_RETRY_POLICY_PASS/); +}); + +test('Windows Inno fixture proves unattended in-place repair after binary corruption', () => { + const smoke = read('scripts/test_inno_graceful_update_windows.ps1'); + assert.match(smoke,/INNO_AUTO_REPAIR_CORRUPT_EXE_PASS/); + assert.match(smoke,/Same-version repair did not restore verified EXE/); + assert.match(smoke,/Same-version repair erased Studio or install-local user files/); +}); + +test('one-click recovery can restore main EXE without a live app', () => { + const updater = read('installer/ArSonMixAutoUpdate.ps1'); + assert.match(iss, /Name: "\{autoprograms\}\\Repair ArSonMix"/); + assert.match(iss, /-RecoveryMode/); + assert.match(iss, /function IsArSonMixRecovery: Boolean;/); + assert.match(iss, /if not FileExists\(Target\) and not IsArSonMixRecovery then/); + assert.match(updater, /\[switch\]\$RecoveryMode/); + assert.match(updater, /Restore-InstalledRelease/); + assert.match(updater, /-AllowMissingExeRecovery/); + assert.match(updater, /\/ARSONMIXRECOVERY/); + assert.match(updater, /ABANDONED_MUTEX_RECLAIMED/); + assert.match(updater, /Test-NoActiveMixer/); + assert.match(isolatedSmoke, /INNO_MISSING_EXE_RECOVERY_PASS/); + assert.doesNotMatch(updater, /\bStop-Process\b|\btaskkill\b/); +}); + +test('updater script has one coherent main try/finally and no duplicated tail', () => { + const script = read('installer/ArSonMixAutoUpdate.ps1').replace(/\r\n/g, '\n'); + const tail = [ + '} finally {', + ' if($locked -and $null -ne $mutex){$mutex.ReleaseMutex()}', + ' if($null -ne $mutex){$mutex.Dispose()}', + '}', + ].join('\n'); + assert.equal(script.split(tail).length - 1, 1, 'duplicate main-script terminator'); + assert.ok(script.trimEnd().endsWith(tail), 'script has garbage after terminator'); + assert.equal(script.split('function Restore-InstalledRelease').length - 1, 1); + assert.equal(script.split('if($PolicySelfTest)').length - 1, 1); +}); + +test('healthy install, repair and rollback require real EXE SHA, not provenance commit alone', () => { + const script = read('installer/ArSonMixAutoUpdate.ps1'); + const smoke = read('scripts/test_inno_graceful_update_windows.ps1'); + assert.match(script, /function Test-InstalledRelease\(/); + assert.match(script, /Get-InstalledImageStatus \$manifest/); + assert.match(script, /Repair did not restore exact authenticated EXE and source manifest/); + assert.match(script, /if\(\$upgradeOK -and \(Test-InstalledRelease/); + assert.match(script, /if\(Test-InstalledRelease \$installedSha\)/); + assert.match(script, /GUI_READY' -and\s*\n\s*\(Test-InstalledRelease \$expectedSha\)/); + assert.match(script, /Same source with changed EXE accepted/); + assert.match(smoke, /ARSONMIX_UPDATER_EXACT_IMAGE_POLICY_PASS/); +}); + +test('two genuine release installers upgrade and roll back only in disposable Windows FAT', () => { + const real = read('scripts/test_two_genuine_inno_releases_windows.ps1'); + const ci = read('.github/workflows/p1-windows.yml'); + assert.match(real, /REAL_RELEASE_FAT_REQUIRES_DISPOSABLE_GITHUB_WINDOWS_RUNNER/); + assert.match(real, /v0\.5\.0-alpha\.4/); + assert.match(real, /v0\.5\.0-alpha\.5/); + assert.match(real, /GENUINE_RELEASE_BASELINE_PASS/); + assert.match(real, /GENUINE_RELEASE_UPGRADE_PASS/); + assert.match(real, /GENUINE_RELEASE_ROLLBACK_PASS/); + assert.match(real, /INSTALLER_PROVENANCE\.json/); + assert.match(real, /SHA256SUMS\.txt/); + assert.match(real, /sourceCommit/); + assert.match(real, /exeSha256/); + assert.match(real, /guiExeBytes/); + assert.match(real, /proof-user-session\.smix/); + assert.match(ci, /Prove two authentic historical Inno releases upgrade and roll back/); + assert.match(ci, /scripts\/test_two_genuine_inno_releases_windows\.ps1/); + assert.doesNotMatch(real, /(?:Stop-Process|taskkill|Remove-Item\s+-LiteralPath\s+\$install\s+-Recurse)/); +}); + +test('auto apply authenticates the published rollback asset as well as the new release', () => { + const source = read('installer/ArSonMixAutoUpdate.ps1'); + assert.match(source, /\$approvedOld=Approved-Installer \$release/); + assert.match(source, /\$release\.tag_name -ceq \$state\.previousTag/); + assert.match(source, /\$release\.target_commitish -ceq \$state\.previousSha/); + assert.match(source, /\$approvedOld\.name -cne \$state\.previousAsset\.name/); + assert.match(source, /\$approvedOld\.digest -cne \$state\.previousAsset\.digest/); + assert.match(source, /ROLLBACK_RELEASE_UNAVAILABLE_UPDATE_DEFERRED/); + assert.ok(source.indexOf('ROLLBACK_RELEASE_UNAVAILABLE_UPDATE_DEFERRED') < + source.indexOf("$state.phase='installing'")); +}); + +test('updater enumerates GitHub JSON release arrays correctly in Windows PowerShell 5.1', () => { + const script=read('installer/ArSonMixAutoUpdate.ps1'); + assert.doesNotMatch(script, /@\(\s*Invoke-RestMethod -Uri \$api/); + for (const name of ['releases','liveReleases']) { + assert.match(script, new RegExp('\\$'+name+'=Invoke-RestMethod -Uri \\$api')); + } + assert.match(script, /foreach\(\$release in \$releases\)/); + assert.match(script, /foreach\(\$release in \$liveReleases\)/); +}); +test('WebView2 error screen cannot acknowledge healthy GUI; staging retries after 20m', () => { + const script=read('installer/ArSonMixAutoUpdate.ps1'); + const native=read('src/Main.cpp'); + assert.match(native,/if \(stage == 2 && probe\.length\(\) == 36/); + assert.match(native,/if \(stage >= 2\)/); // still dismiss error splash + assert.match(native,/onStartupStage_ \(3\)/); // error stage must not set marker + assert.match(script, /\$state\.phase='staging-retry'\s*\n\s*\$state\.lastCheckUtc=''/); + assert.match(script, /\$state\.phase='staged'\s*\n\s*\$state\.lastCheckUtc=\[DateTime\]::UtcNow\.ToString\('o'\)/); + assert.match(script, /TotalMinutes -lt 20/); +});