windows: updates from the app, and a dark theme

The service looks at the project's releases (windows-v* tags; pre-releases
for a pre-release), fetches the newer setup program, checks its SHA-256
against the one published beside it, and runs it silently, detached, out of
any job: the setup stops the service, replaces it, and starts it again.
Run by the service (session 0), the setup's install starts the app in each
signed-in user's session with their token rather than through Explorer. A
failed copy during an upgrade starts the old service and app again.
Request::UpdateCheck (anyone), UpdateInstall (services scope);
proxy-ctl update [check|install]; the app's Overview card.

The app's own preferences (%APPDATA%\ProxySuite\app.json): the theme
(light, dark, or as Windows, followed as it changes; the title bar too) and
whether to look for updates at start and daily. Settings > This app, and a
sun/moon toggle in the sidebar.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-10-27 22:21:27 +03:00
1 parent ed9275250b
commit 5bd47f7676
32 files changed
+911 -26

No files matched your search

+21 -1
View File
@@ -134,7 +134,8 @@ fn scope_of(req: &Request) -> Option<Scope> {
Request::Disable { .. } | Request::SubsUpdate { .. } | Request::Test { .. } => Some(Scope::Outbounds),
// Backend logs name the sites visited (at info), and errors may quote what was dialled.
Request::RenderedConfig | Request::Logs { .. } | Request::TgLinks => Some(Scope::Secrets),
Request::Restart { .. } | Request::Start { .. } | Request::Stop { .. } => Some(Scope::Services),
// An update runs only the project's own setup program, checked: no more than a restart.
Request::Restart { .. } | Request::Start { .. } | Request::Stop { .. } | Request::UpdateInstall => Some(Scope::Services),
Request::WlList | Request::WlLink { .. } | Request::WlAuth { .. } | Request::WlJoin { .. } | Request::WlNew { .. } => Some(Scope::WhitelistBypass),
Request::AutoList | Request::AutoProbe { .. } | Request::AutoLearn { .. } | Request::AutoForget { .. } => Some(Scope::AutoProxy),
Request::AwgList | Request::AwgSet { .. } => Some(Scope::AmneziaWg),
@@ -673,6 +674,25 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
Response::ok(json!({ "lines": crate::awgvpn::log_tail(s.paths(), &vpn.iface, lines.min(2000)) }))
}
Request::UpdateCheck => {
let routes = shared.lock().await.fetch_routes(true);
match crate::update::check(&routes).await {
Ok(r) => Response::ok(json!({ "current": env!("CARGO_PKG_VERSION"), "available": r.map(|r| r.to_json()) })),
Err(e) => Response::err(format!("{e:#}")),
}
}
Request::UpdateInstall => {
let (routes, dir) = {
let s = shared.lock().await;
(s.fetch_routes(true), s.paths().updates())
};
match crate::update::install(&routes, &dir).await {
Ok(r) => Response::ok(r.to_json()),
Err(e) => Response::err(format!("{e:#}")),
}
}
Request::ComponentsInstall { names } => {
// Programs the service runs as SYSTEM: an administrator's call, whatever the scopes.
if !peer.admin {
+2 -1
View File
@@ -9,7 +9,8 @@ use sha2::{Digest, Sha256};
use crate::fetch;
fn hex(data: &[u8]) -> String {
/// A SHA-256, in lower-case hex.
pub(crate) fn hex(data: &[u8]) -> String {
let mut h = Sha256::new();
h.update(data);
h.finalize().iter().map(|b| format!("{b:02x}")).collect()
+2
View File
@@ -20,6 +20,7 @@ mod store;
mod tg;
mod tor;
mod units;
mod update;
mod warp;
#[cfg(windows)]
mod winsvc;
@@ -99,6 +100,7 @@ pub async fn run(
let addr = address(socket);
let server = Server::bind(&addr, interactive).with_context(|| format!("listening on {addr:?}"))?;
tracing::info!("listening on {addr:?}, state in {}", paths.root.display());
update::report(&paths.updates());
ready();
if let Err(e) = shared.lock().await.apply().await {
+5
View File
@@ -58,6 +58,11 @@ impl Paths {
pub fn run(&self) -> PathBuf {
self.root.join("run")
}
/// Setup programs the service fetched to update itself.
pub fn updates(&self) -> PathBuf {
self.root.join("updates")
}
pub fn logs(&self) -> PathBuf {
self.root.join("logs")
}
+380
View File
@@ -0,0 +1,380 @@
//! Updating Proxy Suite itself: the newest release on the project's Gitea, its setup program
//! fetched, checked against the SHA-256 published beside it and run silently, as SYSTEM. The
//! setup stops this service, puts the new files in place, and starts the service and the app
//! (in the signed-in users' sessions) again.
use std::cmp::Ordering;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{Duration, Instant};
use anyhow::{Context, Result, anyhow, bail};
use serde_json::{Value, json};
use crate::fetch::{self, Route};
/// The project's releases. `PROXY_SUITE_UPDATE_URL` in the service's own environment (which
/// only an administrator sets) points it at another listing, for tests.
const RELEASES: &str = "https://git.faumaray.com/api/v1/repos/faumaray/proxy-suite-flake/releases?limit=30";
/// The Windows port's tags, apart from upstream's `v0.x.0`.
const TAG_PREFIX: &str = "windows-v";
/// A setup program is ~80 MB.
const MAX_SETUP: usize = 512 << 20;
/// One update at a time: when the one under way began. A setup that never stopped this
/// service (it failed early) leaves the way open again after a while.
static BUSY: Mutex<Option<Instant>> = Mutex::new(None);
const GIVE_UP: Duration = Duration::from_secs(15 * 60);
fn begin() -> bool {
let mut busy = BUSY.lock().unwrap_or_else(|e| e.into_inner());
if busy.is_some_and(|t| t.elapsed() < GIVE_UP) {
return false;
}
*busy = Some(Instant::now());
true
}
fn end() {
*BUSY.lock().unwrap_or_else(|e| e.into_inner()) = None;
}
fn releases_url() -> String {
std::env::var("PROXY_SUITE_UPDATE_URL").unwrap_or_else(|_| RELEASES.into())
}
/// A release's version: `major.minor.patch`, with `-pre.N` for a pre-release.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Version {
major: u64,
minor: u64,
patch: u64,
pre: Option<u64>,
}
impl Version {
pub fn parse(s: &str) -> Option<Self> {
let (core, pre) = match s.split_once('-') {
Some((core, pre)) => (core, Some(pre.strip_prefix("pre.")?.parse().ok()?)),
None => (s, None),
};
let mut parts = core.split('.').map(|p| p.parse::<u64>().ok());
let v = Version { major: parts.next()??, minor: parts.next()??, patch: parts.next()??, pre };
parts.next().is_none().then_some(v)
}
pub fn current() -> Self {
Self::parse(env!("CARGO_PKG_VERSION")).expect("the package's version reads")
}
}
impl Ord for Version {
fn cmp(&self, other: &Self) -> Ordering {
(self.major, self.minor, self.patch).cmp(&(other.major, other.minor, other.patch)).then(match (self.pre, other.pre) {
(None, None) => Ordering::Equal,
// A release is newer than its pre-releases.
(None, Some(_)) => Ordering::Greater,
(Some(_), None) => Ordering::Less,
(Some(a), Some(b)) => a.cmp(&b),
})
}
}
impl PartialOrd for Version {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl std::fmt::Display for Version {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}.{}.{}", self.major, self.minor, self.patch)?;
match self.pre {
Some(n) => write!(f, "-pre.{n}"),
None => Ok(()),
}
}
}
/// A newer release, with its setup program.
#[derive(Debug, Clone, PartialEq)]
pub struct Release {
pub version: Version,
pub page: String,
pub notes: String,
pub published: String,
pub setup: String,
pub size: u64,
pub checksum: String,
}
impl Release {
pub fn to_json(&self) -> Value {
json!({
"version": self.version.to_string(),
"page": self.page,
"notes": self.notes,
"published": self.published,
"size": self.size,
})
}
}
/// `scheme://host[:port]` of a URL.
fn origin(url: &str) -> Option<&str> {
let start = url.find("://")? + 3;
let end = url[start..].find(['/', '?', '#']).map_or(url.len(), |i| start + i);
(end > start).then(|| &url[..end])
}
/// The newest release newer than `current` in a Gitea releases listing. Drafts and other tags
/// are left out, pre-releases unless `current` is one (who runs a release stays on releases),
/// and a release without its setup program and checksum, or with them on another host than
/// the listing's.
pub fn newest(list: &Value, current: Version, listing: &str) -> Option<Release> {
let home = origin(listing)?;
list.as_array()?
.iter()
.filter_map(|r| {
if r["draft"] == true {
return None;
}
let version = Version::parse(r["tag_name"].as_str()?.strip_prefix(TAG_PREFIX)?)?;
if version <= current || ((r["prerelease"] == true || version.pre.is_some()) && current.pre.is_none()) {
return None;
}
let name = format!("ProxySuite-{version}-windows-x64-setup.exe");
let asset = |n: &str| r["assets"].as_array()?.iter().find(|a| a["name"] == n);
let url = |a: &Value| a["browser_download_url"].as_str().filter(|u| origin(u) == Some(home)).map(str::to_owned);
let setup = asset(&name)?;
Some(Release {
version,
page: r["html_url"].as_str().unwrap_or_default().to_owned(),
notes: r["body"].as_str().unwrap_or_default().to_owned(),
published: r["published_at"].as_str().unwrap_or_default().to_owned(),
setup: url(setup)?,
size: setup["size"].as_u64().unwrap_or(0),
checksum: url(asset(&format!("{name}.sha256"))?)?,
})
})
.max_by_key(|r| r.version)
}
/// The first route's answer that comes.
async fn first<T, F: Future<Output = Result<T>>>(routes: &[Route], each: impl Fn(Route) -> F) -> Result<T> {
let mut last = None;
for route in routes {
match each(route.clone()).await {
Ok(v) => return Ok(v),
Err(e) => last = Some(e),
}
}
Err(last.unwrap_or_else(|| anyhow!("no way to reach the network")))
}
/// The newest release, if there is one newer than this.
pub async fn check(routes: &[Route]) -> Result<Option<Release>> {
let url = releases_url();
let body = first(routes, |r| {
let url = url.clone();
async move { fetch::get(&url, &r, 4 << 20).await }
})
.await
.context("the releases")?;
let list: Value = serde_json::from_slice(&body).context("the releases' listing")?;
Ok(newest(&list, Version::current(), &url))
}
/// The SHA-256 a `.sha256` file holds (`sha256sum`'s line).
fn published_sum(text: &[u8]) -> Result<String> {
let text = std::str::from_utf8(text).unwrap_or_default();
match text.split_whitespace().next() {
Some(h) if h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit()) => Ok(h.to_ascii_lowercase()),
_ => bail!("the published checksum does not read"),
}
}
/// The release's setup program in `dir` (older ones gone), once its SHA-256 matches.
async fn download(release: &Release, routes: &[Route], dir: &Path) -> Result<PathBuf> {
let sum = first(routes, |r| {
let url = release.checksum.clone();
async move { fetch::get(&url, &r, 4096).await }
})
.await
.context("the setup program's checksum")?;
let want = published_sum(&sum)?;
let body = first(routes, |r| {
let url = release.setup.clone();
async move { fetch::get_large(&url, &r, MAX_SETUP).await }
})
.await
.context("the setup program")?;
if crate::install::hex(&body) != want {
bail!("the setup program's SHA-256 is not the one published beside it");
}
std::fs::create_dir_all(dir)?;
for e in std::fs::read_dir(dir)?.flatten() {
let _ = std::fs::remove_file(e.path());
}
let path = dir.join(format!("ProxySuite-{}-windows-x64-setup.exe", release.version));
crate::paths::write_atomic(&path, &body).with_context(|| format!("writing {}", path.display()))?;
Ok(path)
}
/// What `install` leaves for the service that the setup starts: the version it went for.
const PENDING: &str = "pending";
/// Fetches the newest release's setup program and runs it, a moment after this returns (so
/// the caller hears of it before the setup stops the service).
pub async fn install(routes: &[Route], dir: &Path) -> Result<Release> {
if !begin() {
bail!("an update is under way already");
}
let r = async {
let release = check(routes).await?.ok_or_else(|| anyhow!("this is the newest release ({})", env!("CARGO_PKG_VERSION")))?;
tracing::info!("update: fetching {}", release.version);
let setup = download(&release, routes, dir).await?;
std::fs::write(dir.join(PENDING), release.version.to_string())?;
run_later(setup);
Ok(release)
}
.await;
if r.is_err() {
end();
}
r
}
fn run_later(setup: PathBuf) {
tokio::spawn(async move {
tokio::time::sleep(Duration::from_secs(1)).await;
tracing::info!("update: running {}", setup.display());
if let Err(e) = run(&setup) {
tracing::error!("update: {e:#}");
let _ = std::fs::remove_file(setup.with_file_name(PENDING));
end();
}
});
}
/// The setup, silent, on its own: out of any job this process is in, and of its console, as it
/// outlives the service it stops.
#[cfg(windows)]
fn run(setup: &Path) -> Result<()> {
use std::os::windows::process::CommandExt;
const DETACHED_PROCESS: u32 = 0x8;
const CREATE_NEW_PROCESS_GROUP: u32 = 0x200;
const CREATE_BREAKAWAY_FROM_JOB: u32 = 0x0100_0000;
let spawn = |flags: u32| {
std::process::Command::new(setup)
.arg("/S")
.current_dir(setup.parent().unwrap_or(Path::new(".")))
.creation_flags(flags)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
};
// A job that allows no breakaway refuses the flag; none to break away from ignores it.
spawn(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP | CREATE_BREAKAWAY_FROM_JOB)
.or_else(|_| spawn(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP))
.context("starting the setup program")?;
Ok(())
}
#[cfg(not(windows))]
fn run(setup: &Path) -> Result<()> {
bail!("{} is a Windows setup program; not run here", setup.display())
}
/// Said once in the log at start: whether the update `install` went for is the version now
/// running.
pub fn report(dir: &Path) {
let path = dir.join(PENDING);
let Ok(wanted) = std::fs::read_to_string(&path) else { return };
let _ = std::fs::remove_file(&path);
if wanted.trim() == env!("CARGO_PKG_VERSION") {
tracing::info!("updated to {}", env!("CARGO_PKG_VERSION"));
} else {
tracing::warn!("the update to {} did not finish; this is still {}", wanted.trim(), env!("CARGO_PKG_VERSION"));
}
}
#[cfg(test)]
mod tests {
use super::*;
fn v(s: &str) -> Version {
Version::parse(s).unwrap()
}
#[test]
fn versions_order_as_releases() {
assert!(v("0.3.0-pre.1") > v("0.2.0-pre.1"));
assert!(v("0.3.0-pre.2") > v("0.3.0-pre.1"));
assert!(v("0.3.0") > v("0.3.0-pre.9"));
assert!(v("0.10.0") > v("0.9.1"));
assert_eq!(v("1.2.3-pre.4").to_string(), "1.2.3-pre.4");
for bad in ["0.3", "0.3.0.1", "0.3.0-rc.1", "x.1.2", "0.3.0-pre."] {
assert_eq!(Version::parse(bad), None, "{bad}");
}
assert_eq!(Version::current().to_string(), env!("CARGO_PKG_VERSION"));
}
fn release(tag: &str, pre: bool, host: &str) -> Value {
let v = tag.trim_start_matches(TAG_PREFIX);
let name = format!("ProxySuite-{v}-windows-x64-setup.exe");
json!({
"tag_name": tag, "prerelease": pre, "draft": false, "body": "notes", "html_url": format!("{host}/r/{tag}"),
"assets": [
{ "name": name, "size": 5, "browser_download_url": format!("{host}/d/{tag}/{name}") },
{ "name": format!("{name}.sha256"), "size": 1, "browser_download_url": format!("{host}/d/{tag}/{name}.sha256") },
],
})
}
const HOME: &str = "https://git.example";
const LIST: &str = "https://git.example/api/v1/repos/o/r/releases?limit=30";
#[test]
fn the_newest_release_with_a_setup_program() {
let list = json!([release("windows-v0.3.0-pre.2", true, HOME), release("windows-v0.3.0-pre.1", true, HOME), release("v0.9.0", false, HOME)]);
let r = newest(&list, v("0.3.0-pre.1"), LIST).unwrap();
assert_eq!(r.version, v("0.3.0-pre.2"));
assert_eq!(r.setup, "https://git.example/d/windows-v0.3.0-pre.2/ProxySuite-0.3.0-pre.2-windows-x64-setup.exe");
assert!(r.checksum.ends_with(".exe.sha256"));
// Nothing newer.
assert_eq!(newest(&list, v("0.3.0-pre.2"), LIST), None);
// Who runs a release is not offered pre-releases, but a newer release.
assert_eq!(newest(&list, v("0.2.0"), LIST), None);
let list = json!([release("windows-v0.3.0-pre.2", true, HOME), release("windows-v0.2.1", false, HOME)]);
assert_eq!(newest(&list, v("0.2.0"), LIST).unwrap().version, v("0.2.1"));
assert_eq!(newest(&list, v("0.2.0-pre.1"), LIST).unwrap().version, v("0.3.0-pre.2"));
}
#[test]
fn drafts_strangers_and_releases_without_a_setup_are_passed_over() {
let mut draft = release("windows-v0.4.0", false, HOME);
draft["draft"] = true.into();
let elsewhere = release("windows-v0.5.0", false, "https://evil.example");
let mut zip_only = release("windows-v0.6.0", false, HOME);
zip_only["assets"].as_array_mut().unwrap().remove(0);
let mut no_sum = release("windows-v0.7.0", false, HOME);
no_sum["assets"].as_array_mut().unwrap().remove(1);
let list = json!([draft, elsewhere, zip_only, no_sum, release("windows-v0.3.1", false, HOME)]);
assert_eq!(newest(&list, v("0.3.0"), LIST).unwrap().version, v("0.3.1"));
// http is another origin than https.
let list = json!([release("windows-v0.3.1", false, "http://git.example")]);
assert_eq!(newest(&list, v("0.3.0"), LIST), None);
}
#[test]
fn origins_and_checksums_read() {
assert_eq!(origin("https://h.example:3000/a/b?c"), Some("https://h.example:3000"));
assert_eq!(origin("https://h.example?x"), Some("https://h.example"));
assert_eq!(origin("https://"), None);
let h = "3ff31008aa1d9f4e".repeat(4);
assert_eq!(published_sum(format!("{h} ProxySuite-0.2.0-pre.1-windows-x64-setup.exe\n").as_bytes()).unwrap(), h);
assert!(published_sum(b"not a sum").is_err());
}
}
+101 -3
View File
@@ -98,7 +98,12 @@ pub fn install() -> Result<()> {
}
if from != to {
desktop::close();
copy_release(&from, &to)?;
if let Err(e) = copy_release(&from, &to) {
// Unattended (an update), no one would start again what was running.
let _ = existing.start::<&str>(&[]);
desktop::start(&to);
return Err(e);
}
}
existing.change_config(&info)?;
existing
@@ -365,9 +370,102 @@ mod desktop {
Ok(true)
}
/// The app, as the signed-in user rather than as this elevated installer: Explorer starts it.
/// The app, as the signed-in user rather than as this elevated installer: Explorer starts
/// it. Run by the service (an update, as SYSTEM, in session 0, which no one sees), it is
/// started in each signed-in user's session as that user instead, as at their sign-in.
pub fn start(dir: &Path) {
let _ = Command::new("explorer.exe").arg(dir.join("proxy-suite.exe")).spawn();
let app = dir.join("proxy-suite.exe");
if session::own() == Some(0) {
session::start_for_each_user(&app);
} else {
let _ = Command::new("explorer.exe").arg(&app).spawn();
}
}
mod session {
use std::path::Path;
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
use windows_sys::Win32::System::Environment::{CreateEnvironmentBlock, DestroyEnvironmentBlock};
use windows_sys::Win32::System::RemoteDesktop::{
ProcessIdToSessionId, WTS_CURRENT_SERVER_HANDLE, WTS_SESSION_INFOW, WTSActive, WTSEnumerateSessionsW, WTSFreeMemory, WTSQueryUserToken,
};
use windows_sys::Win32::System::Threading::{
CREATE_UNICODE_ENVIRONMENT, CreateProcessAsUserW, GetCurrentProcessId, PROCESS_INFORMATION, STARTUPINFOW,
};
/// This process's session.
pub fn own() -> Option<u32> {
let mut id = 0u32;
// SAFETY: an out pointer to a u32.
(unsafe { ProcessIdToSessionId(GetCurrentProcessId(), &mut id) } != 0).then_some(id)
}
/// `app` in every session a user is signed in to and at (a console's, a remote
/// desktop's), with that user's token and environment.
pub fn start_for_each_user(app: &Path) {
let mut list: *mut WTS_SESSION_INFOW = std::ptr::null_mut();
let mut count = 0u32;
// SAFETY: out pointers; the list is freed below and read within `count`.
let sessions: Vec<u32> = unsafe {
if WTSEnumerateSessionsW(WTS_CURRENT_SERVER_HANDLE, 0, 1, &mut list, &mut count) == 0 {
return;
}
let ids = std::slice::from_raw_parts(list, count as usize).iter().filter(|s| s.State == WTSActive).map(|s| s.SessionId).collect();
WTSFreeMemory(list.cast());
ids
};
for id in sessions {
if let Err(e) = start_in(id, app) {
println!("warning: the app in session {id}: {e}");
}
}
}
fn start_in(session: u32, app: &Path) -> std::io::Result<()> {
let wide = |s: &str| s.encode_utf16().chain(Some(0)).collect::<Vec<u16>>();
let mut command = wide(&format!("\"{}\"", app.display()));
let dir = wide(&app.parent().unwrap_or(app).display().to_string());
let mut desktop = wide("winsta0\\default");
// SAFETY: the token and environment are released below; the strings are
// NUL-terminated and live across the call; the out structs are zeroed.
unsafe {
let mut token: HANDLE = std::ptr::null_mut();
if WTSQueryUserToken(session, &mut token) == 0 {
return Err(std::io::Error::last_os_error());
}
let mut env: *mut core::ffi::c_void = std::ptr::null_mut();
let have_env = CreateEnvironmentBlock(&mut env, token, 0) != 0;
let mut si: STARTUPINFOW = std::mem::zeroed();
si.cb = std::mem::size_of::<STARTUPINFOW>() as u32;
si.lpDesktop = desktop.as_mut_ptr();
let mut pi: PROCESS_INFORMATION = std::mem::zeroed();
let ok = CreateProcessAsUserW(
token,
std::ptr::null(),
command.as_mut_ptr(),
std::ptr::null(),
std::ptr::null(),
0,
CREATE_UNICODE_ENVIRONMENT,
if have_env { env } else { std::ptr::null() },
dir.as_ptr(),
&si,
&mut pi,
) != 0;
let err = std::io::Error::last_os_error();
if have_env {
DestroyEnvironmentBlock(env);
}
CloseHandle(token);
if !ok {
return Err(err);
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
Ok(())
}
}
pub fn remove() {