merge: integrate updater recovery and installer into pre-release

cx
This commit is contained in:
vicrodh committed 2026-09-12 16:25:14 -06:00
commit 3cf1f32177
45 files changed
+3725 -10

No files matched your search

+1 -1
View File
@@ -259,7 +259,7 @@ jobs:
# verify artifacts with the Tauri minisign pubkey baked into the old
# binaries. Signing with the SAME private key lets them auto-update
# straight into this AppImage. release-updater-manifest.yml collects
# the .sig. The app itself has no auto-updater.
# the .sig. The Qt updater also consumes this signed manifest.
- name: Sign AppImage (Tauri-updater bridge)
if: startsWith(github.ref, 'refs/tags/')
env:
+1 -1
View File
@@ -263,7 +263,7 @@ jobs:
# verify artifacts with the Tauri minisign pubkey baked into the old
# binaries. Signing with the SAME private key lets them auto-update
# straight into this AppImage. release-updater-manifest.yml collects
# the .sig. The app itself has no auto-updater.
# the .sig. The Qt updater also consumes this signed manifest.
- name: Sign AppImage (Tauri-updater bridge)
if: startsWith(github.ref, 'refs/tags/')
env:
+11 -2
View File
@@ -5,6 +5,7 @@ on:
workflows:
- release-macos
- release-linux
- release-windows
- "Linux ARM64 (aarch64) Build"
types:
- completed
@@ -76,6 +77,7 @@ jobs:
"x64.app.tar.gz.sig"
"amd64.AppImage.sig"
"aarch64.AppImage.sig"
"x64.msi.sig"
)
MAX_ATTEMPTS=40
SLEEP_SECONDS=30
@@ -186,9 +188,16 @@ jobs:
'. + {"linux-aarch64": {"signature": $sig, "url": $url}}')
fi
WINDOWS_MSI=$(find_asset "_x64.msi$")
WINDOWS_SIG=$(read_sig "*_x64.msi.sig")
if [ -n "$WINDOWS_MSI" ] && [ -n "$WINDOWS_SIG" ]; then
PLATFORMS=$(echo "$PLATFORMS" | jq --arg url "${RELEASE_URL}/${WINDOWS_MSI}" --arg sig "$WINDOWS_SIG" \
'. + {"windows-x86_64": {"signature": $sig, "url": $url}}')
fi
PLATFORM_COUNT=$(echo "$PLATFORMS" | jq 'length')
if [ "$PLATFORM_COUNT" -ne 4 ]; then
echo "::error::Expected four updater platforms, generated $PLATFORM_COUNT."
if [ "$PLATFORM_COUNT" -ne 5 ]; then
echo "::error::Expected five updater platforms, generated $PLATFORM_COUNT."
echo "$PLATFORMS" | jq .
exit 1
fi
+25
View File
@@ -349,6 +349,15 @@ jobs:
# installer on the last compatible pre-OSMF toolchain instead of making
# a CI job accept legal terms on a maintainer's behalf. The committed
# authoring deliberately stays within WiX 5 syntax.
- name: Validate updater helper syntax
shell: pwsh
run: |
$tokens = $null
$errors = $null
[System.Management.Automation.Language.Parser]::ParseFile(
"$PWD/crates/qbz-updater/src/install-msi.ps1", [ref]$tokens, [ref]$errors) | Out-Null
if ($errors.Count -gt 0) { $errors | Format-List; throw 'Invalid updater helper' }
- name: WiX
run: dotnet tool install --global wix --version 5.0.2 && wix --version
@@ -420,6 +429,20 @@ jobs:
run: |
& "$(vswhere -latest -find '**\signtool.exe' | Select-Object -First 1)" sign /f cert.pfx /p $env:WINDOWS_CERT_PASSWORD /fd SHA256 /tr http://timestamp.digicert.com /td SHA256 "dist\QBZ_$env:VERSION`_x64.msi"
# Minisign is the updater signature, separate from optional Authenticode.
# Sign the final MSI bytes after Authenticode, with the existing release key.
- name: Sign MSI for the QBZ updater
if: startsWith(github.ref, 'refs/tags/')
env:
VERSION: ${{ steps.release.outputs.version }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
run: |
npx --yes @tauri-apps/cli@^2 signer sign \
--private-key "$TAURI_SIGNING_PRIVATE_KEY" \
--password "$TAURI_SIGNING_PRIVATE_KEY_PASSWORD" \
"dist/QBZ_${VERSION}_x64.msi"
# Portable zip of the same directory (testers without install rights),
# plus the PDB (MSVC emits it regardless of `strip = "symbols"`).
- name: Portable zip + symbols
@@ -462,6 +485,7 @@ jobs:
retention-days: ${{ startsWith(github.ref, 'refs/tags/v') && 90 || 7 }}
path: |
dist/*.msi
dist/*.msi.sig
dist/*.zip
dist/*.pdb
@@ -472,6 +496,7 @@ jobs:
with:
files: |
dist/*.msi
dist/*.msi.sig
dist/*.zip
prerelease: ${{ steps.release.outputs.prerelease }}
make_latest: ${{ steps.release.outputs.prerelease == 'true' && 'false' || 'true' }}
+9 -1
View File
@@ -34,6 +34,8 @@
# pre-release
# integration so regressions land before a release cut.
# Shared cargo-test.sh also gates signed updater verification, version selection
# and preference preservation; qt-runtime-gate.sh covers the update UI.
# Shared cargo-test.sh also gates Orbit HTTP host isolation, library profiles
# and the SSE public-identity projection. No separate test command to drift.
name: test-crates
@@ -46,6 +48,8 @@ on:
paths:
- "crates/**"
- "scripts/cargo-test.sh"
- "scripts/install.sh"
- "scripts/test-installer.py"
- "scripts/qt-*.py"
- "scripts/qt-*.sh"
- "scripts/test_qt_build_gates.py"
@@ -57,6 +61,7 @@ on:
- "scripts/qml-tests/**"
- "scripts/test-search-local-qml.sh"
- "scripts/test-orbit-qml.sh"
- "scripts/test-updates-qml.sh"
- "scripts/test-orbit-daemon.py"
- ".github/workflows/test-crates.yml"
push:
@@ -65,6 +70,8 @@ on:
paths:
- "crates/**"
- "scripts/cargo-test.sh"
- "scripts/install.sh"
- "scripts/test-installer.py"
- "scripts/qt-*.py"
- "scripts/qt-*.sh"
- "scripts/test_qt_build_gates.py"
@@ -76,6 +83,7 @@ on:
- "scripts/qml-tests/**"
- "scripts/test-search-local-qml.sh"
- "scripts/test-orbit-qml.sh"
- "scripts/test-updates-qml.sh"
- "scripts/test-orbit-daemon.py"
- ".github/workflows/test-crates.yml"
workflow_dispatch:
@@ -109,7 +117,7 @@ jobs:
# OpenSSL (reqwest).
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
build-essential pkg-config gettext \
build-essential pkg-config gettext dbus-daemon desktop-file-utils \
libasound2-dev libjack-jackd2-dev \
libdbus-1-dev libssl-dev
+45
View File
@@ -126,6 +126,32 @@ another module, and it didn't go well.
## Installation
### One-line installer (Linux and macOS, from 2.1.2)
```bash
curl -fsSL https://qbz.lol/install.sh | bash
```
Installs the official AppImage on Linux or the upstream `.app` in
`~/Applications` on macOS, for the current user. It detects Intel/AMD or ARM64,
verifies the package SHA-256 against GitHub's release metadata, and preserves
existing installations from other sources. Future updates use **Settings →
Updates** in QBZ. Linux needs curl and Python 3 or jq; the launcher works without
FUSE. The existing glibc requirements still apply. The macOS package uses the
upstream ad-hoc signature; the notarized community channel remains available below.
To inspect the script before running it, or remove this installation while
keeping personal data:
```bash
curl -fsSL https://qbz.lol/install.sh -o qbz-install.sh
less qbz-install.sh
bash qbz-install.sh --check
bash qbz-install.sh
# Close QBZ before uninstalling:
bash qbz-install.sh --uninstall
```
### Arch Linux (AUR)
Install the prebuilt packages (recommended):
@@ -333,6 +359,25 @@ subscription, Gatekeeper blocks its first run. On recent macOS versions
it's a one-time unlock for this copy of the app; updates installed through
QBZ's own updater don't need it again.
### Updates
Use **Check for updates now** in the app menu or **Settings → Updates**.
Launch checks are optional and preserve existing preferences. GitHub release
notifications wait until a stable release is at least 12 hours old. Manual checks find new stable
releases immediately and report network errors separately from “up to date”.
AppImage and upstream macOS `.app` installations can download and install
signed updates from QBZ. Close and reopen the app after installation. macOS
builds signed by another distributor, including the notarized community
builds, keep their original update channel. The one-line installer uses these
same update paths. Flatpak checks and updates its own installed ref through the
Flatpak portal, including progress, cancellation and already-deployed updates
that only need a restart. Permission changes require the system software manager.
Windows MSI installations stage a signed MSI and run Windows Installer after
QBZ closes, then reopen the app. The installer never requests a machine restart.
For Snap, APT/RPM, AUR, Gentoo, Nix, Homebrew and other manual installs, update through the original
installation source; its package may arrive after the GitHub release.
## Features
### Audio and playback
+51
View File
@@ -579,6 +579,7 @@ dependencies = [
"js-sys",
"num-traits",
"pure-rust-locales",
"serde",
"wasm-bindgen",
"windows-link 0.2.1",
]
@@ -2945,6 +2946,12 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "minisign-verify"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22f9645cb765ea72b8111f36c522475d2daa0d22c957a9826437e97534bc4e9e"
[[package]]
name = "miniz_oxide"
version = "0.8.9"
@@ -4465,6 +4472,7 @@ dependencies = [
"qbz-subsonic",
"qbz-text-utils",
"qbz-theme",
"qbz-updater",
"qconnect-app",
"qconnect-lan",
"qconnect-protocol",
@@ -4591,6 +4599,28 @@ dependencies = [
"serde_json",
]
[[package]]
name = "qbz-updater"
version = "2.1.1"
dependencies = [
"base64 0.23.1",
"chrono",
"flate2",
"futures-util",
"minisign-verify",
"reqwest",
"rusqlite",
"semver",
"serde",
"serde_json",
"sha2 0.10.9",
"tar",
"tempfile",
"tokio",
"windows-sys 0.61.2",
"zbus 5.19.0",
]
[[package]]
name = "qbzd"
version = "2.1.1"
@@ -5992,6 +6022,17 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "tar"
version = "0.4.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"
dependencies = [
"filetime",
"libc",
"xattr",
]
[[package]]
name = "task-local"
version = "0.1.1"
@@ -7475,6 +7516,16 @@ version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
[[package]]
name = "xattr"
version = "1.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
dependencies = [
"libc",
"rustix 1.1.4",
]
[[package]]
name = "xdg-home"
version = "1.3.0"
+1
View File
@@ -2,6 +2,7 @@
resolver = "2"
members = [
"qbz-updater",
"qbz-app",
"qbz-control",
"qbz-theme",
@@ -7140,3 +7140,112 @@ msgstr "Dieser Host unterstützt keine Bibliotheksabfragen."
#. Experimental Orbit host inspection and persistent remote context.
msgid "Verify host"
msgstr "Host überprüfen"
#: qbz-qt updates
msgid "A new version of QBZ is available."
msgstr "Eine neue Version von QBZ ist verfügbar."
#: qbz-qt updates
msgid "Cancel download"
msgstr "Download abbrechen"
#: qbz-qt updates
msgid "Check for new releases on launch"
msgstr "Beim Start nach neuen Versionen suchen"
#: qbz-qt updates
msgid "Check for updates now"
msgstr "Jetzt nach Updates suchen"
#: qbz-qt updates
msgid "Checking for updates..."
msgstr "Suche nach Updates..."
#: qbz-qt updates
msgid "Current version"
msgstr "Aktuelle Version"
#: qbz-qt updates
msgid "Download and install"
msgstr "Herunterladen und installieren"
#: qbz-qt updates
msgid "Downloading update..."
msgstr "Update wird heruntergeladen..."
#: qbz-qt updates
msgid "Installation"
msgstr "Installation"
#: qbz-qt updates
msgid "Installing update..."
msgstr "Update wird installiert..."
#: qbz-qt updates
msgid "Show changelog for current version"
msgstr "Änderungen der aktuellen Version anzeigen"
#: qbz-qt updates
msgid "Skip this version"
msgstr "Diese Version überspringen"
#: qbz-qt updates
msgid "The update could not be completed. Please try again."
msgstr "Das Update konnte nicht abgeschlossen werden. Bitte erneut versuchen."
#: qbz-qt updates
msgid "Update QBZ through your installation source. Packages may become available after the GitHub release."
msgstr "Aktualisiere QBZ über die ursprüngliche Installationsquelle. Pakete können erst nach der GitHub-Veröffentlichung verfügbar sein."
#: qbz-qt updates
msgid "Update cancelled."
msgstr "Update abgebrochen."
#: qbz-qt updates
msgid "Update installed. Close and reopen QBZ to use the new version."
msgstr "Update installiert. Schließe QBZ und öffne es erneut, um die neue Version zu verwenden."
#: qbz-qt updates
msgid "Updates"
msgstr "Updates"
#: qbz-qt updates
msgid "Verifying update signature..."
msgstr "Update-Signatur wird überprüft..."
#: qbz-qt updates
msgid "Visit release page"
msgstr "Veröffentlichungsseite öffnen"
#: qbz-qt updates
msgid "You are using the latest version of QBZ."
msgstr "Du verwendest die neueste Version von QBZ."
#: qbz-qt updates
msgid "System / manual"
msgstr "System / manuell"
#: qbz-qt/qml/shell/UpdatesModal.qml
msgid "Update ready. Close QBZ to finish installation. It will reopen automatically."
msgstr "Update bereit. Schließe QBZ, um die Installation abzuschließen. QBZ wird automatisch wieder geöffnet."
@@ -2740,3 +2740,112 @@ msgstr "This host does not support library inspection."
#. Experimental Orbit host inspection and persistent remote context.
msgid "Verify host"
msgstr "Verify host"
#: qbz-qt updates
msgid "A new version of QBZ is available."
msgstr "A new version of QBZ is available."
#: qbz-qt updates
msgid "Cancel download"
msgstr "Cancel download"
#: qbz-qt updates
msgid "Check for new releases on launch"
msgstr "Check for new releases on launch"
#: qbz-qt updates
msgid "Check for updates now"
msgstr "Check for updates now"
#: qbz-qt updates
msgid "Checking for updates..."
msgstr "Checking for updates..."
#: qbz-qt updates
msgid "Current version"
msgstr "Current version"
#: qbz-qt updates
msgid "Download and install"
msgstr "Download and install"
#: qbz-qt updates
msgid "Downloading update..."
msgstr "Downloading update..."
#: qbz-qt updates
msgid "Installation"
msgstr "Installation"
#: qbz-qt updates
msgid "Installing update..."
msgstr "Installing update..."
#: qbz-qt updates
msgid "Show changelog for current version"
msgstr "Show changelog for current version"
#: qbz-qt updates
msgid "Skip this version"
msgstr "Skip this version"
#: qbz-qt updates
msgid "The update could not be completed. Please try again."
msgstr "The update could not be completed. Please try again."
#: qbz-qt updates
msgid "Update QBZ through your installation source. Packages may become available after the GitHub release."
msgstr "Update QBZ through your installation source. Packages may become available after the GitHub release."
#: qbz-qt updates
msgid "Update cancelled."
msgstr "Update cancelled."
#: qbz-qt updates
msgid "Update installed. Close and reopen QBZ to use the new version."
msgstr "Update installed. Close and reopen QBZ to use the new version."
#: qbz-qt updates
msgid "Updates"
msgstr "Updates"
#: qbz-qt updates
msgid "Verifying update signature..."
msgstr "Verifying update signature..."
#: qbz-qt updates
msgid "Visit release page"
msgstr "Visit release page"
#: qbz-qt updates
msgid "You are using the latest version of QBZ."
msgstr "You are using the latest version of QBZ."
#: qbz-qt updates
msgid "System / manual"
msgstr "System / manual"
#: qbz-qt/qml/shell/UpdatesModal.qml
msgid "Update ready. Close QBZ to finish installation. It will reopen automatically."
msgstr "Update ready. Close QBZ to finish installation. It will reopen automatically."
@@ -7146,3 +7146,112 @@ msgstr "Este equipo no permite consultar su biblioteca."
#. Experimental Orbit host inspection and persistent remote context.
msgid "Verify host"
msgstr "Verificar equipo"
#: qbz-qt updates
msgid "A new version of QBZ is available."
msgstr "Hay una nueva versión de QBZ disponible."
#: qbz-qt updates
msgid "Cancel download"
msgstr "Cancelar descarga"
#: qbz-qt updates
msgid "Check for new releases on launch"
msgstr "Buscar nuevas versiones al iniciar"
#: qbz-qt updates
msgid "Check for updates now"
msgstr "Buscar actualizaciones ahora"
#: qbz-qt updates
msgid "Checking for updates..."
msgstr "Buscando actualizaciones..."
#: qbz-qt updates
msgid "Current version"
msgstr "Versión actual"
#: qbz-qt updates
msgid "Download and install"
msgstr "Descargar e instalar"
#: qbz-qt updates
msgid "Downloading update..."
msgstr "Descargando actualización..."
#: qbz-qt updates
msgid "Installation"
msgstr "Instalación"
#: qbz-qt updates
msgid "Installing update..."
msgstr "Instalando actualización..."
#: qbz-qt updates
msgid "Show changelog for current version"
msgstr "Mostrar cambios de la versión actual"
#: qbz-qt updates
msgid "Skip this version"
msgstr "Omitir esta versión"
#: qbz-qt updates
msgid "The update could not be completed. Please try again."
msgstr "No se pudo completar la actualización. Inténtalo de nuevo."
#: qbz-qt updates
msgid "Update QBZ through your installation source. Packages may become available after the GitHub release."
msgstr "Actualiza QBZ desde el medio que usaste para instalarlo. Los paquetes pueden estar disponibles después del lanzamiento en GitHub."
#: qbz-qt updates
msgid "Update cancelled."
msgstr "Actualización cancelada."
#: qbz-qt updates
msgid "Update installed. Close and reopen QBZ to use the new version."
msgstr "Actualización instalada. Cierra y vuelve a abrir QBZ para usar la nueva versión."
#: qbz-qt updates
msgid "Updates"
msgstr "Actualizaciones"
#: qbz-qt updates
msgid "Verifying update signature..."
msgstr "Verificando la firma de la actualización..."
#: qbz-qt updates
msgid "Visit release page"
msgstr "Ver página del lanzamiento"
#: qbz-qt updates
msgid "You are using the latest version of QBZ."
msgstr "Estás usando la versión más reciente de QBZ."
#: qbz-qt updates
msgid "System / manual"
msgstr "Sistema / manual"
#: qbz-qt/qml/shell/UpdatesModal.qml
msgid "Update ready. Close QBZ to finish installation. It will reopen automatically."
msgstr "Actualización lista. Cierra QBZ para terminar la instalación. Se abrirá de nuevo automáticamente."
@@ -7138,3 +7138,112 @@ msgstr "Cet hôte ne permet pas de consulter sa bibliothèque."
#. Experimental Orbit host inspection and persistent remote context.
msgid "Verify host"
msgstr "Vérifier l’hôte"
#: qbz-qt updates
msgid "A new version of QBZ is available."
msgstr "Une nouvelle version de QBZ est disponible."
#: qbz-qt updates
msgid "Cancel download"
msgstr "Annuler le téléchargement"
#: qbz-qt updates
msgid "Check for new releases on launch"
msgstr "Rechercher de nouvelles versions au démarrage"
#: qbz-qt updates
msgid "Check for updates now"
msgstr "Rechercher des mises à jour"
#: qbz-qt updates
msgid "Checking for updates..."
msgstr "Recherche de mises à jour..."
#: qbz-qt updates
msgid "Current version"
msgstr "Version actuelle"
#: qbz-qt updates
msgid "Download and install"
msgstr "Télécharger et installer"
#: qbz-qt updates
msgid "Downloading update..."
msgstr "Téléchargement de la mise à jour..."
#: qbz-qt updates
msgid "Installation"
msgstr "Installation"
#: qbz-qt updates
msgid "Installing update..."
msgstr "Installation de la mise à jour..."
#: qbz-qt updates
msgid "Show changelog for current version"
msgstr "Afficher les changements de la version actuelle"
#: qbz-qt updates
msgid "Skip this version"
msgstr "Ignorer cette version"
#: qbz-qt updates
msgid "The update could not be completed. Please try again."
msgstr "La mise à jour a échoué. Veuillez réessayer."
#: qbz-qt updates
msgid "Update QBZ through your installation source. Packages may become available after the GitHub release."
msgstr "Mettez QBZ à jour depuis sa source d’installation. Les paquets peuvent être disponibles après la publication sur GitHub."
#: qbz-qt updates
msgid "Update cancelled."
msgstr "Mise à jour annulée."
#: qbz-qt updates
msgid "Update installed. Close and reopen QBZ to use the new version."
msgstr "Mise à jour installée. Fermez puis rouvrez QBZ pour utiliser la nouvelle version."
#: qbz-qt updates
msgid "Updates"
msgstr "Mises à jour"
#: qbz-qt updates
msgid "Verifying update signature..."
msgstr "Vérification de la signature de la mise à jour..."
#: qbz-qt updates
msgid "Visit release page"
msgstr "Voir la page de la version"
#: qbz-qt updates
msgid "You are using the latest version of QBZ."
msgstr "Vous utilisez la dernière version de QBZ."
#: qbz-qt updates
msgid "System / manual"
msgstr "Système / manuelle"
#: qbz-qt/qml/shell/UpdatesModal.qml
msgid "Update ready. Close QBZ to finish installation. It will reopen automatically."
msgstr "Mise à jour prête. Fermez QBZ pour terminer l’installation. Il se rouvrira automatiquement."
@@ -7121,3 +7121,112 @@ msgstr "このホストはライブラリの参照に対応していません。
#. Experimental Orbit host inspection and persistent remote context.
msgid "Verify host"
msgstr "ホストを確認"
#: qbz-qt updates
msgid "A new version of QBZ is available."
msgstr "QBZの新しいバージョンが利用可能です。"
#: qbz-qt updates
msgid "Cancel download"
msgstr "ダウンロードをキャンセル"
#: qbz-qt updates
msgid "Check for new releases on launch"
msgstr "起動時に新しいバージョンを確認"
#: qbz-qt updates
msgid "Check for updates now"
msgstr "今すぐ更新を確認"
#: qbz-qt updates
msgid "Checking for updates..."
msgstr "更新を確認中..."
#: qbz-qt updates
msgid "Current version"
msgstr "現在のバージョン"
#: qbz-qt updates
msgid "Download and install"
msgstr "ダウンロードしてインストール"
#: qbz-qt updates
msgid "Downloading update..."
msgstr "更新をダウンロード中..."
#: qbz-qt updates
msgid "Installation"
msgstr "インストール方法"
#: qbz-qt updates
msgid "Installing update..."
msgstr "更新をインストール中..."
#: qbz-qt updates
msgid "Show changelog for current version"
msgstr "現在のバージョンの変更履歴を表示"
#: qbz-qt updates
msgid "Skip this version"
msgstr "このバージョンをスキップ"
#: qbz-qt updates
msgid "The update could not be completed. Please try again."
msgstr "更新を完了できませんでした。もう一度お試しください。"
#: qbz-qt updates
msgid "Update QBZ through your installation source. Packages may become available after the GitHub release."
msgstr "インストール元からQBZを更新してください。パッケージはGitHubでのリリース後に利用可能になる場合があります。"
#: qbz-qt updates
msgid "Update cancelled."
msgstr "更新をキャンセルしました。"
#: qbz-qt updates
msgid "Update installed. Close and reopen QBZ to use the new version."
msgstr "更新をインストールしました。新しいバージョンを使うにはQBZを閉じて再度開いてください。"
#: qbz-qt updates
msgid "Updates"
msgstr "更新"
#: qbz-qt updates
msgid "Verifying update signature..."
msgstr "更新の署名を検証中..."
#: qbz-qt updates
msgid "Visit release page"
msgstr "リリースページを開く"
#: qbz-qt updates
msgid "You are using the latest version of QBZ."
msgstr "最新バージョンのQBZを使用しています。"
#: qbz-qt updates
msgid "System / manual"
msgstr "システム / 手動"
#: qbz-qt/qml/shell/UpdatesModal.qml
msgid "Update ready. Close QBZ to finish installation. It will reopen automatically."
msgstr "更新の準備ができました。QBZ を終了するとインストールが完了し、自動的に再起動します。"
@@ -7128,3 +7128,112 @@ msgstr "Deze host ondersteunt geen bibliotheekinzage."
#. Experimental Orbit host inspection and persistent remote context.
msgid "Verify host"
msgstr "Host controleren"
#: qbz-qt updates
msgid "A new version of QBZ is available."
msgstr "Er is een nieuwe versie van QBZ beschikbaar."
#: qbz-qt updates
msgid "Cancel download"
msgstr "Download annuleren"
#: qbz-qt updates
msgid "Check for new releases on launch"
msgstr "Bij het opstarten naar nieuwe versies zoeken"
#: qbz-qt updates
msgid "Check for updates now"
msgstr "Nu op updates controleren"
#: qbz-qt updates
msgid "Checking for updates..."
msgstr "Controleren op updates..."
#: qbz-qt updates
msgid "Current version"
msgstr "Huidige versie"
#: qbz-qt updates
msgid "Download and install"
msgstr "Downloaden en installeren"
#: qbz-qt updates
msgid "Downloading update..."
msgstr "Update downloaden..."
#: qbz-qt updates
msgid "Installation"
msgstr "Installatie"
#: qbz-qt updates
msgid "Installing update..."
msgstr "Update installeren..."
#: qbz-qt updates
msgid "Show changelog for current version"
msgstr "Wijzigingen van de huidige versie tonen"
#: qbz-qt updates
msgid "Skip this version"
msgstr "Deze versie overslaan"
#: qbz-qt updates
msgid "The update could not be completed. Please try again."
msgstr "De update kon niet worden voltooid. Probeer het opnieuw."
#: qbz-qt updates
msgid "Update QBZ through your installation source. Packages may become available after the GitHub release."
msgstr "Werk QBZ bij via de oorspronkelijke installatiebron. Pakketten kunnen na de GitHub-release beschikbaar komen."
#: qbz-qt updates
msgid "Update cancelled."
msgstr "Update geannuleerd."
#: qbz-qt updates
msgid "Update installed. Close and reopen QBZ to use the new version."
msgstr "Update geïnstalleerd. Sluit en heropen QBZ om de nieuwe versie te gebruiken."
#: qbz-qt updates
msgid "Updates"
msgstr "Updates"
#: qbz-qt updates
msgid "Verifying update signature..."
msgstr "Handtekening van update controleren..."
#: qbz-qt updates
msgid "Visit release page"
msgstr "Releasepagina openen"
#: qbz-qt updates
msgid "You are using the latest version of QBZ."
msgstr "Je gebruikt de nieuwste versie van QBZ."
#: qbz-qt updates
msgid "System / manual"
msgstr "Systeem / handmatig"
#: qbz-qt/qml/shell/UpdatesModal.qml
msgid "Update ready. Close QBZ to finish installation. It will reopen automatically."
msgstr "Update gereed. Sluit QBZ om de installatie te voltooien. Het wordt automatisch opnieuw geopend."
@@ -7138,3 +7138,112 @@ msgstr "Este host não permite consultar sua biblioteca."
#. Experimental Orbit host inspection and persistent remote context.
msgid "Verify host"
msgstr "Verificar host"
#: qbz-qt updates
msgid "A new version of QBZ is available."
msgstr "Uma nova versão do QBZ está disponível."
#: qbz-qt updates
msgid "Cancel download"
msgstr "Cancelar download"
#: qbz-qt updates
msgid "Check for new releases on launch"
msgstr "Buscar novas versões ao iniciar"
#: qbz-qt updates
msgid "Check for updates now"
msgstr "Buscar atualizações agora"
#: qbz-qt updates
msgid "Checking for updates..."
msgstr "Buscando atualizações..."
#: qbz-qt updates
msgid "Current version"
msgstr "Versão atual"
#: qbz-qt updates
msgid "Download and install"
msgstr "Baixar e instalar"
#: qbz-qt updates
msgid "Downloading update..."
msgstr "Baixando atualização..."
#: qbz-qt updates
msgid "Installation"
msgstr "Instalação"
#: qbz-qt updates
msgid "Installing update..."
msgstr "Instalando atualização..."
#: qbz-qt updates
msgid "Show changelog for current version"
msgstr "Mostrar alterações da versão atual"
#: qbz-qt updates
msgid "Skip this version"
msgstr "Ignorar esta versão"
#: qbz-qt updates
msgid "The update could not be completed. Please try again."
msgstr "Não foi possível concluir a atualização. Tente novamente."
#: qbz-qt updates
msgid "Update QBZ through your installation source. Packages may become available after the GitHub release."
msgstr "Atualize o QBZ pela fonte usada na instalação. Os pacotes podem ficar disponíveis após o lançamento no GitHub."
#: qbz-qt updates
msgid "Update cancelled."
msgstr "Atualização cancelada."
#: qbz-qt updates
msgid "Update installed. Close and reopen QBZ to use the new version."
msgstr "Atualização instalada. Feche e reabra o QBZ para usar a nova versão."
#: qbz-qt updates
msgid "Updates"
msgstr "Atualizações"
#: qbz-qt updates
msgid "Verifying update signature..."
msgstr "Verificando a assinatura da atualização..."
#: qbz-qt updates
msgid "Visit release page"
msgstr "Ver página do lançamento"
#: qbz-qt updates
msgid "You are using the latest version of QBZ."
msgstr "Você está usando a versão mais recente do QBZ."
#: qbz-qt updates
msgid "System / manual"
msgstr "Sistema / manual"
#: qbz-qt/qml/shell/UpdatesModal.qml
msgid "Update ready. Close QBZ to finish installation. It will reopen automatically."
msgstr "Atualização pronta. Feche o QBZ para concluir a instalação. Ele será reaberto automaticamente."
@@ -7159,3 +7159,112 @@ msgstr "Этот хост не поддерживает просмотр биб
#. Experimental Orbit host inspection and persistent remote context.
msgid "Verify host"
msgstr "Проверить хост"
#: qbz-qt updates
msgid "A new version of QBZ is available."
msgstr "Доступна новая версия QBZ."
#: qbz-qt updates
msgid "Cancel download"
msgstr "Отменить загрузку"
#: qbz-qt updates
msgid "Check for new releases on launch"
msgstr "Проверять новые версии при запуске"
#: qbz-qt updates
msgid "Check for updates now"
msgstr "Проверить обновления сейчас"
#: qbz-qt updates
msgid "Checking for updates..."
msgstr "Проверка обновлений..."
#: qbz-qt updates
msgid "Current version"
msgstr "Текущая версия"
#: qbz-qt updates
msgid "Download and install"
msgstr "Скачать и установить"
#: qbz-qt updates
msgid "Downloading update..."
msgstr "Загрузка обновления..."
#: qbz-qt updates
msgid "Installation"
msgstr "Установка"
#: qbz-qt updates
msgid "Installing update..."
msgstr "Установка обновления..."
#: qbz-qt updates
msgid "Show changelog for current version"
msgstr "Показать изменения текущей версии"
#: qbz-qt updates
msgid "Skip this version"
msgstr "Пропустить эту версию"
#: qbz-qt updates
msgid "The update could not be completed. Please try again."
msgstr "Не удалось завершить обновление. Повторите попытку."
#: qbz-qt updates
msgid "Update QBZ through your installation source. Packages may become available after the GitHub release."
msgstr "Обновите QBZ через источник установки. Пакеты могут появиться позже выпуска на GitHub."
#: qbz-qt updates
msgid "Update cancelled."
msgstr "Обновление отменено."
#: qbz-qt updates
msgid "Update installed. Close and reopen QBZ to use the new version."
msgstr "Обновление установлено. Закройте и снова откройте QBZ, чтобы использовать новую версию."
#: qbz-qt updates
msgid "Updates"
msgstr "Обновления"
#: qbz-qt updates
msgid "Verifying update signature..."
msgstr "Проверка подписи обновления..."
#: qbz-qt updates
msgid "Visit release page"
msgstr "Открыть страницу выпуска"
#: qbz-qt updates
msgid "You are using the latest version of QBZ."
msgstr "Вы используете последнюю версию QBZ."
#: qbz-qt updates
msgid "System / manual"
msgstr "Системная / ручная"
#: qbz-qt/qml/shell/UpdatesModal.qml
msgid "Update ready. Close QBZ to finish installation. It will reopen automatically."
msgstr "Обновление готово. Закройте QBZ для завершения установки. Приложение откроется автоматически."
+1
View File
@@ -12,6 +12,7 @@ name = "qbz"
path = "src/main.rs"
[dependencies]
qbz-updater = { path = "../qbz-updater" }
qbz-control = { path = "../qbz-control" }
cxx = "1"
cxx-qt = "0.7"
+2
View File
@@ -642,6 +642,7 @@ fn main() {
"qml/rows/TrackRow.qml",
"qml/settings/AppearanceSettings.qml",
"qml/settings/NavigationSettings.qml",
"qml/settings/UpdatesSettings.qml",
"qml/settings/CustomThemeEditor.qml",
"qml/settings/IntegrationsSettings.qml",
"qml/settings/SettingsView.qml",
@@ -721,6 +722,7 @@ fn main() {
// QbzAbout's two documents.
"qml/shell/AboutModal.qml",
"qml/shell/WhatsNewModal.qml",
"qml/shell/UpdatesModal.qml",
"qml/shell/WindowsDisclaimerModal.qml",
// Immersive mode (2026-08-02 immersive-port contract §2) —
// its own module directory like views/local/ and
+10
View File
@@ -940,6 +940,10 @@ ApplicationWindow {
property bool quitAccepted: false
function requestQuit() {
if (JSON.parse(QbzAbout.updatesJson).phase === "installing") {
QbzAbout.updatesCheck()
return
}
if (quitAccepted || quitConfirmation.opened)
return
if (!QbzTray.confirmQuitEnabled()) {
@@ -955,6 +959,12 @@ ApplicationWindow {
}
function finishQuit() {
// The download may have reached replacement while a quit confirmation
// was open. Check again before arming the hard-exit watchdog.
if (JSON.parse(QbzAbout.updatesJson).phase === "installing") {
QbzAbout.updatesCheck()
return
}
if (quitAccepted)
return
quitAccepted = true
@@ -76,6 +76,7 @@ Item {
{ label: QbzSession.tr("Blacklist", QbzSession.trRev), section: 5 },
{ label: QbzSession.tr("Integrations", QbzSession.trRev), section: 6 },
{ label: QbzSession.tr("Import / Export", QbzSession.trRev), section: 9 },
{ label: QbzSession.tr("Updates", QbzSession.trRev), section: 12 },
{ label: QbzSession.tr("Developer", QbzSession.trRev), section: 7 }
].concat(QbzOrbit.enabled ? [{ label: "Orbit", section: 11 }] : []).concat(root.sandboxed ? [{ label: (doc.dev || ({})).installMethod === "snap"
? QbzSession.tr("Snap", QbzSession.trRev) : QbzSession.tr("Flatpak", QbzSession.trRev), section: 8 }] : [])
@@ -281,6 +282,12 @@ Item {
active: root.section === 9
onClicked: QbzBridge.settingsSetSection(9)
}
SubNavItem {
name: "refresh-cw"
label: QbzSession.tr("Updates", QbzSession.trRev)
active: root.section === 12
onClicked: QbzBridge.settingsSetSection(12)
}
SubNavItem {
name: "bug"
label: QbzSession.tr("Developer", QbzSession.trRev)
@@ -413,6 +420,12 @@ Item {
width: parent ? parent.width : 0
}
Panel {
panelIndex: 12
sourceComponent: Component {
UpdatesSettings { width: parent.width; kioskHost: root.kioskHost }
}
}
OrbitSettingsPanel {
width: parent.width
selected: root.section === 11
@@ -0,0 +1,57 @@
import QtQuick
import com.blitzfc.qbz
import "../controls"
import "../theme"
Column {
id: root
property bool kioskHost: false
readonly property var doc: JSON.parse(QbzAbout.updatesJson)
spacing: 4
QbzTheme { id: theme }
SettingRow {
kioskHost: root.kioskHost
label: QbzSession.tr("Check for new releases on launch", QbzSession.trRev)
QbzToggle {
kioskHost: root.kioskHost
checked: root.doc.checkOnLaunch !== false
onToggled: function (enabled) { QbzAbout.updatesSetLaunch(enabled) }
}
}
SettingRow {
kioskHost: root.kioskHost
label: QbzSession.tr("Check for updates now", QbzSession.trRev)
SettingsButton {
objectName: "updateCheckButton"
kioskHost: root.kioskHost
width: 160
text: root.doc.busy ? QbzSession.tr("Checking...", QbzSession.trRev) : QbzSession.tr("Check", QbzSession.trRev)
enabled: root.doc.busy !== true
onClicked: QbzAbout.updatesCheck()
}
}
Text {
width: parent.width
text: QbzSession.tr("Current version", QbzSession.trRev) + ": " + (root.doc.currentVersion || "")
color: theme.textMuted
font.pixelSize: theme.fontBody
}
Text {
width: parent.width
text: QbzSession.tr("Installation", QbzSession.trRev) + ": " + (root.doc.installMethod === "System / manual" ? QbzSession.tr("System / manual", QbzSession.trRev) : (root.doc.installMethod || ""))
color: theme.textMuted
font.pixelSize: theme.fontBody
}
SettingsSpacer { }
SettingRow {
kioskHost: root.kioskHost
label: QbzSession.tr("Show changelog for current version", QbzSession.trRev)
SettingsButton {
kioskHost: root.kioskHost
width: 160
text: QbzSession.tr("Show", QbzSession.trRev)
onClicked: QbzAbout.whatsNewOpen()
}
}
}
+5 -1
View File
@@ -141,7 +141,10 @@ Rectangle {
// until the first click (measured 2026-08-03, RFB H0 first pass). Grab
// once at mount; every other lifecycle arm (immersive close, modal
// closes) hands focus BACK here.
Component.onCompleted: root.forceActiveFocus()
Component.onCompleted: {
root.forceActiveFocus()
Qt.callLater(function () { QbzAbout.updatesLaunch() })
}
// THE ONE key entry (§1.1 route (b), divergence K1): NOTHING is handled
// locally. The ordered pipeline (capture steal, search-dropdown Up/Down
@@ -1051,6 +1054,7 @@ Rectangle {
// while closed it is an invisible, non-interactive Item that parses one
// small JSON string — and each carries an explicit `z: 3000` (ADR-009 as
// this port spells it) rather than relying on declaration order alone.
UpdatesModal { }
AboutModal {
anchors.fill: parent
}
+8
View File
@@ -1497,6 +1497,14 @@ Rectangle {
root.reportIssueRequested()
}
}
AppMenuItem {
name: "refresh-cw"
label: QbzSession.tr("Check for updates now", QbzSession.trRev)
onClicked: {
appMenu.close()
QbzAbout.updatesCheck()
}
}
AppMenuItem {
name: "wand-sparkles"
label: QbzSession.tr("What's New", QbzSession.trRev)
+6 -1
View File
@@ -48,9 +48,14 @@ Rectangle {
// in a WM-less session.
readonly property bool isQbzShellRoot: true
focus: true
Component.onCompleted: root.forceActiveFocus()
Component.onCompleted: {
root.forceActiveFocus()
Qt.callLater(function () { QbzAbout.updatesLaunch() })
}
QbzTheme { id: theme }
UpdatesModal { kioskHost: true }
WhatsNewModal { }
/// The back bar's one button form: 44x36, radius-sm hover fill, a 20px
/// glyph. `available` dims the glyph and disarms the area (Back/Forward
+169
View File
@@ -0,0 +1,169 @@
import QtQuick
import com.blitzfc.qbz
import "../controls"
import "../theme"
FocusScope {
id: root
property bool kioskHost: false
anchors.fill: parent
z: 3000
readonly property var doc: JSON.parse(QbzAbout.updatesJson)
readonly property bool installing: doc.phase === "installing"
visible: doc.open === true
enabled: visible
QbzTheme { id: theme }
onVisibleChanged: if (visible) root.forceActiveFocus()
Keys.onEscapePressed: root.dismiss()
function dismiss() { if (!installing) QbzAbout.updatesClose() }
function statusText() {
switch (doc.phase) {
case "checking": return QbzSession.tr("Checking for updates...", QbzSession.trRev)
case "current": return QbzSession.tr("You are using the latest version of QBZ.", QbzSession.trRev)
case "available": return QbzSession.tr("A new version of QBZ is available.", QbzSession.trRev)
case "downloading": return QbzSession.tr("Downloading update...", QbzSession.trRev)
case "verifying": return QbzSession.tr("Verifying update signature...", QbzSession.trRev)
case "installing": return QbzSession.tr("Installing update...", QbzSession.trRev)
case "updating": return QbzSession.tr("Installing update...", QbzSession.trRev)
case "installed": return QbzSession.tr("Update installed. Close and reopen QBZ to use the new version.", QbzSession.trRev)
case "prepared": return QbzSession.tr("Update ready. Close QBZ to finish installation. It will reopen automatically.", QbzSession.trRev)
case "cancelled": return QbzSession.tr("Update cancelled.", QbzSession.trRev)
case "error": return QbzSession.tr("The update could not be completed. Please try again.", QbzSession.trRev)
default: return ""
}
}
Rectangle {
anchors.fill: parent
color: Qt.rgba(0, 0, 0, 0.75)
MouseArea {
anchors.fill: parent
onClicked: root.dismiss()
onWheel: function (wheel) { wheel.accepted = true }
}
}
Rectangle {
id: panel
anchors.centerIn: parent
width: Math.min(root.width - 40, 640)
height: Math.min(root.height - 40, content.implicitHeight + 40)
radius: theme.radiusMd
color: theme.surfaceCard
border.width: 1
border.color: theme.borderSubtle
MouseArea { anchors.fill: parent; onWheel: function (wheel) { wheel.accepted = true } }
Flickable {
anchors.fill: parent
anchors.margins: 20
contentHeight: content.implicitHeight
clip: true
Column {
id: content
width: parent.width
spacing: 16
Text {
width: parent.width
text: QbzSession.tr("Updates", QbzSession.trRev)
font.pixelSize: theme.fontTitle
font.weight: theme.weightBold
color: theme.textPrimary
}
Text {
width: parent.width
text: root.statusText()
wrapMode: Text.WordWrap
font.pixelSize: theme.fontBody
color: theme.textPrimary
}
Text {
width: parent.width
visible: (root.doc.version || "") !== ""
text: (root.doc.currentVersion || "") + " → " + (root.doc.version || "")
font.pixelSize: theme.fontBody
color: theme.textSecondary
}
Text {
width: parent.width
visible: root.doc.phase === "available" && !root.doc.canInstall
text: QbzSession.tr("Update QBZ through your installation source. Packages may become available after the GitHub release.", QbzSession.trRev)
wrapMode: Text.WordWrap
font.pixelSize: theme.fontBody
color: theme.textMuted
}
Text {
width: parent.width
visible: root.doc.phase === "downloading"
text: Math.floor((root.doc.downloaded || 0) / 1048576) + " MB"
+ (root.doc.total ? " / " + Math.ceil(root.doc.total / 1048576) + " MB" : "")
font.pixelSize: theme.fontBody
color: theme.textSecondary
}
Text {
width: parent.width
visible: root.doc.phase === "updating"
text: (root.doc.percent || 0) + "%"
font.pixelSize: theme.fontBody
color: theme.textSecondary
}
Text {
width: parent.width
visible: root.doc.phase === "error"
text: root.doc.error || ""
textFormat: Text.PlainText
wrapMode: Text.WrapAnywhere
font.pixelSize: theme.fontBody
color: theme.textMuted
}
Flow {
width: parent.width
layoutDirection: Qt.RightToLeft
spacing: 10
SettingsButton {
kioskHost: root.kioskHost
minWidth: 0
btnHeight: 36
objectName: "updateInstallButton"
visible: root.doc.canInstall === true && !root.doc.busy
text: QbzSession.tr("Download and install", QbzSession.trRev)
onClicked: QbzAbout.updatesInstall()
}
SettingsButton {
kioskHost: root.kioskHost
minWidth: 0
btnHeight: 36
objectName: "updateReleaseButton"
visible: !!root.doc.version && !root.doc.busy && root.doc.phase !== "installed"
text: QbzSession.tr("Visit release page", QbzSession.trRev)
onClicked: QbzShell.openExternalUrl(root.doc.releaseUrl || "")
}
SettingsButton {
kioskHost: root.kioskHost
minWidth: 0
btnHeight: 36
visible: root.doc.phase === "downloading" || root.doc.phase === "verifying" || root.doc.phase === "updating"
objectName: "updateCancelButton"
text: root.doc.phase === "updating" ? QbzSession.tr("Cancel", QbzSession.trRev) : QbzSession.tr("Cancel download", QbzSession.trRev)
onClicked: QbzAbout.updatesCancel()
}
SettingsButton {
kioskHost: root.kioskHost
minWidth: 0
btnHeight: 36
objectName: "updateCloseButton"
enabled: !root.installing
text: QbzSession.tr("Close", QbzSession.trRev)
onClicked: root.dismiss()
}
SettingsButton {
kioskHost: root.kioskHost
minWidth: 0
btnHeight: 36
visible: root.doc.phase === "available"
text: QbzSession.tr("Skip this version", QbzSession.trRev)
onClicked: QbzAbout.updatesIgnore()
}
}
}
}
}
}
+52 -3
View File
@@ -1,7 +1,7 @@
//! QbzAbout — the About QBZ + What's New bridge.
//! QbzAbout — About QBZ, release notes and local application updates.
//!
//! Two documents and four invokables. The controllers are `about_qt.rs` and
//! `whats_new_qt.rs`; this file is glue and nothing else, exactly like
//! Controllers: `about_qt.rs`, `whats_new_qt.rs`, and `updates_qt.rs`.
//! This file is glue and nothing else, exactly like
//! `musician_bridge.rs`.
//!
//! # Why a NEW bridge instead of more members on QbzShell
@@ -65,6 +65,7 @@ pub mod qbz_about_bridge {
/// `hasBody`, the TOC and the flat block model. Produced by
/// `whats_new_qt.rs`. Same `"{}"` default, same reason.
#[qproperty(QString, whats_new_json)]
#[qproperty(QString, updates_json)]
type QbzAbout = super::QbzAboutRust;
/// Registers this object's Qt-thread hop. Harmless to call twice, and
@@ -73,6 +74,21 @@ pub mod qbz_about_bridge {
#[qinvokable]
fn boot(self: Pin<&mut QbzAbout>);
#[qinvokable]
fn updates_launch(self: Pin<&mut QbzAbout>);
#[qinvokable]
fn updates_check(self: Pin<&mut QbzAbout>);
#[qinvokable]
fn updates_close(self: Pin<&mut QbzAbout>);
#[qinvokable]
fn updates_ignore(self: Pin<&mut QbzAbout>);
#[qinvokable]
fn updates_install(self: Pin<&mut QbzAbout>);
#[qinvokable]
fn updates_cancel(self: Pin<&mut QbzAbout>);
#[qinvokable]
fn updates_set_launch(self: Pin<&mut QbzAbout>, enabled: bool);
/// The header menu's "About QBZ" row. Publishes the document open and
/// kicks the one-shot GitHub avatar fetch.
#[qinvokable]
@@ -103,6 +119,7 @@ use qbz_about_bridge::QbzAbout;
pub struct QbzAboutRust {
about_json: QString,
whats_new_json: QString,
updates_json: QString,
}
impl Default for QbzAboutRust {
@@ -112,6 +129,7 @@ impl Default for QbzAboutRust {
// empty string throws on the very first frame.
about_json: QString::from("{}"),
whats_new_json: QString::from("{}"),
updates_json: QString::from("{}"),
}
}
}
@@ -163,3 +181,34 @@ impl qbz_about_bridge::QbzAbout {
crate::whats_new_qt::close();
}
}
impl qbz_about_bridge::QbzAbout {
pub fn updates_launch(self: Pin<&mut Self>) {
self.register_thread();
crate::updates_qt::launch();
}
pub fn updates_check(self: Pin<&mut Self>) {
self.register_thread();
crate::updates_qt::check();
}
pub fn updates_close(self: Pin<&mut Self>) {
self.register_thread();
crate::updates_qt::close();
}
pub fn updates_ignore(self: Pin<&mut Self>) {
self.register_thread();
crate::updates_qt::ignore();
}
pub fn updates_install(self: Pin<&mut Self>) {
self.register_thread();
crate::updates_qt::install();
}
pub fn updates_cancel(self: Pin<&mut Self>) {
self.register_thread();
crate::updates_qt::cancel();
}
pub fn updates_set_launch(self: Pin<&mut Self>, enabled: bool) {
self.register_thread();
crate::updates_qt::set_launch(enabled);
}
}
+1
View File
@@ -196,6 +196,7 @@ mod log_viewer_qt;
// other two are plain controller modules and must NOT be.
mod about_bridge;
mod about_qt;
mod updates_qt;
mod library_bulk;
mod library_db_qt;
mod library_prefs;
+359
View File
@@ -0,0 +1,359 @@
//! Local application updates. Orbit's selected host never owns this state.
use cxx_qt_lib::QString;
use qbz_updater::{Asset, Release, install::Installation, store::Store};
use serde::Serialize;
use std::sync::{
LazyLock, Mutex,
atomic::{AtomicBool, Ordering},
};
static STARTED: AtomicBool = AtomicBool::new(false);
static CANCEL: AtomicBool = AtomicBool::new(false);
static STATE: LazyLock<Mutex<State>> = LazyLock::new(|| Mutex::new(State::default()));
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct State {
open: bool,
phase: String,
busy: bool,
check_on_launch: bool,
current_version: &'static str,
version: String,
release_url: String,
install_method: &'static str,
can_install: bool,
downloaded: u64,
total: Option<u64>,
error: String,
percent: Option<u32>,
#[serde(skip)]
reminder_key: String,
#[cfg(target_os = "linux")]
#[serde(skip)]
flatpak: Option<std::sync::Arc<qbz_updater::flatpak::Monitor>>,
#[serde(skip)]
manual: bool,
#[serde(skip)]
release: Option<Release>,
#[serde(skip)]
asset: Option<Asset>,
}
impl Default for State {
fn default() -> Self {
Self {
open: false,
phase: "idle".into(),
busy: false,
check_on_launch: true,
current_version: crate::about_qt::app_version(),
version: String::new(),
release_url: qbz_updater::RELEASE_PAGE.into(),
install_method: Installation::detect().label(),
can_install: false,
downloaded: 0,
total: None,
error: String::new(),
percent: None,
reminder_key: String::new(),
#[cfg(target_os = "linux")]
flatpak: None,
manual: false,
release: None,
asset: None,
}
}
}
fn update(f: impl FnOnce(&mut State)) {
let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner());
f(&mut state);
let json = serde_json::to_string(&*state).unwrap_or_else(|_| "{}".into());
// Enqueue while holding the state lock, so publishes preserve mutation order.
crate::about_bridge::ui(move |mut b| b.as_mut().set_updates_json(QString::from(&json)));
}
fn store() -> Result<Store, String> {
let path = dirs::data_dir()
.ok_or("No application data directory")?
.join("qbz/updates.db");
Store::open(&path)
}
fn failed(error: String) {
log::warn!("[updates] {error}");
update(|s| {
s.busy = false;
s.phase = "error".into();
s.error = error;
});
}
fn preference_failed(error: String) {
log::warn!("[updates] {error}");
update(|s| {
// A settings write must never unlock an active installer/check.
if !s.busy {
s.phase = "error".into();
s.error = error;
s.open = true;
}
});
}
/// Called after the shell is mounted, once per process. No polling timer.
pub fn launch() {
if STARTED.swap(true, Ordering::SeqCst) {
return;
}
crate::spawn(async {
let pref = tokio::task::spawn_blocking(|| store()?.check_on_launch()).await;
match pref {
Ok(Ok(enabled)) => {
update(|s| s.check_on_launch = enabled);
if enabled {
begin_check(false);
}
}
result => log::warn!("[updates] startup preference unavailable: {result:?}"),
}
});
}
pub fn check() {
begin_check(true);
}
fn begin_check(manual: bool) {
let mut start = false;
update(|s| {
if manual {
s.open = true;
s.manual = true;
}
if !s.busy && s.phase != "installed" && s.phase != "prepared" {
s.busy = true;
s.phase = "checking".into();
s.error.clear();
s.manual = manual;
s.asset = None;
s.release = None;
s.can_install = false;
s.version.clear();
s.reminder_key.clear();
s.percent = None;
#[cfg(target_os = "linux")]
{
s.flatpak = None;
}
start = true;
}
});
if !start {
return;
}
crate::spawn(async {
#[cfg(target_os = "linux")]
if Installation::detect() == Installation::Flatpak {
check_flatpak().await;
return;
}
// Fetch without suppression first: a manual request can join a launch
// request while it is in flight and must still see the actual latest.
match qbz_updater::check(crate::about_qt::app_version(), false).await {
Err(error) => failed(error),
Ok(None) => update(|s| {
s.busy = false;
s.phase = "current".into();
}),
Ok(Some(release)) => {
let version = match release.version() {
Ok(v) => v.to_string(),
Err(e) => {
failed(e);
return;
}
};
let suppression_version = version.clone();
let suppressed =
tokio::task::spawn_blocking(move || store()?.suppressed(&suppression_version))
.await;
let suppressed = !matches!(suppressed, Ok(Ok(false)));
let old_enough = release.notification_ready();
let asset = if let Some(platform) = Installation::detect().platform() {
match qbz_updater::asset(&release, &platform).await {
Ok(asset) => Some(asset),
Err(e) => {
log::info!("[updates] signed installer not available yet: {e}");
None
}
}
} else {
None
};
update(|s| {
s.busy = false;
s.phase = "available".into();
s.version = version;
s.reminder_key = s.version.clone();
s.release_url = release.page();
s.release = Some(release);
s.can_install = asset.is_some();
s.asset = asset;
if !s.manual && s.check_on_launch && old_enough && !suppressed {
s.open = true;
}
});
}
}
});
}
pub fn close() {
update(|s| s.open = false);
}
pub fn set_launch(enabled: bool) {
crate::spawn(async move {
match tokio::task::spawn_blocking(move || store()?.set_check_on_launch(enabled)).await {
Ok(Ok(())) => update(|s| s.check_on_launch = enabled),
error => preference_failed(format!("Could not save update preferences: {error:?}")),
}
});
}
pub fn ignore() {
let version = STATE
.lock()
.unwrap_or_else(|e| e.into_inner())
.reminder_key
.clone();
if version.is_empty() {
return;
}
crate::spawn(async move {
match tokio::task::spawn_blocking(move || store()?.ignore(&version)).await {
Ok(Ok(())) => close(),
error => preference_failed(format!("Could not save release reminder: {error:?}")),
}
});
}
pub fn cancel() {
CANCEL.store(true, Ordering::Relaxed);
}
pub fn install() {
let mut asset = None;
#[cfg(target_os = "linux")]
let mut flatpak = None;
update(|s| {
if !s.busy && s.can_install && s.phase != "installed" {
#[cfg(target_os = "linux")]
if let Some(monitor) = &s.flatpak {
flatpak = Some(monitor.clone());
s.busy = true;
s.open = true;
s.phase = "updating".into();
s.error.clear();
s.percent = Some(0);
CANCEL.store(false, Ordering::Relaxed);
return;
}
asset = s.asset.clone();
if asset.is_some() {
s.busy = true;
s.open = true;
s.phase = "downloading".into();
s.downloaded = 0;
s.total = None;
s.error.clear();
CANCEL.store(false, Ordering::Relaxed);
}
}
});
#[cfg(target_os = "linux")]
if let Some(monitor) = flatpak {
crate::spawn(async move {
let result = monitor
.install(&CANCEL, |percent| update(|s| s.percent = Some(percent)))
.await;
update(|s| {
s.flatpak = None;
s.can_install = false;
});
match result {
Ok(()) => update(|s| {
s.phase = "installed".into();
s.busy = false;
}),
Err(_) if CANCEL.load(Ordering::Relaxed) => update(|s| {
s.phase = "cancelled".into();
s.busy = false;
}),
Err(error) => failed(error),
}
});
return;
}
let Some(asset) = asset else { return };
crate::spawn(async move {
let result = qbz_updater::install::install(
Installation::detect(),
asset,
&CANCEL,
|phase, downloaded, total| {
update(|s| {
s.phase = phase.into();
s.downloaded = downloaded;
s.total = total;
})
},
)
.await;
match result {
Ok(outcome) => {
let (staged, backup) = match outcome {
qbz_updater::install::InstallOutcome::Installed(path) => (false, path),
qbz_updater::install::InstallOutcome::Prepared(path) => (true, path),
};
log::info!(
"[updates] completed staging/install; recovery or installer files: {}",
backup.display()
);
update(|s| {
s.phase = if staged { "prepared" } else { "installed" }.into();
s.busy = false;
s.can_install = false;
});
}
Err(_) if CANCEL.load(Ordering::Relaxed) => update(|s| {
s.phase = "cancelled".into();
s.busy = false;
}),
Err(error) => failed(error),
}
});
}
#[cfg(target_os = "linux")]
async fn check_flatpak() {
use qbz_updater::flatpak::{Availability, Monitor};
match Monitor::check().await {
Err(error) => failed(error),
Ok(monitor) => {
let key = monitor.info.reminder_key();
let suppression_key = key.clone();
let suppressed =
tokio::task::spawn_blocking(move || store()?.suppressed(&suppression_key)).await;
let suppressed = !matches!(suppressed, Ok(Ok(false)));
update(|s| {
s.busy = false;
s.reminder_key = key;
match monitor.info.availability() {
Availability::Current => s.phase = "current".into(),
Availability::Restart => s.phase = "installed".into(),
Availability::Available => {
s.phase = "available".into();
s.can_install = true;
s.flatpak = Some(std::sync::Arc::new(monitor));
if !s.manual && s.check_on_launch && !suppressed {
s.open = true;
}
}
}
});
}
}
}
+29
View File
@@ -0,0 +1,29 @@
[package]
name = "qbz-updater"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
base64.workspace = true
chrono = { workspace = true, features = ["serde"] }
reqwest.workspace = true
serde.workspace = true
serde_json.workspace = true
tokio.workspace = true
semver = "1"
minisign-verify = "0.2.5"
rusqlite = { version = "0.40", features = ["bundled"] }
tempfile = "3"
flate2 = "1"
tar = "0.4"
[target.'cfg(target_os = "linux")'.dependencies]
# Match Qt/ksni: never enable zbus/tokio through feature unification.
zbus = { version = "5", default-features = false, features = ["async-io"] }
futures-util = "0.3"
[target.'cfg(windows)'.dependencies]
sha2 = "0.10"
windows-sys = { version = "0.61", features = ["Win32_System_Registry"] }
+18
View File
@@ -0,0 +1,18 @@
//! Verify a downloaded release without installing or launching it.
fn main() {
let args: Vec<_> = std::env::args_os().skip(1).collect();
if args.len() != 2 {
eprintln!("usage: verify ASSET SIGNATURE_FILE");
std::process::exit(2);
}
let result = std::fs::read_to_string(&args[1])
.map_err(|e| e.to_string())
.and_then(|sig| qbz_updater::install::verify(std::path::Path::new(&args[0]), &sig));
match result {
Ok(()) => println!("QBZ release signature verified"),
Err(error) => {
eprintln!("{error}");
std::process::exit(1);
}
}
}
+225
View File
@@ -0,0 +1,225 @@
//! Update only the caller's Flatpak ref through its native portal. GitHub
//! release versions do not establish availability in this installation's remote.
use crate::Result;
use futures_util::StreamExt;
use std::{
collections::HashMap,
sync::atomic::{AtomicBool, AtomicU64, Ordering},
time::Duration,
};
use zbus::{
Connection, Proxy,
zvariant::{OwnedObjectPath, OwnedValue, Value},
};
const SERVICE: &str = "org.freedesktop.portal.Flatpak";
const ROOT: &str = "/org/freedesktop/portal/Flatpak";
const INTERFACE: &str = "org.freedesktop.portal.Flatpak.UpdateMonitor";
static TOKEN: AtomicU64 = AtomicU64::new(0);
type Dict = HashMap<String, OwnedValue>;
#[derive(Debug, PartialEq, Eq)]
pub enum Availability {
Current,
Available,
Restart,
}
#[derive(Debug)]
pub struct Info {
pub running: String,
pub local: String,
pub remote: String,
}
impl Info {
pub fn availability(&self) -> Availability {
if self.remote != self.local {
Availability::Available
} else if self.local != self.running {
Availability::Restart
} else {
Availability::Current
}
}
pub fn reminder_key(&self) -> String {
format!("flatpak:{}", self.remote)
}
fn parse(dict: &Dict) -> Result<Self> {
fn commit(dict: &Dict, key: &str) -> Result<String> {
let value = dict
.get(key)
.and_then(|v| <&str>::try_from(v).ok())
.ok_or_else(|| format!("Flatpak omitted {key}; update availability is unknown"))?;
if value.len() != 64 || !value.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(format!("Flatpak returned an invalid {key}"));
}
Ok(value.into())
}
Ok(Self {
running: commit(dict, "running-commit")?,
local: commit(dict, "local-commit")?,
remote: commit(dict, "remote-commit")?,
})
}
}
/// Owns a dedicated bus connection. Dropping the monitor disconnects its unique
/// sender, which also releases the portal object, including failed checks.
pub struct Monitor {
proxy: Proxy<'static>,
pub info: Info,
}
impl Monitor {
pub async fn check() -> Result<Self> {
tokio::time::timeout(Duration::from_secs(45), async {
let connection = Connection::session().await.map_err(|e| e.to_string())?;
Self::with_connection(connection).await
})
.await
.map_err(|_| "Flatpak did not report update availability in time".to_string())?
}
async fn with_connection(connection: Connection) -> Result<Self> {
let token = format!(
"qbz{}_{}",
std::process::id(),
TOKEN.fetch_add(1, Ordering::Relaxed)
);
let sender = connection
.unique_name()
.ok_or("Flatpak connection has no unique name")?
.as_str()
.trim_start_matches(':')
.replace('.', "_");
let path = format!("{ROOT}/update_monitor/{sender}/{token}");
let proxy = Proxy::new_owned(connection.clone(), SERVICE, path.clone(), INTERFACE)
.await
.map_err(|e| e.to_string())?;
// Subscribe BEFORE creation: a locally cached update can arrive before
// CreateUpdateMonitor returns. The caller-provided token fixes the path.
let mut signals = proxy
.receive_signal("UpdateAvailable")
.await
.map_err(|e| e.to_string())?;
let portal = Proxy::new(&connection, SERVICE, ROOT, SERVICE)
.await
.map_err(|e| e.to_string())?;
let options = HashMap::from([("handle_token", Value::from(token.as_str()))]);
let handle: OwnedObjectPath = portal
.call("CreateUpdateMonitor", &(options,))
.await
.map_err(|e| e.to_string())?;
if handle.as_str() != path {
return Err("Flatpak returned an unexpected update monitor".into());
}
let message = signals
.next()
.await
.ok_or("Flatpak update monitor disconnected")?;
let (dict,): (Dict,) = message.body().deserialize().map_err(|e| e.to_string())?;
let info = Info::parse(&dict)?;
drop(signals);
Ok(Self { proxy, info })
}
pub async fn install(&self, cancel: &AtomicBool, progress: impl Fn(u32)) -> Result<()> {
let operation = async {
let mut signals = self
.proxy
.receive_signal("Progress")
.await
.map_err(|e| e.to_string())?;
let options: HashMap<&str, Value<'_>> = HashMap::new();
// An empty parent is permitted; Flatpak presents its own consent UI.
self.proxy
.call::<_, _, ()>("Update", &("", options))
.await
.map_err(|e| e.to_string())?;
loop {
let message = signals
.next()
.await
.ok_or("Flatpak update monitor disconnected")?;
let (dict,): (Dict,) = message.body().deserialize().map_err(|e| e.to_string())?;
match progress_state(&dict)? {
Progress::Running(percent) => progress(percent),
Progress::Done => return Ok(()),
}
}
};
let cancellation = async {
while !cancel.load(Ordering::Relaxed) {
tokio::time::sleep(Duration::from_millis(100)).await;
}
};
let result = tokio::select! {
r = tokio::time::timeout(Duration::from_secs(1800), operation) =>
r.map_err(|_| "Flatpak update timed out".to_string()).and_then(|r| r),
_ = cancellation => Err("Update cancelled".into()),
};
// Close cancels the native transaction on failure/cancellation too.
let _ = tokio::time::timeout(
Duration::from_secs(5),
self.proxy.call::<_, _, ()>("Close", &()),
)
.await;
result
}
}
enum Progress {
Running(u32),
Done,
}
fn progress_state(dict: &Dict) -> Result<Progress> {
let uint = |key| dict.get(key).and_then(|v| u32::try_from(v).ok());
match uint("status").unwrap_or(0) {
0 => {
let count = uint("n_ops").unwrap_or(1).max(1) as u64;
let operation = uint("op").unwrap_or(0) as u64;
let percent = uint("progress").unwrap_or(0).min(100) as u64;
Ok(Progress::Running(
((operation * 100 + percent) / count).min(100) as u32,
))
}
1 => Err("Flatpak found no update to install. Check for updates again.".into()),
2 => Ok(Progress::Done),
3 => Err(dict
.get("error_message")
.and_then(|v| <&str>::try_from(v).ok())
.unwrap_or("Flatpak could not install the update; use your software manager")
.into()),
_ => Err("Flatpak returned an unknown update status".into()),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn distinguishes_channel_update_from_already_deployed_restart() {
let mut i = Info {
running: "a".repeat(64),
local: "a".repeat(64),
remote: "a".repeat(64),
};
assert_eq!(i.availability(), Availability::Current);
i.remote = "b".repeat(64);
assert_eq!(i.availability(), Availability::Available);
i.local = i.remote.clone();
assert_eq!(i.availability(), Availability::Restart);
assert!(i.reminder_key().starts_with("flatpak:"));
assert!(Info::parse(&Dict::new()).is_err());
}
#[test]
fn progress_failure_is_not_install_success() {
let d = HashMap::from([("status".into(), OwnedValue::from(3u32))]);
assert!(progress_state(&d).is_err());
let d = HashMap::from([("status".into(), OwnedValue::from(2u32))]);
assert!(matches!(progress_state(&d), Ok(Progress::Done)));
}
}
#[cfg(test)]
#[path = "flatpak_tests.rs"]
mod wire_tests;
+192
View File
@@ -0,0 +1,192 @@
use super::*;
use std::{
io::{BufRead, BufReader},
process::{Child, Command, Stdio},
sync::Arc,
};
struct Bus(Child, String);
impl Bus {
fn new() -> Self {
let mut child = Command::new("dbus-daemon")
.args(["--session", "--nofork", "--print-address=1"])
.stdout(Stdio::piped())
.spawn()
.expect("dbus-daemon is required for the updater wire tests");
let mut address = String::new();
BufReader::new(child.stdout.take().unwrap())
.read_line(&mut address)
.unwrap();
Self(child, address.trim().into())
}
async fn connect(&self) -> Connection {
zbus::connection::Builder::address(self.1.as_str())
.unwrap()
.build()
.await
.unwrap()
}
}
impl Drop for Bus {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
struct Portal {
closed: Arc<AtomicBool>,
status: u32,
}
struct UpdateObject {
closed: Arc<AtomicBool>,
status: u32,
}
#[zbus::interface(name = "org.freedesktop.portal.Flatpak")]
impl Portal {
async fn create_update_monitor(
&self,
options: Dict,
#[zbus(connection)] connection: &Connection,
#[zbus(header)] header: zbus::message::Header<'_>,
) -> zbus::fdo::Result<OwnedObjectPath> {
let token = <&str>::try_from(options.get("handle_token").unwrap()).unwrap();
let sender = header
.sender()
.unwrap()
.as_str()
.trim_start_matches(':')
.replace('.', "_");
let path = format!("{ROOT}/update_monitor/{sender}/{token}");
connection
.object_server()
.at(
path.clone(),
UpdateObject {
closed: self.closed.clone(),
status: self.status,
},
)
.await
.unwrap();
let info = HashMap::from([
("running-commit", Value::from("a".repeat(64))),
("local-commit", Value::from("a".repeat(64))),
("remote-commit", Value::from("b".repeat(64))),
]);
// Intentionally send before the method reply: subscriptions installed
// afterwards lose this cached initial notification.
connection
.emit_signal(
header.sender().cloned(),
path.as_str(),
INTERFACE,
"UpdateAvailable",
&(info,),
)
.await
.unwrap();
Ok(OwnedObjectPath::try_from(path).unwrap())
}
}
#[zbus::interface(name = "org.freedesktop.portal.Flatpak.UpdateMonitor")]
impl UpdateObject {
async fn update(
&self,
parent_window: &str,
options: Dict,
#[zbus(connection)] connection: &Connection,
#[zbus(header)] header: zbus::message::Header<'_>,
) -> zbus::fdo::Result<()> {
assert!(parent_window.is_empty());
assert!(options.is_empty());
if self.status == 0 {
return Ok(());
}
let progress = HashMap::from([("status", Value::from(self.status))]);
connection
.emit_signal(
header.sender().cloned(),
header.path().unwrap(),
INTERFACE,
"Progress",
&(progress,),
)
.await
.unwrap();
Ok(())
}
fn close(&self) {
self.closed.store(true, Ordering::Relaxed);
}
}
async fn fixture(status: u32) -> (Bus, Connection, Arc<AtomicBool>, Monitor) {
let bus = Bus::new();
let closed = Arc::new(AtomicBool::new(false));
let server = zbus::connection::Builder::address(bus.1.as_str())
.unwrap()
.name(SERVICE)
.unwrap()
.serve_at(
ROOT,
Portal {
closed: closed.clone(),
status,
},
)
.unwrap()
.build()
.await
.unwrap();
let monitor = tokio::time::timeout(
Duration::from_secs(5),
Monitor::with_connection(bus.connect().await),
)
.await
.unwrap()
.unwrap();
(bus, server, closed, monitor)
}
#[tokio::test]
async fn early_portal_signals_survive_check_and_install() {
let (_bus, _server, closed, monitor) = fixture(2).await;
assert_eq!(monitor.info.availability(), Availability::Available);
let cancel = AtomicBool::new(false);
tokio::time::timeout(Duration::from_secs(5), monitor.install(&cancel, |_| {}))
.await
.unwrap()
.unwrap();
assert!(closed.load(Ordering::Relaxed));
}
#[tokio::test]
async fn portal_failure_is_reported_and_monitor_closed() {
let (_bus, _server, closed, monitor) = fixture(3).await;
let cancel = AtomicBool::new(false);
let result = tokio::time::timeout(Duration::from_secs(5), monitor.install(&cancel, |_| {}))
.await
.unwrap();
assert!(result.is_err());
assert!(closed.load(Ordering::Relaxed));
}
#[tokio::test]
async fn cancelling_portal_update_closes_the_native_transaction() {
let (_bus, _server, closed, monitor) = fixture(0).await;
let cancel = AtomicBool::new(true);
let result = tokio::time::timeout(Duration::from_secs(5), monitor.install(&cancel, |_| {}))
.await
.unwrap();
assert!(result.unwrap_err().contains("cancelled"));
assert!(closed.load(Ordering::Relaxed));
}
#[tokio::test]
async fn an_empty_transaction_never_reports_a_successful_installation() {
let (_bus, _server, closed, monitor) = fixture(1).await;
let cancel = AtomicBool::new(false);
let result = tokio::time::timeout(Duration::from_secs(5), monitor.install(&cancel, |_| {}))
.await.unwrap();
assert!(result.unwrap_err().contains("no update to install"));
assert!(closed.load(Ordering::Relaxed));
}
+35
View File
@@ -0,0 +1,35 @@
param(
[Parameter(Mandatory=$true)][int]$ParentPid,
[Parameter(Mandatory=$true)][string]$AppPath,
[Parameter(Mandatory=$true)][string]$Package,
[Parameter(Mandatory=$true)][ValidatePattern('^[a-f0-9]{64}$')][string]$Sha256
)
$ErrorActionPreference = 'Stop'
$stage = Split-Path -Parent $Package
$result = Join-Path $stage 'result.txt'
try {
$parent = Get-Process -Id $ParentPid
if ($parent.Path -ine $AppPath) { throw 'The parent application path changed.' }
# Open the actual process handle BEFORE the ready handshake. PID reuse
# cannot make us wait for or terminate an unrelated process afterwards.
$null = $parent.Handle
[IO.File]::WriteAllText((Join-Path $stage 'ready'), 'ready')
$parent.WaitForExit()
if ((Get-FileHash -LiteralPath $Package -Algorithm SHA256).Hash -ine $Sha256) {
throw 'The verified MSI changed before installation.'
}
$log = Join-Path $stage 'msiexec.log'
# No elevation or machine restart. The MSI retains its per-user scope and
# MajorUpgrade/rollback behavior. Keep the log and package on failure.
$arguments = '/i "{0}" /passive /norestart REBOOT=ReallySuppress /l*v "{1}"' -f $Package,$log
$installer = Start-Process -FilePath "$env:SystemRoot\System32\msiexec.exe" -ArgumentList $arguments -Wait -PassThru
if ($installer.ExitCode -notin @(0,3010)) { throw "Windows Installer returned $($installer.ExitCode). See $log" }
[IO.File]::WriteAllText($result, "Installed; Windows Installer exit $($installer.ExitCode)")
Start-Process -FilePath $AppPath
} catch {
[IO.File]::WriteAllText($result, $_.Exception.Message)
# The parent has exited; show the failure instead of silently losing it.
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.MessageBox]::Show($_.Exception.Message, 'QBZ update', 'OK', 'Error') | Out-Null
exit 1
}
+539
View File
@@ -0,0 +1,539 @@
use crate::{Asset, Result};
use base64::Engine;
use std::{
io::Read,
path::{Path, PathBuf},
sync::atomic::{AtomicBool, Ordering},
time::{Duration, Instant},
};
// Public verification key from the shipping Tauri updater. Not an API secret.
const PUBLIC_KEY: &str = "RWSGlbvrbc5/P3/4zoXZfBd+pee5Kw7h5/gUIE7B9GiL47dvUSNpNGLm";
const MAX_DOWNLOAD: u64 = 2 * 1024 * 1024 * 1024;
pub enum InstallOutcome {
Installed(PathBuf),
Prepared(PathBuf),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Installation {
AppImage(PathBuf),
MacBundle(PathBuf),
WindowsMsi(PathBuf),
Flatpak,
Snap,
Nix,
Managed,
}
impl Installation {
pub fn detect() -> Self {
if std::env::var_os("FLATPAK_ID").is_some() || Path::new("/.flatpak-info").exists() {
return Self::Flatpak;
}
if std::env::var_os("SNAP").is_some() {
return Self::Snap;
}
let exe = std::env::current_exe().unwrap_or_default();
#[cfg(windows)]
if crate::windows::is_msi_install(&exe) {
return Self::WindowsMsi(exe);
}
if exe.starts_with("/nix/store") {
return Self::Nix;
}
if cfg!(target_os = "linux") {
if let Some(path) = std::env::var_os("APPIMAGE").map(PathBuf::from) {
// The runtime supplies the original image, outside its mount.
if path.is_absolute() && path.is_file() {
return Self::AppImage(path);
}
}
}
if cfg!(target_os = "macos") {
if let Some(bundle) = exe
.ancestors()
.find(|p| p.extension().is_some_and(|x| x == "app"))
{
// Homebrew owns bundles in its cellar; do not replace them.
if !bundle.starts_with("/Volumes")
&& !bundle.to_string_lossy().contains("/Caskroom/")
&& mac_bundle_uses_upstream_signature(bundle)
{
return Self::MacBundle(bundle.into());
}
}
}
Self::Managed
}
pub fn label(&self) -> &'static str {
match self {
Self::AppImage(_) => "AppImage",
Self::MacBundle(_) => "macOS",
Self::WindowsMsi(_) => "Windows MSI",
Self::Flatpak => "Flatpak",
Self::Snap => "Snap",
Self::Nix => "Nix",
Self::Managed => "System / manual",
}
}
pub fn platform(&self) -> Option<String> {
if !matches!(std::env::consts::ARCH, "x86_64" | "aarch64") {
return None;
}
let os = match self {
Self::AppImage(_) => "linux",
Self::MacBundle(_) => "darwin",
Self::WindowsMsi(_) if std::env::consts::ARCH == "x86_64" => "windows",
_ => return None,
};
Some(format!("{os}-{}", std::env::consts::ARCH))
}
fn destination(&self) -> Result<&Path> {
match self {
Self::AppImage(p) | Self::MacBundle(p) | Self::WindowsMsi(p) => Ok(p),
_ => Err("This installation is managed outside QBZ".into()),
}
}
}
fn mac_bundle_uses_upstream_signature(bundle: &Path) -> bool {
#[cfg(target_os = "macos")]
{
// Community DMGs/Homebrew use a Developer ID and notarization. The
// upstream manifest contains an ad-hoc bundle: never downgrade that
// trust channel merely because both bundles are named QBZ.app.
let Ok(output) = std::process::Command::new("/usr/bin/codesign")
.args(["--display", "--verbose=2"])
.arg(bundle)
.output()
else {
return false;
};
output.status.success()
&& upstream_signature_description(&String::from_utf8_lossy(&output.stderr))
}
#[cfg(not(target_os = "macos"))]
{
let _ = bundle;
false
}
}
#[cfg(any(target_os = "macos", test))]
fn upstream_signature_description(description: &str) -> bool {
description.lines().any(|l| l.trim() == "Signature=adhoc")
&& !description
.lines()
.any(|l| l.starts_with("TeamIdentifier=") && l != "TeamIdentifier=not set")
}
fn cancelled(cancel: &AtomicBool) -> Result<()> {
if cancel.load(Ordering::Relaxed) {
Err("Update cancelled".into())
} else {
Ok(())
}
}
fn signature(encoded: &str) -> Result<minisign_verify::Signature> {
let bytes = base64::engine::general_purpose::STANDARD
.decode(encoded.trim())
.map_err(|e| e.to_string())?;
let text = std::str::from_utf8(&bytes).map_err(|e| e.to_string())?;
minisign_verify::Signature::decode(text).map_err(|e| e.to_string())
}
pub fn verify(file: &Path, encoded: &str) -> Result<()> {
verify_with_key(file, encoded, PUBLIC_KEY)
}
fn verify_with_key(file: &Path, encoded: &str, public_key: &str) -> Result<()> {
let key = minisign_verify::PublicKey::from_base64(public_key).map_err(|e| e.to_string())?;
let sig = signature(encoded)?;
let mut verifier = key.verify_stream(&sig).map_err(|e| e.to_string())?;
let mut input = std::fs::File::open(file).map_err(|e| e.to_string())?;
let mut buffer = [0u8; 65536];
loop {
let n = input.read(&mut buffer).map_err(|e| e.to_string())?;
if n == 0 {
break;
}
verifier.update(&buffer[..n]);
}
verifier
.finalize()
.map_err(|e| format!("Update signature verification failed: {e}"))
}
/// Downloads onto the installation filesystem, verifies before touching the
/// live application, and keeps the old application as a rollback copy.
/// The caller serializes installs and disables exit during final replacement.
pub async fn install(
installation: Installation,
asset: Asset,
cancel: &AtomicBool,
progress: impl Fn(&str, u64, Option<u64>) + Send + Sync,
) -> Result<InstallOutcome> {
let destination = installation.destination()?.to_path_buf();
let parent = destination
.parent()
.ok_or("Installation has no parent directory")?;
// Advisory OS lock survives an async hop and is released after a crash.
// Keep the lock file: removing it would let another process lock a new inode.
let install_lock = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(parent.join(".qbz-updater.lock"))
.map_err(|e| e.to_string())?;
install_lock
.try_lock()
.map_err(|e| format!("Another update is already running: {e}"))?;
// Do not follow a launcher symlink and unexpectedly replace its target.
let original = std::fs::symlink_metadata(&destination).map_err(|e| e.to_string())?;
if original.file_type().is_symlink() {
return Err(
"This installation is a symlink; update it using its installation manager".into(),
);
}
let stage = tempfile::Builder::new()
.prefix(".qbz-update-")
.tempdir_in(parent)
.map_err(|e| format!("Cannot write to the installation directory: {e}"))?;
let payload = stage.path().join("download");
let mut output = tokio::fs::File::create(&payload)
.await
.map_err(|e| e.to_string())?;
cancelled(cancel)?;
let mut response = crate::client(Duration::from_secs(30 * 60))?
.get(&asset.url)
.send()
.await
.and_then(reqwest::Response::error_for_status)
.map_err(|e| e.to_string())?;
let total = response.content_length();
if total.is_some_and(|v| v > MAX_DOWNLOAD) {
return Err("Update exceeds size limit".into());
}
let mut downloaded = 0;
let mut last = Instant::now();
progress("downloading", 0, total);
loop {
cancelled(cancel)?;
// Bounded inactivity, separate from the full download deadline.
let chunk = tokio::time::timeout(Duration::from_secs(30), response.chunk())
.await
.map_err(|_| "Update download timed out")?
.map_err(|e| e.to_string())?;
let Some(chunk) = chunk else { break };
downloaded += chunk.len() as u64;
if downloaded > MAX_DOWNLOAD {
return Err("Update exceeds size limit".into());
}
tokio::io::AsyncWriteExt::write_all(&mut output, &chunk)
.await
.map_err(|e| e.to_string())?;
if last.elapsed() >= Duration::from_millis(200) {
progress("downloading", downloaded, total);
last = Instant::now();
}
}
output.sync_all().await.map_err(|e| e.to_string())?;
drop(output);
cancelled(cancel)?;
progress("verifying", downloaded, total);
let signature = asset.signature;
let verify_path = payload.clone();
tokio::task::spawn_blocking(move || verify(&verify_path, &signature))
.await
.map_err(|e| e.to_string())??;
cancelled(cancel)?;
progress("installing", downloaded, total);
tokio::task::spawn_blocking(move || {
let _lock = install_lock;
let current = std::fs::symlink_metadata(&destination).map_err(|e| e.to_string())?;
if current.file_type().is_symlink()
|| current.len() != original.len()
|| current.modified().ok() != original.modified().ok()
{
return Err(
"The installation changed while downloading; check for updates again".into(),
);
}
#[cfg(windows)]
if let Installation::WindowsMsi(exe) = &installation {
return crate::windows::stage_msi(exe, stage, &payload).map(InstallOutcome::Prepared);
}
apply(&installation, stage, &payload).map(InstallOutcome::Installed)
})
.await
.map_err(|e| e.to_string())?
}
fn apply(installation: &Installation, stage: tempfile::TempDir, payload: &Path) -> Result<PathBuf> {
let destination = installation.destination()?;
let backup = stage.path().join("previous");
match installation {
Installation::AppImage(_) => {
// Signatures authenticate bytes; format validation prevents a
// mismatched official asset from replacing a working installation.
let mut header = [0u8; 11];
std::fs::File::open(payload)
.and_then(|mut f| f.read_exact(&mut header))
.map_err(|e| e.to_string())?;
if &header[..4] != b"\x7fELF" || &header[8..11] != b"AI\x02" {
return Err("The signed file is not an AppImage".into());
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(payload, std::fs::Permissions::from_mode(0o755))
.map_err(|e| e.to_string())?;
}
// Hard-link backup keeps the live path present until atomic rename.
std::fs::hard_link(destination, &backup).map_err(|e| e.to_string())?;
std::fs::rename(payload, destination).map_err(|e| e.to_string())?;
}
Installation::MacBundle(_) => {
#[cfg(target_os = "macos")]
if !mac_bundle_uses_upstream_signature(destination) {
return Err(
"This macOS app must be updated through its original signing channel".into(),
);
}
let unpacked = stage.path().join("unpacked");
unpack_bundle(payload, &unpacked)?;
let bundle = unpacked.join("QBZ.app");
#[cfg(target_os = "macos")]
{
let status = std::process::Command::new("/usr/bin/codesign")
.args(["--verify", "--deep", "--strict"])
.arg(&bundle)
.status()
.map_err(|e| e.to_string())?;
if !status.success() {
return Err("The updated application failed code-signature validation".into());
}
}
std::fs::rename(destination, &backup).map_err(|e| e.to_string())?;
if let Err(error) = std::fs::rename(&bundle, destination) {
if let Err(rollback) = std::fs::rename(&backup, destination) {
let retained = stage.keep();
return Err(format!("Install failed: {error}; restore failed: {rollback}. Original retained at {}", retained.join("previous").display()));
}
return Err(error.to_string());
}
}
_ => return Err("This installation is managed outside QBZ".into()),
}
// Retain ONE old application per explicit update; never delete files a
// still-running process may need. No cleanup of arbitrary sibling folders.
let retained = stage.keep();
Ok(retained.join("previous"))
}
fn unpack_bundle(payload: &Path, destination: &Path) -> Result<()> {
std::fs::create_dir_all(destination).map_err(|e| e.to_string())?;
let file = std::fs::File::open(payload).map_err(|e| e.to_string())?;
let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(file));
let mut size = 0u64;
for entry in archive.entries().map_err(|e| e.to_string())? {
let mut entry = entry.map_err(|e| e.to_string())?;
let path = entry.path().map_err(|e| e.to_string())?.into_owned();
if !path.starts_with("QBZ.app")
|| path.components().any(|c| {
matches!(
c,
std::path::Component::ParentDir
| std::path::Component::RootDir
| std::path::Component::Prefix(_)
)
})
{
return Err("Update archive contains an invalid path".into());
}
if let Some(target) = entry.link_name().map_err(|e| e.to_string())? {
// Framework bundles contain relative symlinks. Permit those only
// while their lexical target remains inside the staged QBZ.app.
let base = if entry.header().entry_type().is_hard_link() {
Path::new("")
} else {
path.parent().unwrap_or(Path::new(""))
};
let mut resolved = PathBuf::new();
for component in base.join(target.as_ref()).components() {
match component {
std::path::Component::Normal(name) => resolved.push(name),
std::path::Component::CurDir => {}
std::path::Component::ParentDir => {
if !resolved.pop() {
return Err("Update archive link escapes its bundle".into());
}
}
_ => return Err("Update archive contains an absolute link".into()),
}
}
if !resolved.starts_with("QBZ.app") {
return Err("Update archive link escapes its bundle".into());
}
}
size = size
.checked_add(entry.size())
.ok_or("Update archive size overflow")?;
if size > 4 * MAX_DOWNLOAD {
return Err("Update archive exceeds size limit".into());
}
if !entry.unpack_in(destination).map_err(|e| e.to_string())? {
return Err("Update archive escaped its staging directory".into());
}
}
if !destination.join("QBZ.app/Contents/MacOS/qbz").is_file()
|| !destination.join("QBZ.app/Contents/Info.plist").is_file()
{
return Err("Update archive does not contain a QBZ application".into());
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn notarized_macos_channel_is_never_replaced_with_an_ad_hoc_bundle() {
assert!(upstream_signature_description(
"Signature=adhoc\nTeamIdentifier=not set\n"
));
assert!(!upstream_signature_description(
"Authority=Developer ID Application: Publisher\nTeamIdentifier=ABC123\n"
));
assert!(!upstream_signature_description(
"Signature=adhoc\nTeamIdentifier=ABC123\n"
));
assert!(!upstream_signature_description(""));
}
#[test]
fn public_key_and_bad_signature_fail_closed() {
assert!(minisign_verify::PublicKey::from_base64(PUBLIC_KEY).is_ok());
let f = tempfile::NamedTempFile::new().unwrap();
assert!(verify(f.path(), "not a signature").is_err());
}
#[test]
fn tauri_envelope_verifies_bytes_and_rejects_tampering_or_wrong_key() {
// Public test vector from minisign-verify (MIT); same prehashed
// signature + outer base64 envelope used by the QBZ release signer.
let key = "RWQf6LRCGA9i53mlYecO4IzT51TGPpvWucNSCh1CBM0QTaLn73Y7GFO3";
let text = "untrusted comment: signature from minisign secret key\nRUQf6LRCGA9i559r3g7V1qNyJDApGip8MfqcadIgT9CuhV3EMhHoN1mGTkUidF/z7SrlQgXdy8ofjb7bNJJylDOocrCo8KLzZwo=\ntrusted comment: timestamp:1556193335\tfile:test\ny/rUw2y8/hOUYjZU71eHp/Wo1KZ40fGy2VJEDl34XMJM+TX48Ss/17u3IvIfbVR1FkZZSNCisQbuQY+bHwhEBg==";
let signature = base64::engine::general_purpose::STANDARD.encode(text);
let f = tempfile::NamedTempFile::new().unwrap();
std::fs::write(f.path(), b"test").unwrap();
assert!(verify_with_key(f.path(), &signature, key).is_ok());
assert!(verify(f.path(), &signature).is_err());
std::fs::write(f.path(), b"tampered").unwrap();
assert!(verify_with_key(f.path(), &signature, key).is_err());
}
#[test]
fn mac_archive_rejects_symlink_outside_bundle() {
let dir = tempfile::tempdir().unwrap();
let payload = dir.path().join("update.tar.gz");
let gz = flate2::write::GzEncoder::new(
std::fs::File::create(&payload).unwrap(),
flate2::Compression::fast(),
);
let mut tar = tar::Builder::new(gz);
let mut h = tar::Header::new_gnu();
h.set_entry_type(tar::EntryType::Symlink);
h.set_size(0);
h.set_mode(0o777);
tar.append_link(&mut h, "QBZ.app/escape", "../../outside")
.unwrap();
tar.into_inner().unwrap().finish().unwrap();
assert!(unpack_bundle(&payload, &dir.path().join("unpacked")).is_err());
assert!(!dir.path().join("unpacked/QBZ.app/escape").exists());
}
#[cfg(not(target_os = "macos"))]
#[test]
fn mac_bundle_layout_replaces_whole_bundle_and_retains_previous_files() {
// Exercise archive/filesystem behavior independently of macOS's native
// codesign gate; that gate still requires a real macOS smoke test.
let dir = tempfile::tempdir().unwrap();
let destination = dir.path().join("QBZ.app");
std::fs::create_dir_all(destination.join("Contents/MacOS")).unwrap();
std::fs::write(destination.join("Contents/MacOS/qbz"), b"old executable").unwrap();
std::fs::write(destination.join("old-only"), b"old resource").unwrap();
let stage = tempfile::tempdir_in(dir.path()).unwrap();
let payload = stage.path().join("download");
let gz = flate2::write::GzEncoder::new(
std::fs::File::create(&payload).unwrap(),
flate2::Compression::fast(),
);
let mut tar = tar::Builder::new(gz);
for (path, bytes) in [
("QBZ.app/Contents/MacOS/qbz", b"new executable".as_slice()),
("QBZ.app/Contents/Info.plist", b"bundle metadata".as_slice()),
] {
let mut header = tar::Header::new_gnu();
header.set_size(bytes.len() as u64);
header.set_mode(0o755);
header.set_cksum();
tar.append_data(&mut header, path, bytes).unwrap();
}
tar.into_inner().unwrap().finish().unwrap();
let backup = apply(
&Installation::MacBundle(destination.clone()),
stage,
&payload,
)
.unwrap();
assert_eq!(
std::fs::read(destination.join("Contents/MacOS/qbz")).unwrap(),
b"new executable"
);
assert!(!destination.join("old-only").exists());
assert_eq!(
std::fs::read(backup.join("Contents/MacOS/qbz")).unwrap(),
b"old executable"
);
assert_eq!(
std::fs::read(backup.join("old-only")).unwrap(),
b"old resource"
);
}
#[test]
fn package_managers_never_offer_binary_replacement() {
for install in [
Installation::Flatpak,
Installation::Snap,
Installation::Nix,
Installation::Managed,
] {
assert!(install.platform().is_none());
assert!(install.destination().is_err());
}
}
#[test]
fn invalid_payload_leaves_installation_untouched() {
let d = tempfile::tempdir().unwrap();
let dest = d.path().join("QBZ.AppImage");
std::fs::write(&dest, b"old application").unwrap();
let stage = tempfile::tempdir_in(d.path()).unwrap();
let payload = stage.path().join("download");
std::fs::write(&payload, b"wrong payload bytes").unwrap();
assert!(apply(&Installation::AppImage(dest.clone()), stage, &payload).is_err());
assert_eq!(std::fs::read(dest).unwrap(), b"old application");
}
#[test]
fn replacement_retains_previous_application() {
let d = tempfile::tempdir().unwrap();
let dest = d.path().join("QBZ.AppImage");
std::fs::write(&dest, b"old application").unwrap();
let stage = tempfile::tempdir_in(d.path()).unwrap();
let payload = stage.path().join("download");
let image = b"\x7fELF\0\0\0\0AI\x02new application";
std::fs::write(&payload, image).unwrap();
let backup = apply(&Installation::AppImage(dest.clone()), stage, &payload).unwrap();
assert_eq!(std::fs::read(dest).unwrap(), image);
assert_eq!(std::fs::read(backup).unwrap(), b"old application");
}
}
+253
View File
@@ -0,0 +1,253 @@
//! Release checks and signed updates, independent of the desktop and audio.
//! Package-manager installations only check: their manager owns installation.
#[cfg(target_os = "linux")]
pub mod flatpak;
pub mod install;
pub mod store;
#[cfg(windows)]
mod windows;
use chrono::{DateTime, Utc};
use semver::Version;
use serde::Deserialize;
use std::{collections::HashMap, time::Duration};
pub type Result<T> = std::result::Result<T, String>;
const RELEASES: &str = "https://api.github.com/repos/vicrodh/qbz/releases?per_page=30";
pub const RELEASE_PAGE: &str = "https://github.com/vicrodh/qbz/releases";
const MAX_METADATA: usize = 2 * 1024 * 1024;
#[derive(Clone, Debug, Deserialize)]
pub struct Release {
pub tag_name: String,
pub published_at: Option<DateTime<Utc>>,
pub draft: bool,
pub prerelease: bool,
}
impl Release {
pub fn version(&self) -> Result<Version> {
Version::parse(self.tag_name.strip_prefix('v').unwrap_or(&self.tag_name))
.map_err(|e| e.to_string())
}
pub fn page(&self) -> String {
format!("{RELEASE_PAGE}/tag/{}", self.tag_name)
}
/// Release-age policy stays in the shared updater, not in its UI adapter.
pub fn notification_ready(&self) -> bool {
self.published_at
.is_some_and(|date| Utc::now().signed_duration_since(date).num_hours() >= 12)
}
}
/// Manual checks bypass notification suppression and the automatic 12-hour delay.
pub fn select_release(
releases: Vec<Release>,
current: &str,
automatic: bool,
now: DateTime<Utc>,
) -> Result<Option<Release>> {
let current = Version::parse(current).map_err(|e| e.to_string())?;
Ok(releases
.into_iter()
.filter(|r| {
let Ok(v) = r.version() else { return false };
!r.draft
&& !r.prerelease
&& v.pre.is_empty()
&& v.cmp_precedence(&current).is_gt()
&& r.published_at.is_some_and(|date| {
let age = now.signed_duration_since(date).num_seconds();
age >= if automatic { 12 * 3600 } else { 0 }
})
})
.max_by(|a, b| a.version().unwrap().cmp_precedence(&b.version().unwrap())))
}
pub fn client(timeout: Duration) -> Result<reqwest::Client> {
reqwest::Client::builder()
.user_agent(concat!("QBZ/", env!("CARGO_PKG_VERSION")))
.https_only(true)
.connect_timeout(Duration::from_secs(4))
.timeout(timeout)
.build()
.map_err(|e| e.to_string())
}
pub async fn metadata(url: &str) -> Result<Vec<u8>> {
let mut response = client(Duration::from_secs(4))?
.get(url)
.send()
.await
.and_then(reqwest::Response::error_for_status)
.map_err(|e| e.to_string())?;
let mut bytes = Vec::new();
while let Some(chunk) = response.chunk().await.map_err(|e| e.to_string())? {
if bytes.len() + chunk.len() > MAX_METADATA {
return Err("Update metadata exceeds size limit".into());
}
bytes.extend_from_slice(&chunk);
}
Ok(bytes)
}
pub async fn check(current: &str, automatic: bool) -> Result<Option<Release>> {
let releases = serde_json::from_slice(&metadata(RELEASES).await?).map_err(|e| e.to_string())?;
select_release(releases, current, automatic, Utc::now())
}
#[derive(Clone, Debug, Deserialize)]
pub struct Asset {
pub url: String,
pub signature: String,
}
#[derive(Deserialize)]
struct Manifest {
version: String,
platforms: HashMap<String, Asset>,
}
pub fn select_asset(bytes: &[u8], release: &Release, platform: &str) -> Result<Asset> {
let manifest: Manifest = serde_json::from_slice(bytes).map_err(|e| e.to_string())?;
if Version::parse(&manifest.version).map_err(|e| e.to_string())? != release.version()? {
return Err("Update manifest does not match the selected release".into());
}
let asset = manifest
.platforms
.get(platform)
.ok_or("No signed update for this platform")?;
let prefix = format!(
"https://github.com/vicrodh/qbz/releases/download/{}/",
release.tag_name
);
let name = asset
.url
.strip_prefix(&prefix)
.ok_or("Update asset is outside the selected QBZ release")?;
let expected = match platform {
"linux-x86_64" => format!("QBZ_{}_amd64.AppImage", release.version()?),
"linux-aarch64" => format!("QBZ_{}_aarch64.AppImage", release.version()?),
"darwin-x86_64" => "QBZ_x64.app.tar.gz".into(),
"darwin-aarch64" => "QBZ_aarch64.app.tar.gz".into(),
"windows-x86_64" => format!("QBZ_{}_x64.msi", release.version()?),
_ => return Err("No signed update for this platform".into()),
};
if name != expected || asset.signature.is_empty() {
return Err("Invalid signed update asset".into());
}
Ok(asset.clone())
}
pub async fn asset(release: &Release, platform: &str) -> Result<Asset> {
// Bind to the selected tag, never the mutable /latest alias.
let url = format!(
"https://github.com/vicrodh/qbz/releases/download/{}/latest.json",
release.tag_name
);
select_asset(&metadata(&url).await?, release, platform)
}
#[cfg(test)]
mod tests {
use super::*;
fn release(v: &str, age: i64) -> Release {
Release {
tag_name: format!("v{v}"),
published_at: Some(Utc::now() - chrono::Duration::hours(age)),
draft: false,
prerelease: false,
}
}
#[test]
fn versions_order_semantically_and_never_downgrade() {
let r = select_release(
vec![release("2.9.0", 24), release("2.10.0", 24)],
"2.1.1",
true,
Utc::now(),
)
.unwrap()
.unwrap();
assert_eq!(r.tag_name, "v2.10.0");
assert!(select_release(
vec![release("2.1.1+other", 24), release("2.0.0", 24)],
"2.1.1",
false,
Utc::now()
)
.unwrap()
.is_none());
}
#[test]
fn automatic_waits_but_manual_finds_new_release() {
assert!(
select_release(vec![release("2.1.2", 1)], "2.1.1", true, Utc::now())
.unwrap()
.is_none()
);
assert!(
select_release(vec![release("2.1.2", 1)], "2.1.1", false, Utc::now())
.unwrap()
.is_some()
);
}
#[test]
fn rejects_drafts_prereleases_invalid_and_future_versions() {
let mut draft = release("3.0.0", 24);
draft.draft = true;
let mut pre = release("3.0.0", 24);
pre.prerelease = true;
assert!(select_release(
vec![
draft,
pre,
release("3.0.0-rc.1", 24),
release("bad", 24),
release("3.0.0", -1)
],
"2.1.1",
false,
Utc::now()
)
.unwrap()
.is_none());
}
#[test]
fn manifest_cannot_switch_version_platform_or_download_origin() {
let r = release("2.1.2", 24);
let valid = serde_json::json!({"version":"2.1.2","platforms":{"linux-x86_64":{"signature":"sig","url":"https://github.com/vicrodh/qbz/releases/download/v2.1.2/QBZ_2.1.2_amd64.AppImage"}}});
assert!(select_asset(&serde_json::to_vec(&valid).unwrap(), &r, "linux-x86_64").is_ok());
assert!(select_asset(&serde_json::to_vec(&valid).unwrap(), &r, "darwin-aarch64").is_err());
for (field, value) in [
("version", "2.1.3"),
("url", "https://evil.example/update.AppImage"),
(
"url",
"https://github.com/vicrodh/qbz/releases/download/v2.1.2/../bad.AppImage",
),
(
"url",
"https://github.com/vicrodh/qbz/releases/download/v2.1.2/QBZ_2.1.2_aarch64.AppImage",
),
] {
let mut invalid = valid.clone();
if field == "version" {
invalid[field] = value.into();
} else {
invalid["platforms"]["linux-x86_64"][field] = value.into();
}
assert!(
select_asset(&serde_json::to_vec(&invalid).unwrap(), &r, "linux-x86_64").is_err()
);
}
}
#[test]
fn windows_msi_manifest_cannot_select_a_portable_archive() {
let r = release("2.1.2", 24);
let mut manifest = serde_json::json!({"version":"2.1.2","platforms":{"windows-x86_64":{"signature":"sig","url":"https://github.com/vicrodh/qbz/releases/download/v2.1.2/QBZ_2.1.2_x64.msi"}}});
assert!(select_asset(&serde_json::to_vec(&manifest).unwrap(), &r, "windows-x86_64").is_ok());
manifest["platforms"]["windows-x86_64"]["url"] = "https://github.com/vicrodh/qbz/releases/download/v2.1.2/qbz_2.1.2_windows_x64.zip".into();
assert!(select_asset(&serde_json::to_vec(&manifest).unwrap(), &r, "windows-x86_64").is_err());
}
}
+72
View File
@@ -0,0 +1,72 @@
//! Reuses the Tauri-era updates.db and preserves existing opt-outs.
use crate::Result;
use rusqlite::Connection;
use std::path::Path;
pub struct Store(Connection);
impl Store {
pub fn open(path: &Path) -> Result<Self> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
let conn = Connection::open(path).map_err(|e| e.to_string())?;
conn.busy_timeout(std::time::Duration::from_secs(2))
.map_err(|e| e.to_string())?;
conn.execute_batch("PRAGMA journal_mode=WAL;
CREATE TABLE IF NOT EXISTS update_preferences (id INTEGER PRIMARY KEY CHECK(id=1), check_on_launch INTEGER NOT NULL DEFAULT 1, show_whats_new_on_launch INTEGER NOT NULL DEFAULT 1);
INSERT OR IGNORE INTO update_preferences (id,check_on_launch,show_whats_new_on_launch) VALUES (1,1,1);
CREATE TABLE IF NOT EXISTS ignored_releases (version TEXT PRIMARY KEY, ignored_at INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS acknowledged_releases (version TEXT PRIMARY KEY, acknowledged_at INTEGER NOT NULL);")
.map_err(|e| e.to_string())?;
Ok(Self(conn))
}
pub fn check_on_launch(&self) -> Result<bool> {
self.0
.query_row(
"SELECT check_on_launch FROM update_preferences WHERE id=1",
[],
|r| r.get(0),
)
.map_err(|e| e.to_string())
}
pub fn set_check_on_launch(&self, enabled: bool) -> Result<()> {
self.0
.execute(
"UPDATE update_preferences SET check_on_launch=? WHERE id=1",
[enabled],
)
.map_err(|e| e.to_string())?;
Ok(())
}
pub fn suppressed(&self, version: &str) -> Result<bool> {
self.0.query_row("SELECT EXISTS(SELECT 1 FROM ignored_releases WHERE version=?1 UNION ALL SELECT 1 FROM acknowledged_releases WHERE version=?1)", [version], |r| r.get(0)).map_err(|e| e.to_string())
}
pub fn ignore(&self, version: &str) -> Result<()> {
self.0
.execute(
"INSERT OR REPLACE INTO ignored_releases VALUES (?1,unixepoch())",
[version],
)
.map_err(|e| e.to_string())?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn preserves_existing_opt_out_and_ignores_across_reopen() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("updates.db");
let s = Store::open(&path).unwrap();
assert!(s.check_on_launch().unwrap());
s.set_check_on_launch(false).unwrap();
s.ignore("2.1.2").unwrap();
drop(s);
let s = Store::open(&path).unwrap();
assert!(!s.check_on_launch().unwrap());
assert!(s.suppressed("2.1.2").unwrap());
assert!(!s.suppressed("2.1.3").unwrap());
}
}
+132
View File
@@ -0,0 +1,132 @@
//! The MSI owns its files. Stage verified bytes and let Windows Installer do
//! the upgrade after the current application exits; never overwrite DLLs here.
use crate::Result;
use sha2::{Digest, Sha256};
use std::{
io::Read,
os::windows::process::CommandExt,
path::{Path, PathBuf},
process::{Command, Stdio},
time::{Duration, Instant},
};
use windows_sys::Win32::System::Registry::{HKEY_CURRENT_USER, RRF_RT_REG_SZ, RegGetValueW};
fn wide(value: &str) -> Vec<u16> {
value.encode_utf16().chain(Some(0)).collect()
}
pub fn is_msi_install(exe: &Path) -> bool {
let key = wide("Software\\blitzfc\\QBZ");
let name = wide("InstallDir");
let mut size = 0u32;
// This per-user key is authored by the fixed MainExe WiX component.
unsafe {
if RegGetValueW(
HKEY_CURRENT_USER,
key.as_ptr(),
name.as_ptr(),
RRF_RT_REG_SZ,
std::ptr::null_mut(),
std::ptr::null_mut(),
&mut size,
) != 0
|| size > 65536
{
return false;
}
let mut bytes = vec![0u16; size as usize / 2];
if RegGetValueW(
HKEY_CURRENT_USER,
key.as_ptr(),
name.as_ptr(),
RRF_RT_REG_SZ,
std::ptr::null_mut(),
bytes.as_mut_ptr().cast(),
&mut size,
) != 0
{
return false;
}
let end = bytes.iter().position(|c| *c == 0).unwrap_or(bytes.len());
let Ok(dir) = String::from_utf16(&bytes[..end]) else {
return false;
};
let registered = PathBuf::from(dir).join("qbz.exe").canonicalize();
matches!((registered,exe.canonicalize()),(Ok(a),Ok(b)) if a==b)
}
}
pub fn stage_msi(exe: &Path, stage: tempfile::TempDir, payload: &Path) -> Result<PathBuf> {
if !is_msi_install(exe) {
return Err("The installation is no longer owned by the QBZ MSI".into());
}
let mut input = std::fs::File::open(payload).map_err(|e| e.to_string())?;
let mut magic = [0u8; 8];
input.read_exact(&mut magic).map_err(|e| e.to_string())?;
if magic != [0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1] {
return Err("The signed package is not a Windows Installer database".into());
}
drop(input);
let mut input = std::fs::File::open(payload).map_err(|e| e.to_string())?;
let mut hash = Sha256::new();
let mut buffer = [0u8; 65536];
loop {
let n = input.read(&mut buffer).map_err(|e| e.to_string())?;
if n == 0 {
break;
}
hash.update(&buffer[..n]);
}
drop(input);
let digest = format!("{:x}", hash.finalize());
let package = stage.path().join("update.msi");
std::fs::rename(payload, &package).map_err(|e| e.to_string())?;
let script = stage.path().join("install.ps1");
let ready = stage.path().join("ready");
std::fs::write(&script, include_str!("install-msi.ps1")).map_err(|e| e.to_string())?;
let powershell =
PathBuf::from(std::env::var_os("SystemRoot").ok_or("SystemRoot is unavailable")?)
.join("System32/WindowsPowerShell/v1.0/powershell.exe");
let mut child = Command::new(powershell)
.args([
"-NoProfile",
"-NonInteractive",
"-WindowStyle",
"Hidden",
"-ExecutionPolicy",
"Bypass",
"-File",
])
.arg(&script)
.arg("-ParentPid")
.arg(std::process::id().to_string())
.arg("-AppPath")
.arg(exe)
.arg("-Package")
.arg(&package)
.arg("-Sha256")
.arg(digest)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.creation_flags(0x08000000)
.spawn()
.map_err(|e| format!("Could not start Windows Installer helper: {e}"))?;
let start = Instant::now();
loop {
if ready.is_file() {
return Ok(stage.keep());
}
if let Some(status) = child.try_wait().map_err(|e| e.to_string())? {
return Err(format!(
"Windows Installer helper exited before becoming ready: {status}"
));
}
if start.elapsed() > Duration::from_secs(15) {
let _ = child.kill();
let _ = child.wait();
return Err("Windows Installer helper did not become ready".into());
}
std::thread::sleep(Duration::from_millis(50));
}
}
+7
View File
@@ -75,6 +75,13 @@ cargo test \
--no-fail-fast \
"$@"
say "gate: one-line installer (isolated fixture homes)"
python3 scripts/test-installer.py
say "gate: signed updater regression suite present"
n=$(cargo test --manifest-path crates/Cargo.toml -p qbz-updater --lib -- --list 2>/dev/null | grep -c ': test$' || true)
(( n >= 11 )) || { echo "Updater suite has $n tests (expected >= 11)"; exit 1; }
say "gate: Orbit HTTP host isolation and library profile regressions present"
# The workspace run executes these. Keep actual socket/gate/shutdown tests and
# profile isolation from disappearing during the next extraction phases.
+249
View File
@@ -0,0 +1,249 @@
#!/usr/bin/env bash
# QBZ per-user installer. Canonical source: vicrodh/qbz scripts/install.sh.
# Published verbatim at https://qbz.lol/install.sh with the 2.1.2 website.
# Keep execution after the complete function definition: a truncated download
# must not start installing half a script. Compatible with macOS Bash 3.2.
qbz_install_main() (
set -euo pipefail
umask 077
local requested='' check_only=0 action=install arg
for arg in "$@"; do
case "$arg" in
--help|-h)
printf '%s\n' 'QBZ installer — Linux and macOS, x86_64 and ARM64' \
'Usage: bash install.sh [--check] [--version=X.Y.Z] [--uninstall]' \
'Default: latest stable release (2.1.2 or newer), installed for this user.' \
'--check: resolve and validate release metadata without installing.' \
'--uninstall: remove only this installer’s application and launchers; keep your data.'
return 0 ;;
--check) check_only=1 ;;
--uninstall) action=uninstall ;;
--version=*) requested=${arg#--version=} ;;
*) printf 'Unknown argument: %s\n' "$arg" >&2; return 1 ;;
esac
done
fail() { printf 'QBZ: %s\n' "$*" >&2; exit 1; }
if [ "$action" = uninstall ] && { [ "$check_only" = 1 ] || [ -n "$requested" ]; }; then
fail '--uninstall cannot be combined with --check or --version.'
fi
[ "${EUID:-$(id -u)}" -ne 0 ] || fail 'Run as your normal user, without sudo.'
[ -n "${HOME:-}" ] && [ "${HOME#/}" != "$HOME" ] && [ "$HOME" != / ] || fail 'HOME must be an absolute user directory.'
# Desktop Exec and shell launchers cannot safely represent control characters.
case "$HOME" in *$'\n'*|*$'\r'*|*$'\t'*) fail 'HOME contains an unsupported control character.' ;; esac
local system arch platform install_dir destination receipt launcher desktop icon
system=$(uname -s)
arch=$(uname -m)
case "$arch" in x86_64|amd64) arch=x86_64 ;; aarch64|arm64) arch=aarch64 ;; *) fail "Unsupported architecture: $arch" ;; esac
case "$system" in
Linux)
local libc libc_major libc_minor floor=35
[ "$arch" != aarch64 ] || floor=39
libc=$(getconf GNU_LIBC_VERSION 2>/dev/null) || fail 'The official Linux package requires glibc (musl systems are not supported).'
libc=${libc#glibc }
IFS=. read -r libc_major libc_minor <<< "$libc"
[[ "$libc_major" =~ ^[0-9]+$ ]] && [[ "$libc_minor" =~ ^[0-9]+$ ]] || fail 'Could not determine the glibc version.'
(( libc_major > 2 || (libc_major == 2 && libc_minor >= floor) )) || fail "This architecture requires glibc 2.$floor or newer. Use your distribution's package instead."
platform="linux-$arch"
install_dir="$HOME/.local/opt/qbz"
destination="$install_dir/QBZ.AppImage"
receipt="$install_dir/.qbz-installer"
launcher="$HOME/.local/bin/qbz"
desktop="$HOME/.local/share/applications/com.blitzfc.qbz.desktop"
icon="$install_dir/qbz.png" ;;
Darwin)
# Prefer a native bundle even when invoked from a Rosetta terminal.
if [ "$(/usr/sbin/sysctl -n hw.optional.arm64 2>/dev/null || :)" = 1 ]; then arch=aarch64; fi
platform="darwin-$arch"
install_dir="$HOME/Applications"
destination="$install_dir/QBZ.app"
receipt="$install_dir/.qbz-installer"
launcher=''; desktop=''; icon='' ;;
*) fail "Unsupported operating system: $system" ;;
esac
[ ! -L "$install_dir" ] && [ ! -L "$destination" ] && [ ! -L "$receipt" ] || fail 'Installation path is a symlink; manage it through its original installer.'
if [ "$action" = uninstall ]; then
if command -v pgrep >/dev/null 2>&1 && pgrep -x qbz >/dev/null 2>&1; then fail 'Close QBZ before uninstalling it.'; fi
[ -f "$receipt" ] && [ "$(cat "$receipt")" = 'qbz-one-line-v1' ] || fail 'This installation is not owned by this script.'
if [ "$system" = Linux ]; then
for arg in "$launcher" "$desktop"; do
if [ -f "$arg" ] && [ ! -L "$arg" ] && grep -q '^# QBZ one-line installer$' "$arg"; then rm -- "$arg"; fi
done
rm -f -- "$destination" "$icon" "$receipt"
rmdir "$install_dir" 2>/dev/null || :
else
[ -d "$destination" ] || fail 'QBZ.app is missing.'
/usr/bin/codesign -d --verbose=2 "$destination" 2>&1 | grep -q '^Signature=adhoc$' || fail 'The macOS signing channel changed; remove the app through its current installer.'
rm -rf -- "$destination"
rm -- "$receipt"
fi
printf '%s\n' 'QBZ removed. Your settings, library and downloads were kept.'
return 0
fi
if [ "$check_only" = 0 ]; then
if [ -e "$destination" ]; then
if [ -f "$receipt" ] && [ "$(cat "$receipt")" = 'qbz-one-line-v1' ]; then
printf '%s\n' 'QBZ is already installed. Use Settings → Updates in QBZ.'
return 0
fi
fail "An existing installation occupies $destination. Use its original updater."
fi
if [ "$system" = Linux ]; then
for arg in "$launcher" "$desktop"; do
[ ! -e "$arg" ] && [ ! -L "$arg" ] || fail "Existing launcher preserved: $arg"
done
fi
# A second install would shadow a distribution package or signed Mac app.
if command -v qbz >/dev/null 2>&1; then fail 'QBZ is already on PATH. Update it through its original installer.'; fi
if [ "$system" = Darwin ] && [ -e /Applications/QBZ.app ]; then fail 'QBZ already exists in /Applications. Keep its original update channel.'; fi
if [ "$system" = Linux ]; then
if command -v flatpak >/dev/null 2>&1 && flatpak info com.blitzfc.qbz >/dev/null 2>&1; then fail 'QBZ is installed with Flatpak. Update it through Flatpak.'; fi
if command -v snap >/dev/null 2>&1 && snap list qbz-player >/dev/null 2>&1; then fail 'QBZ is installed with Snap. Snap manages its updates.'; fi
fi
fi
command -v curl >/dev/null 2>&1 || fail 'curl is required.'
if ! command -v python3 >/dev/null 2>&1 && ! command -v jq >/dev/null 2>&1 && [ "$system" != Darwin ]; then
fail 'Install python3 or jq with your package manager, then run this command again.'
fi
local scratch
scratch=$(mktemp -d "${TMPDIR:-/tmp}/qbz-install.XXXXXXXX")
# A private scratch directory is the only recursively cleaned temporary path.
trap 'rm -rf -- "$scratch"' EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
fetch() { curl --proto '=https' --proto-redir '=https' --tlsv1.2 --fail --location --silent --show-error --connect-timeout 10 --max-time 600 --max-filesize 2147483648 --retry 2 --output "$2" "$1"; }
local api='https://api.github.com/repos/vicrodh/qbz/releases/latest'
if [ -n "$requested" ]; then
[[ "$requested" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || fail '--version must be a stable X.Y.Z version.'
api="https://api.github.com/repos/vicrodh/qbz/releases/tags/v$requested"
fi
printf '%s\n' 'Finding the latest stable QBZ package...'
fetch "$api" "$scratch/release.json" || fail 'Cannot read the release. Check your connection or GitHub rate limit.'
# Parse JSON as data. No eval, shell interpolation or regex JSON parsing.
json_get() {
# macOS ships JXA. Prefer it to Apple's python3 stub, which can trigger
# a Command Line Tools installation on an otherwise stock machine.
if [ "$system" = Darwin ] && [ -x /usr/bin/osascript ]; then
/usr/bin/osascript -l JavaScript - "$scratch/release.json" "$1" <<'JS'
ObjC.import('Foundation');
function run(args) {
const data = $.NSData.dataWithContentsOfFile(args[0]);
let value = JSON.parse(ObjC.unwrap($.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding)));
args[1].split('.').forEach(function (key) { value = value[key]; });
if (Array.isArray(value)) return String(value.length);
if (['string', 'boolean', 'number'].indexOf(typeof value) < 0) throw Error('Unsupported release field');
return String(value);
}
JS
elif command -v python3 >/dev/null 2>&1; then
python3 - "$scratch/release.json" "$1" <<'PY'
import json,sys
v=json.load(open(sys.argv[1]))
for key in sys.argv[2].split('.'): v=v[int(key)] if isinstance(v,list) else v[key]
if isinstance(v,list): print(len(v))
elif isinstance(v,bool): print(str(v).lower())
elif isinstance(v,(str,int)): print(v)
else: raise SystemExit('Unsupported release field')
PY
else
jq -er --arg path "$1" 'getpath($path | split(".") | map(tonumber? // .)) | if type == "array" then length elif type == "boolean" then tostring else . end' "$scratch/release.json"
fi
}
local tag version major minor patch filename url='' digest='' size='' count i name
tag=$(json_get tag_name)
[[ "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] || fail 'The release is not a stable version.'
[ "$(json_get draft)" = false ] && [ "$(json_get prerelease)" = false ] || fail 'Pre-release installation is not supported.'
version=${tag#v}
IFS=. read -r major minor patch <<< "$version"
if (( 10#$major < 2 || (10#$major == 2 && 10#$minor < 1) || (10#$major == 2 && 10#$minor == 1 && 10#$patch < 2) )); then
fail 'The one-line installer requires QBZ 2.1.2 or newer. It will become available with that release.'
fi
[ -z "$requested" ] || [ "$version" = "$requested" ] || fail 'The response does not match the requested version.'
case "$platform" in
linux-x86_64) filename="QBZ_${version}_amd64.AppImage" ;;
linux-aarch64) filename="QBZ_${version}_aarch64.AppImage" ;;
darwin-x86_64) filename='QBZ_x64.app.tar.gz' ;;
darwin-aarch64) filename='QBZ_aarch64.app.tar.gz' ;;
esac
count=$(json_get assets)
[[ "$count" =~ ^[0-9]+$ ]] && [ "$count" -le 1000 ] || fail 'Invalid asset count.'
for ((i=0; i<count; i++)); do
name=$(json_get "assets.$i.name")
if [ "$name" = "$filename" ]; then
[ -z "$url" ] || fail 'The release contains duplicate packages.'
url=$(json_get "assets.$i.browser_download_url")
digest=$(json_get "assets.$i.digest")
size=$(json_get "assets.$i.size")
fi
done
[ "$url" = "https://github.com/vicrodh/qbz/releases/download/$tag/$filename" ] || fail "The official $platform package is not available yet. Try again after its release build finishes."
[[ "$digest" =~ ^sha256:[0-9a-f]{64}$ ]] || fail 'The release has no SHA-256 digest. Refusing an unchecked download.'
[[ "$size" =~ ^[0-9]+$ ]] && [ "$size" -gt 0 ] && [ "$size" -le 2147483648 ] || fail 'Invalid package size.'
printf 'QBZ %s · %s\nDestination: %s\n' "$version" "$platform" "$destination"
if [ "$check_only" = 1 ]; then printf 'Package: %s\nSHA-256: %s\n' "$url" "${digest#sha256:}"; return 0; fi
fetch "$url" "$scratch/package" || fail 'Download failed. No installation was changed.'
local actual
if command -v sha256sum >/dev/null 2>&1; then actual=$(sha256sum "$scratch/package"); else actual=$(shasum -a 256 "$scratch/package"); fi
[ "${actual%% *}" = "${digest#sha256:}" ] || fail 'Package checksum mismatch. No installation was changed.'
[ "$(wc -c < "$scratch/package" | tr -d ' ')" = "$size" ] || fail 'Package size mismatch.'
mkdir -p "$install_dir"
mkdir "$install_dir/.qbz-setup.lock" 2>/dev/null || fail 'Another installer is active (or left .qbz-setup.lock after interruption).'
trap 'rm -rf -- "$scratch"; rmdir "$install_dir/.qbz-setup.lock"' EXIT
[ ! -e "$destination" ] && [ ! -L "$destination" ] || fail 'An installation appeared while downloading. It was preserved.'
local stage
stage=$(mktemp -d "$install_dir/.qbz-setup.XXXXXXXX")
local committed=0 published=("$stage")
trap 'if [ "$committed" = 0 ]; then for arg in "${published[@]}"; do rm -rf -- "$arg"; done; fi; rm -rf -- "$scratch" "$stage"; rmdir "$install_dir/.qbz-setup.lock"' EXIT
if [ "$system" = Linux ]; then
for arg in "$launcher" "$desktop"; do
[ ! -e "$arg" ] && [ ! -L "$arg" ] || fail "A launcher appeared while downloading: $arg"
done
[ "$(od -An -tx1 -N4 "$scratch/package" | tr -d ' \n')" = 7f454c46 ] || fail 'The package is not an ELF executable.'
[ "$(od -An -tx1 -j8 -N3 "$scratch/package" | tr -d ' \n')" = 414902 ] || fail 'The package is not a type-2 AppImage.'
cp "$scratch/package" "$stage/QBZ.AppImage"
chmod 755 "$stage/QBZ.AppImage"
# The logo is data from the same website that hosts this script.
fetch 'https://qbz.lol/assets/brand/64x64.png' "$stage/qbz.png" || fail 'Could not download the application icon.'
mkdir -p "$HOME/.local/bin" "$HOME/.local/share/applications"
{
printf '%s\n' '#!/usr/bin/env bash' '# QBZ one-line installer'
# Extract-and-run works without FUSE and preserves APPIMAGE for the updater.
printf 'export APPIMAGE_EXTRACT_AND_RUN=1\nexec %q "$@"\n' "$destination"
} > "$stage/launcher"
chmod 755 "$stage/launcher"
local desktop_exec desktop_icon
desktop_exec=${launcher//\\/\\\\}; desktop_exec=${desktop_exec//\"/\\\"}; desktop_exec=${desktop_exec//\$/\\$}; desktop_exec=${desktop_exec//\`/\\\`}; desktop_exec=${desktop_exec//%/%%}
# Desktop Entry string escaping happens before Exec argument unquoting.
desktop_exec=${desktop_exec//\\/\\\\}
desktop_icon=${icon//\\/\\\\}
printf '# QBZ one-line installer\n[Desktop Entry]\nType=Application\nName=QBZ\nComment=Qobuz hi-res player\nExec="%s" %%U\nIcon=%s\nTerminal=false\nCategories=AudioVideo;Audio;Player;\nStartupWMClass=qbz\n' "$desktop_exec" "$desktop_icon" > "$stage/desktop"
chmod 644 "$stage/desktop" "$stage/qbz.png"
# Publish the executable last. All downloads and verification precede this.
mv "$stage/qbz.png" "$icon"
published+=("$icon")
mv "$stage/launcher" "$launcher"
published+=("$launcher")
mv "$stage/desktop" "$desktop"
published+=("$desktop")
mv "$stage/QBZ.AppImage" "$destination"
published+=("$destination")
else
mkdir "$stage/unpacked"
tar -tzf "$scratch/package" > "$stage/contents"
while IFS= read -r name; do
case "$name" in QBZ.app|QBZ.app/*) ;; *) fail 'The archive contains files outside QBZ.app.' ;; esac
case "/$name/" in */../*) fail 'The archive contains a parent path.' ;; esac
done < "$stage/contents"
tar -xzf "$scratch/package" -C "$stage/unpacked"
[ -f "$stage/unpacked/QBZ.app/Contents/MacOS/qbz" ] && [ -f "$stage/unpacked/QBZ.app/Contents/Info.plist" ] || fail 'The archive is not a QBZ app bundle.'
/usr/bin/codesign --verify --deep --strict "$stage/unpacked/QBZ.app" || fail 'The app bundle failed code-signature validation.'
mv "$stage/unpacked/QBZ.app" "$destination"
published+=("$destination")
fi
printf '%s\n' 'qbz-one-line-v1' > "$receipt"
committed=1
printf '%s\n' 'Installed. Open QBZ from your applications menu.' 'Future updates: Settings → Updates in QBZ.'
if [ "$system" = Linux ]; then
case ":$PATH:" in *":$HOME/.local/bin:"*) ;; *) printf 'For terminal launches, add %s to PATH. The menu launcher already works.\n' "$HOME/.local/bin" ;; esac
fi
)
qbz_install_main "$@"
@@ -0,0 +1,20 @@
pragma Singleton
import QtQuick
QtObject {
property string updatesJson: "{}"
property int checkCalls: 0
property int installCalls: 0
property int cancelCalls: 0
property int ignoreCalls: 0
function updatesCheck() { checkCalls++ }
function updatesInstall() { installCalls++ }
function updatesCancel() { cancelCalls++ }
function updatesIgnore() { ignoreCalls++ }
function updatesClose() {
var doc = JSON.parse(updatesJson)
doc.open = false
updatesJson = JSON.stringify(doc)
}
function updatesSetLaunch(enabled) {}
function whatsNewOpen() {}
}
@@ -7,3 +7,5 @@ singleton QbzBridge 1.0 QbzBridge.qml
singleton QbzLibrary 1.0 QbzLibrary.qml
singleton QbzPurchases 1.0 QbzPurchases.qml
singleton QbzOrbit 1.0 QbzOrbit.qml
singleton QbzAbout 1.0 QbzAbout.qml
+85
View File
@@ -0,0 +1,85 @@
import QtQuick
import QtTest
import com.blitzfc.qbz
import "../../crates/qbz-qt/qml/settings" as Settings
import "../../crates/qbz-qt/qml/shell" as Shell
Item {
width: 1000; height: 800
Settings.UpdatesSettings { id: settings; width: 900 }
Shell.UpdatesModal { id: modal }
TestCase {
name: "Updates"; when: windowShown
function init() {
modal.kioskHost = false
QbzAbout.checkCalls = 0
QbzAbout.installCalls = 0
QbzAbout.cancelCalls = 0
QbzAbout.updatesJson = JSON.stringify({open:false, phase:"idle", currentVersion:"2.1.1"})
}
function test_manual_check_action() {
var button = findChild(settings, "updateCheckButton")
verify(button.enabled)
mouseClick(button)
compare(QbzAbout.checkCalls, 1)
QbzAbout.updatesJson = JSON.stringify({busy:true, phase:"checking"})
verify(!button.enabled)
}
function test_managed_install_has_release_link_without_installer() {
QbzAbout.updatesJson = JSON.stringify({open:true, phase:"available", version:"2.1.2", canInstall:false})
verify(modal.visible)
verify(!findChild(modal, "updateInstallButton").visible)
verify(findChild(modal, "updateReleaseButton").visible)
modal.dismiss()
verify(!modal.visible)
}
function test_signed_installer_action_and_commit_cannot_be_dismissed() {
QbzAbout.updatesJson = JSON.stringify({open:true, phase:"available", version:"2.1.2", canInstall:true})
var button = findChild(modal, "updateInstallButton")
verify(button.visible)
verify(waitForRendering(modal))
mouseClick(button)
compare(QbzAbout.installCalls, 1)
QbzAbout.updatesJson = JSON.stringify({open:true, phase:"installing", busy:true})
modal.dismiss()
verify(modal.visible)
verify(!findChild(modal, "updateCloseButton").enabled)
verify(!button.visible)
}
function test_kiosk_update_buttons_have_touch_height() {
modal.kioskHost = true
QbzAbout.updatesJson = JSON.stringify({open:true, phase:"available", version:"2.1.2", canInstall:true})
verify(findChild(modal, "updateInstallButton").height >= 44)
verify(findChild(modal, "updateCloseButton").height >= 44)
}
function test_network_failure_is_not_reported_as_up_to_date() {
QbzAbout.updatesJson = JSON.stringify({open:true, phase:"error", error:"HTTP 403"})
verify(modal.statusText().indexOf("could not be completed") >= 0)
QbzAbout.updatesJson = JSON.stringify({open:true, phase:"current"})
verify(modal.statusText().indexOf("latest version") >= 0)
}
function test_flatpak_channel_update_without_github_version() {
QbzAbout.updatesJson = JSON.stringify({open:true, phase:"available", version:"", canInstall:true, installMethod:"Flatpak"})
var install = findChild(modal, "updateInstallButton")
verify(install.visible)
verify(!findChild(modal, "updateReleaseButton").visible)
verify(waitForRendering(modal))
mouseClick(install)
compare(QbzAbout.installCalls, 1)
QbzAbout.updatesJson = JSON.stringify({open:true, phase:"updating", busy:true, percent:42})
var cancel = findChild(modal, "updateCancelButton")
verify(cancel.visible)
verify(waitForRendering(modal))
mouseClick(cancel)
compare(QbzAbout.cancelCalls, 1)
}
function test_msi_staged_is_not_reported_as_installed() {
QbzAbout.updatesJson = JSON.stringify({open:true, phase:"prepared", busy:false, canInstall:false})
verify(modal.statusText().indexOf("finish installation") >= 0)
verify(findChild(modal, "updateCloseButton").enabled)
verify(!findChild(modal, "updateInstallButton").visible)
modal.dismiss()
verify(!modal.visible)
}
}
}
+1
View File
@@ -4,6 +4,7 @@ set -euo pipefail
cd "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/.."
export QBZ_PREBUILT_SHADERS=1
bash scripts/test-search-local-qml.sh
bash scripts/test-updates-qml.sh
bash scripts/test-orbit-qml.sh
node scripts/test_qt_local_views.mjs
node scripts/test_qt_kiosk_art.mjs
+150
View File
@@ -0,0 +1,150 @@
#!/usr/bin/env python3
"""Exercise the shipped shell installer in disposable homes, with no live installs."""
import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
SCRIPT = Path(__file__).resolve().with_name('install.sh')
class InstallerTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory(prefix='qbz-installer-test-')
self.root = Path(self.tmp.name)
self.home = self.root / 'home space $cash 100% "quoted" `ticks`'
self.home.mkdir()
self.bin = self.root / 'bin'
self.bin.mkdir()
for cmd in ('bash','id','python3','mktemp','rm','rmdir','grep','cat','tr',
'mkdir','cp','chmod','mv','od','wc','sha256sum','getconf'):
(self.bin / cmd).symlink_to(shutil.which(cmd))
(self.bin/'uname').write_text('#!/usr/bin/env bash\nif [ "$1" = -s ]; then printf "%s\\n" "${FIXTURE_OS:-Linux}"; else printf "%s\\n" "${FIXTURE_ARCH:-x86_64}"; fi\n')
(self.bin/'uname').chmod(0o755)
self.payload = b'\x7fELF' + b'\x00'*4 + b'AI\x02' + b'fixture only, never executed'
(self.root/'package').write_bytes(self.payload)
self.asset = {
'name':'QBZ_2.1.2_amd64.AppImage',
'browser_download_url':'https://github.com/vicrodh/qbz/releases/download/v2.1.2/QBZ_2.1.2_amd64.AppImage',
'digest':'sha256:'+hashlib.sha256(self.payload).hexdigest(),
'size':len(self.payload),
}
self.release = {'tag_name':'v2.1.2','draft':False,'prerelease':False,'assets':[self.asset]}
# Only curl is replaced. Real bash, JSON parser, hashes and filesystem
# operations exercise the production script, including spaces/$/% in HOME.
(self.bin/'curl').write_text('#!'+sys.executable+'''
import os,sys,pathlib,shutil
args=sys.argv[1:]; root=pathlib.Path(os.environ['INSTALLER_FIXTURE'])
out=pathlib.Path(args[args.index('--output')+1]); url=args[-1]
with (root/'requests').open('a') as f: f.write(url+'\\n')
if url.startswith('https://api.github.com/repos/vicrodh/qbz/releases/'):
shutil.copyfile(root/'release.json',out)
elif url=='https://github.com/vicrodh/qbz/releases/download/v2.1.2/QBZ_2.1.2_amd64.AppImage':
shutil.copyfile(root/'package',out)
elif url=='https://qbz.lol/assets/brand/64x64.png': out.write_bytes(b'icon fixture')
else: raise SystemExit('Unexpected URL: '+url)
''')
(self.bin/'curl').chmod(0o755)
self.env = dict(os.environ, HOME=str(self.home), PATH=str(self.bin),
TMPDIR=str(self.root), INSTALLER_FIXTURE=str(self.root))
self.env.pop('BASH_ENV', None)
self.dest = self.home/'.local/opt/qbz/QBZ.AppImage'
def tearDown(self):
self.tmp.cleanup()
def run_installer(self,*args):
(self.root/'release.json').write_text(json.dumps(self.release))
return subprocess.run([shutil.which('bash'),str(SCRIPT),*args],env=self.env,text=True,capture_output=True,timeout=20)
def test_install_verify_launchers_repeat_and_uninstall_keep_data(self):
data=self.home/'.local/share/qbz/personal.db'
data.parent.mkdir(parents=True); data.write_text('keep')
r=self.run_installer(); self.assertEqual(r.returncode,0,r.stderr)
self.assertEqual(self.dest.read_bytes(),self.payload)
launcher=self.home/'.local/bin/qbz'
self.assertIn('APPIMAGE_EXTRACT_AND_RUN=1',launcher.read_text())
subprocess.run(['bash','-n',str(launcher)],check=True)
self.assertIn('100%%',(self.home/'.local/share/applications/com.blitzfc.qbz.desktop').read_text())
if shutil.which('desktop-file-validate'):
subprocess.run(['desktop-file-validate',str(self.home/'.local/share/applications/com.blitzfc.qbz.desktop')],check=True)
self.assertFalse(list(self.root.glob('qbz-install.*')))
requests=(self.root/'requests').read_text()
r=self.run_installer(); self.assertEqual(r.returncode,0,r.stderr)
self.assertEqual((self.root/'requests').read_text(),requests)
r=self.run_installer('--uninstall'); self.assertEqual(r.returncode,0,r.stderr)
self.assertFalse(self.dest.exists()); self.assertFalse(launcher.exists())
self.assertEqual(data.read_text(),'keep')
def test_hash_failure_never_creates_installation(self):
self.asset['digest']='sha256:'+'0'*64
r=self.run_installer(); self.assertNotEqual(r.returncode,0)
self.assertIn('checksum mismatch',r.stderr)
self.assertFalse(self.dest.exists())
def test_existing_app_and_launcher_are_preserved(self):
self.dest.parent.mkdir(parents=True); self.dest.write_text('existing')
self.assertNotEqual(self.run_installer().returncode,0)
self.assertEqual(self.dest.read_text(),'existing')
self.dest.unlink()
launcher=self.home/'.local/bin/qbz'; launcher.parent.mkdir(parents=True)
launcher.write_text('existing launcher')
self.assertNotEqual(self.run_installer().returncode,0)
self.assertEqual(launcher.read_text(),'existing launcher')
def test_symlink_installation_is_not_followed(self):
outside=self.root/'outside'; outside.mkdir()
self.dest.parent.parent.mkdir(parents=True)
self.dest.parent.symlink_to(outside,target_is_directory=True)
self.assertNotEqual(self.run_installer().returncode,0)
self.assertEqual(list(outside.iterdir()),[])
def test_check_is_read_only_and_rejects_missing_digest_or_foreign_url(self):
r=self.run_installer('--check'); self.assertEqual(r.returncode,0,r.stderr)
self.assertFalse(self.dest.parent.exists())
self.asset['digest']=''
self.assertNotEqual(self.run_installer('--check').returncode,0)
self.asset['digest']='sha256:'+'0'*64
self.asset['browser_download_url']='https://example.org/payload'
self.assertNotEqual(self.run_installer('--check').returncode,0)
def test_older_release_and_prerelease_never_install(self):
self.release['tag_name']='v2.1.1'
r=self.run_installer(); self.assertNotEqual(r.returncode,0)
self.assertIn('2.1.2 or newer',r.stderr)
self.release['tag_name']='v2.1.2'; self.release['prerelease']=True
self.assertNotEqual(self.run_installer().returncode,0)
def test_all_four_platform_assets_are_selected(self):
for system,arch,name in [('Linux','x86_64','QBZ_2.1.2_amd64.AppImage'),
('Linux','aarch64','QBZ_2.1.2_aarch64.AppImage'),
('Darwin','x86_64','QBZ_x64.app.tar.gz'),
('Darwin','arm64','QBZ_aarch64.app.tar.gz')]:
with self.subTest(system=system,arch=arch):
self.env.update(FIXTURE_OS=system,FIXTURE_ARCH=arch)
self.asset['name']=name
self.asset['browser_download_url']='https://github.com/vicrodh/qbz/releases/download/v2.1.2/'+name
r=self.run_installer('--check')
self.assertEqual(r.returncode,0,r.stderr)
self.assertIn(name,r.stdout)
def test_check_cannot_accidentally_uninstall(self):
r=self.run_installer('--check','--uninstall')
self.assertNotEqual(r.returncode,0)
self.assertIn('cannot be combined',r.stderr)
@unittest.skipUnless(shutil.which('jq'), 'jq is required for its parser fallback test')
def test_jq_parser_works_without_python_on_path(self):
(self.bin/'python3').unlink()
(self.bin/'jq').symlink_to(shutil.which('jq'))
r=self.run_installer()
self.assertEqual(r.returncode,0,r.stderr)
self.assertEqual(self.dest.read_bytes(),self.payload)
if __name__=='__main__': unittest.main()
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env bash
# The same bounded view/activation regression runs in CI and locally.
set -euo pipefail
cd "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/.."
if [[ -n "${QT_ROOT_DIR:-}" ]]; then
qt_updates_bins="$QT_ROOT_DIR/bin"
else
qt_updates_qmake="${QMAKE:-}"
if [[ -z "$qt_updates_qmake" ]]; then
qt_updates_qmake="$(command -v qmake6 || command -v qmake)"
fi
qt_updates_bins="$("$qt_updates_qmake" -query QT_INSTALL_BINS)"
fi
QT_QPA_PLATFORM=offscreen QT_QUICK_BACKEND=software \
"$qt_updates_bins/qmltestrunner" \
-input scripts/qml-tests/tst_updates.qml \
-import scripts/qml-tests/imports