From e3b1bbde77c991e39409b61594b4e1520bb7a216 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 23:53:05 +0700 Subject: [PATCH 01/62] feat(updater): independent release-verified staging and exit-safe Inno supervisor --- installer/ArSonMixAutoUpdate.ps1 | 318 +++++++++++++++++++++++++++++++ 1 file changed, 318 insertions(+) create mode 100644 installer/ArSonMixAutoUpdate.ps1 diff --git a/installer/ArSonMixAutoUpdate.ps1 b/installer/ArSonMixAutoUpdate.ps1 new file mode 100644 index 000000000..703603894 --- /dev/null +++ b/installer/ArSonMixAutoUpdate.ps1 @@ -0,0 +1,318 @@ +# 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([Parameter(Mandatory=$true)][ValidateRange(1,2147483647)][int]$OwnerProcessId) +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 + +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 + $input=$null + $output=$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'} + $input=$response.GetResponseStream() + $output=[IO.File]::Open($part,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::None) + $buffer=New-Object byte[] 65536 + [int64]$total=0 + while(($read=$input.Read($buffer,0,$buffer.Length)) -gt 0) { + $total+=$read + if($total -gt $expectedBytes){Fail 'Response larger than release metadata'} + $output.Write($buffer,0,$read) + } + $output.Flush($true) + $output.Dispose();$output=$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 $output){$output.Dispose()} + if($null -ne $input){$input.Dispose()} + if($null -ne $response){$response.Dispose()} + if(Test-Path -LiteralPath $part){Remove-Item -LiteralPath $part -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 Run-Installer([string]$file) { + # 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 /DIR="'+$PSScriptRoot+'"' + $info.UseShellExecute=$false + $info.CreateNoWindow=$true + $process=[Diagnostics.Process]::Start($info) + if($null -eq $process){return $false} + try { + if(-not $process.WaitForExit(120000)){return $false} + 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 + $process=[Diagnostics.Process]::Start($info) + 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 + (Read-Json $provenance).sourceCommit -ceq $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 + } +} +try { + if(-not (Test-Path -LiteralPath $exe -PathType Leaf) -or + -not (Test-Path -LiteralPath $provenance -PathType Leaf) -or + -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=New-Object Threading.Mutex($false,'Local\ArSonMix.AutoUpdater.v1') + $locked=$mutex.WaitOne(0) + 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}$'){exit 0} + $state=[pscustomobject]@{lastCheckUtc='';blockedTag='';lastInstalledTag='';phase='idle'} + if(Test-Path -LiteralPath $statePath -PathType Leaf) { + $read=Read-Json $statePath + foreach($key in @('lastCheckUtc','blockedTag','lastInstalledTag','phase')) { + if($read.PSObject.Properties.Name -contains $key){$state.$key=$read.$key} + } + } + if($state.lastCheckUtc) { + $checked=[DateTime]::MinValue + if([DateTime]::TryParse([string]$state.lastCheckUtc,[ref]$checked) -and + [DateTime]::UtcNow.Subtract($checked.ToUniversalTime()).TotalHours -lt 6 -and + [DateTime]::UtcNow -ge $checked.ToUniversalTime()) {exit 0} + } + $state.lastCheckUtc=[DateTime]::UtcNow.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) + $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 + } + } + if($null -eq $new){Log-Result 'UP_TO_DATE';exit 0} + 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) + Download-Verified $newAsset $newPath + # Rollback must be possible offline. Do not begin update without a + # byte-verified previous installer. + Download-Verified $oldAsset $oldPath + $state.phase='staged' + Write-State $state + Log-Result ('STAGED '+$new.tag_name+' WAITING_FOR_NORMAL_EXIT') + # 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(43200000)) {exit 0} # 12h cap + } 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' + Write-State $state + if(-not (Run-Installer $newPath)) {Fail 'Silent Inno upgrade failed or timed out'} + if((Read-Json $provenance).sourceCommit -cne $new.target_commitish) {Fail 'Installed provenance differs from selected release'} + if(Launch-WithHealth ([string]$new.target_commitish)) { + $state.lastInstalledTag=$new.tag_name + $state.phase='idle' + $state.blockedTag='' + Write-State $state + Log-Result ('HEALTHY '+$new.tag_name) + Remove-Item -LiteralPath $oldPath,$newPath -Force -ErrorAction SilentlyContinue + exit 0 + } + # 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='health-failed' + Write-State $state + 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()} + } + # Roll back by running the previously authenticated Inno installer, + # not by copying arbitrary stale binaries over an installed application. + if(Run-Installer $oldPath) { + if((Read-Json $provenance).sourceCommit -ceq $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 { + Log-Result ('FAIL_CLOSED '+$_.Exception.Message) +} finally { + if($locked -and $null -ne $mutex){$mutex.ReleaseMutex()} + if($null -ne $mutex){$mutex.Dispose()} +} From 418df8fcbd59ae8aa0167f43d3b60ec715724910 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 23:54:29 +0700 Subject: [PATCH 02/62] feat(updater): install external supervisor next to verified native EXE --- installer/ArSonMix.iss | 2 ++ 1 file changed, 2 insertions(+) diff --git a/installer/ArSonMix.iss b/installer/ArSonMix.iss index 351c88d69..bea91e76b 100644 --- a/installer/ArSonMix.iss +++ b/installer/ArSonMix.iss @@ -45,6 +45,8 @@ 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 From d36040860244638d82fdebd2efc8da5d3513b404 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 23:54:33 +0700 Subject: [PATCH 03/62] feat(updater): launch non-audio supervisor and acknowledge GUI startup --- src/Main.cpp | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/src/Main.cpp b/src/Main.cpp index e7b88e1a8..c9ba6e630 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -5146,9 +5146,58 @@ 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 (probe.length() == 36 && juce::Uuid (probe).toString() == 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) + // An installed (not portable) preview checks official GitHub Releases + // in its own short-lived supervisor process. It only installs AFTER + // this GUI has exited normally. No audio callback, router or FX work. + 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())) }; + 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 // Opaque cover exactly matches the large HWND, not a small 740×420 // card leaving white WebView2 edges exposed during first paint. if (splash_ && window_) From 430ed2aa97854a64394f10326b6f6091185181e9 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 23:58:04 +0700 Subject: [PATCH 04/62] fix(updater): cross-check release checksum/provenance and handle failed installs safely --- installer/ArSonMixAutoUpdate.ps1 | 88 ++++++++++++++++++++++++++++---- 1 file changed, 79 insertions(+), 9 deletions(-) diff --git a/installer/ArSonMixAutoUpdate.ps1 b/installer/ArSonMixAutoUpdate.ps1 index 703603894..c9b259de8 100644 --- a/installer/ArSonMixAutoUpdate.ps1 +++ b/installer/ArSonMixAutoUpdate.ps1 @@ -2,7 +2,8 @@ # 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([Parameter(Mandatory=$true)][ValidateRange(1,2147483647)][int]$OwnerProcessId) +param([Parameter(Mandatory=$true)][ValidateRange(1,2147483647)][int]$OwnerProcessId, + [switch]$PolicySelfTest) Set-StrictMode -Version Latest $ErrorActionPreference='Stop' [Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12 @@ -131,6 +132,28 @@ function Download-Verified([object]$asset,[string]$destination) { 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 Owns-Exe([int]$processId) { try { $process=[Diagnostics.Process]::GetProcessById($processId) @@ -190,6 +213,42 @@ function Launch-WithHealth([string]$expectedSha) { 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'} + Write-Output 'ARSONMIX_UPDATER_POLICY_PASS' + exit 0 +} + try { if(-not (Test-Path -LiteralPath $exe -PathType Leaf) -or -not (Test-Path -LiteralPath $provenance -PathType Leaf) -or @@ -197,7 +256,7 @@ try { # 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=New-Object Threading.Mutex($false,'Local\ArSonMix.AutoUpdater.v1') + $mutex=[Threading.Mutex]::new($false,'Local\ArSonMix.AutoUpdater.v1') $locked=$mutex.WaitOne(0) if(-not $locked){exit 0} [IO.Directory]::CreateDirectory($root) | Out-Null @@ -215,7 +274,8 @@ try { $checked=[DateTime]::MinValue if([DateTime]::TryParse([string]$state.lastCheckUtc,[ref]$checked) -and [DateTime]::UtcNow.Subtract($checked.ToUniversalTime()).TotalHours -lt 6 -and - [DateTime]::UtcNow -ge $checked.ToUniversalTime()) {exit 0} + [DateTime]::UtcNow -ge $checked.ToUniversalTime() -and + $state.phase -cne 'staged') {exit 0} } $state.lastCheckUtc=[DateTime]::UtcNow.ToString('o') Write-State $state @@ -248,10 +308,10 @@ try { $stage=Join-Path $root 'stage' $oldPath=Join-Path $stage ([string]$oldAsset.name) $newPath=Join-Path $stage ([string]$newAsset.name) - Download-Verified $newAsset $newPath + Download-Release-Verified $new $newAsset $newPath # Rollback must be possible offline. Do not begin update without a # byte-verified previous installer. - Download-Verified $oldAsset $oldPath + Download-Release-Verified $current $oldAsset $oldPath $state.phase='staged' Write-State $state Log-Result ('STAGED '+$new.tag_name+' WAITING_FOR_NORMAL_EXIT') @@ -275,9 +335,11 @@ try { if((Read-Json $provenance).sourceCommit -cne $installedSha) {Log-Result 'DEFER_VERSION_CHANGED';exit 0} $state.phase='installing' Write-State $state - if(-not (Run-Installer $newPath)) {Fail 'Silent Inno upgrade failed or timed out'} - if((Read-Json $provenance).sourceCommit -cne $new.target_commitish) {Fail 'Installed provenance differs from selected release'} - if(Launch-WithHealth ([string]$new.target_commitish)) { + $upgradeOK=Run-Installer $newPath + $actualSha='' + try {$actualSha=[string](Read-Json $provenance).sourceCommit} catch {} + if($upgradeOK -and $actualSha -ceq $new.target_commitish -and + (Launch-WithHealth ([string]$new.target_commitish))) { $state.lastInstalledTag=$new.tag_name $state.phase='idle' $state.blockedTag='' @@ -286,11 +348,19 @@ try { Remove-Item -LiteralPath $oldPath,$newPath -Force -ErrorAction SilentlyContinue 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='health-failed' + $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, From 0a0cc9d0fd5325bae7a2d59077b5217154f88b92 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 23:59:19 +0700 Subject: [PATCH 05/62] test(updater): preserve native packaging and no-audio safety contracts --- tests/windows_installer_contract_test.mjs | 26 +++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/tests/windows_installer_contract_test.mjs b/tests/windows_installer_contract_test.mjs index 7ba654b07..47e2edbd6 100644 --- a/tests/windows_installer_contract_test.mjs +++ b/tests/windows_installer_contract_test.mjs @@ -112,3 +112,29 @@ 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/); + 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\(43200000\)/); + 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\(/); +}); From 1f68069eb7da4db85d30ee340bf021b3b3e61a19 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 9 Nov 2026 23:59:22 +0700 Subject: [PATCH 06/62] test(updater): execute offline PowerShell policy gate on Windows --- scripts/test_inno_graceful_update_windows.ps1 | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/scripts/test_inno_graceful_update_windows.ps1 b/scripts/test_inno_graceful_update_windows.ps1 index 831bddb11..5278ac7a7 100644 --- a/scripts/test_inno_graceful_update_windows.ps1 +++ b/scripts/test_inno_graceful_update_windows.ps1 @@ -2,6 +2,15 @@ # 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'){ + 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")) From 02314be759d30737590cc1d8d342b77bd6231292 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 00:01:04 +0700 Subject: [PATCH 07/62] docs(updater): formalize live-safe release trust, bootstrap, recovery, and FAT gates --- docs/ADR_SMART_AUTO_UPDATER_20261109.md | 35 +++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 docs/ADR_SMART_AUTO_UPDATER_20261109.md diff --git a/docs/ADR_SMART_AUTO_UPDATER_20261109.md b/docs/ADR_SMART_AUTO_UPDATER_20261109.md new file mode 100644 index 000000000..540116660 --- /dev/null +++ b/docs/ADR_SMART_AUTO_UPDATER_20261109.md @@ -0,0 +1,35 @@ +# 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. +5. Wait up to 12 hours 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. Inno alone handles its normal exact-image shutdown safety checks in case of races. +6. Run the existing per-user Inno installer silently. 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. 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 consequence is that a user who never closes the app does not receive an update; the next launch rechecks and can use staged assets. 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 worker; 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. 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 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), and Inno's graceful/legacy/hung update fixtures. +- 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. From 7e22137e26e262bb64ba64deee52a61c0c71b410 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 00:02:15 +0700 Subject: [PATCH 08/62] fix(updater): avoid PowerShell automatic variable collision and keep failure-blocked state --- installer/ArSonMixAutoUpdate.ps1 | 36 +++++++++++++++++++++----------- 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/installer/ArSonMixAutoUpdate.ps1 b/installer/ArSonMixAutoUpdate.ps1 index c9b259de8..5957af09e 100644 --- a/installer/ArSonMixAutoUpdate.ps1 +++ b/installer/ArSonMixAutoUpdate.ps1 @@ -100,8 +100,8 @@ function Download-Verified([object]$asset,[string]$destination) { $request.AllowAutoRedirect=$true $request.MaximumAutomaticRedirections=5 $response=$null - $input=$null - $output=$null + $streamIn=$null + $streamOut=$null try { $response=$request.GetResponse() $uri=$response.ResponseUri @@ -110,24 +110,24 @@ function Download-Verified([object]$asset,[string]$destination) { Fail 'Unexpected download redirect destination' } if($response.ContentLength -gt $expectedBytes){Fail 'Oversize release response'} - $input=$response.GetResponseStream() - $output=[IO.File]::Open($part,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::None) + $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=$input.Read($buffer,0,$buffer.Length)) -gt 0) { + while(($read=$streamIn.Read($buffer,0,$buffer.Length)) -gt 0) { $total+=$read if($total -gt $expectedBytes){Fail 'Response larger than release metadata'} - $output.Write($buffer,0,$read) + $streamOut.Write($buffer,0,$read) } - $output.Flush($true) - $output.Dispose();$output=$null + $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 $output){$output.Dispose()} - if($null -ne $input){$input.Dispose()} + 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} } @@ -345,7 +345,7 @@ try { $state.blockedTag='' Write-State $state Log-Result ('HEALTHY '+$new.tag_name) - Remove-Item -LiteralPath $oldPath,$newPath -Force -ErrorAction SilentlyContinue + Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction SilentlyContinue exit 0 } # An installer failure leaves the previous app intact or may be partial. @@ -380,7 +380,19 @@ try { } } Fail 'Health failed and verified rollback installer did not restore old source' -} catch { + } 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()} From bc14efef36d9a62c3cc829f9e5f3b84d149f1ac5 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 00:10:51 +0700 Subject: [PATCH 09/62] perf(updater): split short-lived release checker from post-close install supervisor --- installer/ArSonMixAutoUpdate.ps1 | 236 ++++++++++++++++++++++++++++++- 1 file changed, 231 insertions(+), 5 deletions(-) diff --git a/installer/ArSonMixAutoUpdate.ps1 b/installer/ArSonMixAutoUpdate.ps1 index 5957af09e..c528b30a0 100644 --- a/installer/ArSonMixAutoUpdate.ps1 +++ b/installer/ArSonMixAutoUpdate.ps1 @@ -3,7 +3,8 @@ # Independent of JUCE/audio callback; starts from an installed GUI only. # Downloads while the host is active; applies ONLY after normal host exit. param([Parameter(Mandatory=$true)][ValidateRange(1,2147483647)][int]$OwnerProcessId, - [switch]$PolicySelfTest) + [switch]$PolicySelfTest, + [switch]$ApplyStaged) Set-StrictMode -Version Latest $ErrorActionPreference='Stop' [Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12 @@ -252,24 +253,27 @@ if($PolicySelfTest) { try { if(-not (Test-Path -LiteralPath $exe -PathType Leaf) -or -not (Test-Path -LiteralPath $provenance -PathType Leaf) -or - -not (Owns-Exe $OwnerProcessId)) {exit 0} + (-not $ApplyStaged -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') - $locked=$mutex.WaitOne(0) + $locked=$mutex.WaitOne($(if($ApplyStaged){60000}else{0})) 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}$'){exit 0} - $state=[pscustomobject]@{lastCheckUtc='';blockedTag='';lastInstalledTag='';phase='idle'} + $state=[pscustomobject]@{lastCheckUtc='';blockedTag='';lastInstalledTag='';phase='idle'; + candidateTag='';candidateSha='';previousSha='';previousTag=''; + newAsset=$null;previousAsset=$null} if(Test-Path -LiteralPath $statePath -PathType Leaf) { $read=Read-Json $statePath - foreach($key in @('lastCheckUtc','blockedTag','lastInstalledTag','phase')) { + foreach($key in @('lastCheckUtc','blockedTag','lastInstalledTag','phase','candidateTag','candidateSha','previousSha','previousTag','newAsset','previousAsset')) { if($read.PSObject.Properties.Name -contains $key){$state.$key=$read.$key} } } + if(-not $ApplyStaged) { if($state.lastCheckUtc) { $checked=[DateTime]::MinValue if([DateTime]::TryParse([string]$state.lastCheckUtc,[ref]$checked) -and @@ -313,8 +317,230 @@ try { # byte-verified previous installer. Download-Release-Verified $current $oldAsset $oldPath $state.phase='staged' + $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 update checker, no long-running resident + # process while a real audio session is running. + if($state.phase -cne 'staged' -or $state.previousSha -cne $installedSha){exit 0} + if($state.candidateSha -cnotmatch '^[a-f0-9]{40} + # 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' + Write-State $state + $upgradeOK=Run-Installer $newPath + $actualSha='' + try {$actualSha=[string](Read-Json $provenance).sourceCommit} catch {} + if($upgradeOK -and $actualSha -ceq $new.target_commitish -and + (Launch-WithHealth ([string]$new.target_commitish))) { + $state.lastInstalledTag=$new.tag_name + $state.phase='idle' + $state.blockedTag='' + Write-State $state + Log-Result ('HEALTHY '+$new.tag_name) + Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction SilentlyContinue + 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()} + } + # Roll back by running the previously authenticated Inno installer, + # not by copying arbitrary stale binaries over an installed application. + if(Run-Installer $oldPath) { + if((Read-Json $provenance).sourceCommit -ceq $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()} +} + -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 + foreach($pair in @(@($newPath,$state.newAsset),@($oldPath,$state.previousAsset))) { + $path=[string]$pair[0] + $asset=$pair[1] + if($asset.digest -cnotmatch '^sha256:[a-f0-9]{64} + # 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(43200000)) {exit 0} # 12h cap + } 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' + Write-State $state + $upgradeOK=Run-Installer $newPath + $actualSha='' + try {$actualSha=[string](Read-Json $provenance).sourceCommit} catch {} + if($upgradeOK -and $actualSha -ceq $new.target_commitish -and + (Launch-WithHealth ([string]$new.target_commitish))) { + $state.lastInstalledTag=$new.tag_name + $state.phase='idle' + $state.blockedTag='' + Write-State $state + Log-Result ('HEALTHY '+$new.tag_name) + Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction SilentlyContinue + 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()} + } + # Roll back by running the previously authenticated Inno installer, + # not by copying arbitrary stale binaries over an installed application. + if(Run-Installer $oldPath) { + if((Read-Json $provenance).sourceCommit -ceq $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()} +} + -or + [long]$asset.size -lt 2097152 -or [long]$asset.size -gt 209715200 -or + -not (Test-Path -LiteralPath $path -PathType Leaf) -or + (Get-Item -LiteralPath $path).Length -ne [long]$asset.size -or + (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant() -cne + ([string]$asset.digest).Substring(7)) { + Fail 'Offline staged install/rollback bytes not verified' + } + } + # Revocation fence: do not execute a staged EXE from a release that is + # no longer publicly approved or whose digest/source changed. + $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 + foreach($release in $liveReleases) { + if($release.tag_name -ceq $state.candidateTag -and + $release.target_commitish -ceq $state.candidateSha) { + $approved=Approved-Installer $release + break + } + } + if($null -eq $approved -or $approved.digest -cne $state.newAsset.digest -or + [long]$approved.size -ne [long]$state.newAsset.size){ + Fail 'Published update was revoked or its asset identity changed' + } + $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 { From cb677f2913d57cfb9184f0fae8b70c933b993c45 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 00:13:27 +0700 Subject: [PATCH 10/62] perf(updater): short-lived checker and on-exit verified installer; eliminate resident watcher --- installer/ArSonMixAutoUpdate.ps1 | 183 ++----------------------------- 1 file changed, 7 insertions(+), 176 deletions(-) diff --git a/installer/ArSonMixAutoUpdate.ps1 b/installer/ArSonMixAutoUpdate.ps1 index c528b30a0..d17c32553 100644 --- a/installer/ArSonMixAutoUpdate.ps1 +++ b/installer/ArSonMixAutoUpdate.ps1 @@ -327,94 +327,9 @@ try { 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 update checker, no long-running resident - # process while a real audio session is running. + # Post-close supervisor: no resident updater during live audio. if($state.phase -cne 'staged' -or $state.previousSha -cne $installedSha){exit 0} - if($state.candidateSha -cnotmatch '^[a-f0-9]{40} - # 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' - Write-State $state - $upgradeOK=Run-Installer $newPath - $actualSha='' - try {$actualSha=[string](Read-Json $provenance).sourceCommit} catch {} - if($upgradeOK -and $actualSha -ceq $new.target_commitish -and - (Launch-WithHealth ([string]$new.target_commitish))) { - $state.lastInstalledTag=$new.tag_name - $state.phase='idle' - $state.blockedTag='' - Write-State $state - Log-Result ('HEALTHY '+$new.tag_name) - Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction SilentlyContinue - 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()} - } - # Roll back by running the previously authenticated Inno installer, - # not by copying arbitrary stale binaries over an installed application. - if(Run-Installer $oldPath) { - if((Read-Json $provenance).sourceCommit -ceq $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()} -} - -or + 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'} @@ -428,91 +343,7 @@ try { foreach($pair in @(@($newPath,$state.newAsset),@($oldPath,$state.previousAsset))) { $path=[string]$pair[0] $asset=$pair[1] - if($asset.digest -cnotmatch '^sha256:[a-f0-9]{64} - # 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(43200000)) {exit 0} # 12h cap - } 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' - Write-State $state - $upgradeOK=Run-Installer $newPath - $actualSha='' - try {$actualSha=[string](Read-Json $provenance).sourceCommit} catch {} - if($upgradeOK -and $actualSha -ceq $new.target_commitish -and - (Launch-WithHealth ([string]$new.target_commitish))) { - $state.lastInstalledTag=$new.tag_name - $state.phase='idle' - $state.blockedTag='' - Write-State $state - Log-Result ('HEALTHY '+$new.tag_name) - Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction SilentlyContinue - 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()} - } - # Roll back by running the previously authenticated Inno installer, - # not by copying arbitrary stale binaries over an installed application. - if(Run-Installer $oldPath) { - if((Read-Json $provenance).sourceCommit -ceq $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()} -} - -or + if($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) -or (Get-Item -LiteralPath $path).Length -ne [long]$asset.size -or @@ -521,8 +352,8 @@ try { Fail 'Offline staged install/rollback bytes not verified' } } - # Revocation fence: do not execute a staged EXE from a release that is - # no longer publicly approved or whose digest/source changed. + # 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) @@ -536,7 +367,7 @@ try { } if($null -eq $approved -or $approved.digest -cne $state.newAsset.digest -or [long]$approved.size -ne [long]$state.newAsset.size){ - Fail 'Published update was revoked or its asset identity changed' + Fail 'Published update revoked or changed' } $new=[pscustomobject]@{tag_name=$state.candidateTag;target_commitish=$state.candidateSha} $oldAsset=$state.previousAsset @@ -546,7 +377,7 @@ try { try { $hostProcess=[Diagnostics.Process]::GetProcessById($OwnerProcessId) try { - if(-not $hostProcess.WaitForExit(43200000)) {exit 0} # 12h cap + 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. From a85b5954e07abf5b5a4a8c720b0dd4ecc717c985 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 00:14:15 +0700 Subject: [PATCH 11/62] perf(updater): run short-lived checker at startup and apply staged update after normal shutdown --- src/Main.cpp | 69 ++++++++++++++++++++++++++++++++-------------------- 1 file changed, 42 insertions(+), 27 deletions(-) diff --git a/src/Main.cpp b/src/Main.cpp index 2cbf3995c..d95e4a764 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -5231,33 +5231,7 @@ class ConsoleApp final : public juce::JUCEApplication, private juce::Timer } }); #if defined(_WIN32) - // An installed (not portable) preview checks official GitHub Releases - // in its own short-lived supervisor process. It only installs AFTER - // this GUI has exited normally. No audio callback, router or FX work. - 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())) }; - 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); - } + launchSmartUpdater (false); #endif // Opaque cover exactly matches the large HWND, not a small 740×420 // card leaving white WebView2 edges exposed during first paint. @@ -5273,6 +5247,13 @@ 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; + if (!innoIsClosing) + launchSmartUpdater (true); if (installerShutdownEvent_ != nullptr) { ::CloseHandle (installerShutdownEvent_); @@ -5286,6 +5267,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; From 0daf311d48918dbb1e7a7b2d4c5b0b7dff19bf0c Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 00:15:07 +0700 Subject: [PATCH 12/62] test(updater): enforce short-lived checker and on-exit apply --- tests/windows_installer_contract_test.mjs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/windows_installer_contract_test.mjs b/tests/windows_installer_contract_test.mjs index 47e2edbd6..1f2e961ea 100644 --- a/tests/windows_installer_contract_test.mjs +++ b/tests/windows_installer_contract_test.mjs @@ -127,7 +127,11 @@ test('Smart Auto Updater uses an independent process and strict release gates', assert.match(updater, /INSTALLER_PROVENANCE\.json/); assert.match(updater, /SHA256SUMS\.txt/); assert.match(updater, /Get-FileHash -LiteralPath \$part -Algorithm SHA256/); - assert.match(updater, /WaitForExit\(43200000\)/); + 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/); From 88ff4a42997e9e6fcf958da07c1c35923c31d226 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 00:15:10 +0700 Subject: [PATCH 13/62] docs(updater): describe no-resident-worker update flow and revocation check --- docs/ADR_SMART_AUTO_UPDATER_20261109.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/ADR_SMART_AUTO_UPDATER_20261109.md b/docs/ADR_SMART_AUTO_UPDATER_20261109.md index 540116660..25cc1ced0 100644 --- a/docs/ADR_SMART_AUTO_UPDATER_20261109.md +++ b/docs/ADR_SMART_AUTO_UPDATER_20261109.md @@ -7,19 +7,19 @@ Implementation branch: `feature/smart-auto-updater-safe-20261109`. Windows x64 * 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. -5. Wait up to 12 hours 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. Inno alone handles its normal exact-image shutdown safety checks in case of races. +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. Inno alone handles its normal exact-image shutdown safety checks in case of races. 6. Run the existing per-user Inno installer silently. 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. 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 consequence is that a user who never closes the app does not receive an update; the next launch rechecks and can use staged assets. The update may relaunch the GUI after a user intentionally quits. This is a documented tradeoff, not a promise of zero disruption. +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 worker; 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`. +- 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. 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. From 4ad19ad14305659440510f048331c1b5df23feea Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 00:26:08 +0700 Subject: [PATCH 14/62] fix(updater): correctly acknowledge dashed GUID health probe with pinned JUCE 8.0.15 --- src/Main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Main.cpp b/src/Main.cpp index d95e4a764..5376e8d52 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -5214,7 +5214,7 @@ class ConsoleApp final : public juce::JUCEApplication, private juce::Timer ("ARSONMIX_UPDATE_PROBE", {}); const auto localAppData = juce::SystemStats::getEnvironmentVariable ("LOCALAPPDATA", {}); - if (probe.length() == 36 && juce::Uuid (probe).toString() == probe + if (probe.length() == 36 && juce::Uuid (probe).toDashedString() == probe && localAppData.isNotEmpty()) { const auto healthDir = juce::File (localAppData) From 8c0f4591e61a2cc6db15293882d05b7a80d69c25 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 00:26:12 +0700 Subject: [PATCH 15/62] test(updater): lock GUID format across JUCE and PowerShell health signal --- tests/windows_installer_contract_test.mjs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/windows_installer_contract_test.mjs b/tests/windows_installer_contract_test.mjs index 1f2e961ea..7f6550483 100644 --- a/tests/windows_installer_contract_test.mjs +++ b/tests/windows_installer_contract_test.mjs @@ -122,6 +122,9 @@ test('Smart Auto Updater uses an independent process and strict release gates', 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/); From b6c66c7bf911f015668ace150e44627ea3b5ddd3 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 04:25:06 +0700 Subject: [PATCH 16/62] fix(updater): fail-closed auto installation, never request mixer shutdown --- installer/ArSonMix.iss | 52 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/installer/ArSonMix.iss b/installer/ArSonMix.iss index bea91e76b..799d626c3 100644 --- a/installer/ArSonMix.iss +++ b/installer/ArSonMix.iss @@ -96,6 +96,21 @@ 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 PrepareToInstall(var NeedsRestart: Boolean): String; var Target, HelperPath, PowerShellExe, Params: string; @@ -104,6 +119,43 @@ 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) then + begin + Result := 'Automatic update requires an existing ArSonMix installation.'; + Exit; + end; + 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 } From 3400604582736bd13c0d151030bbe81e8d3b104c Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 04:25:08 +0700 Subject: [PATCH 17/62] fix(updater): add exact-image read-only probe for automatic updates --- installer/ArSonMixUpdateShutdown.ps1 | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) 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. From 8967d779715c3cb04fcf8889a37efc350b4ac52d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 04:25:11 +0700 Subject: [PATCH 18/62] fix(updater): pass strict automatic setup mode --- installer/ArSonMixAutoUpdate.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/installer/ArSonMixAutoUpdate.ps1 b/installer/ArSonMixAutoUpdate.ps1 index d17c32553..5036b439d 100644 --- a/installer/ArSonMixAutoUpdate.ps1 +++ b/installer/ArSonMixAutoUpdate.ps1 @@ -170,7 +170,7 @@ function Run-Installer([string]$file) { 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 /DIR="'+$PSScriptRoot+'"' + $info.Arguments='/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /CURRENTUSER /NOCLOSEAPPLICATIONS /ARSONMIXAUTOUPDATE /DIR="'+$PSScriptRoot+'"' $info.UseShellExecute=$false $info.CreateNoWindow=$true $process=[Diagnostics.Process]::Start($info) From 78dd40f1a5dbe9236e1fb0e8cec7ba1d45a8ed81 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 04:25:13 +0700 Subject: [PATCH 19/62] fix(updater): cover automatic mode no-close guarantee --- tests/windows_installer_contract_test.mjs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tests/windows_installer_contract_test.mjs b/tests/windows_installer_contract_test.mjs index 7f6550483..eb2bfac09 100644 --- a/tests/windows_installer_contract_test.mjs +++ b/tests/windows_installer_contract_test.mjs @@ -145,3 +145,17 @@ test('Smart Auto Updater uses an independent process and strict release gates', 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/); +}); From 82e4465f6066af90646ab9c5251c4da23a220cb3 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 04:25:16 +0700 Subject: [PATCH 20/62] fix(updater): exercise active-session preservation in Windows Inno --- scripts/test_inno_graceful_update_windows.ps1 | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/scripts/test_inno_graceful_update_windows.ps1 b/scripts/test_inno_graceful_update_windows.ps1 index 5278ac7a7..7590adf91 100644 --- a/scripts/test_inno_graceful_update_windows.ps1 +++ b/scripts/test_inno_graceful_update_windows.ps1 @@ -103,6 +103,28 @@ try { Assert-Condition ((Get-FileHash -LiteralPath $installedExe -Algorithm SHA256).Hash -eq $fixtureHash) "Legacy upgrade changed verified EXE hash" Assert-Condition ((Test-Path -LiteralPath $userFile) -and (Test-Path -LiteralPath $privateSentinel)) "Legacy upgrade damaged Studio/user files" Write-Host "INNO_LEGACY_NO_HANDSHAKE_UPGRADE_PASS: exact exe process requested WM_CLOSE before replacement" + + # 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" + $fixtureProcess.CloseMainWindow() | Out-Null + Assert-Condition ($fixtureProcess.WaitForExit(10000)) "Auto-update test fixture did not close normally" + $fixtureProcess.Dispose();$fixtureProcess=$null $fixtureProcess.Dispose();$fixtureProcess=$null # Busy/hung GUI: it REFUSES WM_CLOSE and has no newer handshake. From 7470561d42cab538663730c95e0514a54b703745 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 04:26:06 +0700 Subject: [PATCH 21/62] test(updater): validate both live-session rejection and clean auto install --- scripts/test_inno_graceful_update_windows.ps1 | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/scripts/test_inno_graceful_update_windows.ps1 b/scripts/test_inno_graceful_update_windows.ps1 index 7590adf91..065933b1f 100644 --- a/scripts/test_inno_graceful_update_windows.ps1 +++ b/scripts/test_inno_graceful_update_windows.ps1 @@ -103,6 +103,7 @@ try { Assert-Condition ((Get-FileHash -LiteralPath $installedExe -Algorithm SHA256).Hash -eq $fixtureHash) "Legacy upgrade changed verified EXE hash" Assert-Condition ((Test-Path -LiteralPath $userFile) -and (Test-Path -LiteralPath $privateSentinel)) "Legacy upgrade damaged Studio/user files" 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]. @@ -125,7 +126,13 @@ try { $fixtureProcess.CloseMainWindow() | Out-Null Assert-Condition ($fixtureProcess.WaitForExit(10000)) "Auto-update test fixture did not close normally" $fixtureProcess.Dispose();$fixtureProcess=$null - $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" # Busy/hung GUI: it REFUSES WM_CLOSE and has no newer handshake. # Upgrade must fail before [Files], leave old EXE and Studio untouched. From a3cc27e0b8e94aa24301e05c06d75c56aa3705b0 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 04:27:56 +0700 Subject: [PATCH 22/62] fix(updater): prevent relaunch during timed-out installer; recover from EXE launch errors --- installer/ArSonMixAutoUpdate.ps1 | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/installer/ArSonMixAutoUpdate.ps1 b/installer/ArSonMixAutoUpdate.ps1 index 5036b439d..ec1b69d91 100644 --- a/installer/ArSonMixAutoUpdate.ps1 +++ b/installer/ArSonMixAutoUpdate.ps1 @@ -20,6 +20,9 @@ $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 { @@ -176,7 +179,11 @@ function Run-Installer([string]$file) { $process=[Diagnostics.Process]::Start($info) if($null -eq $process){return $false} try { - if(-not $process.WaitForExit(120000)){return $false} + 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()} } @@ -190,7 +197,8 @@ function Launch-WithHealth([string]$expectedSha) { $info.WorkingDirectory=$PSScriptRoot $info.UseShellExecute=$false $info.EnvironmentVariables['ARSONMIX_UPDATE_PROBE']=$token - $process=[Diagnostics.Process]::Start($info) + 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) From 53213761ff10f41318b8182ee33ed40659ee16c9 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 04:28:00 +0700 Subject: [PATCH 23/62] fix(updater): skip automatic update installation during Windows shutdown --- src/Main.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Main.cpp b/src/Main.cpp index 5376e8d52..010a193c4 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -5252,7 +5252,10 @@ class ConsoleApp final : public juce::JUCEApplication, private juce::Timer // not launch a competing installer. const bool innoIsClosing = installerShutdownEvent_ != nullptr && ::WaitForSingleObject (installerShutdownEvent_, 0) == WAIT_OBJECT_0; - if (!innoIsClosing) + // 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) { From a38c667c51a73dcd456b713937a8d531c724f318 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 04:28:02 +0700 Subject: [PATCH 24/62] fix(updater): lock installer timeout, shutdown and resource-priority contracts --- tests/windows_installer_contract_test.mjs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/windows_installer_contract_test.mjs b/tests/windows_installer_contract_test.mjs index eb2bfac09..072ac2317 100644 --- a/tests/windows_installer_contract_test.mjs +++ b/tests/windows_installer_contract_test.mjs @@ -159,3 +159,13 @@ test('automatic Inno update never closes a newly active mixer', () => { 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/); +}); From 531093a2885ef090422656374f5651f79aa250d7 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 04:29:00 +0700 Subject: [PATCH 25/62] test(updater): close legacy fixture using proven exact-path helper after no-close assertion --- scripts/test_inno_graceful_update_windows.ps1 | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/scripts/test_inno_graceful_update_windows.ps1 b/scripts/test_inno_graceful_update_windows.ps1 index 065933b1f..4996c3811 100644 --- a/scripts/test_inno_graceful_update_windows.ps1 +++ b/scripts/test_inno_graceful_update_windows.ps1 @@ -123,8 +123,12 @@ try { 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" - $fixtureProcess.CloseMainWindow() | Out-Null - Assert-Condition ($fixtureProcess.WaitForExit(10000)) "Auto-update test fixture did not close normally" + # 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. From c9cee93b95aee67500f9b51ece9c337f52d948f8 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 04:32:26 +0700 Subject: [PATCH 26/62] test(updater): extract staged integrity predicate and verify tampering offline --- installer/ArSonMixAutoUpdate.ps1 | 40 +++++++++++++++++++++++++++----- 1 file changed, 34 insertions(+), 6 deletions(-) diff --git a/installer/ArSonMixAutoUpdate.ps1 b/installer/ArSonMixAutoUpdate.ps1 index ec1b69d91..6151b30a9 100644 --- a/installer/ArSonMixAutoUpdate.ps1 +++ b/installer/ArSonMixAutoUpdate.ps1 @@ -158,6 +158,17 @@ function Download-Release-Verified([object]$release,[object]$installer,[string]$ 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 Owns-Exe([int]$processId) { try { $process=[Diagnostics.Process]::GetProcessById($processId) @@ -254,6 +265,28 @@ if($PolicySelfTest) { $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 + [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} + } + Write-Output 'ARSONMIX_UPDATER_STAGED_INTEGRITY_PASS' Write-Output 'ARSONMIX_UPDATER_POLICY_PASS' exit 0 } @@ -351,12 +384,7 @@ try { foreach($pair in @(@($newPath,$state.newAsset),@($oldPath,$state.previousAsset))) { $path=[string]$pair[0] $asset=$pair[1] - if($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) -or - (Get-Item -LiteralPath $path).Length -ne [long]$asset.size -or - (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant() -cne - ([string]$asset.digest).Substring(7)) { + if(-not (Test-StagedAsset $path $asset)) { Fail 'Offline staged install/rollback bytes not verified' } } From f7ad3fbe5298426f9a527fe70c46232ae4d1af1d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 04:32:29 +0700 Subject: [PATCH 27/62] test(updater): require actual staged integrity fixtures --- tests/windows_installer_contract_test.mjs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tests/windows_installer_contract_test.mjs b/tests/windows_installer_contract_test.mjs index 072ac2317..c2e3679ac 100644 --- a/tests/windows_installer_contract_test.mjs +++ b/tests/windows_installer_contract_test.mjs @@ -169,3 +169,15 @@ test('auto updater cannot race a still-running installer or Windows shutdown', ( 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, /if\(-not \(Test-StagedAsset \$path \$asset\)\)/); + 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/); +}); From da06e57f5baeb31e6dfd5d9fec2f6cbf101b1a2e Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 04:32:31 +0700 Subject: [PATCH 28/62] test(updater): run staged EXE hash and size policy test on Windows --- scripts/test_inno_graceful_update_windows.ps1 | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/test_inno_graceful_update_windows.ps1 b/scripts/test_inno_graceful_update_windows.ps1 index 4996c3811..00621e441 100644 --- a/scripts/test_inno_graceful_update_windows.ps1 +++ b/scripts/test_inno_graceful_update_windows.ps1 @@ -6,7 +6,8 @@ Set-StrictMode -Version Latest # 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'){ +if($LASTEXITCODE -ne 0 -or $policyOutput -notcontains 'ARSONMIX_UPDATER_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" From 5b79af41ba5196163c815ff8f4e3821fcc72f6d5 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 04:33:17 +0700 Subject: [PATCH 29/62] docs(updater): capture noninterrupting auto mode, staged tamper fixtures and rollback limits --- docs/ADR_SMART_AUTO_UPDATER_20261109.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/ADR_SMART_AUTO_UPDATER_20261109.md b/docs/ADR_SMART_AUTO_UPDATER_20261109.md index 25cc1ced0..da39b0514 100644 --- a/docs/ADR_SMART_AUTO_UPDATER_20261109.md +++ b/docs/ADR_SMART_AUTO_UPDATER_20261109.md @@ -8,9 +8,9 @@ Implementation branch: `feature/smart-auto-updater-safe-20261109`. Windows x64 * 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. Inno alone handles its normal exact-image shutdown safety checks in case of races. -6. Run the existing per-user Inno installer silently. 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. 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. +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. @@ -20,14 +20,14 @@ The update trusts HTTPS to the official GitHub API, immutable release source ide ## 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. Private `.smix`, Studio data and user VSTs are never deleted by the updater. +- 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 running, non-responsive GUI is left intact instead of force-killed. Never promise mathematically impossible “no crash”. +- 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), and Inno's graceful/legacy/hung update fixtures. +- 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. From 37d692313a46a2ef8310db8b5fc3433852c620a9 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 05:17:37 +0700 Subject: [PATCH 30/62] feat(updater): recover interrupted state, verify in-place self-repair and bound network retries --- docs/ADR_SMART_AUTO_UPDATER_20261109.md | 7 ++ installer/ArSonMixAutoUpdate.ps1 | 123 +++++++++++++++++++--- tests/windows_installer_contract_test.mjs | 14 +++ 3 files changed, 129 insertions(+), 15 deletions(-) diff --git a/docs/ADR_SMART_AUTO_UPDATER_20261109.md b/docs/ADR_SMART_AUTO_UPDATER_20261109.md index da39b0514..ff33dfdd2 100644 --- a/docs/ADR_SMART_AUTO_UPDATER_20261109.md +++ b/docs/ADR_SMART_AUTO_UPDATER_20261109.md @@ -33,3 +33,10 @@ The update trusts HTTPS to the official GitHub API, immutable release source ide ## 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. diff --git a/installer/ArSonMixAutoUpdate.ps1 b/installer/ArSonMixAutoUpdate.ps1 index 6151b30a9..03290af0b 100644 --- a/installer/ArSonMixAutoUpdate.ps1 +++ b/installer/ArSonMixAutoUpdate.ps1 @@ -169,6 +169,35 @@ function Test-StagedAsset([string]$path,[object]$asset) { ([string]$asset.digest).Substring(7) } catch {return $false} } + +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 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 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) @@ -281,11 +310,31 @@ if($PolicySelfTest) { $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'} + $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} } + Write-Output 'ARSONMIX_UPDATER_SELF_REPAIR_POLICY_PASS' Write-Output 'ARSONMIX_UPDATER_STAGED_INTEGRITY_PASS' Write-Output 'ARSONMIX_UPDATER_POLICY_PASS' exit 0 @@ -305,28 +354,54 @@ try { $file=Read-Json $provenance $installedSha=[string]$file.sourceCommit if($installedSha -cnotmatch '^[a-f0-9]{40}$'){exit 0} - $state=[pscustomobject]@{lastCheckUtc='';blockedTag='';lastInstalledTag='';phase='idle'; + $state=[pscustomobject]@{lastCheckUtc='';lastAttemptUtc='';blockedTag='';lastInstalledTag='';phase='idle';operation='upgrade'; candidateTag='';candidateSha='';previousSha='';previousTag=''; newAsset=$null;previousAsset=$null} if(Test-Path -LiteralPath $statePath -PathType Leaf) { - $read=Read-Json $statePath - foreach($key in @('lastCheckUtc','blockedTag','lastInstalledTag','phase','candidateTag','candidateSha','previousSha','previousTag','newAsset','previousAsset')) { - if($read.PSObject.Properties.Name -contains $key){$state.$key=$read.$key} + 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','candidateTag','candidateSha','previousSha','previousTag','newAsset','previousAsset')) { + if($null -ne $read -and $read.PSObject.Properties.Name -contains $key){$state.$key=$read.$key} } } - if(-not $ApplyStaged) { - if($state.lastCheckUtc) { - $checked=[DateTime]::MinValue - if([DateTime]::TryParse([string]$state.lastCheckUtc,[ref]$checked) -and - [DateTime]::UtcNow.Subtract($checked.ToUniversalTime()).TotalHours -lt 6 -and - [DateTime]::UtcNow -ge $checked.ToUniversalTime() -and - $state.phase -cne 'staged') {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} } - $state.lastCheckUtc=[DateTime]::UtcNow.ToString('o') + 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){exit 0} + $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 @@ -346,7 +421,15 @@ try { $new=$release } } - if($null -eq $new){Log-Result 'UP_TO_DATE';exit 0} + $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 @@ -358,6 +441,7 @@ try { # byte-verified previous installer. Download-Release-Verified $current $oldAsset $oldPath $state.phase='staged' + $state.operation=$operation $state.candidateTag=[string]$new.tag_name $state.candidateSha=[string]$new.target_commitish $state.previousTag=[string]$current.tag_name @@ -370,6 +454,10 @@ try { } # 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' + } 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 @@ -437,8 +525,8 @@ try { $state.phase='idle' $state.blockedTag='' Write-State $state - Log-Result ('HEALTHY '+$new.tag_name) - Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction SilentlyContinue + Log-Result ($(if($state.operation -ceq 'repair'){'REPAIRED '}else{'HEALTHY '})+$new.tag_name) + Clear-StagedVendorFiles $state exit 0 } # An installer failure leaves the previous app intact or may be partial. @@ -461,6 +549,11 @@ try { } 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) { diff --git a/tests/windows_installer_contract_test.mjs b/tests/windows_installer_contract_test.mjs index c2e3679ac..770313e05 100644 --- a/tests/windows_installer_contract_test.mjs +++ b/tests/windows_installer_contract_test.mjs @@ -181,3 +181,17 @@ test('Windows updater executes byte-level offline stage integrity fixtures', () 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/); +}); From 7dd9956185617c3bb8273c635bbeef5d63aab388 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 05:19:23 +0700 Subject: [PATCH 31/62] fix(updater): revalidate cached installers and quarantine revoked update transactions --- installer/ArSonMixAutoUpdate.ps1 | 63 ++++++++++++++++++- scripts/test_inno_graceful_update_windows.ps1 | 2 + tests/windows_installer_contract_test.mjs | 11 ++++ 3 files changed, 74 insertions(+), 2 deletions(-) diff --git a/installer/ArSonMixAutoUpdate.ps1 b/installer/ArSonMixAutoUpdate.ps1 index 03290af0b..86c90138a 100644 --- a/installer/ArSonMixAutoUpdate.ps1 +++ b/installer/ArSonMixAutoUpdate.ps1 @@ -186,6 +186,22 @@ function Classify-InterruptedTransaction([string]$phase,[string]$actual,[string] 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' @@ -334,6 +350,25 @@ if($PolicySelfTest) { } 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} + 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' @@ -383,7 +418,23 @@ try { 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){exit 0} + 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 @@ -491,7 +542,15 @@ try { } if($null -eq $approved -or $approved.digest -cne $state.newAsset.digest -or [long]$approved.size -ne [long]$state.newAsset.size){ - Fail 'Published update revoked or changed' + # 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 diff --git a/scripts/test_inno_graceful_update_windows.ps1 b/scripts/test_inno_graceful_update_windows.ps1 index 00621e441..bd34c5672 100644 --- a/scripts/test_inno_graceful_update_windows.ps1 +++ b/scripts/test_inno_graceful_update_windows.ps1 @@ -7,6 +7,8 @@ Set-StrictMode -Version Latest $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_CACHE_AND_RECOVERY_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" } diff --git a/tests/windows_installer_contract_test.mjs b/tests/windows_installer_contract_test.mjs index 770313e05..fe293c602 100644 --- a/tests/windows_installer_contract_test.mjs +++ b/tests/windows_installer_contract_test.mjs @@ -195,3 +195,14 @@ test('updater recovers after crash and offers only verified same-version repair' 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/); +}); From 0b4a8288d8a847c701f49a7858416391c5744ba2 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 05:23:19 +0700 Subject: [PATCH 32/62] feat(updater): bounded one-time delayed retry for transient Inno rejection --- docs/ADR_SMART_AUTO_UPDATER_20261109.md | 4 ++ installer/ArSonMixAutoUpdate.ps1 | 39 ++++++++++++++++++- scripts/test_inno_graceful_update_windows.ps1 | 1 + tests/windows_installer_contract_test.mjs | 9 +++++ 4 files changed, 51 insertions(+), 2 deletions(-) diff --git a/docs/ADR_SMART_AUTO_UPDATER_20261109.md b/docs/ADR_SMART_AUTO_UPDATER_20261109.md index ff33dfdd2..b1caea8f2 100644 --- a/docs/ADR_SMART_AUTO_UPDATER_20261109.md +++ b/docs/ADR_SMART_AUTO_UPDATER_20261109.md @@ -40,3 +40,7 @@ No second GUI, updater UI banner/card, silent audio-device remap, DSP changes, W - 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. diff --git a/installer/ArSonMixAutoUpdate.ps1 b/installer/ArSonMixAutoUpdate.ps1 index 86c90138a..7b00ab703 100644 --- a/installer/ArSonMixAutoUpdate.ps1 +++ b/installer/ArSonMixAutoUpdate.ps1 @@ -170,6 +170,11 @@ function Test-StagedAsset([string]$path,[object]$asset) { } 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 @@ -367,6 +372,11 @@ if($PolicySelfTest) { $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_RETRY_POLICY_PASS' Write-Output 'ARSONMIX_UPDATER_CACHE_AND_RECOVERY_PASS' Write-Output 'ARSONMIX_UPDATER_SELF_REPAIR_POLICY_PASS' @@ -389,7 +399,7 @@ try { $file=Read-Json $provenance $installedSha=[string]$file.sourceCommit if($installedSha -cnotmatch '^[a-f0-9]{40}$'){exit 0} - $state=[pscustomobject]@{lastCheckUtc='';lastAttemptUtc='';blockedTag='';lastInstalledTag='';phase='idle';operation='upgrade'; + $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) { @@ -403,7 +413,7 @@ try { Log-Result 'INVALID_UPDATER_STATE_QUARANTINED' $read=$null } - foreach($key in @('lastCheckUtc','lastAttemptUtc','blockedTag','lastInstalledTag','phase','operation','candidateTag','candidateSha','previousSha','previousTag','newAsset','previousAsset')) { + 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} } } @@ -493,6 +503,8 @@ try { Download-Release-Verified $current $oldAsset $oldPath $state.phase='staged' $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 @@ -509,6 +521,13 @@ try { 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 @@ -574,6 +593,7 @@ try { } 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='' @@ -582,12 +602,27 @@ try { (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. diff --git a/scripts/test_inno_graceful_update_windows.ps1 b/scripts/test_inno_graceful_update_windows.ps1 index bd34c5672..b322be172 100644 --- a/scripts/test_inno_graceful_update_windows.ps1 +++ b/scripts/test_inno_graceful_update_windows.ps1 @@ -8,6 +8,7 @@ $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_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" diff --git a/tests/windows_installer_contract_test.mjs b/tests/windows_installer_contract_test.mjs index fe293c602..73397781b 100644 --- a/tests/windows_installer_contract_test.mjs +++ b/tests/windows_installer_contract_test.mjs @@ -206,3 +206,12 @@ test('cached installers are byte-verified and revoked releases cannot loop indef ]) 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/); +}); From 4b08426d530380a110af7117ef5620465de015bc Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 05:24:41 +0700 Subject: [PATCH 33/62] test(updater): prove unattended same-version Inno repair restores corrupted EXE and preserves private data --- docs/ADR_SMART_AUTO_UPDATER_20261109.md | 3 +++ scripts/test_inno_graceful_update_windows.ps1 | 11 +++++++++++ tests/windows_installer_contract_test.mjs | 7 +++++++ 3 files changed, 21 insertions(+) diff --git a/docs/ADR_SMART_AUTO_UPDATER_20261109.md b/docs/ADR_SMART_AUTO_UPDATER_20261109.md index b1caea8f2..b7b507b73 100644 --- a/docs/ADR_SMART_AUTO_UPDATER_20261109.md +++ b/docs/ADR_SMART_AUTO_UPDATER_20261109.md @@ -44,3 +44,6 @@ No second GUI, updater UI banner/card, silent audio-device remap, DSP changes, W ## 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. diff --git a/scripts/test_inno_graceful_update_windows.ps1 b/scripts/test_inno_graceful_update_windows.ps1 index b322be172..46ee833b4 100644 --- a/scripts/test_inno_graceful_update_windows.ps1 +++ b/scripts/test_inno_graceful_update_windows.ps1 @@ -142,6 +142,17 @@ try { 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" + + # 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/tests/windows_installer_contract_test.mjs b/tests/windows_installer_contract_test.mjs index 73397781b..817976b61 100644 --- a/tests/windows_installer_contract_test.mjs +++ b/tests/windows_installer_contract_test.mjs @@ -215,3 +215,10 @@ test('transient Inno failure allows one delayed retry, never a reinstall loop', '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/); +}); From eb5fdcf325091dbd124b54d1713dcecdf97ae5c3 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 05:48:28 +0700 Subject: [PATCH 34/62] feat(updater): install one-click external recovery shortcut with safe missing-EXE Inno preflight --- installer/ArSonMix.iss | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/installer/ArSonMix.iss b/installer/ArSonMix.iss index 799d626c3..4365336e3 100644 --- a/installer/ArSonMix.iss +++ b/installer/ArSonMix.iss @@ -53,6 +53,9 @@ 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. @@ -111,6 +114,19 @@ begin 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; @@ -123,11 +139,14 @@ begin 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) then + 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.'; From 01c800684fed44aaa689316d081deb47b8d3b334 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 05:50:07 +0700 Subject: [PATCH 35/62] feat(updater): standalone authenticated recovery for missing/corrupt EXE and abandoned mutex --- installer/ArSonMixAutoUpdate.ps1 | 101 ++++++++++++++++++++++++++++--- 1 file changed, 94 insertions(+), 7 deletions(-) diff --git a/installer/ArSonMixAutoUpdate.ps1 b/installer/ArSonMixAutoUpdate.ps1 index 7b00ab703..f85d08102 100644 --- a/installer/ArSonMixAutoUpdate.ps1 +++ b/installer/ArSonMixAutoUpdate.ps1 @@ -2,9 +2,10 @@ # 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([Parameter(Mandatory=$true)][ValidateRange(1,2147483647)][int]$OwnerProcessId, +param([ValidateRange(0,2147483647)][int]$OwnerProcessId=0, [switch]$PolicySelfTest, - [switch]$ApplyStaged) + [switch]$ApplyStaged, + [switch]$RecoveryMode) Set-StrictMode -Version Latest $ErrorActionPreference='Stop' [Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12 @@ -228,13 +229,80 @@ function Owns-Exe([int]$processId) { } finally {$process.Dispose()} } catch {return $false} } -function Run-Installer([string]$file) { + +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 -or + (Compare-Version (Version-Key $release.tag_name) + (Version-Key $sourceRelease.tag_name)) -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-Path -LiteralPath $exe -PathType Leaf) -or + [string](Read-Json $provenance).sourceCommit -cne $sourceSha){ + throw 'Repair did not restore the expected release' + } + 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) @@ -386,14 +454,20 @@ if($PolicySelfTest) { } try { - if(-not (Test-Path -LiteralPath $exe -PathType Leaf) -or - -not (Test-Path -LiteralPath $provenance -PathType Leaf) -or - (-not $ApplyStaged -and -not (Owns-Exe $OwnerProcessId))) {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') - $locked=$mutex.WaitOne($(if($ApplyStaged){60000}else{0})) + 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 @@ -417,6 +491,19 @@ try { if($null -ne $read -and $read.PSObject.Properties.Name -contains $key){$state.$key=$read.$key} } } + if($RecoveryMode) { + # Invoked from the installed fallback shortcut, even with missing EXE. + try { + if((Get-InstalledImageStatus $file) -ceq 'healthy') { + if(-not (Test-NoActiveMixer)){throw 'ArSonMix is already running'} + [Diagnostics.Process]::Start($exe) | Out-Null + Log-Result 'RECOVERY_NOT_REQUIRED_LAUNCHED_HEALTHY_EXE' + } else { + 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} From 6f7b7a7ac724226e7c6fc4530b7bb8b9eb13227d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 05:51:28 +0700 Subject: [PATCH 36/62] test(updater): assert external recovery contract and no live-session shutdown --- tests/windows_installer_contract_test.mjs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tests/windows_installer_contract_test.mjs b/tests/windows_installer_contract_test.mjs index 817976b61..c9df736ad 100644 --- a/tests/windows_installer_contract_test.mjs +++ b/tests/windows_installer_contract_test.mjs @@ -222,3 +222,19 @@ test('Windows Inno fixture proves unattended in-place repair after binary corrup 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/); +}); From bb578c17777f6a37ab7503445059eda7aa29c8c5 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 05:51:30 +0700 Subject: [PATCH 37/62] test(updater): repair deleted synthetic EXE with real Windows Inno --- scripts/test_inno_graceful_update_windows.ps1 | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/scripts/test_inno_graceful_update_windows.ps1 b/scripts/test_inno_graceful_update_windows.ps1 index 46ee833b4..1e3acc050 100644 --- a/scripts/test_inno_graceful_update_windows.ps1 +++ b/scripts/test_inno_graceful_update_windows.ps1 @@ -152,6 +152,20 @@ try { 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. From 0fc173ed840c5f85b7b1d16287fdff70d060cec4 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 05:51:33 +0700 Subject: [PATCH 38/62] docs(updater): explain Start Menu recovery and security limitations --- docs/ADR_SMART_AUTO_UPDATER_20261109.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/ADR_SMART_AUTO_UPDATER_20261109.md b/docs/ADR_SMART_AUTO_UPDATER_20261109.md index b7b507b73..bc7c9f1c1 100644 --- a/docs/ADR_SMART_AUTO_UPDATER_20261109.md +++ b/docs/ADR_SMART_AUTO_UPDATER_20261109.md @@ -47,3 +47,9 @@ No second GUI, updater UI banner/card, silent audio-device remap, DSP changes, W ## 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. From 60c7a06355f56180239d1aff75ff73a6e5c1d06b Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 05:52:23 +0700 Subject: [PATCH 39/62] fix(updater): standalone Repair always restore authenticated vendor files and show missing-provenance reason --- installer/ArSonMixAutoUpdate.ps1 | 310 ++++++++++++++++++++++++++++++- 1 file changed, 300 insertions(+), 10 deletions(-) diff --git a/installer/ArSonMixAutoUpdate.ps1 b/installer/ArSonMixAutoUpdate.ps1 index f85d08102..928ed928b 100644 --- a/installer/ArSonMixAutoUpdate.ps1 +++ b/installer/ArSonMixAutoUpdate.ps1 @@ -454,6 +454,10 @@ if($PolicySelfTest) { } 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} @@ -472,7 +476,7 @@ try { [IO.Directory]::CreateDirectory($root) | Out-Null $file=Read-Json $provenance $installedSha=[string]$file.sourceCommit - if($installedSha -cnotmatch '^[a-f0-9]{40}$'){exit 0} + if($installedSha -cnotmatch '^[a-f0-9]{40} $state=[pscustomobject]@{lastCheckUtc='';lastAttemptUtc='';blockedTag='';lastInstalledTag='';phase='idle';operation='upgrade';installAttempts=0;retryAfterUtc=''; candidateTag='';candidateSha='';previousSha='';previousTag=''; newAsset=$null;previousAsset=$null} @@ -492,16 +496,302 @@ try { } } if($RecoveryMode) { - # Invoked from the installed fallback shortcut, even with missing EXE. - try { - if((Get-InstalledImageStatus $file) -ceq 'healthy') { - if(-not (Test-NoActiveMixer)){throw 'ArSonMix is already running'} - [Diagnostics.Process]::Start($exe) | Out-Null - Log-Result 'RECOVERY_NOT_REQUIRED_LAUNCHED_HEALTHY_EXE' - } else { - Restore-InstalledRelease $installedSha + # 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 } - } catch {Show-RecoveryFailure $_.Exception.Message} + } + } + 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) + 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.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 + foreach($pair in @(@($newPath,$state.newAsset),@($oldPath,$state.previousAsset))) { + $path=[string]$pair[0] + $asset=$pair[1] + if(-not (Test-StagedAsset $path $asset)) { + 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 + foreach($release in $liveReleases) { + if($release.tag_name -ceq $state.candidateTag -and + $release.target_commitish -ceq $state.candidateSha) { + $approved=Approved-Installer $release + break + } + } + 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 $actualSha -ceq $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((Read-Json $provenance).sourceCommit -ceq $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()} +} +){ + 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) From acd24bb6c373d9bf03d20fffcfc471e65afd973e Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 05:53:04 +0700 Subject: [PATCH 40/62] fix(updater): remove duplicated trailing PowerShell code before recovery qualification --- installer/ArSonMixAutoUpdate.ps1 | 291 ------------------------------- 1 file changed, 291 deletions(-) diff --git a/installer/ArSonMixAutoUpdate.ps1 b/installer/ArSonMixAutoUpdate.ps1 index 928ed928b..5fdaeee5d 100644 --- a/installer/ArSonMixAutoUpdate.ps1 +++ b/installer/ArSonMixAutoUpdate.ps1 @@ -764,294 +764,3 @@ try { if($locked -and $null -ne $mutex){$mutex.ReleaseMutex()} if($null -ne $mutex){$mutex.Dispose()} } -){ - 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) - 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.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 - foreach($pair in @(@($newPath,$state.newAsset),@($oldPath,$state.previousAsset))) { - $path=[string]$pair[0] - $asset=$pair[1] - if(-not (Test-StagedAsset $path $asset)) { - 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 - foreach($release in $liveReleases) { - if($release.tag_name -ceq $state.candidateTag -and - $release.target_commitish -ceq $state.candidateSha) { - $approved=Approved-Installer $release - break - } - } - 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 $actualSha -ceq $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((Read-Json $provenance).sourceCommit -ceq $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()} -} From d6b5c0eb0b7a0d7e458eafd17b0d38927ea7bdd7 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 05:53:07 +0700 Subject: [PATCH 41/62] test(updater): reject duplicated PowerShell trailer and missing recovery helpers --- tests/windows_installer_contract_test.mjs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tests/windows_installer_contract_test.mjs b/tests/windows_installer_contract_test.mjs index c9df736ad..a685515c7 100644 --- a/tests/windows_installer_contract_test.mjs +++ b/tests/windows_installer_contract_test.mjs @@ -238,3 +238,17 @@ test('one-click recovery can restore main EXE without a live app', () => { 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'); + 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); +}); From 284b5b2b958c90ff9d6e7bdb2592fa85c09903ac Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 05:53:50 +0700 Subject: [PATCH 42/62] test(updater): normalize checked-out Windows CRLF before PowerShell trailer assertion --- tests/windows_installer_contract_test.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/windows_installer_contract_test.mjs b/tests/windows_installer_contract_test.mjs index a685515c7..816973864 100644 --- a/tests/windows_installer_contract_test.mjs +++ b/tests/windows_installer_contract_test.mjs @@ -240,7 +240,7 @@ test('one-click recovery can restore main EXE without a live app', () => { }); test('updater script has one coherent main try/finally and no duplicated tail', () => { - const script = read('installer/ArSonMixAutoUpdate.ps1'); + const script = read('installer/ArSonMixAutoUpdate.ps1').replace(/\r\n/g, '\n'); const tail = [ '} finally {', ' if($locked -and $null -ne $mutex){$mutex.ReleaseMutex()}', From fa53fd170f009fc33bd024e2d41e0ba416ccbd19 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 05:54:56 +0700 Subject: [PATCH 43/62] fix(updater): parse-safe SemVer choice for authenticated external recovery --- installer/ArSonMixAutoUpdate.ps1 | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/installer/ArSonMixAutoUpdate.ps1 b/installer/ArSonMixAutoUpdate.ps1 index 5fdaeee5d..995151ca0 100644 --- a/installer/ArSonMixAutoUpdate.ps1 +++ b/installer/ArSonMixAutoUpdate.ps1 @@ -267,10 +267,14 @@ function Restore-InstalledRelease([string]$sourceSha) { foreach($release in $releases) { if([string]$release.target_commitish -ceq $sourceSha -and $null -ne (Approved-Installer $release)) { - if($null -eq $sourceRelease -or - (Compare-Version (Version-Key $release.tag_name) - (Version-Key $sourceRelease.tag_name)) -gt 0){ + 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 + } } } } From 0763a4ac9bc8a2664a0b51c1e545bc50538cab99 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 05:56:27 +0700 Subject: [PATCH 44/62] fix(updater): restore 40-hex source validation lost to unsafe string replacement --- installer/ArSonMixAutoUpdate.ps1 | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/installer/ArSonMixAutoUpdate.ps1 b/installer/ArSonMixAutoUpdate.ps1 index 995151ca0..71772150d 100644 --- a/installer/ArSonMixAutoUpdate.ps1 +++ b/installer/ArSonMixAutoUpdate.ps1 @@ -480,7 +480,10 @@ try { [IO.Directory]::CreateDirectory($root) | Out-Null $file=Read-Json $provenance $installedSha=[string]$file.sourceCommit - if($installedSha -cnotmatch '^[a-f0-9]{40} + 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} From 88dfdf3f3b3fde0eb30744abea99c3c554fad601 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 06:30:06 +0700 Subject: [PATCH 45/62] fix(updater): require installed EXE SHA for healthy update, repair and rollback --- installer/ArSonMixAutoUpdate.ps1 | 35 ++++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/installer/ArSonMixAutoUpdate.ps1 b/installer/ArSonMixAutoUpdate.ps1 index 71772150d..2a0ba87b9 100644 --- a/installer/ArSonMixAutoUpdate.ps1 +++ b/installer/ArSonMixAutoUpdate.ps1 @@ -186,6 +186,14 @@ function Get-InstalledImageStatus([object]$build) { 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'} @@ -288,9 +296,8 @@ function Restore-InstalledRelease([string]$sourceSha) { if(-not (Run-Installer $destination -AllowMissingExeRecovery)){ throw 'Verified recovery installer was not accepted by Windows' } - if(-not (Test-Path -LiteralPath $exe -PathType Leaf) -or - [string](Read-Json $provenance).sourceCommit -cne $sourceSha){ - throw 'Repair did not restore the expected release' + 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' @@ -339,7 +346,7 @@ function Launch-WithHealth([string]$expectedSha) { if($process.HasExited){return $false} if(Test-Path -LiteralPath $marker -PathType Leaf) { if((Get-Content -LiteralPath $marker -Raw).Trim() -ceq 'GUI_READY' -and - (Read-Json $provenance).sourceCommit -ceq $expectedSha) { + (Test-InstalledRelease $expectedSha)) { Start-Sleep -Seconds 2 $process.Refresh() return (-not $process.HasExited) @@ -408,6 +415,21 @@ if($PolicySelfTest) { $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 @@ -448,6 +470,7 @@ if($PolicySelfTest) { 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' @@ -691,7 +714,7 @@ try { $upgradeOK=Run-Installer $newPath $actualSha='' try {$actualSha=[string](Read-Json $provenance).sourceCommit} catch {} - if($upgradeOK -and $actualSha -ceq $new.target_commitish -and + if($upgradeOK -and (Test-InstalledRelease ([string]$new.target_commitish)) -and (Launch-WithHealth ([string]$new.target_commitish))) { $state.lastInstalledTag=$new.tag_name $state.phase='idle' @@ -744,7 +767,7 @@ try { # Roll back by running the previously authenticated Inno installer, # not by copying arbitrary stale binaries over an installed application. if(Run-Installer $oldPath) { - if((Read-Json $provenance).sourceCommit -ceq $installedSha) { + if(Test-InstalledRelease $installedSha) { $state.phase='rolled-back' Write-State $state Log-Result ('ROLLED_BACK '+$new.tag_name) From 9fb0a2aec95456f610158a0f7e4f124465d31490 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 06:30:23 +0700 Subject: [PATCH 46/62] test(updater): certify exact executable identity before healthy recovery --- tests/windows_installer_contract_test.mjs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/tests/windows_installer_contract_test.mjs b/tests/windows_installer_contract_test.mjs index 816973864..5d1b8a3ac 100644 --- a/tests/windows_installer_contract_test.mjs +++ b/tests/windows_installer_contract_test.mjs @@ -252,3 +252,16 @@ test('updater script has one coherent main try/finally and no duplicated tail', 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/); +}); From 5c72b61e59c19b6b286d0bdac5ca7092f0235f5e Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 06:30:26 +0700 Subject: [PATCH 47/62] test(updater): certify exact executable identity before healthy recovery --- scripts/test_inno_graceful_update_windows.ps1 | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/test_inno_graceful_update_windows.ps1 b/scripts/test_inno_graceful_update_windows.ps1 index 1e3acc050..dff028a53 100644 --- a/scripts/test_inno_graceful_update_windows.ps1 +++ b/scripts/test_inno_graceful_update_windows.ps1 @@ -7,6 +7,7 @@ Set-StrictMode -Version Latest $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 From 99bab641287597f2fbf69cd74b5cfd985820d768 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 06:30:29 +0700 Subject: [PATCH 48/62] test(updater): certify exact executable identity before healthy recovery --- docs/ADR_SMART_AUTO_UPDATER_20261109.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/ADR_SMART_AUTO_UPDATER_20261109.md b/docs/ADR_SMART_AUTO_UPDATER_20261109.md index bc7c9f1c1..7e66a142f 100644 --- a/docs/ADR_SMART_AUTO_UPDATER_20261109.md +++ b/docs/ADR_SMART_AUTO_UPDATER_20261109.md @@ -53,3 +53,6 @@ No second GUI, updater UI banner/card, silent audio-device remap, DSP changes, W - 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. From b70a520c8a345aaa6e529baefba9bd601946ab2c Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 06:32:22 +0700 Subject: [PATCH 49/62] test(updater): verify real alpha.4 to alpha.5 upgrade and rollback with preserved Studio --- ...test_two_genuine_inno_releases_windows.ps1 | 121 ++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 scripts/test_two_genuine_inno_releases_windows.ps1 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} +} From f889ded9c6155d1c7916fe41c5adc1707ca4be80 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 06:32:40 +0700 Subject: [PATCH 50/62] ci(updater): opt-in Windows FAT for two published real release installers and rollback --- .github/workflows/p1-windows.yml | 9 +++++++++ 1 file changed, 9 insertions(+) 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: From 27b79c14dbac95c7fb750822ee97655cb54bec2f Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 06:33:04 +0700 Subject: [PATCH 51/62] test(updater): guard opt-in genuine two-release FAT and non-destructive rollback --- tests/windows_installer_contract_test.mjs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/tests/windows_installer_contract_test.mjs b/tests/windows_installer_contract_test.mjs index 5d1b8a3ac..19aad56be 100644 --- a/tests/windows_installer_contract_test.mjs +++ b/tests/windows_installer_contract_test.mjs @@ -265,3 +265,23 @@ test('healthy install, repair and rollback require real EXE SHA, not provenance 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)/); +}); From a6e8fd3bff3e83eea6e579747027b49fdf86761d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 06:33:06 +0700 Subject: [PATCH 52/62] docs(updater): document real published-release upgrade and rollback FAT --- docs/ADR_SMART_AUTO_UPDATER_20261109.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/ADR_SMART_AUTO_UPDATER_20261109.md b/docs/ADR_SMART_AUTO_UPDATER_20261109.md index 7e66a142f..217c3da17 100644 --- a/docs/ADR_SMART_AUTO_UPDATER_20261109.md +++ b/docs/ADR_SMART_AUTO_UPDATER_20261109.md @@ -56,3 +56,6 @@ No second GUI, updater UI banner/card, silent audio-device remap, DSP changes, W ## 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. From c5f58dd15efb402d1f12de27fa5f4925f71cade6 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 06:33:45 +0700 Subject: [PATCH 53/62] test(ci): account for opt-in genuine-release rollback FAT without increasing ordinary PR Windows spend --- tests/ci_workflow_efficiency_test.mjs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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') < From 72ae45dc619bdb168344a9f674ddecf277e33db3 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 06:37:07 +0700 Subject: [PATCH 54/62] fix(updater): reauthenticate published rollback source and SHA before touching installation --- installer/ArSonMixAutoUpdate.ps1 | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/installer/ArSonMixAutoUpdate.ps1 b/installer/ArSonMixAutoUpdate.ps1 index 2a0ba87b9..9ea6ef8e6 100644 --- a/installer/ArSonMixAutoUpdate.ps1 +++ b/installer/ArSonMixAutoUpdate.ps1 @@ -668,12 +668,26 @@ try { '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 - break } + 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){ From c177bc0310b7e484591488bcd4a84ea01ac28446 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 06:37:54 +0700 Subject: [PATCH 55/62] test(updater): enforce rollback asset provenance before Inno applies candidate --- tests/windows_installer_contract_test.mjs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tests/windows_installer_contract_test.mjs b/tests/windows_installer_contract_test.mjs index 19aad56be..7e1c0b494 100644 --- a/tests/windows_installer_contract_test.mjs +++ b/tests/windows_installer_contract_test.mjs @@ -285,3 +285,15 @@ test('two genuine release installers upgrade and roll back only in disposable Wi 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'")); +}); From c8e9af6c828428f181c10e7f7efec076625f7320 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 06:37:56 +0700 Subject: [PATCH 56/62] docs(updater): require published rollback authenticity on every apply --- docs/ADR_SMART_AUTO_UPDATER_20261109.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/ADR_SMART_AUTO_UPDATER_20261109.md b/docs/ADR_SMART_AUTO_UPDATER_20261109.md index 217c3da17..ddd504141 100644 --- a/docs/ADR_SMART_AUTO_UPDATER_20261109.md +++ b/docs/ADR_SMART_AUTO_UPDATER_20261109.md @@ -59,3 +59,6 @@ After install/repair/rollback, success requires the installed sourceCommit, exeS ## 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. From f367c3508f65cdb07655d70c8fa7583947617853 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 06:49:37 +0700 Subject: [PATCH 57/62] fix(updater): enumerate Windows PowerShell 5.1 releases, retry incomplete stage after bounded cooldown --- installer/ArSonMixAutoUpdate.ps1 | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/installer/ArSonMixAutoUpdate.ps1 b/installer/ArSonMixAutoUpdate.ps1 index 9ea6ef8e6..76e51a7d5 100644 --- a/installer/ArSonMixAutoUpdate.ps1 +++ b/installer/ArSonMixAutoUpdate.ps1 @@ -270,7 +270,7 @@ function Restore-InstalledRelease([string]$sourceSha) { # 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) + $releases=Invoke-RestMethod -Uri $api -Headers $headers -TimeoutSec 25 $sourceRelease=$null foreach($release in $releases) { if([string]$release.target_commitish -ceq $sourceSha -and @@ -576,7 +576,7 @@ try { 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) + $releases=Invoke-RestMethod -Uri $api -Headers $headers -TimeoutSec 25 $state.lastCheckUtc=[DateTime]::UtcNow.ToString('o') Write-State $state $current=$null @@ -613,11 +613,19 @@ try { $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='' @@ -666,7 +674,7 @@ try { # 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) + $liveReleases=Invoke-RestMethod -Uri $api -Headers $headers -TimeoutSec 25 $approved=$null $approvedOld=$null foreach($release in $liveReleases) { From 473fa7cf0943ffbc0cf96f678971150eebe83629 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 06:49:40 +0700 Subject: [PATCH 58/62] fix(updater): write healthy GUI marker only on successful WebView startup stage 2 --- src/Main.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Main.cpp b/src/Main.cpp index 010a193c4..9f25c832e 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -5214,7 +5214,8 @@ class ConsoleApp final : public juce::JUCEApplication, private juce::Timer ("ARSONMIX_UPDATE_PROBE", {}); const auto localAppData = juce::SystemStats::getEnvironmentVariable ("LOCALAPPDATA", {}); - if (probe.length() == 36 && juce::Uuid (probe).toDashedString() == probe + if (stage == 2 && probe.length() == 36 + && juce::Uuid (probe).toDashedString() == probe && localAppData.isNotEmpty()) { const auto healthDir = juce::File (localAppData) From 610d5e4535bd3bb03eba655b480356eba6a8310f Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 06:49:43 +0700 Subject: [PATCH 59/62] test(updater): guard PowerShell REST array, WebView failure stage and transient stage retry --- tests/windows_installer_contract_test.mjs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/tests/windows_installer_contract_test.mjs b/tests/windows_installer_contract_test.mjs index 7e1c0b494..bc0ca3e29 100644 --- a/tests/windows_installer_contract_test.mjs +++ b/tests/windows_installer_contract_test.mjs @@ -297,3 +297,23 @@ test('auto apply authenticates the published rollback asset as well as the new r 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/); +}); From e6fbde15cf9fca90672db3eb4682c8885a8f723d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 06:49:46 +0700 Subject: [PATCH 60/62] docs(updater): close open P1/P2 findings from code review --- docs/ADR_SMART_AUTO_UPDATER_20261109.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/ADR_SMART_AUTO_UPDATER_20261109.md b/docs/ADR_SMART_AUTO_UPDATER_20261109.md index ddd504141..ef337e146 100644 --- a/docs/ADR_SMART_AUTO_UPDATER_20261109.md +++ b/docs/ADR_SMART_AUTO_UPDATER_20261109.md @@ -62,3 +62,8 @@ After install/repair/rollback, success requires the installed sourceCommit, exeS ## 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. From e289b3428c6af4daf5c0894162bc3e3bc41566e0 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 06:51:06 +0700 Subject: [PATCH 61/62] fix(updater): validate candidate and rollback cache independently in Windows PowerShell --- installer/ArSonMixAutoUpdate.ps1 | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/installer/ArSonMixAutoUpdate.ps1 b/installer/ArSonMixAutoUpdate.ps1 index 76e51a7d5..4e955c33c 100644 --- a/installer/ArSonMixAutoUpdate.ps1 +++ b/installer/ArSonMixAutoUpdate.ps1 @@ -663,12 +663,11 @@ try { $stage=Join-Path $root 'stage' $newPath=Join-Path $stage $newName $oldPath=Join-Path $stage $oldName - foreach($pair in @(@($newPath,$state.newAsset),@($oldPath,$state.previousAsset))) { - $path=[string]$pair[0] - $asset=$pair[1] - if(-not (Test-StagedAsset $path $asset)) { - Fail 'Offline staged install/rollback bytes not verified' - } + # 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. From af9bdbab0c38c1f3c33dcba0c940afe1740332d4 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Tue, 10 Nov 2026 06:51:09 +0700 Subject: [PATCH 62/62] test(updater): guard explicit two-sided SHA validation before install --- tests/windows_installer_contract_test.mjs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/windows_installer_contract_test.mjs b/tests/windows_installer_contract_test.mjs index bc0ca3e29..20128d27c 100644 --- a/tests/windows_installer_contract_test.mjs +++ b/tests/windows_installer_contract_test.mjs @@ -174,7 +174,9 @@ 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, /if\(-not \(Test-StagedAsset \$path \$asset\)\)/); + 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/);