Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(desktop): add signed application updates with native recovery (#2181)

Maxc3f30f4555ed
diff --git a/.github/workflows/desktop-package.yml b/.github/workflows/desktop-package.yml
index 01c7bea46..40bbe06ca 100644
--- a/.github/workflows/desktop-package.yml
+++ b/.github/workflows/desktop-package.yml
@@ -1,7 +1,7 @@
name: desktop-self-contained-package
# Manual artifacts retain optional Apple identity signing. Reusable TEST builds
-# receive no signing secrets and always use an ad-hoc app / unsigned installer.
+# use ad-hoc OS signatures. Updater keys come only from desktop-updater.
on:
workflow_dispatch:
inputs:
@@ -18,6 +18,10 @@ on:
description: Exact peeled commit of the validated TEST tag
required: true
type: string
+ updater_enabled:
+ description: Require cryptographically signed updater artifacts
+ type: boolean
+ default: false
release_tag:
description: Canonical gh-vX.Y.ZrcN TEST tag
required: true
@@ -34,6 +38,7 @@ jobs:
package:
name: ${{ matrix.target }}
runs-on: ${{ matrix.os }}
+ environment: desktop-updater
strategy:
fail-fast: false
matrix:
@@ -103,6 +108,18 @@ jobs:
--source-sha "$SOURCE_SHA" --config desktop/tauri.release.conf.json \
--env-file "$GITHUB_ENV"
+ - name: Configure signed updater or explicitly disable it
+ shell: bash
+ env:
+ UPDATER_ENABLED: ${{ inputs.updater_enabled }}
+ AVIBE_DESKTOP_UPDATER_PUBLIC_KEY: ${{ vars.DESKTOP_UPDATER_PUBLIC_KEY }}
+ TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
+ run: |
+ args=()
+ if [ "$UPDATER_ENABLED" = "true" ]; then args+=(--enabled); fi
+ python scripts/desktop_updater.py configure \
+ --config desktop/tauri.release.conf.json --env-file "$GITHUB_ENV" ${args[@]+"${args[@]}"}
+
- name: Build verified private Runtime
run: >
python desktop/scripts/build-runtime-bundle.py
@@ -262,6 +279,20 @@ jobs:
--runtime desktop/src-tauri/resources/runtime --output desktop-package \
--signing "$signing"
+ - name: Sign and verify final updater artifacts
+ if: inputs.updater_enabled
+ shell: bash
+ env:
+ RELEASE_TAG: ${{ inputs.release_tag }}
+ SOURCE_SHA: ${{ inputs.source_sha }}
+ TARGET: ${{ matrix.target }}
+ TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
+ TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
+ run: |
+ python scripts/desktop_updater.py produce \
+ --directory desktop-package --tag "$RELEASE_TAG" --source-sha "$SOURCE_SHA" \
+ --target "$TARGET" --app desktop/target/release/bundle/macos/Avibe.app
+
- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
with:
name: avibe-desktop-${{ inputs.version }}-${{ matrix.target }}
diff --git a/.github/workflows/desktop-shell.yml b/.github/workflows/desktop-shell.yml
index 01a29e50c..d51664fd9 100644
--- a/.github/workflows/desktop-shell.yml
+++ b/.github/workflows/desktop-shell.yml
@@ -99,5 +99,10 @@ jobs:
- name: Test Rust
run: cargo test --workspace --all-features
+ - name: Verify Windows installer transaction with isolated native fixtures
+ if: runner.os == 'Windows'
+ shell: powershell
+ run: ./scripts/test-windows-update.ps1
+
- name: Build the shell
run: cargo build --workspace
diff --git a/.github/workflows/release_ai.yml b/.github/workflows/release_ai.yml
index 2b8a54c8b..b4e2e67d3 100644
--- a/.github/workflows/release_ai.yml
+++ b/.github/workflows/release_ai.yml
@@ -28,9 +28,10 @@ permissions:
jobs:
resolve-desktop-release:
- if: startsWith(github.event.inputs.tag || github.ref_name, 'gh-v')
runs-on: ubuntu-latest
outputs:
+ enabled: ${{ steps.resolve.outputs.enabled }}
+ updater_enabled: ${{ steps.resolve.outputs.updater_enabled }}
source_sha: ${{ steps.resolve.outputs.source_sha }}
version: ${{ steps.resolve.outputs.version }}
tag: ${{ steps.resolve.outputs.tag }}
@@ -47,16 +48,35 @@ jobs:
id: resolve
env:
RELEASE_TAG: ${{ github.event.inputs.tag || github.ref_name }}
- run: python scripts/desktop_release.py resolve --tag "$RELEASE_TAG" --output "$GITHUB_OUTPUT"
+ TEST_ENABLED: ${{ vars.DESKTOP_UPDATER_TEST }}
+ STABLE_ENABLED: ${{ vars.DESKTOP_UPDATER_STABLE }}
+ shell: bash
+ run: |
+ enabled=false
+ updater_enabled=false
+ if [[ "$RELEASE_TAG" == gh-v* ]]; then
+ enabled=true
+ if [ "$TEST_ENABLED" = true ]; then updater_enabled=true; fi
+ elif [[ "$RELEASE_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] && [ "$STABLE_ENABLED" = true ]; then
+ enabled=true
+ updater_enabled=true
+ fi
+ echo "enabled=$enabled" >> "$GITHUB_OUTPUT"
+ echo "updater_enabled=$updater_enabled" >> "$GITHUB_OUTPUT"
+ if [ "$enabled" = true ]; then
+ python scripts/desktop_release.py resolve --tag "$RELEASE_TAG" --output "$GITHUB_OUTPUT"
+ fi
desktop-packages:
needs: resolve-desktop-release
+ if: needs.resolve-desktop-release.outputs.enabled == 'true'
uses: ./.github/workflows/desktop-package.yml
with:
source_sha: ${{ needs.resolve-desktop-release.outputs.source_sha }}
version: ${{ needs.resolve-desktop-release.outputs.version }}
release_tag: ${{ needs.resolve-desktop-release.outputs.tag }}
- # Deliberately no secrets: TEST signing is independent of repository identities.
+ updater_enabled: ${{ needs.resolve-desktop-release.outputs.updater_enabled == 'true' }}
+ # OS identities are not inherited. The callee uses its dedicated updater Environment.
resolve-show-runtime-ref:
needs: resolve-desktop-release
@@ -267,11 +287,12 @@ jobs:
cancel-in-progress: false
# Official assets belong to publish.yml; only previews require this build.
if: >-
- ${{ !cancelled() && (needs.build-assets.result == 'success' ||
+ ${{ !cancelled() && needs.resolve-desktop-release.result == 'success' && (needs.build-assets.result == 'success' ||
(needs.build-assets.result == 'skipped' &&
!startsWith(github.event.inputs.tag || github.ref_name, 'gh-v'))) &&
(!startsWith(github.event.inputs.tag || github.ref_name, 'gh-v') ||
- (needs.resolve-desktop-release.result == 'success' && needs.desktop-packages.result == 'success')) }}
+ (needs.resolve-desktop-release.result == 'success' && needs.desktop-packages.result == 'success')) &&
+ (needs.resolve-desktop-release.outputs.enabled != 'true' || needs.desktop-packages.result == 'success') }}
runs-on: ubuntu-latest
steps:
- name: Checkout
@@ -624,7 +645,7 @@ jobs:
path: dist/
- name: Download desktop TEST artifacts
- if: startsWith(steps.tag.outputs.tag, 'gh-v')
+ if: needs.resolve-desktop-release.outputs.enabled == 'true'
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
pattern: avibe-desktop-${{ needs.resolve-desktop-release.outputs.version }}-*
@@ -632,27 +653,35 @@ jobs:
merge-multiple: true
- name: Validate desktop TEST assets and append installation guidance
- if: startsWith(steps.tag.outputs.tag, 'gh-v')
+ if: needs.resolve-desktop-release.outputs.enabled == 'true'
env:
RELEASE_TAG: ${{ steps.tag.outputs.tag }}
SOURCE_SHA: ${{ needs.resolve-desktop-release.outputs.source_sha }}
+ AVIBE_DESKTOP_UPDATER_PUBLIC_KEY: ${{ vars.DESKTOP_UPDATER_PUBLIC_KEY }}
+ UPDATER_ENABLED: ${{ needs.resolve-desktop-release.outputs.updater_enabled }}
run: |
+ args=()
+ if [ "$UPDATER_ENABLED" = true ]; then args+=(--updater-enabled); fi
test "$(git rev-parse "refs/tags/${RELEASE_TAG}^{commit}")" = "$SOURCE_SHA"
python scripts/desktop_release.py verify \
- --directory desktop-dist --tag "$RELEASE_TAG" --source-sha "$SOURCE_SHA"
- cat docs/desktop-test-installation.md >> release.md
+ --directory desktop-dist --tag "$RELEASE_TAG" --source-sha "$SOURCE_SHA" ${args[@]+"${args[@]}"}
+ if [[ "$RELEASE_TAG" == gh-v* ]]; then cat docs/desktop-test-installation.md >> release.md; fi
- name: Create GitHub-only Release
if: startsWith(steps.tag.outputs.tag, 'gh-v')
env:
GH_TOKEN: ${{ github.token }}
SOURCE_SHA: ${{ needs.resolve-desktop-release.outputs.source_sha }}
+ AVIBE_DESKTOP_UPDATER_PUBLIC_KEY: ${{ vars.DESKTOP_UPDATER_PUBLIC_KEY }}
+ UPDATER_ENABLED: ${{ needs.resolve-desktop-release.outputs.updater_enabled }}
shell: bash
run: |
set -euo pipefail
TAG="${{ steps.tag.outputs.tag }}"
+ args=()
+ if [ "${UPDATER_ENABLED:-false}" = true ]; then args+=(--updater-enabled); fi
python scripts/desktop_release.py check-remote \
- --directory desktop-dist --tag "$TAG" --source-sha "$SOURCE_SHA" --repo "$GITHUB_REPOSITORY"
+ --directory desktop-dist --tag "$TAG" --source-sha "$SOURCE_SHA" --repo "$GITHUB_REPOSITORY" ${args[@]+"${args[@]}"}
python scripts/github_release.py update-notes \
--repo "$GITHUB_REPOSITORY" \
--tag "$TAG" \
@@ -706,7 +735,7 @@ jobs:
python scripts/desktop_release.py check-remote \
--directory desktop-dist --tag "$TAG" --source-sha "$SOURCE_SHA" \
- --repo "$GITHUB_REPOSITORY" --complete
+ --repo "$GITHUB_REPOSITORY" --complete ${args[@]+"${args[@]}"}
python scripts/github_release.py finalize \
--repo "$GITHUB_REPOSITORY" \
--tag "$TAG" \
@@ -725,3 +754,14 @@ jobs:
--tag "$TAG" \
--title "$TAG" \
--notes-file release.md
+
+ - name: Stage signed stable desktop assets before official finalization
+ if: needs.resolve-desktop-release.outputs.enabled == 'true' && !startsWith(steps.tag.outputs.tag, 'gh-v')
+ env:
+ GH_TOKEN: ${{ github.token }}
+ RELEASE_TAG: ${{ steps.tag.outputs.tag }}
+ SOURCE_SHA: ${{ needs.resolve-desktop-release.outputs.source_sha }}
+ AVIBE_DESKTOP_UPDATER_PUBLIC_KEY: ${{ vars.DESKTOP_UPDATER_PUBLIC_KEY }}
+ run: |
+ python scripts/desktop_updater.py stage --enabled \
+ --directory desktop-dist --tag "$RELEASE_TAG" --source-sha "$SOURCE_SHA" --repo "$GITHUB_REPOSITORY"
diff --git a/desktop/Cargo.lock b/desktop/Cargo.lock
index 4c4a2027a..7302a04a5 100644
--- a/desktop/Cargo.lock
+++ b/desktop/Cargo.lock
@@ -240,13 +240,16 @@ dependencies = [
"async-trait",
"avibe-runtime-host",
"block2",
+ "flate2",
"objc2",
"objc2-app-kit",
"objc2-foundation",
"objc2-web-kit",
+ "reqwest 0.12.28",
"serde",
"serde_json",
"sys-locale",
+ "tar",
"tauri",
"tauri-build",
"tauri-plugin-autostart",
@@ -255,7 +258,9 @@ dependencies = [
"tauri-plugin-notification",
"tauri-plugin-opener",
"tauri-plugin-single-instance",
+ "tauri-plugin-updater",
"tauri-plugin-window-state",
+ "tempfile",
"tokio",
"url",
]
@@ -265,8 +270,11 @@ name = "avibe-runtime-host"
version = "0.1.0"
dependencies = [
"async-trait",
+ "base64 0.22.1",
"chrono",
+ "minisign-verify",
"reqwest 0.12.28",
+ "semver",
"serde",
"serde_json",
"sha2",
@@ -516,6 +524,12 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+[[package]]
+name = "cfg_aliases"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
+
[[package]]
name = "chrono"
version = "0.4.45"
@@ -577,6 +591,16 @@ dependencies = [
"version_check",
]
+[[package]]
+name = "core-foundation"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
[[package]]
name = "core-foundation"
version = "0.10.1"
@@ -600,7 +624,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97"
dependencies = [
"bitflags 2.13.1",
- "core-foundation",
+ "core-foundation 0.10.1",
"core-graphics-types",
"foreign-types",
"libc",
@@ -613,7 +637,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"
dependencies = [
"bitflags 2.13.1",
- "core-foundation",
+ "core-foundation 0.10.1",
"libc",
]
@@ -1083,6 +1107,16 @@ dependencies = [
"rustc_version",
]
+[[package]]
+name = "filetime"
+version = "0.2.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
+dependencies = [
+ "cfg-if",
+ "libc",
+]
+
[[package]]
name = "find-msvc-tools"
version = "0.1.9"
@@ -1348,8 +1382,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
+ "js-sys",
"libc",
"wasi",
+ "wasm-bindgen",
]
[[package]]
@@ -1359,9 +1395,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
dependencies = [
"cfg-if",
+ "js-sys",
"libc",
"r-efi 5.3.0",
"wasip2",
+ "wasm-bindgen",
]
[[package]]
@@ -1634,6 +1672,22 @@ dependencies = [
"want",
]
+[[package]]
+name = "hyper-rustls"
+version = "0.27.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53"
+dependencies = [
+ "http",
+ "hyper",
+ "hyper-util",
+ "rustls",
+ "tokio",
+ "tokio-rustls",
+ "tower-service",
+ "webpki-roots",
+]
+
[[package]]
name = "hyper-util"
version = "0.1.20"
@@ -1652,9 +1706,11 @@ dependencies = [
"percent-encoding",
"pin-project-lite",
"socket2",
+ "system-configuration",
"tokio",
"tower-service",
"tracing",
+ "windows-registry",
]
[[package]]
@@ -1902,6 +1958,36 @@ dependencies = [
"windows-sys 0.45.0",
]
+[[package]]
+name = "jni"
+version = "0.22.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"
+dependencies = [
+ "cfg-if",
+ "combine",
+ "jni-macros",
+ "jni-sys 0.4.1",
+ "log",
+ "simd_cesu8",
+ "thiserror 2.0.19",
+ "walkdir",
+ "windows-link 0.2.1",
+]
+
+[[package]]
+name = "jni-macros"
+version = "0.22.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "rustc_version",
+ "simd_cesu8",
+ "syn 2.0.119",
+]
+
[[package]]
name = "jni-sys"
version = "0.3.1"
@@ -2059,6 +2145,12 @@ version = "0.4.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
+[[package]]
+name = "lru-slab"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"
+
[[package]]
name = "mac-notification-sys"
version = "0.6.15"
@@ -2105,6 +2197,12 @@ version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
+[[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"
@@ -2367,6 +2465,18 @@ dependencies = [
"objc2-core-foundation",
]
+[[package]]
+name = "objc2-osa-kit"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f112d1746737b0da274ef79a23aac283376f335f4095a083a267a082f21db0c0"
+dependencies = [
+ "bitflags 2.13.1",
+ "objc2",
+ "objc2-app-kit",
+ "objc2-foundation",
+]
+
[[package]]
name = "objc2-quartz-core"
version = "0.3.2"
@@ -2441,6 +2551,12 @@ dependencies = [
"libc",
]
+[[package]]
+name = "openssl-probe"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
+
[[package]]
name = "option-ext"
version = "0.2.0"
@@ -2467,6 +2583,20 @@ dependencies = [
"pin-project-lite",
]
+[[package]]
+name = "osakit"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "732c71caeaa72c065bb69d7ea08717bd3f4863a4f451402fc9513e29dbd5261b"
+dependencies = [
+ "objc2",
+ "objc2-foundation",
+ "objc2-osa-kit",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.19",
+]
+
[[package]]
name = "pango"
version = "0.18.3"
@@ -2757,6 +2887,61 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "quinn"
+version = "0.11.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8"
+dependencies = [
+ "bytes",
+ "cfg_aliases",
+ "pin-project-lite",
+ "quinn-proto",
+ "quinn-udp",
+ "rustc-hash",
+ "rustls",
+ "socket2",
+ "thiserror 2.0.19",
+ "tokio",
+ "tracing",
+ "web-time",
+]
+
+[[package]]
+name = "quinn-proto"
+version = "0.11.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4fcb935c5bec503c2f0e306bdd3e58bb9029dcb14fa8d9ac76e3a5256ac0763e"
+dependencies = [
+ "bytes",
+ "getrandom 0.3.4",
+ "lru-slab",
+ "rand",
+ "ring",
+ "rustc-hash",
+ "rustls",
+ "rustls-pki-types",
+ "slab",
+ "thiserror 2.0.19",
+ "tinyvec",
+ "tracing",
+ "web-time",
+]
+
+[[package]]
+name = "quinn-udp"
+version = "0.5.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694"
+dependencies = [
+ "cfg_aliases",
+ "libc",
+ "once_cell",
+ "socket2",
+ "tracing",
+ "windows-sys 0.52.0",
+]
+
[[package]]
name = "quote"
version = "1.0.47"
@@ -2906,16 +3091,21 @@ dependencies = [
"http-body",
"http-body-util",
"hyper",
+ "hyper-rustls",
"hyper-util",
"js-sys",
"log",
"percent-encoding",
"pin-project-lite",
+ "quinn",
+ "rustls",
+ "rustls-pki-types",
"serde",
"serde_json",
"serde_urlencoded",
"sync_wrapper",
"tokio",
+ "tokio-rustls",
"tower",
"tower-http",
"tower-service",
@@ -2923,6 +3113,7 @@ dependencies = [
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
+ "webpki-roots",
]
[[package]]
@@ -2939,15 +3130,20 @@ dependencies = [
"http-body",
"http-body-util",
"hyper",
+ "hyper-rustls",
"hyper-util",
"js-sys",
"log",
"percent-encoding",
"pin-project-lite",
+ "rustls",
+ "rustls-pki-types",
+ "rustls-platform-verifier",
"serde",
"serde_json",
"sync_wrapper",
"tokio",
+ "tokio-rustls",
"tokio-util",
"tower",
"tower-http",
@@ -2983,6 +3179,20 @@ dependencies = [
"windows-sys 0.60.2",
]
+[[package]]
+name = "ring"
+version = "0.17.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
+dependencies = [
+ "cc",
+ "cfg-if",
+ "getrandom 0.2.17",
+ "libc",
+ "untrusted",
+ "windows-sys 0.52.0",
+]
+
[[package]]
name = "rust-ini"
version = "0.21.3"
@@ -3021,6 +3231,80 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "rustls"
+version = "0.23.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
+dependencies = [
+ "once_cell",
+ "ring",
+ "rustls-pki-types",
+ "rustls-webpki",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-native-certs"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d"
+dependencies = [
+ "openssl-probe",
+ "rustls-pki-types",
+ "schannel",
+ "security-framework",
+]
+
+[[package]]
+name = "rustls-pki-types"
+version = "1.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
+dependencies = [
+ "web-time",
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-platform-verifier"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98"
+dependencies = [
+ "core-foundation 0.10.1",
+ "core-foundation-sys",
+ "jni 0.22.4",
+ "log",
+ "once_cell",
+ "rustls",
+ "rustls-native-certs",
+ "rustls-platform-verifier-android",
+ "rustls-webpki",
+ "security-framework",
+ "security-framework-sys",
+ "webpki-root-certs",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "rustls-platform-verifier-android"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f"
+
+[[package]]
+name = "rustls-webpki"
+version = "0.103.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
+dependencies = [
+ "ring",
+ "rustls-pki-types",
+ "untrusted",
+]
+
[[package]]
name = "rustversion"
version = "1.0.23"
@@ -3042,6 +3326,15 @@ dependencies = [
"winapi-util",
]
+[[package]]
+name = "schannel"
+version = "0.1.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "schemars"
version = "0.8.22"
@@ -3099,6 +3392,29 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+[[package]]
+name = "security-framework"
+version = "3.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
+dependencies = [
+ "bitflags 2.13.1",
+ "core-foundation 0.10.1",
+ "core-foundation-sys",
+ "libc",
+ "security-framework-sys",
+]
+
+[[package]]
+name = "security-framework-sys"
+version = "2.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
[[package]]
name = "selectors"
version = "0.36.1"
@@ -3331,6 +3647,22 @@ version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
+[[package]]
+name = "simd_cesu8"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520"
+dependencies = [
+ "rustc_version",
+ "simdutf8",
+]
+
+[[package]]
+name = "simdutf8"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
+
[[package]]
name = "siphasher"
version = "1.0.3"
@@ -3443,6 +3775,12 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+[[package]]
+name = "subtle"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
+
[[package]]
name = "swift-rs"
version = "1.0.7"
@@ -3515,6 +3853,27 @@ dependencies = [
"libc",
]
+[[package]]
+name = "system-configuration"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b"
+dependencies = [
+ "bitflags 2.13.1",
+ "core-foundation 0.9.4",
+ "system-configuration-sys",
+]
+
+[[package]]
+name = "system-configuration-sys"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
[[package]]
name = "system-deps"
version = "6.2.2"
@@ -3536,7 +3895,7 @@ checksum = "d1c93047acf68669466a34690ac58cca7010bd1b201e1ec86f1fd0a75d3dd4a9"
dependencies = [
"bitflags 2.13.1",
"block2",
- "core-foundation",
+ "core-foundation 0.10.1",
"core-graphics",
"crossbeam-channel",
"dbus",
@@ -3546,7 +3905,7 @@ dependencies = [
"gdkwayland-sys",
"gdkx11-sys",
"gtk",
- "jni",
+ "jni 0.21.1",
"libc",
"log",
"ndk",
@@ -3579,6 +3938,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 = "target-lexicon"
version = "0.12.16"
@@ -3602,7 +3972,7 @@ dependencies = [
"gtk",
"heck 0.5.0",
"http",
- "jni",
+ "jni 0.21.1",
"libc",
"log",
"mime",
@@ -3848,6 +4218,39 @@ dependencies = [
"zbus",
]
+[[package]]
+name = "tauri-plugin-updater"
+version = "2.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a5cad8ed5948d988e1018ecd31e27cacedbf72ce3fb972940c3e4bf51639e4b"
+dependencies = [
+ "base64 0.22.1",
+ "dirs 6.0.0",
+ "flate2",
+ "futures-util",
+ "http",
+ "infer",
+ "log",
+ "minisign-verify",
+ "osakit",
+ "percent-encoding",
+ "reqwest 0.13.4",
+ "rustls",
+ "semver",
+ "serde",
+ "serde_json",
+ "tar",
+ "tauri",
+ "tauri-plugin",
+ "tempfile",
+ "thiserror 2.0.19",
+ "time",
+ "tokio",
+ "url",
+ "windows-sys 0.60.2",
+ "zip",
+]
+
[[package]]
name = "tauri-plugin-window-state"
version = "2.4.1"
@@ -3873,7 +4276,7 @@ dependencies = [
"dpi",
"gtk",
"http",
- "jni",
+ "jni 0.21.1",
"objc2",
"objc2-ui-kit",
"objc2-web-kit",
@@ -3896,7 +4299,7 @@ checksum = "4e6fac707727b7a2f48e4ded90976324267371073edbb415ffb73bb0458d203f"
dependencies = [
"gtk",
"http",
- "jni",
+ "jni 0.21.1",
"log",
"objc2",
"objc2-app-kit",
@@ -4126,6 +4529,16 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "tokio-rustls"
+version = "0.26.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b0c85f2c3ef0b1cd58b36682f4b17aaa995f0e5db534d85692b4903abce21f67"
+dependencies = [
+ "rustls",
+ "tokio",
+]
+
[[package]]
name = "tokio-util"
version = "0.7.19"
@@ -4439,6 +4852,12 @@ version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
+[[package]]
+name = "untrusted"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
+
[[package]]
name = "url"
version = "2.5.8"
@@ -4626,6 +5045,16 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "web-time"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
[[package]]
name = "web_atoms"
version = "0.2.5"
@@ -4682,6 +5111,24 @@ dependencies = [
"system-deps",
]
+[[package]]
+name = "webpki-root-certs"
+version = "1.0.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b"
+dependencies = [
+ "rustls-pki-types",
+]
+
+[[package]]
+name = "webpki-roots"
+version = "1.0.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
+dependencies = [
+ "rustls-pki-types",
+]
+
[[package]]
name = "webview2-com"
version = "0.38.2"
@@ -4923,6 +5370,15 @@ dependencies = [
"windows-targets 0.42.2",
]
+[[package]]
+name = "windows-sys"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
[[package]]
name = "windows-sys"
version = "0.59.0"
@@ -5227,7 +5683,7 @@ dependencies = [
"gtk",
"http",
"javascriptcore-rs",
- "jni",
+ "jni 0.21.1",
"libc",
"ndk",
"objc2",
@@ -5274,6 +5730,16 @@ dependencies = [
"pkg-config",
]
+[[package]]
+name = "xattr"
+version = "1.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
+dependencies = [
+ "libc",
+ "rustix",
+]
+
[[package]]
name = "yoke"
version = "0.8.3"
@@ -5399,6 +5865,12 @@ dependencies = [
"synstructure",
]
+[[package]]
+name = "zeroize"
+version = "1.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
+
[[package]]
name = "zerotrie"
version = "0.2.4"
diff --git a/desktop/README.md b/desktop/README.md
index 1bd5ae762..064bd741c 100644
--- a/desktop/README.md
+++ b/desktop/README.md
@@ -115,8 +115,8 @@ acceptance builds. Windows ARM64 stays outside the current product gate.
for canonical `gh-vX.Y.ZrcN` tags. For example, `gh-v3.1.2rc1` builds the tag's
exact commit, stamps desktop version `3.1.2-rc.1`, and bundles Avibe `3.1.2rc1`.
All three native builds must succeed before the existing release job publishes
-the GitHub prerelease. Official `v*` releases and PyPI publication keep their
-existing workflow; they do not acquire desktop assets from this TEST path.
+the GitHub prerelease. Official stable `vX.Y.Z` releases use the same desktop builder only when the G2
+stable signing gate below is enabled; PyPI publication retains its sole finalizer.
TEST builds never receive Apple or Windows signing credentials, even when the
repository has them configured. The macOS app is ad-hoc signed, its outer DMG
@@ -132,7 +132,7 @@ Already-published releases cannot be retrofitted with missing desktop assets.
The manual workflow remains available for artifact-only builds: select a source
ref and SemVer version in Actions. It retains optional Developer ID signing and
notarization when its complete Apple secret set is configured. Actions artifacts
-are retained for 14 days; neither path enables a desktop auto-updater.
+are retained for 14 days; automatic update metadata is disabled unless the G2 signing gate below is configured.
See [Desktop TEST installation](../docs/desktop-test-installation.md) for
architecture selection, hash checks, app-specific Gatekeeper/SmartScreen
@@ -347,3 +347,83 @@ build unit for `.github/workflows/release_ai.yml`. The manual signing policy and
the deterministic TEST policy are described above. Native packaging and a real
installation on each supported architecture remain separate acceptance gates
from unit/contract tests.
+
+## Signed desktop updates (G2)
+
+The native **Check for Desktop Updates…** entry is the sole update owner. The
+Workbench version badge in a desktop window opens that same entry and shows the
+build-injected desktop version. Startup only checks; a native **Download and
+Install** confirmation authorizes download and replacement. The tray/menu shows
+checking, current, available, downloading, installing, disabled, and error states.
+The **Use TEST Updates** toggle persists beside the private Runtime, defaults on
+for prerelease app versions and off for stable versions, and never downgrades.
+Browsers and Python installations retain their existing update behavior.
+
+The provider discovers published GitHub Releases in `avibe-bot/avibe`, using
+canonical `gh-vX.Y.ZrcN` for TEST and `vX.Y.Z` for stable. It selects the highest
+SemVer in the channel (up to 1,000 releases; overflow is an error). Releases
+without signed metadata cannot be installed automatically, including rc14. A
+signed per-target `desktop-update-<target>.json` binds the repository, tag, peeled
+source commit, desktop version, target, artifact URL, size, SHA-256, and Tauri
+artifact signature. Both metadata and payload signatures are verified locally
+with the build-pinned public key. `.SIGNATURE` is OS-signing status text only.
+The plugin response must equal the authenticated metadata before download.
+
+macOS installs a signed `.app.tar.gz`; the DMG remains the first/manual install
+format. The app is extracted on the installation filesystem, its bundle ID,
+version, CPU architecture, and code seal are checked, then the old app is moved
+aside and restored if replacement fails. A backup is retained if even restoration
+fails. Unwritable installation locations fail before moving the old app; there
+is no privileged destructive fallback. Windows downloads the signed NSIS EXE,
+prepares a backup before exiting, and starts a native PowerShell supervisor which
+waits for NSIS completion, checks the resulting version, and restores/relaunches
+the previous install on failure. The supervisor retains recovery diagnostics and
+backup bytes on failure. No update path deletes `~/.avibe`, private Runtime slots,
+or managed/external Agent backends. A later ordinary app launch follows the
+existing private Runtime lifecycle.
+
+### Release operator configuration
+
+No real signing key or public key is supplied by this change. Until configured,
+TEST remains manual-only and the shell explicitly disables automatic updates.
+The public key must come from the owner's separately generated Tauri signing key;
+never use the disposable test-fixture key for a release.
+
+1. Create the GitHub Environment **desktop-updater**, protect its signing access,
+ and add `TAURI_SIGNING_PRIVATE_KEY` and
+ `TAURI_SIGNING_PRIVATE_KEY_PASSWORD` (empty for an unencrypted key). These are
+ Tauri/Minisign updater credentials, independent of Apple/Windows OS signing.
+2. Set repository variable `DESKTOP_UPDATER_PUBLIC_KEY` to the single-line
+ base64 Tauri public key. It is compiled into the app and used again by the
+ publication verifier. It is public and must be readable by the finalizer.
+3. After native acceptance, set repository variables `DESKTOP_UPDATER_TEST`
+ and/or `DESKTOP_UPDATER_STABLE` to exactly `true`. Absent/false TEST builds
+ remain manual-only; absent/false stable does not add desktop artifacts to
+ Python releases. Enabling either channel requires the complete signing pair;
+ missing keys or any signature/source/asset mismatch aborts publication.
+4. Cut a new owner-authorized tag. Signing happens after the final macOS app seal
+ and Windows installer are produced. Every target signs its own manifest,
+ verifies both signatures with the same Rust contract used by the shell, then
+ uploads. The release job verifies all targets again and reads back uploaded
+ bytes. Stable assets are staged before the exact-source notes workflow can
+ succeed; the existing `publish.yml` finalizer waits for that workflow before
+ publishing. TEST retains its existing sole finalizer. Never retrofit rc14 or
+ overwrite a published asset, and never rotate the public key without a planned
+ bridge release signed by the currently trusted key.
+
+Dependencies: native updater `tauri-plugin-updater` 2.12.0 (locked), shared
+`minisign-verify` 0.2.5 / `base64` 0.22 / `semver` 1, HTTPS `reqwest`, and native
+archive/temporary-file support. The frontend needs no updater JS permission or
+plugin: it opens the native owner through a fixed navigation request.
+
+### Residual native acceptance
+
+Use disposable macOS arm64/x64 and Windows x64 installations with two newly
+signed releases. Confirm startup checks without downloading; approve an upgrade;
+verify the running app version, preserved sessions/settings/private Runtime,
+backend versions, and relaunch. Repeat with corrupt payload/signature, mismatched
+source/target/version, interrupted download, insufficient permissions/disk space,
+installer cancellation/failure, and channel switching. Test Windows paths with
+spaces and non-ASCII, and macOS app replacement in a writable Applications
+folder. Run with the actual release key and actual OS-signing policy. Local
+fixture tests and CI do not claim that this real installation acceptance ran.
diff --git a/desktop/package-lock.json b/desktop/package-lock.json
index 8dc4dedb0..3fb6ae9b6 100644
--- a/desktop/package-lock.json
+++ b/desktop/package-lock.json
@@ -11,7 +11,7 @@
"@tauri-apps/api": "^2.9.0"
},
"devDependencies": {
- "@tauri-apps/cli": "^2.11.0",
+ "@tauri-apps/cli": "2.11.4",
"typescript": "~5.9.3",
"vite": "^8.0.16"
},
@@ -26,7 +26,6 @@
"dev": true,
"license": "MIT",
"optional": true,
- "peer": true,
"dependencies": {
"@emnapi/wasi-threads": "1.2.2",
"tslib": "^2.4.0"
@@ -39,7 +38,6 @@
"dev": true,
"license": "MIT",
"optional": true,
- "peer": true,
"dependencies": {
"tslib": "^2.4.0"
}
@@ -922,7 +920,6 @@
"integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",
"dev": true,
"license": "MIT",
- "peer": true,
"engines": {
"node": ">=12"
},
diff --git a/desktop/package.json b/desktop/package.json
index a69f032b7..b04d731bf 100644
--- a/desktop/package.json
+++ b/desktop/package.json
@@ -12,13 +12,14 @@
"build": "tsc --noEmit && vite build",
"test:i18n": "node scripts/verify-i18n.mjs",
"preview": "vite preview",
- "tauri": "tauri"
+ "tauri": "tauri",
+ "test:updater": "cargo test -p avibe-runtime-host update && cargo test -p avibe-desktop update"
},
"dependencies": {
"@tauri-apps/api": "^2.9.0"
},
"devDependencies": {
- "@tauri-apps/cli": "^2.11.0",
+ "@tauri-apps/cli": "2.11.4",
"typescript": "~5.9.3",
"vite": "^8.0.16"
}
diff --git a/desktop/runtime-host/Cargo.toml b/desktop/runtime-host/Cargo.toml
index 121b0f86f..d93234444 100644
--- a/desktop/runtime-host/Cargo.toml
+++ b/desktop/runtime-host/Cargo.toml
@@ -8,8 +8,11 @@ publish.workspace = true
[dependencies]
async-trait.workspace = true
+base64 = "0.22"
chrono = { version = "0.4", default-features = false, features = ["std"] }
+minisign-verify = "0.2"
reqwest.workspace = true
+semver = "1"
serde.workspace = true
serde_json.workspace = true
sha2.workspace = true
diff --git a/desktop/runtime-host/examples/verify_update.rs b/desktop/runtime-host/examples/verify_update.rs
new file mode 100644
index 000000000..f8de3a230
--- /dev/null
+++ b/desktop/runtime-host/examples/verify_update.rs
@@ -0,0 +1,32 @@
+//! Release gate: authenticate exactly the same manifest and bytes as the shell.
+use avibe_runtime_host::update::{manifest_name, Channel, Manifest};
+use std::{env, fs, path::Path};
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ let args: Vec<String> = env::args().skip(1).collect();
+ if args.len() != 5 {
+ return Err("usage: verify_update DIRECTORY TAG SOURCE_SHA TARGET PUBLIC_KEY_FILE".into());
+ }
+ let root = Path::new(&args[0]);
+ let name = manifest_name(&args[3]);
+ let key = fs::read_to_string(&args[4])?;
+ let manifest = Manifest::authenticated(
+ &fs::read(root.join(&name))?,
+ &fs::read_to_string(root.join(format!("{name}.sig")))?,
+ &key,
+ )?;
+ let channel = if args[1].starts_with("gh-v") {
+ Channel::Test
+ } else {
+ Channel::Stable
+ };
+ let artifact = manifest.validate(channel, &args[1], &args[2], &args[3])?;
+ artifact.verify(
+ &fs::read(root.join(artifact.url.rsplit('/').next().ok_or("invalid URL")?))?,
+ &key,
+ )?;
+ println!(
+ "Authenticated {} {} {}",
+ manifest.tag, manifest.target, manifest.source_sha
+ );
+ Ok(())
+}
diff --git a/desktop/runtime-host/src/lib.rs b/desktop/runtime-host/src/lib.rs
index 4126dbb00..3c0e78f9e 100644
--- a/desktop/runtime-host/src/lib.rs
+++ b/desktop/runtime-host/src/lib.rs
@@ -78,3 +78,5 @@ pub fn bundled_runtime_host(
settings,
))
}
+
+pub mod update;
diff --git a/desktop/runtime-host/src/update.rs b/desktop/runtime-host/src/update.rs
new file mode 100644
index 000000000..230271e2c
--- /dev/null
+++ b/desktop/runtime-host/src/update.rs
@@ -0,0 +1,197 @@
+//! Signed desktop release contract, shared by the shell and release verifier.
+use base64::{engine::general_purpose::STANDARD, Engine};
+use minisign_verify::{PublicKey, Signature};
+use semver::Version;
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+use std::collections::BTreeMap;
+
+pub const REPOSITORY: &str = "avibe-bot/avibe";
+pub const TARGETS: &[(&str, &str, &str)] = &[
+ ("aarch64-apple-darwin", "darwin-aarch64", ".app.tar.gz"),
+ ("x86_64-apple-darwin", "darwin-x86_64", ".app.tar.gz"),
+ ("x86_64-pc-windows-msvc", "windows-x86_64", ".exe"),
+];
+
+#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
+#[serde(rename_all = "lowercase")]
+pub enum Channel {
+ Test,
+ Stable,
+}
+
+impl Channel {
+ pub fn for_version(version: &Version) -> Self {
+ if version.pre.is_empty() {
+ Self::Stable
+ } else {
+ Self::Test
+ }
+ }
+ pub fn version(self, tag: &str) -> Result<Version, String> {
+ let raw = match self {
+ Self::Stable => tag.strip_prefix('v').ok_or("stable tag required")?.to_string(),
+ Self::Test => {
+ let (core, rc) = tag
+ .strip_prefix("gh-v")
+ .ok_or("TEST tag required")?
+ .split_once("rc")
+ .ok_or("canonical rc tag required")?;
+ if rc.is_empty() || !rc.bytes().all(|c| c.is_ascii_digit()) || (rc.len() > 1 && rc.starts_with('0')) {
+ return Err("invalid rc number".into());
+ }
+ format!("{core}-rc.{rc}")
+ }
+ };
+ let version = Version::parse(&raw).map_err(|_| "invalid version")?;
+ if !version.build.is_empty()
+ || match self {
+ Self::Stable => !version.pre.is_empty(),
+ Self::Test => version
+ .pre
+ .to_string()
+ .strip_prefix("rc.")
+ .is_none_or(|rc| !rc.bytes().all(|c| c.is_ascii_digit())),
+ }
+ {
+ return Err("noncanonical release tag".into());
+ }
+ Ok(version)
+ }
+}
+
+pub fn target_spec(target: &str) -> Result<(&'static str, &'static str), String> {
+ TARGETS
+ .iter()
+ .find(|(name, _, _)| *name == target)
+ .map(|(_, key, suffix)| (*key, *suffix))
+ .ok_or("unsupported target".into())
+}
+pub fn manifest_name(target: &str) -> String {
+ format!("desktop-update-{target}.json")
+}
+pub fn asset_url(tag: &str, name: &str) -> String {
+ format!("https://github.com/{REPOSITORY}/releases/download/{tag}/{name}")
+}
+pub fn artifact_name(version: &str, target: &str) -> Result<String, String> {
+ Ok(format!("Avibe_{version}_{target}{}", target_spec(target)?.1))
+}
+
+#[derive(Clone, Debug, Deserialize, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct Artifact {
+ pub url: String,
+ pub signature: String,
+ pub sha256: String,
+ pub size: u64,
+}
+#[derive(Clone, Debug, Deserialize, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct Manifest {
+ pub schema_version: u32,
+ pub repository: String,
+ pub tag: String,
+ pub source_sha: String,
+ pub channel: Channel,
+ pub version: String,
+ pub target: String,
+ pub platforms: BTreeMap<String, Artifact>,
+}
+
+pub fn verify_signature(bytes: &[u8], signature: &str, public_key: &str) -> Result<(), String> {
+ let decode = |s: &str| -> Result<String, String> {
+ String::from_utf8(STANDARD.decode(s.trim()).map_err(|_| "invalid signature encoding")?)
+ .map_err(|_| "invalid signature text".into())
+ };
+ let key = PublicKey::decode(&decode(public_key)?).map_err(|_| "invalid updater public key")?;
+ let signature = Signature::decode(&decode(signature)?).map_err(|_| "invalid updater signature")?;
+ key.verify(bytes, &signature, true)
+ .map_err(|_| "updater signature verification failed".into())
+}
+
+impl Manifest {
+ pub fn authenticated(bytes: &[u8], signature: &str, public_key: &str) -> Result<Self, String> {
+ verify_signature(bytes, signature, public_key)?;
+ serde_json::from_slice(bytes).map_err(|_| "invalid update manifest".into())
+ }
+ pub fn validate(&self, channel: Channel, tag: &str, source: &str, target: &str) -> Result<&Artifact, String> {
+ let version = channel.version(tag)?;
+ let (key, _) = target_spec(target)?;
+ if self.schema_version != 1
+ || self.repository != REPOSITORY
+ || self.tag != tag
+ || self.channel != channel
+ || self.source_sha != source
+ || self.target != target
+ || self.version != version.to_string()
+ || self.platforms.len() != 1
+ || source.len() != 40
+ || !source.bytes().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
+ {
+ return Err("update provenance mismatch".into());
+ }
+ let artifact = self.platforms.get(key).ok_or("update platform mismatch")?;
+ if artifact.url != asset_url(tag, &artifact_name(&self.version, target)?)
+ || artifact.size == 0
+ || artifact.size > 4 * 1024 * 1024 * 1024
+ || artifact.sha256.len() != 64
+ || !artifact
+ .sha256
+ .bytes()
+ .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
+ || artifact.signature.trim().is_empty()
+ {
+ return Err("invalid update artifact".into());
+ }
+ Ok(artifact)
+ }
+}
+impl Artifact {
+ pub fn verify(&self, bytes: &[u8], public_key: &str) -> Result<(), String> {
+ if bytes.len() as u64 != self.size || format!("{:x}", Sha256::digest(bytes)) != self.sha256 {
+ return Err("update artifact integrity mismatch".into());
+ }
+ verify_signature(bytes, &self.signature, public_key)
+ }
+}
+
+/// The consuming boundary: neither download errors nor unverified bytes may
+/// reach the platform installer. Tests inject failures at this exact boundary.
+pub fn install_verified<T>(
+ download: Result<Vec<u8>, String>,
+ artifact: &Artifact,
+ public_key: &str,
+ install: impl FnOnce(&[u8]) -> Result<T, String>,
+) -> Result<T, String> {
+ let bytes = download?;
+ artifact.verify(&bytes, public_key)?;
+ install(&bytes)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn channels_are_disjoint_and_versions_follow_semver() {
+ assert!(Channel::Test.version("gh-v3.1.2rc10").unwrap() > Channel::Test.version("gh-v3.1.2rc9").unwrap());
+ assert!(Channel::Stable.version("v3.1.2").unwrap() > Channel::Test.version("gh-v3.1.2rc99").unwrap());
+ for tag in [
+ "gh-v3.1.2rc01",
+ "gh-v3.1.2rc",
+ "gh-v3.1.2rc1+foo",
+ "v3.1.2",
+ "gh-v3.1.2",
+ ] {
+ assert!(Channel::Test.version(tag).is_err(), "{tag}");
+ }
+ for tag in ["gh-v3.1.2rc1", "v3.1.2rc1", "v3.1.2-rc.1", "v3.1.2+foo"] {
+ assert!(Channel::Stable.version(tag).is_err(), "{tag}");
+ }
+ }
+ #[test]
+ fn unsigned_or_description_metadata_is_never_a_signature() {
+ for signature in ["", "app-adhoc", "installer-unsigned", "U0lHTkFUVVJF"] {
+ assert!(verify_signature(b"payload", signature, "").is_err());
+ }
+ }
+}
diff --git a/desktop/runtime-host/tests/fixtures/updater/.gitattributes b/desktop/runtime-host/tests/fixtures/updater/.gitattributes
new file mode 100644
index 000000000..0dd8d61c6
--- /dev/null
+++ b/desktop/runtime-host/tests/fixtures/updater/.gitattributes
@@ -0,0 +1,2 @@
+# Signatures authenticate exact bytes, including line endings, on every host.
+* -text
diff --git a/desktop/runtime-host/tests/fixtures/updater/artifact.bin b/desktop/runtime-host/tests/fixtures/updater/artifact.bin
new file mode 100644
index 000000000..968639632
--- /dev/null
+++ b/desktop/runtime-host/tests/fixtures/updater/artifact.bin
@@ -0,0 +1 @@
+Avibe hermetic signed updater fixture
diff --git a/desktop/runtime-host/tests/fixtures/updater/public-key.txt b/desktop/runtime-host/tests/fixtures/updater/public-key.txt
new file mode 100644
index 000000000..ee51eeb15
--- /dev/null
+++ b/desktop/runtime-host/tests/fixtures/updater/public-key.txt
@@ -0,0 +1 @@
+dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDE5NUM3QjQzODJBMDA5QTMKUldTakNhQ0NRM3RjR1FEaVEraTZER1g4RnBwOCtyMVU0QllFN0tydjN6MEJaUGloaEVET0ptczgK
diff --git a/desktop/runtime-host/tests/fixtures/updater/stable-aarch64-apple-darwin.json b/desktop/runtime-host/tests/fixtures/updater/stable-aarch64-apple-darwin.json
new file mode 100644
index 000000000..057c19688
--- /dev/null
+++ b/desktop/runtime-host/tests/fixtures/updater/stable-aarch64-apple-darwin.json
@@ -0,0 +1,17 @@
+{
+ "schema_version": 1,
+ "repository": "avibe-bot/avibe",
+ "tag": "v3.1.2",
+ "source_sha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "channel": "stable",
+ "version": "3.1.2",
+ "target": "aarch64-apple-darwin",
+ "platforms": {
+ "darwin-aarch64": {
+ "url": "https://github.com/avibe-bot/avibe/releases/download/v3.1.2/Avibe_3.1.2_aarch64-apple-darwin.app.tar.gz",
+ "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVTakNhQ0NRM3RjR1VtdVlTWk5QZ011ZTNyMzZjRlhWZ3VTektGclRDa1U1T3Vyc1Y3akRKVDZodEJVT3A2TWlrY01uT3RvWUhnajNoWjhJZGFTRDVMMzBoOXVVYlROZ1FjPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkwMjk4MzM5CWZpbGU6YXJ0aWZhY3QuYmluCkR4WWkrN0dkditkY1hQTXhaTi94ZDdBK2JmY25MUlhmbGxtV3RmbGNRcFhjcSt1dlNhR1JvSFExa2Q5ZjlmVHZ4ZHBBZUVYc0RoV0pPMWoxNHRXZENnPT0K",
+ "sha256": "bbeebd41b0401b2846d675a1c06907036580cdedb6d2a2555970ba06ff2a31bd",
+ "size": 38
+ }
+ }
+}
diff --git a/desktop/runtime-host/tests/fixtures/updater/stable-aarch64-apple-darwin.json.sig b/desktop/runtime-host/tests/fixtures/updater/stable-aarch64-apple-darwin.json.sig
new file mode 100644
index 000000000..60f42396d
--- /dev/null
+++ b/desktop/runtime-host/tests/fixtures/updater/stable-aarch64-apple-darwin.json.sig
@@ -0,0 +1 @@
+dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVTakNhQ0NRM3RjR1pFeFc4TUMwMDQxMnl0amdLY080MnRzNWVFdk01dlZuUjI4ZmxXZENYUUw3ZlQ1dkhScHgwZGl1UjBoN0YvQ1FVejErbDBjMmM1OFQ1ZkpJMzk2dGdnPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkwMjk4MzQwCWZpbGU6c3RhYmxlLWFhcmNoNjQtYXBwbGUtZGFyd2luLmpzb24KUGU2THdVWkJQdTE5Sk9kbW1tYVdwQ1BJSHBvT2s4TFE4ckt4TlM3WEwzSWY3WENyN3RGMGg3eGFaMFJ3YWxMck52YURYcEFUeHlRbXdlSE1ZVzVxQUE9PQo=
\ No newline at end of file
diff --git a/desktop/runtime-host/tests/fixtures/updater/stable-x86_64-apple-darwin.json b/desktop/runtime-host/tests/fixtures/updater/stable-x86_64-apple-darwin.json
new file mode 100644
index 000000000..55582dfa7
--- /dev/null
+++ b/desktop/runtime-host/tests/fixtures/updater/stable-x86_64-apple-darwin.json
@@ -0,0 +1,17 @@
+{
+ "schema_version": 1,
+ "repository": "avibe-bot/avibe",
+ "tag": "v3.1.2",
+ "source_sha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "channel": "stable",
+ "version": "3.1.2",
+ "target": "x86_64-apple-darwin",
+ "platforms": {
+ "darwin-x86_64": {
+ "url": "https://github.com/avibe-bot/avibe/releases/download/v3.1.2/Avibe_3.1.2_x86_64-apple-darwin.app.tar.gz",
+ "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVTakNhQ0NRM3RjR1VtdVlTWk5QZ011ZTNyMzZjRlhWZ3VTektGclRDa1U1T3Vyc1Y3akRKVDZodEJVT3A2TWlrY01uT3RvWUhnajNoWjhJZGFTRDVMMzBoOXVVYlROZ1FjPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkwMjk4MzM5CWZpbGU6YXJ0aWZhY3QuYmluCkR4WWkrN0dkditkY1hQTXhaTi94ZDdBK2JmY25MUlhmbGxtV3RmbGNRcFhjcSt1dlNhR1JvSFExa2Q5ZjlmVHZ4ZHBBZUVYc0RoV0pPMWoxNHRXZENnPT0K",
+ "sha256": "bbeebd41b0401b2846d675a1c06907036580cdedb6d2a2555970ba06ff2a31bd",
+ "size": 38
+ }
+ }
+}
diff --git a/desktop/runtime-host/tests/fixtures/updater/stable-x86_64-apple-darwin.json.sig b/desktop/runtime-host/tests/fixtures/updater/stable-x86_64-apple-darwin.json.sig
new file mode 100644
index 000000000..8d0e7582b
--- /dev/null
+++ b/desktop/runtime-host/tests/fixtures/updater/stable-x86_64-apple-darwin.json.sig
@@ -0,0 +1 @@
+dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVTakNhQ0NRM3RjR1dHQy96dWY3M0VCWTE1QzBmVmllSTZVelJlVEJ1VEhKaUNmYkZnQXROVUtyTXJ5RFlHeFZaeURybjZYMUZoeXptV3NxUExNT0dtMldpSG5LeVZCVVFnPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkwMjk4MzQwCWZpbGU6c3RhYmxlLXg4Nl82NC1hcHBsZS1kYXJ3aW4uanNvbgpZbHh4OFZSbkMxTnVMUzAwWVM4Ly93N3c4N1BIbEg2ZGs1YnBZbVlYNHVhUzRLTVBGM1BuUTNDZVVFM1NzR3hXKy9KYUN3ekN5YWFYVXBwUmJMNEhDUT09Cg==
\ No newline at end of file
diff --git a/desktop/runtime-host/tests/fixtures/updater/stable-x86_64-pc-windows-msvc.json b/desktop/runtime-host/tests/fixtures/updater/stable-x86_64-pc-windows-msvc.json
new file mode 100644
index 000000000..29e3eb23e
--- /dev/null
+++ b/desktop/runtime-host/tests/fixtures/updater/stable-x86_64-pc-windows-msvc.json
@@ -0,0 +1,17 @@
+{
+ "schema_version": 1,
+ "repository": "avibe-bot/avibe",
+ "tag": "v3.1.2",
+ "source_sha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "channel": "stable",
+ "version": "3.1.2",
+ "target": "x86_64-pc-windows-msvc",
+ "platforms": {
+ "windows-x86_64": {
+ "url": "https://github.com/avibe-bot/avibe/releases/download/v3.1.2/Avibe_3.1.2_x86_64-pc-windows-msvc.exe",
+ "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVTakNhQ0NRM3RjR1VtdVlTWk5QZ011ZTNyMzZjRlhWZ3VTektGclRDa1U1T3Vyc1Y3akRKVDZodEJVT3A2TWlrY01uT3RvWUhnajNoWjhJZGFTRDVMMzBoOXVVYlROZ1FjPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkwMjk4MzM5CWZpbGU6YXJ0aWZhY3QuYmluCkR4WWkrN0dkditkY1hQTXhaTi94ZDdBK2JmY25MUlhmbGxtV3RmbGNRcFhjcSt1dlNhR1JvSFExa2Q5ZjlmVHZ4ZHBBZUVYc0RoV0pPMWoxNHRXZENnPT0K",
+ "sha256": "bbeebd41b0401b2846d675a1c06907036580cdedb6d2a2555970ba06ff2a31bd",
+ "size": 38
+ }
+ }
+}
diff --git a/desktop/runtime-host/tests/fixtures/updater/stable-x86_64-pc-windows-msvc.json.sig b/desktop/runtime-host/tests/fixtures/updater/stable-x86_64-pc-windows-msvc.json.sig
new file mode 100644
index 000000000..bf53b0b24
--- /dev/null
+++ b/desktop/runtime-host/tests/fixtures/updater/stable-x86_64-pc-windows-msvc.json.sig
@@ -0,0 +1 @@
+dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVTakNhQ0NRM3RjR1MxM0R5Y1VqblpMa1lKTU5pWS9NcWU1Z2c2NUtUT3dIeUZhb1ovSFl3eERTdHlKdi9Zbm8vVjVHdWcyekNYWlNuZGowSzQvV2l5eXVCbjNsVG52MmdVPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkwMjk4MzQwCWZpbGU6c3RhYmxlLXg4Nl82NC1wYy13aW5kb3dzLW1zdmMuanNvbgpEMERyZkFKcW5PY1JDcnpEVVhlclJURUUxbnhFZ0dBN1pmWmR4eklVay92QTlLT0hpcm4wcjlpMWNlN090dU00OTdhbTcyOGhtRVZpaWx5cllKUjFDdz09Cg==
\ No newline at end of file
diff --git a/desktop/runtime-host/tests/fixtures/updater/test-aarch64-apple-darwin.json b/desktop/runtime-host/tests/fixtures/updater/test-aarch64-apple-darwin.json
new file mode 100644
index 000000000..ed155dcfa
--- /dev/null
+++ b/desktop/runtime-host/tests/fixtures/updater/test-aarch64-apple-darwin.json
@@ -0,0 +1,17 @@
+{
+ "schema_version": 1,
+ "repository": "avibe-bot/avibe",
+ "tag": "gh-v3.1.2rc15",
+ "source_sha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "channel": "test",
+ "version": "3.1.2-rc.15",
+ "target": "aarch64-apple-darwin",
+ "platforms": {
+ "darwin-aarch64": {
+ "url": "https://github.com/avibe-bot/avibe/releases/download/gh-v3.1.2rc15/Avibe_3.1.2-rc.15_aarch64-apple-darwin.app.tar.gz",
+ "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVTakNhQ0NRM3RjR1VtdVlTWk5QZ011ZTNyMzZjRlhWZ3VTektGclRDa1U1T3Vyc1Y3akRKVDZodEJVT3A2TWlrY01uT3RvWUhnajNoWjhJZGFTRDVMMzBoOXVVYlROZ1FjPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkwMjk4MzM5CWZpbGU6YXJ0aWZhY3QuYmluCkR4WWkrN0dkditkY1hQTXhaTi94ZDdBK2JmY25MUlhmbGxtV3RmbGNRcFhjcSt1dlNhR1JvSFExa2Q5ZjlmVHZ4ZHBBZUVYc0RoV0pPMWoxNHRXZENnPT0K",
+ "sha256": "bbeebd41b0401b2846d675a1c06907036580cdedb6d2a2555970ba06ff2a31bd",
+ "size": 38
+ }
+ }
+}
diff --git a/desktop/runtime-host/tests/fixtures/updater/test-aarch64-apple-darwin.json.sig b/desktop/runtime-host/tests/fixtures/updater/test-aarch64-apple-darwin.json.sig
new file mode 100644
index 000000000..fbb6f1f6d
--- /dev/null
+++ b/desktop/runtime-host/tests/fixtures/updater/test-aarch64-apple-darwin.json.sig
@@ -0,0 +1 @@
+dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVTakNhQ0NRM3RjR2JHU2JRS2JZSXZnbUJRWGFaclh5cFF2TGdoa0dsbDNOSXFXeU1FVVY2ZmFHQ2tzOWFMaWVGMXpkQ3F0eXBWK25kOEJ3Y01iSkhDVDJYQXZEUkJ0MEFvPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkwMjk4MzM5CWZpbGU6dGVzdC1hYXJjaDY0LWFwcGxlLWRhcndpbi5qc29uCkZIZHUyUHhhN2pRUUFxVjNpM1VvYTdNdGxYQnUxaXMvSkZ0MHlRME5FL0RMQkgxVTJEV0djU0o4Uzd1ck41OFlxTngwZzE5cDc4RU1heGtCN2xKZERnPT0K
\ No newline at end of file
diff --git a/desktop/runtime-host/tests/fixtures/updater/test-x86_64-apple-darwin.json b/desktop/runtime-host/tests/fixtures/updater/test-x86_64-apple-darwin.json
new file mode 100644
index 000000000..4855f120f
--- /dev/null
+++ b/desktop/runtime-host/tests/fixtures/updater/test-x86_64-apple-darwin.json
@@ -0,0 +1,17 @@
+{
+ "schema_version": 1,
+ "repository": "avibe-bot/avibe",
+ "tag": "gh-v3.1.2rc15",
+ "source_sha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "channel": "test",
+ "version": "3.1.2-rc.15",
+ "target": "x86_64-apple-darwin",
+ "platforms": {
+ "darwin-x86_64": {
+ "url": "https://github.com/avibe-bot/avibe/releases/download/gh-v3.1.2rc15/Avibe_3.1.2-rc.15_x86_64-apple-darwin.app.tar.gz",
+ "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVTakNhQ0NRM3RjR1VtdVlTWk5QZ011ZTNyMzZjRlhWZ3VTektGclRDa1U1T3Vyc1Y3akRKVDZodEJVT3A2TWlrY01uT3RvWUhnajNoWjhJZGFTRDVMMzBoOXVVYlROZ1FjPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkwMjk4MzM5CWZpbGU6YXJ0aWZhY3QuYmluCkR4WWkrN0dkditkY1hQTXhaTi94ZDdBK2JmY25MUlhmbGxtV3RmbGNRcFhjcSt1dlNhR1JvSFExa2Q5ZjlmVHZ4ZHBBZUVYc0RoV0pPMWoxNHRXZENnPT0K",
+ "sha256": "bbeebd41b0401b2846d675a1c06907036580cdedb6d2a2555970ba06ff2a31bd",
+ "size": 38
+ }
+ }
+}
diff --git a/desktop/runtime-host/tests/fixtures/updater/test-x86_64-apple-darwin.json.sig b/desktop/runtime-host/tests/fixtures/updater/test-x86_64-apple-darwin.json.sig
new file mode 100644
index 000000000..a42bbd294
--- /dev/null
+++ b/desktop/runtime-host/tests/fixtures/updater/test-x86_64-apple-darwin.json.sig
@@ -0,0 +1 @@
+dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVTakNhQ0NRM3RjR1crakpncVMxSHhwYVluOWMwV25hME1uazNQcFFXV1k0aHdUZHNXeDBDWXdzQTBYK0syQXFOWExtaVRGUEZuK3pNcUovall1L1Y5cEh5NmI5REo5TEFnPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkwMjk4MzQwCWZpbGU6dGVzdC14ODZfNjQtYXBwbGUtZGFyd2luLmpzb24KbFlkWHZXOFM5NnNPV29ESFNHOU4xclYzM3J5R0FJVlBDRnJESTZhdzJLTWtXbmhUYmJqdWV1UGd1Z05NblV0bkVwL3ExUTNGYkJURWpaWE1YZE4xQmc9PQo=
\ No newline at end of file
diff --git a/desktop/runtime-host/tests/fixtures/updater/test-x86_64-pc-windows-msvc.json b/desktop/runtime-host/tests/fixtures/updater/test-x86_64-pc-windows-msvc.json
new file mode 100644
index 000000000..4f4a5dc39
--- /dev/null
+++ b/desktop/runtime-host/tests/fixtures/updater/test-x86_64-pc-windows-msvc.json
@@ -0,0 +1,17 @@
+{
+ "schema_version": 1,
+ "repository": "avibe-bot/avibe",
+ "tag": "gh-v3.1.2rc15",
+ "source_sha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "channel": "test",
+ "version": "3.1.2-rc.15",
+ "target": "x86_64-pc-windows-msvc",
+ "platforms": {
+ "windows-x86_64": {
+ "url": "https://github.com/avibe-bot/avibe/releases/download/gh-v3.1.2rc15/Avibe_3.1.2-rc.15_x86_64-pc-windows-msvc.exe",
+ "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVTakNhQ0NRM3RjR1VtdVlTWk5QZ011ZTNyMzZjRlhWZ3VTektGclRDa1U1T3Vyc1Y3akRKVDZodEJVT3A2TWlrY01uT3RvWUhnajNoWjhJZGFTRDVMMzBoOXVVYlROZ1FjPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkwMjk4MzM5CWZpbGU6YXJ0aWZhY3QuYmluCkR4WWkrN0dkditkY1hQTXhaTi94ZDdBK2JmY25MUlhmbGxtV3RmbGNRcFhjcSt1dlNhR1JvSFExa2Q5ZjlmVHZ4ZHBBZUVYc0RoV0pPMWoxNHRXZENnPT0K",
+ "sha256": "bbeebd41b0401b2846d675a1c06907036580cdedb6d2a2555970ba06ff2a31bd",
+ "size": 38
+ }
+ }
+}
diff --git a/desktop/runtime-host/tests/fixtures/updater/test-x86_64-pc-windows-msvc.json.sig b/desktop/runtime-host/tests/fixtures/updater/test-x86_64-pc-windows-msvc.json.sig
new file mode 100644
index 000000000..055d0d04f
--- /dev/null
+++ b/desktop/runtime-host/tests/fixtures/updater/test-x86_64-pc-windows-msvc.json.sig
@@ -0,0 +1 @@
+dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVTakNhQ0NRM3RjR1ZtUnV6MlNKRHFPT1c4YXdyMDBXS3BBWDIwRi81My82d3dXdG9RaXZpTWwwd1VBdjQ3d1RFZkNSL0krTDlmQnk1b0tOelpSc1Z4M2hCNXVkMGJ0QUFrPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkwMjk4MzQwCWZpbGU6dGVzdC14ODZfNjQtcGMtd2luZG93cy1tc3ZjLmpzb24KWkFwUG1uOU1sckZ4MS9uT3NtSWR3VmZuNktuM05ML21NYkFnUmRMQXJWdmJ1UGwrS0ZCa3VzM0xiOU5CTG80clUvMEhVMWxvMitRTkp3b05UUlR5Q3c9PQo=
\ No newline at end of file
diff --git a/desktop/runtime-host/tests/updater.rs b/desktop/runtime-host/tests/updater.rs
new file mode 100644
index 000000000..19811338e
--- /dev/null
+++ b/desktop/runtime-host/tests/updater.rs
@@ -0,0 +1,127 @@
+use avibe_runtime_host::update::{Artifact, Channel, Manifest, TARGETS};
+use std::{fs, path::PathBuf};
+fn fixtures() -> PathBuf {
+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/updater")
+}
+fn public_key() -> String {
+ fs::read_to_string(fixtures().join("public-key.txt")).unwrap()
+}
+fn authenticated(channel: &str, target: &str) -> Manifest {
+ let name = format!("{channel}-{target}.json");
+ Manifest::authenticated(
+ &fs::read(fixtures().join(&name)).unwrap(),
+ &fs::read_to_string(fixtures().join(format!("{name}.sig"))).unwrap(),
+ &public_key(),
+ )
+ .unwrap()
+}
+#[test]
+fn real_tauri_signatures_authenticate_both_channels_and_every_platform() {
+ for (channel, name, tag) in [
+ (Channel::Test, "test", "gh-v3.1.2rc15"),
+ (Channel::Stable, "stable", "v3.1.2"),
+ ] {
+ for (target, _, _) in TARGETS {
+ let manifest = authenticated(name, target);
+ let artifact = manifest.validate(channel, tag, &"a".repeat(40), target).unwrap();
+ artifact
+ .verify(&fs::read(fixtures().join("artifact.bin")).unwrap(), &public_key())
+ .unwrap();
+ let wrong_channel = if channel == Channel::Test {
+ Channel::Stable
+ } else {
+ Channel::Test
+ };
+ assert!(manifest.validate(wrong_channel, tag, &"a".repeat(40), target).is_err());
+ assert!(manifest.validate(channel, tag, &"b".repeat(40), target).is_err());
+ assert!(manifest
+ .validate(channel, "gh-v3.1.2rc16", &"a".repeat(40), target)
+ .is_err());
+ for (other, _, _) in TARGETS.iter().filter(|(other, _, _)| other != target) {
+ assert!(manifest.validate(channel, tag, &"a".repeat(40), other).is_err());
+ }
+ }
+ }
+}
+#[test]
+fn tampering_with_any_signed_manifest_byte_is_rejected() {
+ let raw = fs::read(fixtures().join("test-aarch64-apple-darwin.json")).unwrap();
+ let signature = fs::read_to_string(fixtures().join("test-aarch64-apple-darwin.json.sig")).unwrap();
+ for index in 0..raw.len() {
+ let mut altered = raw.clone();
+ altered[index] ^= 1;
+ assert!(
+ Manifest::authenticated(&altered, &signature, &public_key()).is_err(),
+ "byte {index}"
+ );
+ }
+}
+#[test]
+fn payload_signature_and_integrity_are_independent_install_gates() {
+ let manifest = authenticated("test", "aarch64-apple-darwin");
+ let artifact = manifest.platforms.values().next().unwrap();
+ let data = fs::read(fixtures().join("artifact.bin")).unwrap();
+ assert!(artifact.verify(b"wrong payload", &public_key()).is_err());
+ assert!(Artifact {
+ signature: "app-adhoc".into(),
+ ..artifact.clone()
+ }
+ .verify(&data, &public_key())
+ .is_err());
+ assert!(Artifact {
+ sha256: "0".repeat(64),
+ ..artifact.clone()
+ }
+ .verify(&data, &public_key())
+ .is_err());
+ assert!(Artifact {
+ size: 1,
+ ..artifact.clone()
+ }
+ .verify(&data, &public_key())
+ .is_err());
+}
+#[test]
+fn semantic_mismatches_cannot_be_hidden_by_valid_json() {
+ let original = authenticated("test", "aarch64-apple-darwin");
+ for field in [
+ "schema_version",
+ "repository",
+ "tag",
+ "source_sha",
+ "channel",
+ "version",
+ "target",
+ "platforms",
+ ] {
+ let mut value = serde_json::to_value(&original).unwrap();
+ value[field] = serde_json::json!("invalid");
+ if let Ok(manifest) = serde_json::from_value::<Manifest>(value) {
+ assert!(
+ manifest
+ .validate(Channel::Test, "gh-v3.1.2rc15", &"a".repeat(40), "aarch64-apple-darwin")
+ .is_err(),
+ "{field}"
+ );
+ }
+ }
+}
+
+#[test]
+fn download_and_verification_failures_never_reach_the_replacement_boundary() {
+ use avibe_runtime_host::update::install_verified;
+ let manifest = authenticated("stable", "x86_64-pc-windows-msvc");
+ let artifact = manifest.platforms.values().next().unwrap();
+ for download in [Err("network failed".into()), Ok(b"tampered payload".to_vec())] {
+ let result = install_verified(download, artifact, &public_key(), |_| -> Result<(), String> {
+ panic!("unverified download reached the installer")
+ });
+ assert!(result.is_err());
+ }
+ let payload = fs::read(fixtures().join("artifact.bin")).unwrap();
+ let result = install_verified(Ok(payload.clone()), artifact, &public_key(), |data| {
+ assert_eq!(data, payload);
+ Err::<(), String>("replacement failure".into())
+ });
+ assert_eq!(result, Err("replacement failure".into()));
+}
diff --git a/desktop/scripts/test-windows-update.ps1 b/desktop/scripts/test-windows-update.ps1
new file mode 100644
index 000000000..e09a1b469
--- /dev/null
+++ b/desktop/scripts/test-windows-update.ps1
@@ -0,0 +1,92 @@
+# Hermetic Windows process/filesystem acceptance of the real install supervisor.
+$ErrorActionPreference = 'Stop'
+. "$PSScriptRoot/../src-tauri/src/update_windows.ps1"
+$root = Join-Path ([IO.Path]::GetTempPath()) ('avibe-update-test-' + [Guid]::NewGuid())
+[IO.Directory]::CreateDirectory($root) | Out-Null
+try {
+ function Build-App($path, $version, $marker, $class) {
+ $source = @"
+using System;
+using System.IO;
+using System.Reflection;
+[assembly: AssemblyProduct("Avibe")]
+[assembly: AssemblyInformationalVersion("$version")]
+public class $class {
+ public static void Main() {
+ File.WriteAllText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "$marker"), "started");
+ }
+}
+"@
+ Add-Type -TypeDefinition $source -OutputAssembly $path -OutputType ConsoleApplication
+ }
+ $old = Join-Path $root 'old.exe'
+ $next = Join-Path $root 'next.exe'
+ Build-App $old '3.1.1' 'ran-old' 'OldApp'
+ Build-App $next '3.1.2' 'ran-new' 'NewApp'
+ $installer = Join-Path $root 'installer.exe'
+ Add-Type -TypeDefinition @'
+using System;
+using System.IO;
+using System.Reflection;
+[assembly: AssemblyProduct("Avibe")]
+[assembly: AssemblyInformationalVersion("3.1.2")]
+public class Installer {
+ public static int Main(string[] args) {
+ var root = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
+ var joined = String.Join(" ", args);
+ var destination = joined.Substring(joined.IndexOf("/D=") + 3);
+ var mode = File.ReadAllText(Path.Combine(root, "mode"));
+ if (mode == "deleted") {
+ Directory.Delete(destination, true);
+ return 1;
+ }
+ if (mode == "partial" || mode == "wrong-version") {
+ File.WriteAllText(Path.Combine(destination, "new-only.dll"), "failed version bytes");
+ Directory.CreateDirectory(Path.Combine(destination, "new-resources"));
+ File.WriteAllText(Path.Combine(destination, "new-resources", "partial.txt"), "partial");
+ File.WriteAllText(Path.Combine(destination, "resources.txt"), "damaged resources");
+ return mode == "partial" ? 1 : 0;
+ }
+ File.Copy(Path.Combine(root, "next.exe"), Path.Combine(destination, "app.exe"), true);
+ return 0;
+ }
+}
+'@ -OutputAssembly $installer -OutputType ConsoleApplication
+ foreach ($mode in @('success', 'deleted', 'partial', 'wrong-version')) {
+ $failure = $mode -ne 'success'
+ $directory = Join-Path $root ("installation space 中文 " + $mode)
+ $staging = Join-Path $root ("stage-" + $mode)
+ [IO.Directory]::CreateDirectory($directory) | Out-Null
+ [IO.Directory]::CreateDirectory($staging) | Out-Null
+ Copy-Item -LiteralPath $old -Destination (Join-Path $directory 'app.exe')
+ [IO.File]::WriteAllText((Join-Path $directory 'resources.txt'), 'previous resources')
+ [IO.File]::WriteAllText((Join-Path $root 'mode'), $mode)
+ $requestData = [pscustomobject]@{
+ directory=$directory; staging=$staging; executable=(Join-Path $directory 'app.exe');
+ installer=$installer; version='3.1.2'; pid=2147483647
+ }
+ $threw = $false
+ try { Invoke-AvibeReplacement $requestData } catch { $threw = $true }
+ if ($threw -ne $failure) { throw "Unexpected transaction outcome: $threw / $failure" }
+ $expected = if ($failure) { $old } else { $next }
+ if ((Get-FileHash (Join-Path $directory 'app.exe')).Hash -ne (Get-FileHash $expected).Hash) {
+ throw 'Application bytes did not match the successful or restored version'
+ }
+ if ([IO.File]::ReadAllText((Join-Path $directory 'resources.txt')) -ne 'previous resources') {
+ throw 'Previous application resources were not preserved'
+ }
+ if ((Test-Path -LiteralPath (Join-Path $directory 'new-only.dll')) -or
+ (Test-Path -LiteralPath (Join-Path $directory 'new-resources'))) {
+ throw 'Failed installation left new files mixed into the restored application'
+ }
+ $marker = Join-Path $directory $(if ($failure) { 'ran-old' } else { 'ran-new' })
+ $deadline = [DateTime]::UtcNow.AddSeconds(10)
+ while (-not (Test-Path -LiteralPath $marker)) {
+ if ([DateTime]::UtcNow -gt $deadline) { throw 'Application was not relaunched' }
+ Start-Sleep -Milliseconds 100
+ }
+ }
+ Write-Output 'Native Windows update success and rollback fixtures passed.'
+} finally {
+ Remove-Item -LiteralPath $root -Recurse -Force
+}
diff --git a/desktop/scripts/verify-i18n.mjs b/desktop/scripts/verify-i18n.mjs
index 57e8fa059..d631fbeb5 100644
--- a/desktop/scripts/verify-i18n.mjs
+++ b/desktop/scripts/verify-i18n.mjs
@@ -80,3 +80,8 @@ for (const code of expectedNoticeCodes) {
`placeholder mismatch for ${code}`,
)
}
+
+for (const key of leafShape(en.updater)) {
+ assert.ok(en.updater[key].length > 0 && zh.updater[key].length > 0)
+ assert.deepEqual(placeholders(en.updater[key]), placeholders(zh.updater[key]), `updater.${key}`)
+}
diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml
index 0a22b0a52..620d1f1a5 100644
--- a/desktop/src-tauri/Cargo.toml
+++ b/desktop/src-tauri/Cargo.toml
@@ -21,9 +21,12 @@ tauri-build = { version = "2", features = [] }
[dependencies]
avibe-runtime-host = { path = "../runtime-host" }
+flate2 = "1"
+reqwest = { workspace = true, features = ["json", "rustls-tls"] }
serde.workspace = true
serde_json.workspace = true
sys-locale.workspace = true
+tar = "0.4"
tauri = { version = "2", features = ["tray-icon"] }
tauri-plugin-autostart = "2"
tauri-plugin-deep-link = "2"
@@ -31,7 +34,9 @@ tauri-plugin-dialog = "2"
tauri-plugin-notification = "2"
tauri-plugin-opener = "2"
tauri-plugin-single-instance = "2"
+tauri-plugin-updater = "=2.12.0"
tauri-plugin-window-state = "2"
+tempfile = "3"
tokio.workspace = true
url.workspace = true
diff --git a/desktop/src-tauri/build.rs b/desktop/src-tauri/build.rs
index 0e30259f1..55a5fe653 100644
--- a/desktop/src-tauri/build.rs
+++ b/desktop/src-tauri/build.rs
@@ -1,4 +1,5 @@
fn main() {
+ println!("cargo:rerun-if-env-changed=AVIBE_DESKTOP_UPDATER_PUBLIC_KEY");
// Application commands are ungated by default in Tauri v2: any page loaded in
// any window could invoke them. Declaring them here makes `tauri-build`
// generate per-command permissions, so `capabilities/bootstrap.json`
diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs
index 57b3da6ea..793fbc352 100644
--- a/desktop/src-tauri/src/lib.rs
+++ b/desktop/src-tauri/src/lib.rs
@@ -20,6 +20,8 @@ use std::time::Duration;
mod native_frame;
mod notifications;
+mod update_install;
+mod updater;
#[cfg(target_os = "macos")]
mod macos_deep_link;
@@ -99,6 +101,7 @@ struct ProductCatalog {
#[derive(Deserialize)]
struct DesktopBootstrapCatalog {
tray: NativeTrayCatalog,
+ updater: updater::Catalog,
notifications: notifications::NativeNotificationCatalog,
#[cfg(feature = "bundled-runtime")]
uninstall: NativeUninstallCatalog,
@@ -318,6 +321,7 @@ fn install_native_tray(app: &AppHandle) -> tauri::Result<()> {
app.state::<notifications::Notifications>().enabled(),
None::<&str>,
)?;
+ let updater = app.state::<updater::Updater>();
let tray = Menu::with_items(
app,
&[
@@ -325,6 +329,8 @@ fn install_native_tray(app: &AppHandle) -> tauri::Result<()> {
&status,
&PredefinedMenuItem::separator(app)?,
&settings,
+ &updater.menu,
+ &updater.channel_menu,
&login,
&notifications,
&PredefinedMenuItem::separator(app)?,
@@ -342,6 +348,7 @@ fn install_native_tray(app: &AppHandle) -> tauri::Result<()> {
// Elsewhere the first submenu is File, and Settings leads it.
let settings_position = if cfg!(target_os = "macos") { 2 } else { 0 };
submenu.insert_items(&[&settings, &PredefinedMenuItem::separator(app)?], settings_position)?;
+ submenu.insert_items(&[&updater.menu, &updater.channel_menu], settings_position + 1)?;
submenu.insert_items(&[&open, &status, &login, &PredefinedMenuItem::separator(app)?], 0)?;
}
app.set_menu(application_menu)?;
@@ -1191,6 +1198,10 @@ fn ensure_main_window(app: &AppHandle) -> Option<WebviewWindow> {
let builder = WebviewWindowBuilder::from_config(app, &config)
.ok()?
.initialization_script(DESKTOP_SHELL_MARKER)
+ .initialization_script(format!(
+ "if (window.self === window.top) Object.defineProperty(window, '__AVIBE_DESKTOP_VERSION__', {{ value: {} }});",
+ serde_json::to_string(&app.package_info().version.to_string()).expect("version JSON")
+ ))
.on_new_window(|url, _features| handle_new_window_request(url));
// macOS draws the page under an overlay title bar (`tauri.conf.json`).
#[cfg(target_os = "macos")]
@@ -1583,12 +1594,15 @@ pub fn run() {
)
.plugin(native_frame::init())
.plugin(tauri_plugin_dialog::init())
+ .plugin(tauri_plugin_updater::Builder::new().build())
.plugin(tauri_plugin_autostart::Builder::new().build())
.plugin(tauri_plugin_notification::init())
.on_menu_event(|app, event| {
match event.id().as_ref() {
OPEN_MENU_ID => focus_or_restore_main_window(app),
SETTINGS_MENU_ID => open_workbench_settings(app),
+ updater::MENU_ID => updater::check(app.clone(), true),
+ updater::CHANNEL_ID => updater::toggle_channel(app),
STOP_MENU_ID => request_runtime_lifecycle(app.clone(), false),
QUIT_MENU_ID => request_runtime_lifecycle(app.clone(), true),
LOGIN_MENU_ID => toggle_start_at_login(app),
@@ -1622,6 +1636,10 @@ pub fn run() {
}
})
.on_navigation(|webview, url| {
+ if webview.label() == MAIN_WINDOW && url.as_str() == updater::OPEN_URL {
+ updater::check(webview.app_handle().clone(), true);
+ return false;
+ }
let active_origin = webview
.try_state::<Shell>()
.and_then(|shell| shell.active_origin.lock().ok().and_then(|active| active.clone()));
@@ -1713,7 +1731,9 @@ pub fn run() {
.filter_map(|argument| argument.into_string().ok()),
);
}
+ updater::init(app.handle())?;
install_native_tray(app.handle())?;
+ updater::check(app.handle().clone(), false);
let _ = spawn_bootstrap(app.handle().clone());
Ok(())
})
diff --git a/desktop/src-tauri/src/update_install.rs b/desktop/src-tauri/src/update_install.rs
new file mode 100644
index 000000000..379a7d990
--- /dev/null
+++ b/desktop/src-tauri/src/update_install.rs
@@ -0,0 +1,199 @@
+//! Replacement is a filesystem transaction; user state is never an input.
+use tauri::AppHandle;
+
+#[cfg(target_os = "macos")]
+pub fn install(_app: &AppHandle, bytes: &[u8], version: &str) -> Result<(), String> {
+ use std::{fs, io::Cursor, process::Command};
+ let executable = std::env::current_exe().map_err(|e| e.to_string())?;
+ let current = executable
+ .parent()
+ .and_then(|p| p.parent())
+ .and_then(|p| p.parent())
+ .filter(|p| p.extension().is_some_and(|e| e == "app"))
+ .ok_or("not running from an application bundle")?;
+ let parent = current.parent().ok_or("missing application directory")?;
+ // Same filesystem as the installation. Permission/capacity errors occur
+ // before moving the running app. No privileged rm/mv fallback.
+ let staging = tempfile::Builder::new()
+ .prefix(".avibe-update-")
+ .tempdir_in(parent)
+ .map_err(|e| e.to_string())?;
+ let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(Cursor::new(bytes)));
+ archive.unpack(staging.path()).map_err(|e| e.to_string())?;
+ let replacement = staging.path().join("Avibe.app");
+ let plist = replacement.join("Contents/Info.plist");
+ for (field, expected) in [
+ ("CFBundleIdentifier", "bot.avibe.desktop"),
+ ("CFBundleShortVersionString", version),
+ ] {
+ let output = Command::new("/usr/bin/plutil")
+ .args(["-extract", field, "raw", "-o", "-"])
+ .arg(&plist)
+ .output()
+ .map_err(|e| e.to_string())?;
+ if !output.status.success() || String::from_utf8_lossy(&output.stdout).trim() != expected {
+ return Err("replacement application identity mismatch".into());
+ }
+ }
+ let binary = replacement.join("Contents/MacOS/avibe-desktop");
+ let arch = if cfg!(target_arch = "aarch64") {
+ "arm64"
+ } else {
+ "x86_64"
+ };
+ let output = Command::new("/usr/bin/lipo")
+ .arg("-archs")
+ .arg(&binary)
+ .output()
+ .map_err(|e| e.to_string())?;
+ if !output.status.success() || String::from_utf8_lossy(&output.stdout).trim() != arch {
+ return Err("replacement architecture mismatch".into());
+ }
+ if !Command::new("/usr/bin/codesign")
+ .args(["--verify", "--deep", "--strict"])
+ .arg(&replacement)
+ .status()
+ .map_err(|e| e.to_string())?
+ .success()
+ {
+ return Err("replacement app seal is invalid".into());
+ }
+ let backup = staging.path().join("previous.app");
+ match replace_with_rollback(current, &replacement, &backup, |a, b| fs::rename(a, b)) {
+ Ok(()) => Ok(()),
+ Err(error) => {
+ // Never let TempDir cleanup erase a backup that restoration could
+ // not move back (for example a filesystem failure).
+ if backup.exists() {
+ let _ = staging.keep();
+ }
+ Err(error)
+ }
+ }
+}
+
+#[cfg(any(target_os = "macos", test))]
+fn replace_with_rollback(
+ current: &std::path::Path,
+ replacement: &std::path::Path,
+ backup: &std::path::Path,
+ mut rename: impl FnMut(&std::path::Path, &std::path::Path) -> std::io::Result<()>,
+) -> Result<(), String> {
+ rename(current, backup).map_err(|e| format!("application retained: {e}"))?;
+ if let Err(error) = rename(replacement, current) {
+ rename(backup, current).map_err(|restore| {
+ format!(
+ "replacement failed: {error}; previous app retained at {}: {restore}",
+ backup.display()
+ )
+ })?;
+ return Err(format!("replacement failed; previous app restored: {error}"));
+ }
+ Ok(())
+}
+
+#[cfg(target_os = "windows")]
+pub fn install(app: &AppHandle, bytes: &[u8], version: &str) -> Result<(), String> {
+ use std::{
+ fs,
+ os::windows::process::CommandExt,
+ process::Command,
+ time::{Duration, Instant},
+ };
+ let current = std::env::current_exe().map_err(|e| e.to_string())?;
+ let directory = current.parent().ok_or("missing installation directory")?;
+ let staging = tempfile::Builder::new()
+ .prefix("avibe-update-")
+ .tempdir()
+ .map_err(|e| e.to_string())?;
+ let installer = staging.path().join("update.exe");
+ fs::write(&installer, bytes).map_err(|e| e.to_string())?;
+ let script = staging.path().join("install.ps1");
+ fs::write(&script, include_str!("update_windows.ps1")).map_err(|e| e.to_string())?;
+ let request = staging.path().join("request.json");
+ fs::write(
+ &request,
+ serde_json::to_vec(&serde_json::json!({
+ "pid": std::process::id(), "directory": directory, "executable": current,
+ "installer": installer, "version": version, "staging": staging.path(),
+ "errorTitle": super::native_catalog_for_locales(sys_locale::get_locales()).updater.title,
+ "errorMessage": super::native_catalog_for_locales(sys_locale::get_locales()).updater.install_failed,
+ }))
+ .map_err(|e| e.to_string())?,
+ )
+ .map_err(|e| e.to_string())?;
+ let system = std::env::var_os("SystemRoot").ok_or("missing Windows system directory")?;
+ let powershell = std::path::Path::new(&system).join("System32/WindowsPowerShell/v1.0/powershell.exe");
+ let mut child = Command::new(powershell)
+ .creation_flags(0x08000000) // CREATE_NO_WINDOW; errors use the native dialog.
+ .args(["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File"])
+ .arg(script)
+ .arg("-Request")
+ .arg(request)
+ .spawn()
+ .map_err(|e| e.to_string())?;
+ let deadline = Instant::now() + Duration::from_secs(600);
+ while !staging.path().join("ready").exists() {
+ if child.try_wait().map_err(|e| e.to_string())?.is_some() {
+ return Err("installer preparation failed; current application retained".into());
+ }
+ if Instant::now() > deadline {
+ let _ = child.kill();
+ let _ = child.wait();
+ return Err("installer preparation timed out".into());
+ }
+ std::thread::sleep(Duration::from_millis(100));
+ }
+ // The helper has copied the previous install and now waits for this PID.
+ // Ownership transfers to it; it reports failures and relaunches the old app.
+ let _ = staging.keep();
+ super::exit_shell(app);
+ Ok(())
+}
+
+#[cfg(not(any(target_os = "macos", target_os = "windows")))]
+pub fn install(_app: &AppHandle, _bytes: &[u8], _version: &str) -> Result<(), String> {
+ Err("unsupported update platform".into())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn replacement_failure_restores_the_current_runnable_bytes() {
+ let root = tempfile::tempdir().unwrap();
+ let current = root.path().join("Avibe.app");
+ let next = root.path().join("next.app");
+ let backup = root.path().join("old.app");
+ std::fs::write(&current, b"current runnable application").unwrap();
+ std::fs::write(&next, b"new application").unwrap();
+ let mut calls = 0;
+ let result = replace_with_rollback(&current, &next, &backup, |a, b| {
+ calls += 1;
+ if calls == 2 {
+ return Err(std::io::Error::other("injected disk failure"));
+ }
+ std::fs::rename(a, b)
+ });
+ assert!(result.is_err());
+ assert_eq!(std::fs::read(&current).unwrap(), b"current runnable application");
+ assert!(!backup.exists());
+ }
+ #[test]
+ fn failed_restore_keeps_the_backup_for_recovery() {
+ let root = tempfile::tempdir().unwrap();
+ let current = root.path().join("app");
+ let next = root.path().join("next");
+ let backup = root.path().join("backup");
+ std::fs::write(&current, b"old").unwrap();
+ let result = replace_with_rollback(&current, &next, &backup, |a, b| {
+ if a == current {
+ std::fs::rename(a, b)
+ } else {
+ Err(std::io::Error::other("disk unavailable"))
+ }
+ });
+ assert!(result.is_err());
+ assert_eq!(std::fs::read(&backup).unwrap(), b"old");
+ }
+}
diff --git a/desktop/src-tauri/src/update_windows.ps1 b/desktop/src-tauri/src/update_windows.ps1
new file mode 100644
index 000000000..54fb8e037
--- /dev/null
+++ b/desktop/src-tauri/src/update_windows.ps1
@@ -0,0 +1,65 @@
+# Native installer transaction. The signed app owns this script and request.
+# Only the app installation directory is copied; user/Runtime data is outside it.
+param([string]$Request)
+$ErrorActionPreference = 'Stop'
+
+function Invoke-AvibeReplacement($requestData) {
+ $backup = Join-Path $requestData.staging 'previous'
+ $ready = Join-Path $requestData.staging 'ready'
+ $started = $false
+ try {
+ # Check installer identity before asking the running app to exit.
+ $info = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($requestData.installer)
+ if ($info.ProductName -ne 'Avibe') { throw 'Installer product mismatch' }
+ if ($info.ProductVersion -ne $requestData.version) { throw 'Installer version mismatch' }
+ # Per-user NSIS installs are writable. Refuse elevation or a different scope.
+ $probe = Join-Path $requestData.directory ([Guid]::NewGuid().ToString() + '.probe')
+ [IO.File]::WriteAllText($probe, '')
+ Remove-Item -LiteralPath $probe
+ Copy-Item -LiteralPath $requestData.directory -Destination $backup -Recurse
+ [IO.File]::WriteAllText($ready, 'ready')
+ Wait-Process -Id $requestData.pid -ErrorAction SilentlyContinue
+ $started = $true
+ # /D is the final NSIS argument, with its entire remainder as the path.
+ # No /R: this helper alone decides which application to restart.
+ $installerProcess = Start-Process -FilePath $requestData.installer -ArgumentList @('/S', '/UPDATE', "/D=$($requestData.directory)") -Wait -PassThru
+ if ($installerProcess.ExitCode -ne 0) { throw 'Installer failed' }
+ if (-not (Test-Path -LiteralPath $requestData.executable)) { throw 'Installed executable missing' }
+ $installed = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($requestData.executable)
+ if ($installed.ProductVersion -ne $requestData.version) { throw 'Installed version mismatch' }
+ Start-Process -FilePath $requestData.executable
+ } catch {
+ $failure = $_
+ if ($started) {
+ try {
+ # A failed installer may have introduced DLLs/resources that are
+ # absent from the backup. Never merge those into the old app.
+ # Keep the backup intact even if cleanup or restoration fails.
+ if (Test-Path -LiteralPath $requestData.directory) {
+ Remove-Item -LiteralPath $requestData.directory -Recurse -Force
+ }
+ Copy-Item -LiteralPath $backup -Destination $requestData.directory -Recurse -Force
+ Start-Process -FilePath $requestData.executable
+ } catch {
+ $_ | Out-String | Set-Content -LiteralPath (Join-Path $requestData.staging 'restore-error.txt')
+ }
+ }
+ throw $failure
+ }
+}
+
+# The transaction is dot-sourceable for hermetic native CI fixtures. The entry
+# point, not the transaction, owns user dialogs and the temporary directory.
+if ($MyInvocation.InvocationName -eq '.') { return }
+$requestData = Get-Content -LiteralPath $Request -Raw -Encoding UTF8 | ConvertFrom-Json
+try {
+ Invoke-AvibeReplacement $requestData
+ Remove-Item -LiteralPath $requestData.staging -Recurse -Force
+} catch {
+ $_ | Out-String | Set-Content -LiteralPath (Join-Path $requestData.staging 'error.txt')
+ if (Test-Path -LiteralPath (Join-Path $requestData.staging 'ready')) {
+ Add-Type -AssemblyName PresentationFramework
+ [System.Windows.MessageBox]::Show($requestData.errorMessage, $requestData.errorTitle) | Out-Null
+ }
+ exit 1
+}
diff --git a/desktop/src-tauri/src/updater.rs b/desktop/src-tauri/src/updater.rs
new file mode 100644
index 000000000..d872f1058
--- /dev/null
+++ b/desktop/src-tauri/src/updater.rs
@@ -0,0 +1,556 @@
+//! Native-only desktop updater. Remote WebViews never receive updater commands.
+use avibe_runtime_host::update::{self, Channel, Manifest, REPOSITORY};
+use serde::Deserialize;
+use std::{
+ path::PathBuf,
+ sync::{
+ atomic::{AtomicBool, Ordering},
+ Mutex,
+ },
+ time::Duration,
+};
+use tauri::{
+ menu::{CheckMenuItem, MenuItem},
+ AppHandle, Manager,
+};
+use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind, MessageDialogResult};
+use tauri_plugin_updater::{Update, UpdaterExt};
+
+pub const MENU_ID: &str = "desktop-update";
+pub const CHANNEL_ID: &str = "desktop-update-test";
+pub const OPEN_URL: &str = "avibe://updates";
+const KEY: &str = match option_env!("AVIBE_DESKTOP_UPDATER_PUBLIC_KEY") {
+ Some(key) => key,
+ None => "",
+};
+const TARGET: &str = if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
+ "aarch64-apple-darwin"
+} else if cfg!(all(target_os = "macos", target_arch = "x86_64")) {
+ "x86_64-apple-darwin"
+} else if cfg!(all(target_os = "windows", target_arch = "x86_64")) {
+ "x86_64-pc-windows-msvc"
+} else {
+ "unsupported"
+};
+
+#[derive(Clone, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Catalog {
+ menu: String,
+ test_channel: String,
+ pub(super) title: String,
+ current: String,
+ latest: String,
+ checking: String,
+ up_to_date: String,
+ available: String,
+ confirm: String,
+ downloading: String,
+ installing: String,
+ installed: String,
+ disabled: String,
+ disabled_detail: String,
+ error: String,
+ check_failed: String,
+ pub(super) install_failed: String,
+ install: String,
+ skip: String,
+ cancel: String,
+}
+fn catalog() -> Catalog {
+ super::native_catalog_for_locales(sys_locale::get_locales()).updater
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum Phase {
+ Idle,
+ Checking,
+ Current,
+ Available,
+ Downloading,
+ Installing,
+ Installed,
+ Disabled,
+ Error,
+}
+struct State {
+ phase: Phase,
+ latest: Option<String>,
+ channel: Channel,
+}
+pub struct Updater {
+ state: Mutex<State>,
+ busy: AtomicBool,
+ channel_path: PathBuf,
+ skipped_path: PathBuf,
+ pub menu: MenuItem<tauri::Wry>,
+ pub channel_menu: CheckMenuItem<tauri::Wry>,
+}
+fn label(phase: Phase, c: &Catalog) -> &str {
+ match phase {
+ Phase::Idle => &c.menu,
+ Phase::Checking => &c.checking,
+ Phase::Current => &c.up_to_date,
+ Phase::Available => &c.available,
+ Phase::Downloading => &c.downloading,
+ Phase::Installing => &c.installing,
+ Phase::Installed => &c.installed,
+ Phase::Disabled => &c.disabled,
+ Phase::Error => &c.error,
+ }
+}
+pub fn init(app: &AppHandle) -> tauri::Result<()> {
+ let c = catalog();
+ let channel_path = app.path().app_local_data_dir()?.join("update-channel.json");
+ let channel = std::fs::read(&channel_path)
+ .ok()
+ .and_then(|bytes| serde_json::from_slice(&bytes).ok())
+ .unwrap_or_else(|| Channel::for_version(&app.package_info().version));
+ app.manage(Updater {
+ state: Mutex::new(State {
+ phase: Phase::Idle,
+ latest: None,
+ channel,
+ }),
+ busy: AtomicBool::new(false),
+ channel_path,
+ skipped_path: app.path().app_local_data_dir()?.join("update-skipped.json"),
+ menu: MenuItem::with_id(app, MENU_ID, &c.menu, true, None::<&str>)?,
+ channel_menu: CheckMenuItem::with_id(
+ app,
+ CHANNEL_ID,
+ &c.test_channel,
+ true,
+ channel == Channel::Test,
+ None::<&str>,
+ )?,
+ });
+ Ok(())
+}
+fn set_state(app: &AppHandle, phase: Phase, latest: Option<String>) {
+ let updater = app.state::<Updater>();
+ let mut state = updater.state.lock().expect("updater state");
+ state.phase = phase;
+ if latest.is_some() || phase == Phase::Checking {
+ state.latest = latest;
+ }
+ let _ = updater
+ .menu
+ .set_text(format!("{} — {}", label(phase, &catalog()), app.package_info().version));
+ let _ = updater.channel_menu.set_enabled(!updater.busy.load(Ordering::SeqCst));
+}
+pub fn toggle_channel(app: &AppHandle) {
+ let updater = app.state::<Updater>();
+ if updater.busy.load(Ordering::SeqCst) {
+ return;
+ }
+ let result = (|| -> Result<(), Box<dyn std::error::Error>> {
+ let mut state = updater.state.lock().expect("updater state");
+ let channel = if state.channel == Channel::Test {
+ Channel::Stable
+ } else {
+ Channel::Test
+ };
+ std::fs::create_dir_all(updater.channel_path.parent().ok_or("missing config directory")?)?;
+ std::fs::write(&updater.channel_path, serde_json::to_vec(&channel)?)?;
+ state.channel = channel;
+ state.latest = None;
+ updater.channel_menu.set_checked(channel == Channel::Test)?;
+ Ok(())
+ })();
+ if result.is_err() {
+ show(app, &catalog().check_failed, None);
+ return;
+ }
+ check(app.clone(), true);
+}
+fn show(app: &AppHandle, message: &str, latest: Option<&str>) {
+ let c = catalog();
+ let mut text = format!("{}: {}\n{}", c.current, app.package_info().version, message);
+ if let Some(version) = latest {
+ text.push_str(&format!("\n{}: {version}", c.latest));
+ }
+ app.dialog().message(text).title(c.title).show(|_| {});
+}
+
+#[derive(Debug, PartialEq, Eq)]
+enum Choice {
+ Install,
+ Skip,
+ Later,
+}
+/// Closing the dialog (Esc, window close) is never an implicit install or skip.
+fn choice(result: &MessageDialogResult, c: &Catalog) -> Choice {
+ match result {
+ MessageDialogResult::Custom(label) if *label == c.install => Choice::Install,
+ MessageDialogResult::Custom(label) if *label == c.skip => Choice::Skip,
+ _ => Choice::Later,
+ }
+}
+/// Only the automatic startup check honours a skipped version; an explicit menu
+/// check always offers it, and any newer release prompts again.
+fn should_prompt(interactive: bool, skipped: Option<&str>, version: &str) -> bool {
+ interactive || skipped != Some(version)
+}
+fn skipped_version(updater: &Updater) -> Option<String> {
+ std::fs::read(&updater.skipped_path)
+ .ok()
+ .and_then(|bytes| serde_json::from_slice(&bytes).ok())
+}
+fn skip_version(app: &AppHandle, version: &str) {
+ let path = &app.state::<Updater>().skipped_path;
+ let result = path
+ .parent()
+ .ok_or_else(|| std::io::Error::other("missing config directory"))
+ .and_then(std::fs::create_dir_all)
+ .and_then(|()| std::fs::write(path, serde_json::to_vec(version).expect("version JSON")));
+ if let Err(error) = result {
+ eprintln!("desktop update skip: {error}");
+ }
+}
+
+#[derive(Deserialize)]
+struct Release {
+ tag_name: String,
+ draft: bool,
+ prerelease: bool,
+ assets: Vec<ReleaseAsset>,
+}
+#[derive(Deserialize)]
+struct ReleaseAsset {
+ name: String,
+ browser_download_url: String,
+}
+
+async fn bytes(client: &reqwest::Client, url: &str, max: usize) -> Result<Vec<u8>, String> {
+ let mut response = client
+ .get(url)
+ .send()
+ .await
+ .map_err(|_| "network request failed")?
+ .error_for_status()
+ .map_err(|_| "release metadata unavailable")?;
+ let mut result = Vec::new();
+ while let Some(chunk) = response.chunk().await.map_err(|_| "metadata download failed")? {
+ if result.len() + chunk.len() > max {
+ return Err("metadata too large".into());
+ }
+ result.extend_from_slice(&chunk);
+ }
+ Ok(result)
+}
+async fn find_update(app: &AppHandle, channel: Channel) -> Result<Option<(Update, Manifest)>, String> {
+ let client = reqwest::Client::builder()
+ .https_only(true)
+ .timeout(Duration::from_secs(30))
+ .user_agent("Avibe-desktop-updater")
+ .build()
+ .map_err(|_| "HTTP client failed")?;
+ let mut candidates = Vec::new();
+ // GitHub orders by creation, not SemVer. Walk the complete bounded history;
+ // reaching the bound fails instead of claiming an incomplete list is current.
+ for page in 1..=10 {
+ let data = bytes(
+ &client,
+ &format!("https://api.github.com/repos/{REPOSITORY}/releases?per_page=100&page={page}"),
+ 8 * 1024 * 1024,
+ )
+ .await?;
+ let releases: Vec<Release> = serde_json::from_slice(&data).map_err(|_| "invalid releases response")?;
+ let done = releases.len() < 100;
+ for release in releases {
+ if !release.draft && release.prerelease == (channel == Channel::Test) {
+ if let Ok(version) = channel.version(&release.tag_name) {
+ candidates.push((version, release));
+ }
+ }
+ }
+ if done {
+ break;
+ }
+ if page == 10 {
+ return Err("release history exceeds discovery bound".into());
+ }
+ }
+ let Some((version, release)) = candidates.into_iter().max_by(|a, b| a.0.cmp(&b.0)) else {
+ return Err("no release in this channel".into());
+ };
+ set_state(app, Phase::Checking, Some(version.to_string()));
+ if version <= app.package_info().version {
+ return Ok(None);
+ }
+ let name = update::manifest_name(TARGET);
+ for name in [&name, &format!("{name}.sig")] {
+ let expected = update::asset_url(&release.tag_name, name);
+ if release
+ .assets
+ .iter()
+ .filter(|asset| asset.name == *name && asset.browser_download_url == expected)
+ .count()
+ != 1
+ {
+ return Err("signed updater metadata unavailable; manual installation required".into());
+ }
+ }
+ let manifest_url = update::asset_url(&release.tag_name, &name);
+ let raw = bytes(&client, &manifest_url, 64 * 1024).await?;
+ let sig = bytes(&client, &format!("{manifest_url}.sig"), 4096).await?;
+ let manifest = Manifest::authenticated(&raw, std::str::from_utf8(&sig).map_err(|_| "invalid signature")?, KEY)?;
+ let commit: serde_json::Value = serde_json::from_slice(
+ &bytes(
+ &client,
+ &format!("https://api.github.com/repos/{REPOSITORY}/commits/{}", release.tag_name),
+ 2 * 1024 * 1024,
+ )
+ .await?,
+ )
+ .map_err(|_| "invalid source response")?;
+ let artifact = manifest.validate(
+ channel,
+ &release.tag_name,
+ commit["sha"].as_str().ok_or("missing source")?,
+ TARGET,
+ )?;
+ if !release.assets.iter().any(|a| a.browser_download_url == artifact.url) {
+ return Err("updater artifact missing".into());
+ }
+ let updater = app
+ .updater_builder()
+ .pubkey(KEY)
+ .target(update::target_spec(TARGET)?.0)
+ .endpoints(vec![manifest_url.parse().map_err(|_| "invalid endpoint")?])
+ .map_err(|_| "invalid updater endpoint")?
+ .timeout(Duration::from_secs(600))
+ .build()
+ .map_err(|_| "updater initialization failed")?;
+ let update = updater
+ .check()
+ .await
+ .map_err(|_| "updater check failed")?
+ .ok_or("release changed during check")?;
+ let authenticated: serde_json::Value = serde_json::from_slice(&raw).map_err(|_| "invalid manifest")?;
+ if update.raw_json != authenticated
+ || update.version != manifest.version
+ || update.download_url.as_str() != artifact.url
+ || update.signature != artifact.signature
+ {
+ return Err("updater response differs from signed manifest".into());
+ }
+ Ok(Some((update, manifest)))
+}
+
+pub fn check(app: AppHandle, interactive: bool) {
+ let updater = app.state::<Updater>();
+ if updater.busy.swap(true, Ordering::SeqCst) {
+ if interactive {
+ let state = updater.state.lock().expect("updater state");
+ show(&app, label(state.phase, &catalog()), state.latest.as_deref());
+ }
+ return;
+ }
+ if KEY.trim().is_empty() || TARGET == "unsupported" {
+ updater.busy.store(false, Ordering::SeqCst);
+ set_state(&app, Phase::Disabled, None);
+ if interactive {
+ show(&app, &catalog().disabled_detail, None);
+ }
+ return;
+ }
+ let channel = updater.state.lock().expect("updater state").channel;
+ set_state(&app, Phase::Checking, None);
+ tauri::async_runtime::spawn(async move {
+ match find_update(&app, channel).await {
+ Ok(Some((update, manifest))) => {
+ set_state(&app, Phase::Available, Some(manifest.version.clone()));
+ let skipped = skipped_version(&app.state::<Updater>());
+ if !should_prompt(interactive, skipped.as_deref(), &manifest.version) {
+ finish(&app);
+ return;
+ }
+ let c = catalog();
+ let confirmation = app.clone();
+ app.dialog()
+ .message(format!(
+ "{}: {}\n{}: {}\n\n{}",
+ c.current,
+ app.package_info().version,
+ c.latest,
+ manifest.version,
+ c.confirm
+ ))
+ .title(c.title.clone())
+ // The dialog plugin reports Esc/close as the third label, so
+ // that slot must be the harmless "Later", never "Skip".
+ .buttons(MessageDialogButtons::YesNoCancelCustom(
+ c.install.clone(),
+ c.skip.clone(),
+ c.cancel.clone(),
+ ))
+ .show_with_result(move |result| match choice(&result, &c) {
+ Choice::Install => install(confirmation, update, manifest),
+ Choice::Skip => {
+ skip_version(&confirmation, &manifest.version);
+ finish(&confirmation);
+ }
+ Choice::Later => finish(&confirmation),
+ });
+ }
+ Ok(None) => {
+ finish(&app);
+ set_state(&app, Phase::Current, None);
+ if interactive {
+ let latest = app
+ .state::<Updater>()
+ .state
+ .lock()
+ .expect("updater state")
+ .latest
+ .clone();
+ show(&app, &catalog().up_to_date, latest.as_deref());
+ }
+ }
+ Err(error) => {
+ eprintln!("desktop update check: {error}");
+ finish(&app);
+ set_state(&app, Phase::Error, None);
+ if interactive {
+ show(&app, &catalog().check_failed, None);
+ }
+ }
+ }
+ });
+}
+fn finish(app: &AppHandle) {
+ let updater = app.state::<Updater>();
+ updater.busy.store(false, Ordering::SeqCst);
+ let _ = updater.channel_menu.set_enabled(true);
+}
+fn install(app: AppHandle, update: Update, manifest: Manifest) {
+ set_state(&app, Phase::Downloading, None);
+ tauri::async_runtime::spawn(async move {
+ let result = async {
+ let download = update
+ .download(|_, _| {}, || {})
+ .await
+ .map_err(|_| "download or signature verification failed".to_string());
+ let artifact = manifest
+ .validate(manifest.channel, &manifest.tag, &manifest.source_sha, TARGET)?
+ .clone();
+ let handle = app.clone();
+ tauri::async_runtime::spawn_blocking(move || {
+ update::install_verified(download, &artifact, KEY, |data| {
+ set_state(&handle, Phase::Installing, None);
+ super::update_install::install(&handle, data, &manifest.version)
+ })
+ })
+ .await
+ .map_err(|_| "installer task failed")??;
+ Ok::<(), String>(())
+ }
+ .await;
+ finish(&app);
+ match result {
+ Ok(()) => {
+ set_state(&app, Phase::Installed, None);
+ #[cfg(target_os = "macos")]
+ {
+ app.state::<super::Shell>()
+ .exit_authorized
+ .store(true, Ordering::SeqCst);
+ app.restart();
+ }
+ }
+ Err(error) => {
+ eprintln!("desktop update install: {error}");
+ set_state(&app, Phase::Error, None);
+ app.dialog()
+ .message(catalog().install_failed)
+ .title(catalog().title)
+ .kind(MessageDialogKind::Error)
+ .show(|_| {});
+ }
+ }
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn signed_manifests_are_consumed_by_the_pinned_official_updater() {
+ for (target, key, _) in update::TARGETS {
+ for channel in ["test", "stable"] {
+ let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(format!(
+ "../runtime-host/tests/fixtures/updater/{channel}-{target}.json"
+ ));
+ let raw = std::fs::read(path).unwrap();
+ let release: tauri_plugin_updater::RemoteRelease = serde_json::from_slice(&raw).unwrap();
+ let manifest: Manifest = serde_json::from_slice(&raw).unwrap();
+ assert_eq!(release.version.to_string(), manifest.version);
+ assert_eq!(
+ release.download_url(key).unwrap().as_str(),
+ manifest.platforms[*key].url
+ );
+ assert_eq!(release.signature(key).unwrap(), &manifest.platforms[*key].signature);
+ }
+ }
+ }
+
+ #[test]
+ fn dialog_buttons_map_to_one_choice_and_dismissal_is_later() {
+ for locale in ["en", "zh"] {
+ let c = super::super::native_catalog_for_locales([locale.to_owned()]).updater;
+ let labels = [&c.install, &c.skip, &c.cancel];
+ assert_eq!(
+ labels.iter().collect::<std::collections::HashSet<_>>().len(),
+ 3,
+ "button labels identify the choice"
+ );
+ assert_eq!(
+ choice(&MessageDialogResult::Custom(c.install.clone()), &c),
+ Choice::Install
+ );
+ assert_eq!(choice(&MessageDialogResult::Custom(c.skip.clone()), &c), Choice::Skip);
+ assert_eq!(
+ choice(&MessageDialogResult::Custom(c.cancel.clone()), &c),
+ Choice::Later
+ );
+ for dismissed in [
+ MessageDialogResult::Cancel,
+ MessageDialogResult::Ok,
+ MessageDialogResult::Yes,
+ MessageDialogResult::No,
+ ] {
+ assert_eq!(choice(&dismissed, &c), Choice::Later);
+ }
+ }
+ }
+
+ #[test]
+ fn only_the_startup_check_honours_a_skipped_version() {
+ assert!(!should_prompt(false, Some("1.2.3"), "1.2.3"));
+ assert!(should_prompt(false, Some("1.2.3"), "1.2.4"));
+ assert!(should_prompt(false, None, "1.2.3"));
+ assert!(should_prompt(true, Some("1.2.3"), "1.2.3"));
+ }
+
+ #[test]
+ fn every_native_update_state_has_localized_copy() {
+ for locale in ["en", "zh"] {
+ let c = super::super::native_catalog_for_locales([locale.to_owned()]).updater;
+ for phase in [
+ Phase::Idle,
+ Phase::Checking,
+ Phase::Current,
+ Phase::Available,
+ Phase::Downloading,
+ Phase::Installing,
+ Phase::Installed,
+ Phase::Disabled,
+ Phase::Error,
+ ] {
+ assert!(!label(phase, &c).is_empty());
+ }
+ }
+ }
+}
diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.json
index fff5f552d..b4c8750d6 100644
--- a/desktop/src-tauri/tauri.conf.json
+++ b/desktop/src-tauri/tauri.conf.json
@@ -27,15 +27,23 @@
}
],
"security": {
- "capabilities": ["bootstrap"],
+ "capabilities": [
+ "bootstrap"
+ ],
"csp": "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; connect-src 'self' ipc: http://ipc.localhost"
}
},
"plugins": {
"deep-link": {
"desktop": {
- "schemes": ["avibe"]
+ "schemes": [
+ "avibe"
+ ]
}
+ },
+ "updater": {
+ "pubkey": "",
+ "endpoints": []
}
},
"bundle": {
@@ -57,6 +65,7 @@
"icons/icon.icns",
"icons/icon.ico"
- ]
+ ],
+ "createUpdaterArtifacts": false
}
}
diff --git a/desktop/src-tauri/tests/shell_boundaries.rs b/desktop/src-tauri/tests/shell_boundaries.rs
index cd1e0157e..37480a6c4 100644
--- a/desktop/src-tauri/tests/shell_boundaries.rs
+++ b/desktop/src-tauri/tests/shell_boundaries.rs
@@ -825,7 +825,8 @@ fn settings_open_in_the_shown_workbench_and_only_while_one_is_shown() {
source.contains("MenuItem::with_id(app, SETTINGS_MENU_ID, &catalog.settings, false, Some(\"CmdOrCtrl+,\"))")
);
let tray = body("install_native_tray");
- assert!(tray.contains("&settings,\n &login,"));
+ assert!(tray
+ .contains("&settings,\n &updater.menu,\n &updater.channel_menu,\n &login,"));
assert!(
tray.contains("submenu.insert_items(&[&settings, &PredefinedMenuItem::separator(app)?], settings_position)")
);
@@ -947,3 +948,17 @@ fn explicit_stop_does_not_schedule_automatic_recovery() {
);
assert!(monitor.contains("generation.load(Ordering::SeqCst) != observed_generation"));
}
+
+#[test]
+fn updates_have_one_native_owner_and_no_remote_install_permission() {
+ let source = include_str!("../src/lib.rs");
+ let updater = include_str!("../src/updater.rs");
+ assert!(source.contains("tauri_plugin_updater::Builder::new().build()"));
+ assert!(source.contains("updater::check(app.handle().clone(), false)"));
+ assert!(source.contains("updater::MENU_ID => updater::check(app.clone(), true)"));
+ assert!(source.contains("url.as_str() == updater::OPEN_URL"));
+ assert!(updater.contains("MessageDialogButtons::YesNoCancelCustom"));
+ assert!(updater.contains("update::install_verified(download, &artifact, KEY"));
+ assert!(!include_str!("../capabilities/bootstrap.json").contains("updater:"));
+ assert!(!include_str!("../build.rs").contains("update_install"));
+}
diff --git a/docs/plans/desktop-auto-update.md b/docs/plans/desktop-auto-update.md
new file mode 100644
index 000000000..5a02ca106
--- /dev/null
+++ b/docs/plans/desktop-auto-update.md
@@ -0,0 +1,78 @@
+# Desktop signed update contract
+
+## Outcome and boundaries
+
+From baseline `2a8ce221283f81cdd37cf375c92a977669a3b540`, add one native desktop
+update owner. Startup checks only; installation requires a native confirmation.
+The Web version entry routes to that owner without receiving updater IPC powers.
+Current version comes from Tauri package metadata stamped by the release build.
+Stable builds default to stable; prerelease builds default to TEST. Channel choice
+is local to the shell. No downgrade, Python in-place upgrade, backend update, or
+mutation of `~/.avibe` / private Runtime slots is part of application replacement.
+
+## Skip this version
+
+The update prompt offers Install, Skip This Version, and Later. Skip records only
+that exact version in the shell's local data directory; the automatic startup
+check stays silent for it, while an explicit menu check and any newer release
+prompt again. Dismissing the dialog (Esc or close) always means Later. There is
+no silent auto-install option: installation keeps its native confirmation.
+
+## Distribution contract
+
+GitHub Releases in `avibe-bot/avibe` are the discovery source. Canonical stable
+`vX.Y.Z` and TEST `gh-vX.Y.ZrcN` tags select disjoint channels. Each target owns a
+Tauri-compatible manifest plus detached Minisign signature. The signed manifest
+binds repository, tag, peeled source commit, SemVer, target, artifact URL, size,
+SHA-256, and the artifact's own Tauri signature. The shell verifies all these
+fields and the GitHub tag source before offering installation. It checks the
+plugin's fetched JSON against the authenticated manifest before downloading.
+
+macOS updater payloads are `.app.tar.gz`; DMGs remain manual installers. Windows
+uses NSIS EXE. `.SIGNATURE` remains human-readable OS-signing metadata and never
+counts as an updater signature. Missing signing configuration disables update
+publication; an enabled channel with partial configuration fails the workflow.
+Existing unsigned releases cannot become auto-installable retroactively.
+
+## Installation and verification
+
+The pinned Tauri v2 updater owns HTTPS update checks and artifact signature
+verification. Application replacement must preserve the old runnable application
+on failure. The implementation must account for the upstream macOS install path
+not restoring its temporary backup, and Windows returning before NSIS completes.
+Validate metadata/signatures and all bytes before any replacement operation.
+
+Use shared Rust contract verification both in the shell and release validation;
+fixture tests cover source/version/target mismatches, tampering, and failure
+preservation. Run focused Python workflow tests, changed-file Ruff, desktop
+localization/build, Rust fmt/check/test, and the shared Web build. Native signed
+upgrade acceptance on macOS arm64/x64 and Windows x64 remains an explicit release
+operator check; never simulate success by updating this machine's installation.
+
+## Local evidence (2026-09-25)
+
+- 239 Rust tests pass, including real Tauri Minisign fixtures for both channels
+ and all three targets, official plugin manifest consumption, arbitrary-byte
+ metadata tampering, download/install gate failures, and macOS restore failure.
+- 57 focused Python release tests pass, including actual workflow shell fixtures
+ and the real Rust verifier executed under test-owned HOME/state.
+- Desktop and Workbench builds, desktop locale parity, focused VersionBadge tests,
+ Rust formatting/check/Clippy, and changed-file Ruff pass.
+- Windows process/rollback fixtures are wired to the existing Windows CI runner.
+- No real updater secret was used, tag created, release published, or app replaced.
+ Native signed two-version upgrade acceptance remains a release prerequisite.
+
+## First review follow-up
+
+Head `65ff58a2e701df861ddc6a1b0cedd9cfb676c51b` received one Codex finding:
+Windows recovery merged the backup into a partial installation. Recovery now
+removes the failed installation before copying the intact backup; native fixtures
+cover deleted installations, newly introduced DLLs/resources, and a successful
+installer exit followed by a rejected version. Native execution remains a
+Windows CI gate.
+
+Signed fixture files disable Git text conversion. All 14 tracked fixture files
+retain their exact signed bytes under a `core.autocrlf=true` checkout, and all
+five Rust updater contract tests pass. Release job condition fixtures now model
+resolution results and the desktop enable flag independently, including stable
+and TEST failures; the three focused Python release files pass 1,653 tests.
diff --git a/docs/plans/desktop-product-gaps.md b/docs/plans/desktop-product-gaps.md
index 19523ef93..f4fd0dafe 100644
--- a/docs/plans/desktop-product-gaps.md
+++ b/docs/plans/desktop-product-gaps.md
@@ -48,6 +48,10 @@ visibility and launch-at-login **shipped** in #1975.
### G2. Auto-update
+- Implementation: see [signed update contract](desktop-auto-update.md) and the
+ desktop README. Publication remains gated on owner-configured signing keys and
+ real native upgrade acceptance. Existing unsigned TEST releases remain manual.
+
- Problem: today an update means "download and replace the app". No security
fix can reach an installed base.
- Work: integrate `tauri-plugin-updater` against a JSON endpoint (GitHub
diff --git a/scripts/desktop_release.py b/scripts/desktop_release.py
index 2e379f58a..a503ee885 100644
--- a/scripts/desktop_release.py
+++ b/scripts/desktop_release.py
@@ -6,6 +6,7 @@ from __future__ import annotations
import argparse
import hashlib
import json
+import os
import re
import shutil
import subprocess
@@ -32,9 +33,11 @@ SEMVER = re.compile(
def desktop_version_from_tag(tag: str) -> str:
+ if re.fullmatch(r"v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)", tag):
+ return tag[1:]
match = RC_TAG.fullmatch(tag)
if match is None:
- raise ValueError("desktop TEST release requires a canonical gh-vX.Y.ZrcN tag")
+ raise ValueError("desktop TEST release requires a canonical gh-vX.Y.ZrcN or vX.Y.Z tag")
package_version = package_version_from_release_tag(tag)
return package_version.replace("rc", "-rc.")
@@ -142,11 +145,22 @@ def record(*, version: str, target: str, tag: str, source_sha: str,
)
-def verify(directory: Path, tag: str, source_sha: str) -> list[Path]:
+def verify(directory: Path, tag: str, source_sha: str, *, updater_enabled: bool = False) -> list[Path]:
version = desktop_version_from_tag(tag)
if SHA.fullmatch(source_sha) is None:
raise ValueError("Invalid source SHA")
expected = {name for target in TARGETS for name in asset_names(version, target)}
+ if updater_enabled:
+ updater = run_path(str(Path(__file__).with_name("desktop_updater.py")))
+ for target in TARGETS:
+ expected.update(updater["names"](version, target))
+ public = os.environ.get("AVIBE_DESKTOP_UPDATER_PUBLIC_KEY", "")
+ if not public.strip():
+ raise ValueError("Missing updater verification public key")
+ with tempfile.TemporaryDirectory() as temporary:
+ key = Path(temporary) / "public-key.txt"
+ key.write_text(public, encoding="utf-8")
+ updater["verify"](directory, tag, source_sha, key)
if {path.name for path in directory.iterdir()} != expected:
raise ValueError("Desktop asset set must contain exactly all three targets and their metadata")
for target in TARGETS:
@@ -169,8 +183,17 @@ def verify(directory: Path, tag: str, source_sha: str) -> list[Path]:
return [directory / name for name in sorted(expected)]
-def check_remote(directory: Path, tag: str, source_sha: str, repo: str, *, complete: bool) -> None:
- paths = verify(directory, tag, source_sha)
+def check_remote(directory: Path, tag: str, source_sha: str, repo: str, *, complete: bool,
+ updater_enabled: bool = False) -> None:
+ paths = verify(directory, tag, source_sha, updater_enabled=updater_enabled)
+ if updater_enabled:
+ if repo != "avibe-bot/avibe":
+ raise ValueError("Updater repository mismatch")
+ actual_source = subprocess.check_output(
+ ["gh", "api", f"repos/{repo}/commits/{tag}", "--jq", ".sha"], text=True,
+ ).strip()
+ if actual_source != source_sha:
+ raise ValueError("Live release tag no longer matches updater source")
state = _github["get_release"](repo, tag)
if state is None:
if complete:
@@ -217,6 +240,7 @@ def main() -> None:
for command in ("verify", "check-remote"):
consumer = sub.add_parser(command)
consumer.add_argument("--directory", type=Path, required=True)
+ consumer.add_argument("--updater-enabled", action="store_true")
consumer.add_argument("--tag", required=True)
consumer.add_argument("--source-sha", required=True)
if command == "check-remote":
diff --git a/scripts/desktop_updater.py b/scripts/desktop_updater.py
new file mode 100644
index 000000000..f14fd10f4
--- /dev/null
+++ b/scripts/desktop_updater.py
@@ -0,0 +1,151 @@
+#!/usr/bin/env python3
+"""Build authenticated desktop update manifests; never treat .SIGNATURE as a signature."""
+from __future__ import annotations
+
+import argparse
+import json
+import os
+from pathlib import Path
+import subprocess
+from runpy import run_path
+import tarfile
+
+release = run_path(str(Path(__file__).with_name('desktop_release.py')))
+TARGETS = {
+ 'aarch64-apple-darwin': ('darwin-aarch64', '.app.tar.gz'),
+ 'x86_64-apple-darwin': ('darwin-x86_64', '.app.tar.gz'),
+ 'x86_64-pc-windows-msvc': ('windows-x86_64', '.exe'),
+}
+REPOSITORY = 'avibe-bot/avibe'
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def names(version: str, target: str) -> set[str]:
+ manifest = f'desktop-update-{target}.json'
+ return {f'Avibe_{version}_{target}{TARGETS[target][1]}', manifest, manifest + '.sig'}
+
+
+def configuration(enabled: bool, public_key: str, private_key: str) -> None:
+ if enabled and (not public_key.strip() or not private_key.strip()):
+ raise ValueError('Enabled updater requires DESKTOP_UPDATER_PUBLIC_KEY and TAURI_SIGNING_PRIVATE_KEY')
+ if '\n' in public_key or '\r' in public_key:
+ raise ValueError('Updater public key must be the single-line Tauri base64 public key')
+
+
+def configure(config: Path, env_file: Path, enabled: bool) -> None:
+ public = os.environ.get('AVIBE_DESKTOP_UPDATER_PUBLIC_KEY', '')
+ configuration(enabled, public, os.environ.get('TAURI_SIGNING_PRIVATE_KEY', ''))
+ data = json.loads(config.read_text(encoding='utf-8'))
+ # Payloads are sealed after final OS signing. We sign those final bytes below.
+ data.setdefault('bundle', {})['createUpdaterArtifacts'] = False
+ data.setdefault('plugins', {})['updater'] = {'pubkey': public if enabled else '', 'endpoints': []}
+ config.write_text(json.dumps(data) + '\n', encoding='utf-8')
+ with env_file.open('a', encoding='utf-8') as stream:
+ stream.write(f"AVIBE_DESKTOP_UPDATER_PUBLIC_KEY={public if enabled else ''}\n")
+
+
+def verify(directory: Path, tag: str, source_sha: str, public_key: Path, targets=None) -> None:
+ for target in targets or TARGETS:
+ subprocess.run([
+ 'cargo', 'run', '--locked', '--quiet', '--manifest-path', str(ROOT / 'desktop/Cargo.toml'),
+ '-p', 'avibe-runtime-host', '--example', 'verify_update', '--',
+ str(directory.resolve()), tag, source_sha, target, str(public_key.resolve()),
+ ], check=True)
+
+
+def produce(directory: Path, tag: str, source_sha: str, target: str, app: Path | None) -> None:
+ public = os.environ.get('AVIBE_DESKTOP_UPDATER_PUBLIC_KEY', '')
+ configuration(True, public, os.environ.get('TAURI_SIGNING_PRIVATE_KEY', ''))
+ resolved = release['resolve'](tag, source_sha)
+ if release['git_output']('rev-parse', 'HEAD') != source_sha:
+ raise ValueError('Updater build checkout differs from release source')
+ version = resolved['version']
+ provenance = json.loads((directory / f'Avibe_{version}_{target}.SOURCE.json').read_text(encoding='utf-8'))
+ if any(provenance.get(k) != v for k, v in {'tag': tag, 'source_sha': source_sha, 'target': target, 'version': version}.items()):
+ raise ValueError('Updater source provenance mismatch')
+ artifact = directory / f'Avibe_{version}_{target}{TARGETS[target][1]}'
+ if target.endswith('apple-darwin'):
+ if app is None or not app.is_dir() or app.name != 'Avibe.app':
+ raise ValueError('Final sealed Avibe.app is required')
+ with tarfile.open(artifact, 'w:gz') as archive:
+ archive.add(app, arcname='Avibe.app')
+ if not artifact.is_file() or artifact.stat().st_size == 0:
+ raise ValueError('Missing updater artifact')
+ cli = ROOT / 'desktop/node_modules/.bin' / ('tauri.cmd' if os.name == 'nt' else 'tauri')
+
+ def sign(path):
+ # Tauri prints the signature/public key, never pass a secret as argv.
+ subprocess.run([str(cli), 'signer', 'sign', str(path.resolve())], check=True, stdout=subprocess.DEVNULL)
+ return Path(str(path) + '.sig').read_text(encoding='utf-8').strip()
+
+ signature = sign(artifact)
+ manifest = directory / f'desktop-update-{target}.json'
+ manifest.write_text(json.dumps({
+ 'schema_version': 1, 'repository': REPOSITORY, 'tag': tag, 'source_sha': source_sha,
+ 'channel': 'test' if tag.startswith('gh-v') else 'stable', 'version': version, 'target': target,
+ 'platforms': {TARGETS[target][0]: {
+ 'url': f'https://github.com/{REPOSITORY}/releases/download/{tag}/{artifact.name}',
+ 'signature': signature, 'sha256': release['digest'](artifact), 'size': artifact.stat().st_size,
+ }},
+ }, indent=2, sort_keys=True) + '\n', encoding='utf-8')
+ sign(manifest)
+ key_file = directory / 'updater-public-key.txt'
+ try:
+ key_file.write_text(public, encoding='utf-8')
+ verify(directory, tag, source_sha, key_file, [target])
+ finally:
+ key_file.unlink(missing_ok=True)
+ Path(str(artifact) + '.sig').unlink(missing_ok=True)
+
+
+def stage(directory: Path, tag: str, source_sha: str, repo: str, enabled: bool) -> None:
+ """Stage verified stable desktop bytes in the existing Draft, read back every byte."""
+ if repo != REPOSITORY:
+ raise ValueError('Updater repository mismatch')
+ paths = release['verify'](directory, tag, source_sha, updater_enabled=enabled)
+ state = release['_github']['get_release'](repo, tag)
+ if state and not state.draft:
+ raise ValueError('Cannot retrofit a published desktop release')
+ subprocess.run(['gh', 'release', 'view', tag, '--repo', repo], check=True, stdout=subprocess.DEVNULL)
+ # Existing asset bytes are immutable; missing assets may be added only to Drafts.
+ import tempfile
+ with tempfile.TemporaryDirectory() as temporary:
+ remote = json.loads(subprocess.check_output(['gh', 'release', 'view', tag, '--repo', repo, '--json', 'assets'], text=True))
+ existing = {a['name'] for a in remote['assets']}
+ missing = []
+ for path in paths:
+ if path.name in existing:
+ subprocess.run(['gh', 'release', 'download', tag, '--repo', repo, '--pattern', path.name, '--dir', temporary], check=True)
+ if release['digest'](Path(temporary) / path.name) != release['digest'](path):
+ raise ValueError('Immutable desktop release asset differs')
+ else:
+ missing.append(str(path))
+ if missing:
+ subprocess.run(['gh', 'release', 'upload', tag, '--repo', repo, *missing], check=True)
+ release['check_remote'](directory, tag, source_sha, repo, complete=True, updater_enabled=enabled)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ sub = parser.add_subparsers(dest='command', required=True)
+ config = sub.add_parser('configure')
+ config.add_argument('--config', type=Path, required=True)
+ config.add_argument('--env-file', type=Path, required=True)
+ config.add_argument('--enabled', action='store_true')
+ for action in ('produce', 'stage'):
+ command = sub.add_parser(action)
+ command.add_argument('--directory', type=Path, required=True)
+ command.add_argument('--tag', required=True)
+ command.add_argument('--source-sha', required=True)
+ if action == 'produce':
+ command.add_argument('--target', choices=TARGETS, required=True)
+ command.add_argument('--app', type=Path)
+ else:
+ command.add_argument('--repo', required=True)
+ command.add_argument('--enabled', action='store_true')
+ args = vars(parser.parse_args())
+ globals()[args.pop('command')](**args)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tests/test_desktop_updater.py b/tests/test_desktop_updater.py
new file mode 100644
index 000000000..662cd4f59
--- /dev/null
+++ b/tests/test_desktop_updater.py
@@ -0,0 +1,155 @@
+"""Signed update publication fails closed independently from manual installers."""
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+import subprocess
+
+import pytest
+import yaml
+
+from scripts import desktop_release, desktop_updater
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def workflow(name):
+ return yaml.safe_load((ROOT / '.github/workflows' / name).read_text())['jobs']
+
+
[email protected]('enabled,public,private,accepted', [
+ (False, '', '', True), (True, '', '', False), (True, 'public', '', False),
+ (True, '', 'private', False), (True, 'public', 'private', True),
+])
+def test_enabled_channel_requires_both_signing_key_and_pinned_public_key(enabled, public, private, accepted):
+ if accepted:
+ desktop_updater.configuration(enabled, public, private)
+ else:
+ with pytest.raises(ValueError):
+ desktop_updater.configuration(enabled, public, private)
+
+
+def test_disabled_build_explicitly_erases_endpoint_and_embedded_public_key(tmp_path, monkeypatch):
+ config = tmp_path / 'config.json'
+ config.write_text(json.dumps({'version': '3.1.2-rc.15'}))
+ env = tmp_path / 'env'
+ monkeypatch.setenv('AVIBE_DESKTOP_UPDATER_PUBLIC_KEY', 'a configured key')
+ desktop_updater.configure(config, env, False)
+ actual = json.loads(config.read_text())
+ assert actual['plugins']['updater'] == {'pubkey': '', 'endpoints': []}
+ assert not actual['bundle']['createUpdaterArtifacts']
+ assert env.read_text() == 'AVIBE_DESKTOP_UPDATER_PUBLIC_KEY=\n'
+
+
[email protected]('tag,expected', [('v3.1.2', '3.1.2'), ('gh-v3.1.2rc15', '3.1.2-rc.15')])
+def test_source_version_binding_for_both_channels(tag, expected, monkeypatch):
+ source = 'a' * 40
+ monkeypatch.setattr(desktop_release, 'git_output', lambda *_: source)
+ assert desktop_release.resolve(tag, source)['version'] == expected
+ with pytest.raises(ValueError, match='source SHA'):
+ desktop_release.resolve(tag, 'b' * 40)
+
+
[email protected]('tag,test,stable,enabled,signed', [
+ ('gh-v3.1.2rc15', '', '', True, False),
+ ('gh-v3.1.2rc15', 'true', '', True, True),
+ ('v3.1.2', '', '', False, False),
+ ('v3.1.2', '', 'true', True, True),
+ ('v3.1.2rc1', '', 'true', False, False),
+])
+def test_real_workflow_channel_resolution(tmp_path, tag, test, stable, enabled, signed):
+ steps = workflow('release_ai.yml')['resolve-desktop-release']['steps']
+ script = next(s['run'] for s in steps if s.get('id') == 'resolve')
+ # A test-owned resolver witnesses that disabled paths never invoke release tooling.
+ scripts = tmp_path / 'scripts'
+ scripts.mkdir()
+ (scripts / 'desktop_release.py').write_text("from pathlib import Path\nPath('resolved').touch()\n")
+ output = tmp_path / 'output'
+ result = subprocess.run(['bash', '-e', '-c', script], cwd=tmp_path, capture_output=True, text=True,
+ env={**os.environ, 'RELEASE_TAG': tag, 'TEST_ENABLED': test,
+ 'STABLE_ENABLED': stable, 'GITHUB_OUTPUT': str(output)})
+ assert result.returncode == 0, result.stderr
+ assert (tmp_path / 'resolved').exists() == enabled
+ assert dict(line.split('=') for line in output.read_text().splitlines()) == {
+ 'enabled': str(enabled).lower(), 'updater_enabled': str(signed).lower(),
+ }
+
+
+def test_release_cannot_publish_before_all_targets_and_signed_verification():
+ jobs = workflow('release_ai.yml')
+ assert 'desktop-packages' in jobs['release']['needs']
+ assert "needs.desktop-packages.result == 'success'" in jobs['release']['if']
+ assert "needs.resolve-desktop-release.result == 'success'" in jobs['release']['if']
+ package = workflow('desktop-package.yml')['package']
+ assert package['environment'] == 'desktop-updater'
+ steps = package['steps']
+ configure = next(i for i,s in enumerate(steps) if s.get('name') == 'Configure signed updater or explicitly disable it')
+ runtime = next(i for i,s in enumerate(steps) if s.get('name') == 'Build verified private Runtime')
+ sign = next(i for i,s in enumerate(steps) if s.get('name') == 'Sign and verify final updater artifacts')
+ assert configure < runtime < sign < len(steps) - 1
+ assert steps[configure]['env']['TAURI_SIGNING_PRIVATE_KEY'] == '${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}'
+ release_steps = jobs['release']['steps']
+ stable_stage = next(s for s in release_steps if s.get('name', '').startswith('Stage signed stable'))
+ assert '--enabled' in stable_stage['run']
+ finalizer = workflow('publish.yml')['finalize-github-release']['steps']
+ assert next(i for i,s in enumerate(finalizer) if s.get('name') == 'Wait for exact-source release notes') < next(
+ i for i,s in enumerate(finalizer) if s.get('name') == 'Publish GitHub Release')
+
+
+def test_signed_gate_refuses_missing_public_key_and_never_accepts_manual_signature(tmp_path, monkeypatch):
+ monkeypatch.delenv('AVIBE_DESKTOP_UPDATER_PUBLIC_KEY', raising=False)
+ with pytest.raises(ValueError, match='public key'):
+ desktop_release.verify(tmp_path, 'gh-v3.1.2rc15', 'a' * 40, updater_enabled=True)
+ (tmp_path / 'desktop-update-aarch64-apple-darwin.json').write_text('{}')
+ (tmp_path / 'desktop-update-aarch64-apple-darwin.json.sig').write_text('app-adhoc')
+ with pytest.raises(ValueError):
+ desktop_release.verify(tmp_path, 'gh-v3.1.2rc15', 'a' * 40)
+
+
[email protected]('channel,tag,version', [
+ ('test', 'gh-v3.1.2rc15', '3.1.2-rc.15'), ('stable', 'v3.1.2', '3.1.2'),
+])
+def test_real_release_verifier_accepts_signed_fixtures_and_rejects_missing_or_tampered_assets(
+ tmp_path, monkeypatch, channel, tag, version,
+):
+ import shutil
+ executable = ROOT / 'desktop/target/debug/examples' / ('verify_update.exe' if os.name == 'nt' else 'verify_update')
+ if not executable.is_file():
+ pytest.skip('Build the Rust verifier first; its contract is also tested by desktop-shell CI')
+ # Pytest isolates HOME. Use the already-built real verifier instead of
+ # invoking rustup or writing into the user's Cargo/toolchain stores.
+ run = subprocess.run
+
+ def launch(command, **kwargs):
+ assert command[:4] == ['cargo', 'run', '--locked', '--quiet']
+ return run([str(executable), *command[command.index('--') + 1:]], **kwargs)
+
+ monkeypatch.setattr(desktop_updater.subprocess, 'run', launch)
+ fixtures = ROOT / 'desktop/runtime-host/tests/fixtures/updater'
+ target = 'aarch64-apple-darwin'
+ manifest = tmp_path / f'desktop-update-{target}.json'
+ signature = Path(str(manifest) + '.sig')
+ artifact = tmp_path / f'Avibe_{version}_{target}.app.tar.gz'
+ shutil.copyfile(fixtures / f'{channel}-{target}.json', manifest)
+ shutil.copyfile(fixtures / f'{channel}-{target}.json.sig', signature)
+ shutil.copyfile(fixtures / 'artifact.bin', artifact)
+ key = fixtures / 'public-key.txt'
+ desktop_updater.verify(tmp_path, tag, 'a' * 40, key, [target])
+ with pytest.raises(subprocess.CalledProcessError):
+ desktop_updater.verify(tmp_path, tag, 'b' * 40, key, [target])
+ artifact.write_bytes(b'tampered executable')
+ with pytest.raises(subprocess.CalledProcessError):
+ desktop_updater.verify(tmp_path, tag, 'a' * 40, key, [target])
+ shutil.copyfile(fixtures / 'artifact.bin', artifact)
+ signature.unlink()
+ with pytest.raises(subprocess.CalledProcessError):
+ desktop_updater.verify(tmp_path, tag, 'a' * 40, key, [target])
+
+
+def test_remote_tag_rebinding_prevents_signed_publication(tmp_path, monkeypatch):
+ monkeypatch.setattr(desktop_release, 'verify', lambda *a, **kw: [])
+ monkeypatch.setattr(desktop_release.subprocess, 'check_output', lambda *a, **kw: 'b' * 40)
+ monkeypatch.setitem(desktop_release._github, 'get_release', lambda *a: pytest.fail('source mismatch reached publication'))
+ with pytest.raises(ValueError, match='Live release tag'):
+ desktop_release.check_remote(tmp_path, 'v3.1.2', 'a' * 40, 'avibe-bot/avibe', complete=True, updater_enabled=True)
diff --git a/tests/test_release_verification.py b/tests/test_release_verification.py
index 7d785d38d..3f3bbdf2d 100644
--- a/tests/test_release_verification.py
+++ b/tests/test_release_verification.py
@@ -587,10 +587,12 @@ def test_upload_protects_all_existing_bytes_before_any_write(tmp_path, workflow_
@pytest.mark.parametrize("tag", ["v3.1.0", "v3.2.0rc1", "gh-v3.2.0rc1"])
@pytest.mark.parametrize("build_result", ["success", "skipped", "failure", "cancelled"])
@pytest.mark.parametrize("desktop_result", ["success", "skipped", "failure", "cancelled"])
[email protected]("resolve_result", ["success", "skipped", "failure", "cancelled"])
[email protected]("desktop_enabled", [False, True])
@pytest.mark.parametrize("cancelled", [False, True])
@pytest.mark.parametrize("event", ["push", "workflow_dispatch"])
def test_notes_skip_unused_official_build_but_never_publish_a_failed_preview(
- tag, build_result, desktop_result, cancelled, event,
+ tag, build_result, desktop_result, resolve_result, desktop_enabled, cancelled, event,
):
workflow = yaml.safe_load((ROOT / ".github/workflows/release_ai.yml").read_text())
jobs = workflow["jobs"]
@@ -605,17 +607,19 @@ def test_notes_skip_unused_official_build_but_never_publish_a_failed_preview(
expression = jobs["release"]["if"].strip().removeprefix("${{").removesuffix("}}").strip()
expression = expression.replace("needs.build-assets.result", "build_result")
expression = expression.replace("needs.desktop-packages.result", "desktop_result")
- expression = expression.replace("needs.resolve-desktop-release.result", "desktop_result")
+ expression = expression.replace("needs.resolve-desktop-release.result", "resolve_result")
+ expression = expression.replace("needs.resolve-desktop-release.outputs.enabled", "desktop_enabled")
expression = expression.replace("github.event.inputs.tag", "input_tag").replace("github.ref_name", "ref")
- expression = expression.replace("&&", " and ").replace("||", " or ").replace("!", " not ")
+ expression = re.sub(r"!(?!=)", " not ", expression.replace("&&", " and ").replace("||", " or "))
expression = " ".join(expression.split())
result = eval(expression, {"__builtins__": {}}, {
"build_result": build_result, "desktop_result": desktop_result, "input_tag": tag if event == "workflow_dispatch" else "",
+ "resolve_result": resolve_result, "desktop_enabled": "true" if desktop_enabled else "false",
"ref": "master" if event == "workflow_dispatch" else tag,
"cancelled": lambda: cancelled,
"startsWith": lambda value, prefix: value.startswith(prefix),
})
- expected = not cancelled and (
+ expected = not cancelled and resolve_result == "success" and (
build_result == "success" or (build_result == "skipped" and not tag.startswith("gh-v"))
- ) and (not tag.startswith("gh-v") or desktop_result == "success")
+ ) and (not (tag.startswith("gh-v") or desktop_enabled) or desktop_result == "success")
assert result == expected
diff --git a/ui/src/components/VersionBadge.test.tsx b/ui/src/components/VersionBadge.test.tsx
new file mode 100644
index 000000000..c21b8e31f
--- /dev/null
+++ b/ui/src/components/VersionBadge.test.tsx
@@ -0,0 +1,41 @@
+// @vitest-environment jsdom
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { I18nextProvider } from 'react-i18next';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import i18n from '@/i18n';
+import { VersionBadge } from './VersionBadge';
+
+const api = vi.hoisted(() => ({
+ getVersion: vi.fn(async () => ({ current: '9.9.9', latest: '10.0.0', has_update: true, managed_by: 'desktop' })),
+ getConfig: vi.fn(async () => ({ update: { auto_update: true } })),
+}));
+vi.mock('../context/ApiContext', () => ({ useApi: () => api }));
+vi.mock('../lib/useIsDesktop', () => ({ useIsDesktop: () => true }));
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+ delete (window as { __AVIBE_DESKTOP_SHELL__?: true }).__AVIBE_DESKTOP_SHELL__;
+ delete (window as { __AVIBE_DESKTOP_VERSION__?: string }).__AVIBE_DESKTOP_VERSION__;
+});
+
+describe('desktop version ownership', () => {
+ it('uses the stamped app version and never starts the Python updater', () => {
+ Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { value: true, configurable: true });
+ Object.defineProperty(window, '__AVIBE_DESKTOP_VERSION__', { value: '3.1.2-rc.15', configurable: true });
+ render(<I18nextProvider i18n={i18n}><VersionBadge /></I18nextProvider>);
+ expect(screen.getByTitle('v3.1.2-rc.15')).toBeTruthy();
+ expect(api.getVersion).not.toHaveBeenCalled();
+ expect(api.getConfig).not.toHaveBeenCalled();
+ expect(screen.queryByRole('dialog')).toBeNull();
+ });
+
+ it('retains the browser version entry and its existing managed-runtime guidance', async () => {
+ render(<I18nextProvider i18n={i18n}><VersionBadge /></I18nextProvider>);
+ const entry = await screen.findByTitle('v9.9.9');
+ fireEvent.click(entry);
+ expect(await screen.findByRole('dialog')).toBeTruthy();
+ expect(api.getVersion).toHaveBeenCalledOnce();
+ expect(entry.querySelector('.animate-pulse')).toBeNull();
+ });
+});
diff --git a/ui/src/components/VersionBadge.tsx b/ui/src/components/VersionBadge.tsx
index 38484457e..4d862045e 100644
--- a/ui/src/components/VersionBadge.tsx
+++ b/ui/src/components/VersionBadge.tsx
@@ -13,6 +13,7 @@ import {
import { cn } from '@/lib/utils';
import { setConfigField } from '@/lib/configMutations';
import { scheduleUpgradeReload } from '../lib/upgradeReload';
+import { isDesktopShell } from '../lib/desktopShell';
import { useIsDesktop } from '../lib/useIsDesktop';
import { Popover, PopoverContent, PopoverTrigger } from './ui/popover';
@@ -30,6 +31,7 @@ function shortenVersion(value: string, tail = 4): string {
export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward = false }) => {
const { t } = useTranslation();
const api = useApi();
+ const inDesktopShell = isDesktopShell();
const isDesktop = useIsDesktop();
const [versionInfo, setVersionInfo] = React.useState<VersionInfo | null>(null);
const [isPopupOpen, setIsPopupOpen] = React.useState(false);
@@ -43,6 +45,7 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
const popupId = React.useId();
React.useEffect(() => {
+ if (inDesktopShell) return;
checkVersion();
loadAutoUpdateSetting();
}, []);
@@ -115,10 +118,10 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
}
};
- const hasUpdate = versionInfo?.has_update === true;
+ const hasUpdate = !inDesktopShell && versionInfo?.managed_by !== 'desktop' && versionInfo?.has_update === true;
const isDesktopManaged = versionInfo?.managed_by === 'desktop';
- const currentVersion = versionInfo?.current || '...';
- const isSourceBuild = versionInfo?.build?.kind === 'source';
+ const currentVersion = (inDesktopShell ? window.__AVIBE_DESKTOP_VERSION__ : versionInfo?.current) || '...';
+ const isSourceBuild = !inDesktopShell && versionInfo?.build?.kind === 'source';
const sourceRevision = versionInfo?.build?.revision;
const shortSourceRevision = sourceRevision?.slice(0, 12) || t('dashboard.unknownRevision');
const displayVersion = isSourceBuild ? shortSourceRevision : shortenVersion(currentVersion);
@@ -133,7 +136,7 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
const Popup = isDesktop ? PopoverContent : 'div';
return (
- <Popover open={isPopupOpen} onOpenChange={setIsPopupOpen}>
+ <Popover open={!inDesktopShell && isPopupOpen} onOpenChange={setIsPopupOpen}>
<div className="relative" ref={popupRef}>
{/* Version Badge trigger */}
<PopoverTrigger asChild>
@@ -146,6 +149,10 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
)}
title={badgeTitle}
aria-controls={popupId}
+ onClick={inDesktopShell ? (event) => {
+ event.preventDefault();
+ window.location.href = 'avibe://updates';
+ } : undefined}
>
{isSourceBuild ? <GitCommitHorizontal size={12} /> : 'v'}
{displayVersion}
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 234eb53f7..c69e60140 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -77,6 +77,28 @@
"successMessage": "The private Runtime and agent backends were removed. Avibe will now quit. You can delete the application or run the system uninstaller.",
"failureTitle": "Uninstall Failed",
"failureMessage": "Avibe could not remove all private Runtime and backend files. The desktop app remains installed and your user data was not changed."
+ },
+ "updater": {
+ "menu": "Check for Desktop Updates…",
+ "testChannel": "Use TEST Updates",
+ "title": "Avibe Desktop Updates",
+ "current": "Current version",
+ "latest": "Latest version",
+ "checking": "Checking for updates…",
+ "upToDate": "This app is up to date.",
+ "available": "Update available",
+ "downloading": "Downloading and verifying update…",
+ "installing": "Installing update…",
+ "installed": "Update installed. Restarting…",
+ "disabled": "Desktop updates disabled",
+ "checkFailed": "Could not verify an update. Check your connection and try again. This release may require manual installation.",
+ "installFailed": "The update could not be installed. The previous application has been retained. Please retry or reinstall the previous release.",
+ "install": "Download and Install",
+ "skip": "Skip This Version",
+ "cancel": "Later",
+ "confirm": "An update is available. Download and install it now? Avibe will restart. Your sessions and settings will be kept.",
+ "disabledDetail": "Automatic desktop updates are not configured for this build. Install a newer signed release manually.",
+ "error": "Update failed — retry"
}
},
"installHint": {
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 1635da9c4..17941140e 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -77,6 +77,28 @@
"successMessage": "私有 Runtime 和 Agent 后端已移除,Avibe 现在将退出。你可以删除应用或运行系统卸载程序。",
"failureTitle": "卸载失败",
"failureMessage": "Avibe 无法完整移除私有 Runtime 和后端文件。桌面应用仍保持安装状态,你的用户数据没有发生变化。"
+ },
+ "updater": {
+ "menu": "检查桌面应用更新…",
+ "testChannel": "使用测试版更新",
+ "title": "桌面应用更新",
+ "current": "当前版本",
+ "latest": "最新版本",
+ "checking": "正在检查更新…",
+ "upToDate": "当前应用已是最新版本。",
+ "available": "有新版本可用",
+ "downloading": "正在下载并校验更新…",
+ "installing": "正在安装更新…",
+ "installed": "更新已安装,正在重新启动…",
+ "disabled": "桌面自动更新未启用",
+ "checkFailed": "无法验证更新,请检查网络后重试。此版本可能需要手动安装。",
+ "installFailed": "更新安装失败,已保留旧应用。请重试或重新安装之前的版本。",
+ "install": "下载并安装",
+ "skip": "跳过此版本",
+ "cancel": "稍后",
+ "confirm": "发现新版本。现在下载并安装吗?应用将重新启动,会保留会话和设置。",
+ "disabledDetail": "此构建尚未配置桌面自动更新,请手动安装新的签名版本。",
+ "error": "更新失败,可重试"
}
},
"installHint": {
diff --git a/ui/src/lib/desktopShell.ts b/ui/src/lib/desktopShell.ts
index 3a0404ad4..b83a7a7ce 100644
--- a/ui/src/lib/desktopShell.ts
+++ b/ui/src/lib/desktopShell.ts
@@ -2,6 +2,7 @@ declare global {
interface Window {
/** Defined by the Avibe desktop shell before any page script runs, top-level document only. */
readonly __AVIBE_DESKTOP_SHELL__?: true;
+ readonly __AVIBE_DESKTOP_VERSION__?: string;
}
}