Add signed launcher self-updates and publish Linux 0.1.3

This commit is contained in:
Emil
2026-09-10 02:47:16 +03:00
parent bf43254c57
commit bb4b1f8051
55 changed files with 6286 additions and 43 deletions
+212
View File
@@ -0,0 +1,212 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{Result, Update, UpdaterExt};
use http::{HeaderMap, HeaderName, HeaderValue};
use serde::Serialize;
use tauri::{ipc::Channel, Manager, Resource, ResourceId, Runtime, Webview};
use std::{str::FromStr, time::Duration};
use url::Url;
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "event", content = "data")]
pub enum DownloadEvent {
#[serde(rename_all = "camelCase")]
Started {
content_length: Option<u64>,
},
#[serde(rename_all = "camelCase")]
Progress {
chunk_length: usize,
},
Finished,
}
#[derive(Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub(crate) struct Metadata {
rid: ResourceId,
current_version: String,
version: String,
date: Option<String>,
body: Option<String>,
raw_json: serde_json::Value,
}
struct DownloadedBytes(pub Vec<u8>);
impl Resource for DownloadedBytes {}
#[tauri::command]
pub(crate) async fn check<R: Runtime>(
webview: Webview<R>,
headers: Option<Vec<(String, String)>>,
timeout: Option<u64>,
proxy: Option<String>,
target: Option<String>,
allow_downgrades: Option<bool>,
) -> Result<Option<Metadata>> {
let mut builder = webview.updater_builder();
if let Some(headers) = headers {
for (k, v) in headers {
builder = builder.header(k, v)?;
}
}
if let Some(timeout) = timeout {
builder = builder.timeout(Duration::from_millis(timeout));
}
if let Some(ref proxy) = proxy {
let url = Url::parse(proxy.as_str())?;
builder = builder.proxy(url);
}
if let Some(target) = target {
builder = builder.target(target);
}
if allow_downgrades.unwrap_or(false) {
builder = builder.version_comparator(|current, update| update.version != current);
}
let updater = builder.build()?;
let update = updater.check().await?;
if let Some(update) = update {
let formatted_date = if let Some(date) = update.date {
let formatted_date = date
.format(&time::format_description::well_known::Rfc3339)
.map_err(|_| crate::Error::FormatDate)?;
Some(formatted_date)
} else {
None
};
let metadata = Metadata {
current_version: update.current_version.clone(),
version: update.version.clone(),
date: formatted_date,
body: update.body.clone(),
raw_json: update.raw_json.clone(),
rid: webview.resources_table().add(update),
};
Ok(Some(metadata))
} else {
Ok(None)
}
}
#[tauri::command]
pub(crate) async fn download<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
on_event: Channel<DownloadEvent>,
headers: Option<Vec<(String, String)>>,
timeout: Option<u64>,
) -> Result<ResourceId> {
let update = webview.resources_table().get::<Update>(rid)?;
let mut update = (*update).clone();
if let Some(headers) = headers {
let mut map = HeaderMap::new();
for (k, v) in headers {
map.append(HeaderName::from_str(&k)?, HeaderValue::from_str(&v)?);
}
update.headers = map;
}
if let Some(timeout) = timeout {
update.timeout = Some(Duration::from_millis(timeout));
}
let mut first_chunk = true;
let bytes = update
.download(
|chunk_length, content_length| {
if first_chunk {
first_chunk = !first_chunk;
let _ = on_event.send(DownloadEvent::Started { content_length });
}
let _ = on_event.send(DownloadEvent::Progress { chunk_length });
},
|| {
let _ = on_event.send(DownloadEvent::Finished);
},
)
.await?;
Ok(webview.resources_table().add(DownloadedBytes(bytes)))
}
#[tauri::command]
pub(crate) async fn install<R: Runtime>(
webview: Webview<R>,
update_rid: ResourceId,
bytes_rid: ResourceId,
restart_after_install: Option<bool>,
) -> Result<()> {
let update = webview.resources_table().get::<Update>(update_rid)?;
let bytes = webview
.resources_table()
.get::<DownloadedBytes>(bytes_rid)?;
if let Some(restart_after_install) = restart_after_install {
let update = (*update).clone();
update
.restart_after_install(restart_after_install)
.install(&bytes.0)?;
} else {
update.install(&bytes.0)?;
}
let _ = webview.resources_table().close(bytes_rid);
Ok(())
}
#[tauri::command]
pub(crate) async fn download_and_install<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
on_event: Channel<DownloadEvent>,
headers: Option<Vec<(String, String)>>,
timeout: Option<u64>,
restart_after_install: Option<bool>,
) -> Result<()> {
let update = webview.resources_table().get::<Update>(rid)?;
let mut update = (*update).clone();
if let Some(headers) = headers {
let mut map = HeaderMap::new();
for (k, v) in headers {
map.append(HeaderName::from_str(&k)?, HeaderValue::from_str(&v)?);
}
update.headers = map;
}
if let Some(timeout) = timeout {
update.timeout = Some(Duration::from_millis(timeout));
}
if let Some(restart_after_install) = restart_after_install {
update = update.restart_after_install(restart_after_install);
}
let mut first_chunk = true;
update
.download_and_install(
|chunk_length, content_length| {
if first_chunk {
first_chunk = !first_chunk;
let _ = on_event.send(DownloadEvent::Started { content_length });
}
let _ = on_event.send(DownloadEvent::Progress { chunk_length });
},
|| {
let _ = on_event.send(DownloadEvent::Finished);
},
)
.await?;
Ok(())
}
+179
View File
@@ -0,0 +1,179 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{ffi::OsString, fmt::Display};
use serde::{Deserialize, Deserializer};
use url::Url;
/// Install modes for the Windows update.
#[derive(Debug, PartialEq, Eq, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
#[derive(Default)]
pub enum WindowsUpdateInstallMode {
/// Specifies there's a basic UI during the installation process, including a final dialog box at the end.
BasicUi,
/// The quiet mode means there's no user interaction required.
/// Requires admin privileges if the installer does.
Quiet,
/// Specifies unattended mode, which means the installation only shows a progress bar.
#[default]
Passive,
}
impl WindowsUpdateInstallMode {
/// Returns the associated `msiexec.exe` arguments.
pub fn msiexec_args(&self) -> &'static [&'static str] {
match self {
Self::BasicUi => &["/qb+"],
Self::Quiet => &["/quiet"],
Self::Passive => &["/passive"],
}
}
#[cfg(windows)]
pub(crate) fn msi_restart_after_install_args(&self) -> &'static [&'static str] {
&["AUTOLAUNCHAPP=True"]
}
/// Returns the associated nsis arguments.
pub fn nsis_args(&self) -> &'static [&'static str] {
// `/P`: Passive
// `/S`: Silent
// `/R`: Restart
match self {
Self::Passive => &["/P"],
Self::Quiet => &["/S"],
_ => &[],
}
}
#[cfg(windows)]
pub(crate) fn nsis_restart_after_install_args(&self) -> &'static [&'static str] {
match self {
Self::BasicUi => &[],
_ => &["/R"],
}
}
}
impl Display for WindowsUpdateInstallMode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Self::BasicUi => "basicUi",
Self::Quiet => "quiet",
Self::Passive => "passive",
}
)
}
}
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct WindowsConfig {
/// Additional arguments given to the NSIS or WiX installer.
///
/// Note: this applies to both WiX and NSIS installers
#[serde(
default,
alias = "installer-args",
deserialize_with = "deserialize_os_string"
)]
pub installer_args: Vec<OsString>,
/// Updating mode, defaults to `passive` mode.
///
/// See [`WindowsUpdateInstallMode`] for more info.
#[serde(default, alias = "install-mode")]
pub install_mode: WindowsUpdateInstallMode,
}
fn deserialize_os_string<'de, D>(deserializer: D) -> Result<Vec<OsString>, D::Error>
where
D: Deserializer<'de>,
{
Ok(Vec::<String>::deserialize(deserializer)?
.into_iter()
.map(OsString::from)
.collect::<Vec<_>>())
}
/// Updater configuration.
#[derive(Debug, Clone, Default)]
pub struct Config {
/// Dangerously allow using insecure transport protocols for update endpoints.
pub dangerous_insecure_transport_protocol: bool,
/// Dangerously accept invalid TLS certificates for update requests.
pub dangerous_accept_invalid_certs: bool,
/// Dangerously accept invalid hostnames for TLS certificates for update requests.
pub dangerous_accept_invalid_hostnames: bool,
/// Updater endpoints.
pub endpoints: Vec<Url>,
/// Signature public key.
pub pubkey: String,
/// The Windows configuration for the updater.
pub windows: Option<WindowsConfig>,
}
impl<'de> Deserialize<'de> for Config {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Config {
#[serde(default, alias = "dangerous-insecure-transport-protocol")]
pub dangerous_insecure_transport_protocol: bool,
#[serde(default, alias = "dangerous-accept-invalid-certs")]
pub dangerous_accept_invalid_certs: bool,
#[serde(default, alias = "dangerous-accept-invalid-hostnames")]
pub dangerous_accept_invalid_hostnames: bool,
#[serde(default)]
pub endpoints: Vec<Url>,
pub pubkey: String,
pub windows: Option<WindowsConfig>,
}
let config = Config::deserialize(deserializer)?;
validate_endpoints(
&config.endpoints,
config.dangerous_insecure_transport_protocol,
)
.map_err(serde::de::Error::custom)?;
Ok(Self {
dangerous_insecure_transport_protocol: config.dangerous_insecure_transport_protocol,
dangerous_accept_invalid_certs: config.dangerous_accept_invalid_certs,
dangerous_accept_invalid_hostnames: config.dangerous_accept_invalid_hostnames,
endpoints: config.endpoints,
pubkey: config.pubkey,
windows: config.windows,
})
}
}
pub(crate) fn validate_endpoints(
endpoints: &[Url],
dangerous_insecure_transport_protocol: bool,
) -> crate::Result<()> {
if !dangerous_insecure_transport_protocol {
for url in endpoints {
if url.scheme() != "https" {
#[cfg(debug_assertions)]
{
eprintln!("[\x1b[33mWARNING\x1b[0m] The updater endpoint \"{url}\" doesn't use `https` protocol. This is allowed in development but will fail in release builds.");
eprintln!("[\x1b[33mWARNING\x1b[0m] if this is a desired behavior, you can enable `dangerousInsecureTransportProtocol` in the plugin configuration");
}
#[cfg(not(debug_assertions))]
return Err(crate::Error::InsecureTransportProtocol);
}
}
}
Ok(())
}
+105
View File
@@ -0,0 +1,105 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use serde::{Serialize, Serializer};
use thiserror::Error;
/// All errors that can occur while running the updater.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum Error {
/// Endpoints are not sent.
#[error("Updater does not have any endpoints set.")]
EmptyEndpoints,
/// IO errors.
#[error(transparent)]
Io(#[from] std::io::Error),
/// Semver errors.
#[error(transparent)]
Semver(#[from] semver::Error),
/// Serialization errors.
#[error(transparent)]
Serialization(#[from] serde_json::Error),
/// Could not fetch a valid response from the server.
#[error("Could not fetch a valid release JSON from the remote")]
ReleaseNotFound,
/// Unsupported app architecture.
#[error("Unsupported application architecture, expected one of `x86`, `x86_64`, `arm` or `aarch64`.")]
UnsupportedArch,
/// Operating system is not supported.
#[error("Unsupported OS, expected one of `linux`, `darwin` or `windows`.")]
UnsupportedOs,
/// Failed to determine updater package extract path
#[error("Failed to determine updater package extract path.")]
FailedToDetermineExtractPath,
/// Url parsing errors.
#[error(transparent)]
UrlParse(#[from] url::ParseError),
/// `reqwest` crate errors.
#[error(transparent)]
Reqwest(#[from] reqwest::Error),
/// The platform was not found in the updater JSON response.
#[error("the platform `{0}` was not found in the response `platforms` object")]
TargetNotFound(String),
/// Neither the platform nor the fallback platform was found in the updater JSON response.
#[error(
"None of the fallback platforms `{0:?}` were found in the response `platforms` object"
)]
TargetsNotFound(Vec<String>),
/// Download failed
#[error("`{0}`")]
Network(String),
/// `minisign_verify` errors.
#[error(transparent)]
Minisign(#[from] minisign_verify::Error),
/// `base64` errors.
#[error(transparent)]
Base64(#[from] base64::DecodeError),
/// UTF8 Errors in signature.
#[error("The signature {0} could not be decoded, please check if it is a valid base64 string. The signature must be the contents of the `.sig` file generated by the Tauri bundler, as a string.")]
SignatureUtf8(String),
#[cfg(all(target_os = "windows", feature = "zip"))]
/// `zip` errors.
#[error(transparent)]
Extract(#[from] zip::result::ZipError),
/// Temp dir is not on same mount mount. This prevents our updater to rename the AppImage to a temp file.
#[error("temp directory is not on the same mount point as the AppImage")]
TempDirNotOnSameMountPoint,
#[error("binary for the current target not found in the archive")]
BinaryNotFoundInArchive,
#[error("failed to create temporary directory")]
TempDirNotFound,
#[error("Authentication failed or was cancelled")]
AuthenticationFailed,
#[error("Failed to install .deb package")]
DebInstallFailed,
#[error("Failed to install package")]
PackageInstallFailed,
#[error("invalid updater binary format")]
InvalidUpdaterFormat,
#[error(transparent)]
Http(#[from] http::Error),
#[error(transparent)]
InvalidHeaderValue(#[from] http::header::InvalidHeaderValue),
#[error(transparent)]
InvalidHeaderName(#[from] http::header::InvalidHeaderName),
#[error("Failed to format date")]
FormatDate,
/// The configured updater endpoint must use a secure protocol like `https`
#[error("The configured updater endpoint must use a secure protocol like `https`.")]
InsecureTransportProtocol,
#[error(transparent)]
Tauri(#[from] tauri::Error),
}
impl Serialize for Error {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.to_string().as_ref())
}
}
pub type Result<T> = std::result::Result<T, Error>;
+248
View File
@@ -0,0 +1,248 @@
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! In-app updates for Tauri applications.
//!
//! Supported platforms: Windows, Linux and macOS.
//!
//! ## Cargo features
//!
//! - **zip** *(enabled by default)*: Adds support for compressed updater bundles from Tauri v1.
//! - **rustls-tls** *(enabled by default)*: Enables TLS functionality provided by `rustls`.
//! - **native-tls**: Enables TLS functionality provided by `native-tls`.
//! - **native-tls-vendored**: Enables the `vendored` feature of `native-tls`.
//! - **system-proxy** *(enabled by default)*: Use Windows and macOS system proxy settings automatically.
#![doc(
html_logo_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png",
html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png"
)]
use std::{ffi::OsString, sync::Arc};
use http::{HeaderMap, HeaderName, HeaderValue};
use semver::Version;
use tauri::{
plugin::{Builder as PluginBuilder, TauriPlugin},
Manager, Runtime,
};
mod commands;
mod config;
mod error;
mod updater;
pub use config::Config;
pub use error::{Error, Result};
pub use updater::*;
/// Extensions to [`tauri::App`], [`tauri::AppHandle`], [`tauri::WebviewWindow`], [`tauri::Webview`] and [`tauri::Window`] to access the updater APIs.
pub trait UpdaterExt<R: Runtime> {
/// Gets the updater builder to build and updater
/// that can manually check if an update is available.
///
/// # Examples
///
/// ```no_run
/// use tauri_plugin_updater::UpdaterExt;
/// tauri::Builder::default()
/// .setup(|app| {
/// let handle = app.handle().clone();
/// tauri::async_runtime::spawn(async move {
/// let response = handle.updater_builder().build().unwrap().check().await;
/// });
/// Ok(())
/// });
/// ```
fn updater_builder(&self) -> UpdaterBuilder;
/// Gets the updater to manually check if an update is available.
///
/// # Examples
///
/// ```no_run
/// use tauri_plugin_updater::UpdaterExt;
/// tauri::Builder::default()
/// .setup(|app| {
/// let handle = app.handle().clone();
/// tauri::async_runtime::spawn(async move {
/// let response = handle.updater().unwrap().check().await;
/// });
/// Ok(())
/// });
/// ```
fn updater(&self) -> Result<Updater>;
}
impl<R: Runtime, T: Manager<R>> UpdaterExt<R> for T {
fn updater_builder(&self) -> UpdaterBuilder {
let app = self.app_handle();
let UpdaterState {
config,
target,
version_comparator,
headers,
} = self.state::<UpdaterState>().inner();
let mut builder = UpdaterBuilder::new(app, config.clone()).headers(headers.clone());
if let Some(target) = target {
builder = builder.target(target);
}
#[cfg(windows)]
{
builder = builder.current_exe_args(self.env().args_os);
}
builder.version_comparator = version_comparator.clone();
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
{
let env = app.env();
if let Some(appimage) = env.appimage {
builder = builder.executable_path(appimage);
}
}
let app_handle = app.app_handle().clone();
builder = builder.on_before_exit(move || {
app_handle.cleanup_before_exit();
});
builder
}
fn updater(&self) -> Result<Updater> {
self.updater_builder().build()
}
}
struct UpdaterState {
target: Option<String>,
config: Config,
version_comparator: Option<VersionComparator>,
headers: HeaderMap,
}
#[derive(Default)]
pub struct Builder {
target: Option<String>,
pubkey: Option<String>,
installer_args: Vec<OsString>,
headers: HeaderMap,
default_version_comparator: Option<VersionComparator>,
}
impl Builder {
pub fn new() -> Self {
Self::default()
}
pub fn target(mut self, target: impl Into<String>) -> Self {
self.target.replace(target.into());
self
}
pub fn pubkey<S: Into<String>>(mut self, pubkey: S) -> Self {
self.pubkey.replace(pubkey.into());
self
}
/// Adds an additional argument to pass to the Windows installer.
pub fn installer_args<I, S>(mut self, args: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<OsString>,
{
self.installer_args.extend(args.into_iter().map(Into::into));
self
}
/// Adds multiple additional arguments to pass to the Windows installer.
pub fn installer_arg<S>(mut self, arg: S) -> Self
where
S: Into<OsString>,
{
self.installer_args.push(arg.into());
self
}
/// Removes all the additional arguments to pass to the Windows installer.
///
/// Note: this only removes the additional arguments added through [`Self::installer_args`],
/// not the ones managed by us (e.g. `/UPDATER` flag passed to the NSIS installer)
pub fn clear_installer_args(mut self) -> Self {
self.installer_args.clear();
self
}
pub fn header<K, V>(mut self, key: K, value: V) -> Result<Self>
where
HeaderName: TryFrom<K>,
<HeaderName as TryFrom<K>>::Error: Into<http::Error>,
HeaderValue: TryFrom<V>,
<HeaderValue as TryFrom<V>>::Error: Into<http::Error>,
{
let key: std::result::Result<HeaderName, http::Error> = key.try_into().map_err(Into::into);
let value: std::result::Result<HeaderValue, http::Error> =
value.try_into().map_err(Into::into);
self.headers.insert(key?, value?);
Ok(self)
}
pub fn headers(mut self, headers: HeaderMap) -> Self {
self.headers = headers;
self
}
pub fn default_version_comparator<
F: Fn(Version, RemoteRelease) -> bool + Send + Sync + 'static,
>(
mut self,
f: F,
) -> Self {
self.default_version_comparator.replace(Arc::new(f));
self
}
pub fn build<R: Runtime>(self) -> TauriPlugin<R, Config> {
let pubkey = self.pubkey;
let target = self.target;
let version_comparator = self.default_version_comparator;
let installer_args = self.installer_args;
let headers = self.headers;
PluginBuilder::<R, Config>::new("updater")
.setup(move |app, api| {
let mut config = api.config().clone();
if let Some(pubkey) = pubkey {
config.pubkey = pubkey;
}
if let Some(windows) = &mut config.windows {
windows.installer_args.extend(installer_args);
}
app.manage(UpdaterState {
target,
config,
version_comparator,
headers,
});
Ok(())
})
.invoke_handler(tauri::generate_handler![
commands::check,
commands::download,
commands::install,
commands::download_and_install,
])
.build()
}
}
File diff suppressed because it is too large Load Diff