tauri_updater_private/lib.rs
1//! # tauri-updater-private
2//!
3//! Thin wrapper over the official [`tauri-plugin-updater`] that enables
4//! in-app updates for Tauri 2 applications distributed from **private
5//! GitHub repositories**.
6//!
7//! It configures the official updater plugin with an
8//! `Authorization: Bearer <token>` header, embedded into the binary at
9//! build time from the `UPDATER_GH_TOKEN` environment variable, plus an
10//! `Accept: application/octet-stream` header for private-repo asset
11//! downloads. The frontend keeps using the official
12//! `@tauri-apps/plugin-updater` JS API unchanged.
13//!
14//! See `DESIGN.md` for the full design rationale.
15//!
16//! [`tauri-plugin-updater`]: https://github.com/tauri-apps/plugins-workspace/tree/dev/plugins/updater
17
18/// Re-export of the official crate so apps can chain further official-builder
19/// calls (e.g. `pubkey`, `target`) without guessing version alignment.
20/// Note: apps must still depend on `tauri-plugin-updater` directly — plugin
21/// permissions (ACL) are collected from direct dependencies only.
22pub use tauri_plugin_updater;
23
24/// Errors returned when presetting the Authorization header fails.
25#[derive(Debug, thiserror::Error)]
26pub enum Error {
27 /// `UPDATER_GH_TOKEN` was absent or empty when the crate was compiled,
28 /// and no explicit token was provided.
29 #[error(
30 "UPDATER_GH_TOKEN was not set (or was empty) at build time; set it in your release \
31 environment, or pass a token explicitly via TauriUpdaterPrivateBuilder::token()"
32 )]
33 MissingToken,
34 /// The preset Authorization header was rejected by the official updater
35 /// builder (e.g. the token contains characters illegal in a header value).
36 #[error(transparent)]
37 Header(#[from] tauri_plugin_updater::Error),
38}
39
40/// Convenience alias used by this crate's public API.
41pub type Result<T> = std::result::Result<T, Error>;
42
43/// Returns the official updater [`tauri_plugin_updater::Builder`] with the
44/// `Authorization: Bearer <token>` header preset from the compile-time
45/// `UPDATER_GH_TOKEN`, plus `Accept: application/octet-stream`.
46///
47/// # Errors
48///
49/// Returns [`Error::MissingToken`] when the variable was absent or empty at
50/// build time — a runtime error (not `compile_error!`) so builds without the
51/// updater configured, e.g. local dev, still compile.
52///
53/// # Examples
54///
55/// ```no_run
56/// # fn main() -> tauri_updater_private::Result<()> {
57/// let builder = tauri_updater_private::updater_builder()?;
58/// # Ok(())
59/// # }
60/// ```
61pub fn updater_builder() -> Result<tauri_plugin_updater::Builder> {
62 match option_env!("UPDATER_GH_TOKEN") {
63 Some(token) if !token.is_empty() => TauriUpdaterPrivateBuilder::new()
64 .token(token)
65 .updater_builder(),
66 _ => Err(Error::MissingToken),
67 }
68}
69
70/// Builder for apps that supply the token explicitly (tests, non-CI builds)
71/// instead of embedding it from the compile-time environment.
72///
73/// # Examples
74///
75/// ```no_run
76/// # fn main() -> tauri_updater_private::Result<()> {
77/// let builder = tauri_updater_private::TauriUpdaterPrivateBuilder::new()
78/// .token("personal-access-token")
79/// .updater_builder()?;
80/// # Ok(())
81/// # }
82/// ```
83#[derive(Default)]
84pub struct TauriUpdaterPrivateBuilder {
85 token: Option<String>,
86}
87
88// Why: manual Debug so debug-printing the builder never reveals the token
89// (DESIGN.md §5: the crate must not expose the token), unlike a derived impl.
90impl std::fmt::Debug for TauriUpdaterPrivateBuilder {
91 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92 f.debug_struct("TauriUpdaterPrivateBuilder")
93 .field("token", &self.token.as_ref().map(|_| "<redacted>"))
94 .finish()
95 }
96}
97
98impl TauriUpdaterPrivateBuilder {
99 /// Creates a builder with no token set.
100 pub fn new() -> Self {
101 Self::default()
102 }
103
104 /// Sets the token to embed into the `Authorization` header.
105 /// An empty token is treated as missing and rejected at [`Self::updater_builder`].
106 pub fn token(mut self, token: impl Into<String>) -> Self {
107 self.token = Some(token.into());
108 self
109 }
110
111 /// Returns the official updater [`tauri_plugin_updater::Builder`] with
112 /// the `Authorization` and `Accept: application/octet-stream` headers
113 /// preset.
114 ///
115 /// # Errors
116 ///
117 /// Returns [`Error::MissingToken`] when no non-empty token was set, and
118 /// [`Error::Header`] when the token is not a legal header value.
119 pub fn updater_builder(self) -> Result<tauri_plugin_updater::Builder> {
120 let token = self
121 .token
122 .filter(|token| !token.is_empty())
123 .ok_or(Error::MissingToken)?;
124 // Why: github.com/<owner>/<repo>/releases/download/... does NOT honor
125 // Authorization on private repos (browser cookies only) — the request
126 // 404s. The manifest must come from raw.githubusercontent.com (serves
127 // the body regardless of Accept) and the package from the
128 // api.github.com releases/assets endpoint, which only returns the
129 // binary (302 to a signed URL) with this Accept header — with
130 // application/vnd.github.raw it returns the asset metadata JSON
131 // instead, which breaks signature verification.
132 Ok(tauri_plugin_updater::Builder::default()
133 .header("authorization", format!("Bearer {token}"))?
134 .header("accept", "application/octet-stream")?)
135 }
136}
137
138#[cfg(test)]
139mod tests {
140 use super::*;
141
142 #[test]
143 fn builder_without_token_is_missing_token_error() {
144 assert!(matches!(
145 TauriUpdaterPrivateBuilder::new().updater_builder(),
146 Err(Error::MissingToken)
147 ));
148 }
149
150 #[test]
151 fn empty_token_is_missing_token_error() {
152 assert!(matches!(
153 TauriUpdaterPrivateBuilder::new()
154 .token("")
155 .updater_builder(),
156 Err(Error::MissingToken)
157 ));
158 }
159
160 #[test]
161 fn valid_token_returns_builder() {
162 assert!(TauriUpdaterPrivateBuilder::new()
163 .token("ghp_test_token")
164 .updater_builder()
165 .is_ok());
166 }
167
168 #[test]
169 fn invalid_header_token_is_header_error() {
170 // '\n' is illegal in an HTTP header value: proves the token flows into
171 // the preset Authorization header (the official Builder has no getter).
172 assert!(matches!(
173 TauriUpdaterPrivateBuilder::new()
174 .token("bad\ntoken")
175 .updater_builder(),
176 Err(Error::Header(_))
177 ));
178 }
179
180 #[test]
181 fn debug_output_masks_token() {
182 let builder = TauriUpdaterPrivateBuilder::new().token("ghp_secret");
183 let debug = format!("{builder:?}");
184 assert!(
185 !debug.contains("ghp_secret"),
186 "token leaked in Debug: {debug}"
187 );
188 assert!(debug.contains("<redacted>"));
189 }
190
191 #[test]
192 fn free_function_without_env_is_missing_token_error() {
193 // The compile-time token is baked in; only assert when it was absent
194 // or empty so this test passes in both build contexts.
195 if option_env!("UPDATER_GH_TOKEN").map_or(true, |token| token.is_empty()) {
196 assert!(matches!(updater_builder(), Err(Error::MissingToken)));
197 }
198 }
199}