Choose the update channel and download authenticated updates (#58)
CI / core (pull_request) Successful in 35s
CI / core (push) Successful in 1m16s

The settings offer Stable or Bêta. The choice is saved only once made;
until then the installed version's channel applies, so the beta
installer follows Bêta. Updates never change a saved choice.

Each launch, and each channel change, runs one check on a below-normal
thread. It lists the channel's Releases through the public Gitea API
(betas are pre-releases) and takes the highest version above the
installed one. The package is downloaded into
%LOCALAPPDATA%\arena-tracker\updates\partial, verified with
verify_release, then kept as <channel>-<version>; another channel's
package is removed before any network access. Only then does a green
title-bar button show « Mise à jour prête » and open the settings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit was merged in pull request #66.
This commit is contained in:
nessarandClaude Opus 5.5 committed 2026-11-20 12:14:25 +01:00
1 parent 24aca3c93d
commit 8e12abf7f4
11 files changed
+842 -37

No files matched your search

+157 -2
View File
@@ -1,12 +1,19 @@
use std::fs::File;
use std::fs::{self, File};
use std::io::Read;
use std::path::Path;
use std::time::Duration;
use base64::prelude::{BASE64_STANDARD, Engine};
use ring::{digest, signature};
use serde::Deserialize;
use ureq::Agent;
use crate::Error;
use crate::{Error, SourceError, UpdateChannel};
/// Bounds what a source can write to disk: a full package is a few tens of MiB.
const MAX_DOWNLOAD: u64 = 256 << 20;
/// A connection or a read that stalls this long fails; a slow download does not.
const STALL: Duration = Duration::from_secs(30);
#[derive(Deserialize)]
struct Manifest {
@@ -76,3 +83,151 @@ pub fn verify_release(
}
Ok(release.commit)
}
#[derive(Deserialize)]
struct Release {
assets: Vec<Asset>,
}
#[derive(Deserialize)]
struct Asset {
name: String,
browser_download_url: String,
}
/// Orders `X.Y.Z` after its betas and `beta.2` before `beta.10`; `None` for any other form.
fn version_order(version: &str) -> Option<[u64; 4]> {
let number = |text: &str| text.parse::<u64>().ok().filter(|n| n.to_string() == text);
let (core, beta) = match version.split_once("-beta.") {
Some((core, n)) => (core, number(n).filter(|n| (1..u64::MAX).contains(n))?),
None => (version, u64::MAX),
};
let mut parts = core.split('.').map(number);
let order = [parts.next()??, parts.next()??, parts.next()??, beta];
parts.next().is_none().then_some(order)
}
/// Removes the entries of `dir` whose name `matches`, as far as it can: an entry another program
/// holds open stays until a later check, and must not hide an authenticated package.
fn remove_entries(dir: &Path, matches: impl Fn(&str) -> bool) {
for entry in fs::read_dir(dir).into_iter().flatten().flatten() {
if matches(&entry.file_name().to_string_lossy()) {
let _ = if entry.file_type().is_ok_and(|kind| kind.is_dir()) {
fs::remove_dir_all(entry.path())
} else {
fs::remove_file(entry.path())
};
}
}
}
/// Keeps the newest release of `channel` above `installed` downloaded and authenticated in
/// `dir/<channel>-<version>` and returns its version, or `None` when there is none. Anything
/// else in `dir` is removed; another channel's package goes before any network access, so it can
/// never be taken for this channel's. Bytes are downloaded into `dir/partial` and renamed only
/// once `verify_release` accepts them. A kept package is verified again instead of downloaded.
/// `releases_url` is a Gitea releases API endpoint, where betas are pre-releases.
/// One call at a time per `dir`.
pub fn download_update(
releases_url: &str,
dir: &Path,
public_key: &[u8],
channel: UpdateChannel,
installed: &str,
) -> Result<Option<String>, Error> {
let installed = version_order(installed)
.ok_or_else(|| Error::InvalidUpdate("version installée illisible".into()))?;
let name = channel.name();
fs::create_dir_all(dir).map_err(storage)?;
remove_entries(dir, |entry| !entry.starts_with(&format!("{name}-")));
let agent: Agent = Agent::config_builder()
.http_status_as_error(false)
.user_agent("arena-tracker")
.timeout_connect(Some(STALL))
.timeout_per_read(Some(STALL))
.build()
.into();
let get = |url: &str| {
let response = agent.get(url).call().map_err(network)?;
match response.status().as_u16() {
200..=299 => Ok(response),
status => Err(network(format!("HTTP {status}"))),
}
};
let beta = channel == UpdateChannel::Beta;
let list = get(&format!(
"{releases_url}?draft=false&pre-release={beta}&limit=10"
))?
.into_body()
.read_to_string()
.map_err(network)?;
let releases: Vec<Release> = serde_json::from_str(&list)
.map_err(|e| Error::InvalidUpdate(format!("liste des versions illisible ({e})")))?;
let manifest_files = [
format!("release-{name}.json"),
format!("release-{name}.sig"),
];
let newest = releases
.iter()
.filter_map(|release| {
let has = |file: &str| release.assets.iter().any(|asset| asset.name == file);
let version = release.assets.iter().find_map(|asset| {
let rest = asset.name.strip_prefix("ArenaTracker-")?;
rest.strip_suffix(&format!("-{name}-full.nupkg"))
})?;
let order = version_order(version)?;
// Betas end below u64::MAX, stables at it: a channel only takes its own versions.
let complete = manifest_files.iter().all(|file| has(file));
(order > installed && (order[3] < u64::MAX) == beta && complete)
.then_some((order, version, release))
})
.max_by_key(|(order, ..)| *order);
let Some((_, version, release)) = newest else {
remove_entries(dir, |_| true);
return Ok(None);
};
let kept = format!("{name}-{version}");
if verify_release(&dir.join(&kept), public_key, name, version).is_ok() {
remove_entries(dir, |entry| entry != kept);
return Ok(Some(version.into()));
}
// An older package of this channel stays until the newer one is ready.
remove_entries(dir, |entry| entry == kept);
let partial = dir.join("partial");
fs::create_dir(&partial).map_err(storage)?;
let package = format!("ArenaTracker-{version}-{name}-full.nupkg");
let downloaded = manifest_files
.iter()
.chain([&package])
.try_for_each(|file| {
let asset = release.assets.iter().find(|asset| &asset.name == file);
let asset = asset.ok_or_else(|| Error::InvalidUpdate(format!("{file} absent")))?;
// verify_release reads at most 4 KiB of manifest and 64 bytes of signature.
let limit = if file == &package { MAX_DOWNLOAD } else { 4096 };
let mut body = get(&asset.browser_download_url)?.into_body();
let mut reader = body.with_config().limit(limit).reader();
let mut target = File::create(partial.join(file)).map_err(storage)?;
std::io::copy(&mut reader, &mut target)
.map_err(|e| Error::InvalidUpdate(format!("{file} incomplet ({e})")))?;
Ok(())
});
if let Err(error) =
downloaded.and_then(|()| verify_release(&partial, public_key, name, version))
{
let _ = fs::remove_dir_all(&partial);
return Err(error);
}
fs::rename(&partial, dir.join(&kept)).map_err(storage)?;
remove_entries(dir, |entry| entry != kept);
Ok(Some(version.into()))
}
fn network(error: impl ToString) -> Error {
Error::Source(SourceError::Network(error.to_string()))
}
fn storage(error: std::io::Error) -> Error {
Error::Storage(error.to_string())
}