okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-027-gh-app: GitHub app and Terminal items for 0.2.73cabb9e3f

main
12.2 KiB288 linesraw
1//! The shell's half of the app update: Tauri's signed updater behind a loopback bridge for the App Host.
2//!
3//! The UI is served by the App Host, so it cannot call Tauri's updater plugin; and the host is Node, which has no updater.
4//! The shell therefore opens one loopback listener, protected by a random token it hands only to the host it started
5//! (`STRATA_SHELL_BRIDGE`, `STRATA_SHELL_TOKEN`), and the host's `app-updater.mjs` talks to it:
6//!
7//!   GET  /app-update/check    -> { available, version, current, notes }   (signature-verified metadata from the feed)
8//!   POST /app-update/install  -> starts download + install in the background
9//!   GET  /app-update/status   -> { state: idle|downloading|installing|done|error, downloaded, total, version, error }
10//!
11//! The update itself is Tauri's: it downloads the installer, checks its minisign signature against the public key in
12//! `tauri.conf.json` (`plugins.updater.pubkey`, the owner's separate updater key) and installs. A check or an install happens
13//! only when the user presses "Check for updates" / "Update Strata"; nothing here runs on start, and nothing here touches
14//! engines or models (those are Control's component updater: `strata update`).
15
16use std::io::{Read, Write};
17use std::net::{TcpListener, TcpStream};
18use std::sync::{Arc, Mutex};
19use std::time::Duration;
20
21use tauri::AppHandle;
22use tauri_plugin_updater::UpdaterExt;
23
24/// Where an endpoint other than the one in `tauri.conf.json` may come from: a local test feed. Only loopback or https.
25const ENDPOINT_ENV: &str = "STRATA_UPDATE_APP_ENDPOINT";
26
27#[derive(Clone, Default)]
28struct Progress {
29    state: &'static str,
30    downloaded: u64,
31    total: u64,
32    version: Option<String>,
33    error: Option<String>,
34}
35
36impl Progress {
37    fn json(&self) -> serde_json::Value {
38        serde_json::json!({
39            "state": if self.state.is_empty() { "idle" } else { self.state },
40            "downloaded": self.downloaded, "total": self.total, "version": self.version, "error": self.error,
41        })
42    }
43}
44
45/// What the host needs to find the bridge.
46pub struct Bridge {
47    pub url: String,
48    pub token: String,
49}
50
51fn endpoint_override() -> Option<String> {
52    let url = std::env::var(ENDPOINT_ENV).ok()?;
53    if url.starts_with("https://") || url.starts_with("http://127.0.0.1:") || url.starts_with("http://localhost:") {
54        Some(url)
55    } else {
56        None
57    }
58}
59
60fn updater_for(app: &AppHandle) -> Result<tauri_plugin_updater::Updater, String> {
61    match endpoint_override() {
62        Some(url) => {
63            let url: tauri::Url = url.parse().map_err(|e| format!("bad update endpoint: {e}"))?;
64            app.updater_builder().endpoints(vec![url]).map_err(|e| e.to_string())?.build().map_err(|e| e.to_string())
65        }
66        None => app.updater().map_err(|e| e.to_string()),
67    }
68}
69
70async fn check(app: &AppHandle) -> Result<serde_json::Value, String> {
71    let updater = updater_for(app)?;
72    match updater.check().await.map_err(|e| e.to_string())? {
73        Some(update) => Ok(serde_json::json!({
74            "available": true, "version": update.version, "current": update.current_version, "notes": update.body,
75        })),
76        None => Ok(serde_json::json!({ "available": false, "current": app.package_info().version.to_string() })),
77    }
78}
79
80async fn install(app: AppHandle, progress: Arc<Mutex<Progress>>) {
81    let fail = |message: String| {
82        let mut p = progress.lock().unwrap();
83        p.state = "error";
84        p.error = Some(message);
85    };
86    let updater = match updater_for(&app) {
87        Ok(u) => u,
88        Err(e) => return fail(e),
89    };
90    let update = match updater.check().await {
91        Ok(Some(update)) => update,
92        Ok(None) => return fail("There is no newer version of the Strata app.".into()),
93        Err(e) => return fail(e.to_string()),
94    };
95    {
96        let mut p = progress.lock().unwrap();
97        *p = Progress { state: "downloading", version: Some(update.version.clone()), ..Default::default() };
98    }
99    let on_chunk = {
100        let progress = progress.clone();
101        move |chunk: usize, total: Option<u64>| {
102            let mut p = progress.lock().unwrap();
103            p.downloaded += chunk as u64;
104            p.total = total.unwrap_or(p.total);
105        }
106    };
107    let on_finish = {
108        let progress = progress.clone();
109        move || progress.lock().unwrap().state = "installing"
110    };
111    // Tauri checks the installer's minisign signature when it downloads it. Installing is done here, not by the plugin's
112    // download_and_install: on Windows this app lives in a kill-on-close Job Object, and an installer the plugin starts is in
113    // that job, so it is ended the moment the app exits and the update never happens. `launch_installer` starts it outside
114    // the job; the app then exits and the installer (passive: a progress window, no questions) replaces it and starts it again.
115    let bytes = match update.download(on_chunk, on_finish).await {
116        Ok(bytes) => bytes,
117        Err(e) => return fail(e.to_string()),
118    };
119    progress.lock().unwrap().state = "installing";
120    match launch_installer(&update.version, &bytes) {
121        Ok(()) => {
122            progress.lock().unwrap().state = "done";
123            app.exit(0);
124        }
125        Err(first) => match update.install(&bytes) {
126            Ok(()) => {
127                progress.lock().unwrap().state = "done";
128                app.restart();
129            }
130            Err(e) => fail(format!("{first}; {e}")),
131        },
132    }
133}
134
135/// Windows: write the verified installer to a temp folder and start it detached and outside the app's Job Object.
136#[cfg(windows)]
137fn launch_installer(version: &str, bytes: &[u8]) -> Result<(), String> {
138    use std::os::windows::process::CommandExt;
139    const CREATE_BREAKAWAY_FROM_JOB: u32 = 0x0100_0000;
140    const DETACHED_PROCESS: u32 = 0x0000_0008;
141    let dir = std::env::temp_dir().join(format!("strata-app-update-{version}"));
142    std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
143    let installer = dir.join("installer.exe");
144    std::fs::write(&installer, bytes).map_err(|e| e.to_string())?;
145    std::process::Command::new(&installer)
146        .args(["/P", "/R", "/UPDATE"])
147        .creation_flags(CREATE_BREAKAWAY_FROM_JOB | DETACHED_PROCESS)
148        .spawn()
149        .map(|_| ())
150        .map_err(|e| format!("could not start the installer outside the app: {e}"))
151}
152
153/// Elsewhere the plugin's own install is used (the installer replaces the app in place).
154#[cfg(not(windows))]
155fn launch_installer(_version: &str, _bytes: &[u8]) -> Result<(), String> {
156    Err("not Windows".into())
157}
158
159fn respond(stream: &mut TcpStream, status: &str, body: &serde_json::Value) {
160    let text = body.to_string();
161    let _ = stream.write_all(
162        format!(
163            "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{text}",
164            text.len()
165        )
166        .as_bytes(),
167    );
168}
169
170fn same(a: &str, b: &str) -> bool {
171    a.len() == b.len() && a.bytes().zip(b.bytes()).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
172}
173
174fn handle(mut stream: TcpStream, app: &AppHandle, token: &str, progress: &Arc<Mutex<Progress>>) {
175    let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
176    let mut buf = Vec::new();
177    let mut chunk = [0u8; 1024];
178    while !buf.windows(4).any(|w| w == b"\r\n\r\n") && buf.len() < 8192 {
179        match stream.read(&mut chunk) {
180            Ok(0) | Err(_) => break,
181            Ok(n) => buf.extend_from_slice(&chunk[..n]),
182        }
183    }
184    let head = String::from_utf8_lossy(&buf).to_string();
185    let mut lines = head.lines();
186    let request = lines.next().unwrap_or_default().to_string();
187    let supplied = lines
188        .find_map(|l| l.strip_prefix("authorization: ").or_else(|| l.strip_prefix("Authorization: ")))
189        .map(|v| v.trim().trim_start_matches("Bearer ").to_string())
190        .unwrap_or_default();
191    if !same(&supplied, token) {
192        return respond(&mut stream, "401 Unauthorized", &serde_json::json!({ "error": "not allowed" }));
193    }
194    let mut parts = request.split_whitespace();
195    let (method, path) = (parts.next().unwrap_or(""), parts.next().unwrap_or(""));
196    match (method, path) {
197        ("GET", "/app-update/check") => match tauri::async_runtime::block_on(check(app)) {
198            Ok(value) => respond(&mut stream, "200 OK", &value),
199            Err(e) => respond(&mut stream, "502 Bad Gateway", &serde_json::json!({ "error": e })),
200        },
201        ("POST", "/app-update/install") => {
202            {
203                let mut p = progress.lock().unwrap();
204                if p.state == "downloading" || p.state == "installing" {
205                    return respond(&mut stream, "409 Conflict", &serde_json::json!({ "error": "An app update is already running." }));
206                }
207                *p = Progress { state: "downloading", ..Default::default() };
208            }
209            tauri::async_runtime::spawn(install(app.clone(), progress.clone()));
210            respond(&mut stream, "202 Accepted", &progress.lock().unwrap().json());
211        }
212        ("GET", "/app-update/status") => respond(&mut stream, "200 OK", &progress.lock().unwrap().json()),
213        // The host asks for a desktop notification (an approval is waiting): title and body are in the query, bounded and cleaned here.
214        ("POST", p) if p.starts_with("/shell/notify") => {
215            let title = crate::shell::clean_text(&crate::shell::query_value(p, "title").unwrap_or_default(), 120);
216            let body = crate::shell::clean_text(&crate::shell::query_value(p, "body").unwrap_or_default(), 300);
217            #[cfg(not(target_os = "linux"))]
218            let shown = crate::shell::notify(app, &title, &body);
219            #[cfg(target_os = "linux")]
220            let shown = false;
221            respond(&mut stream, "200 OK", &serde_json::json!({ "shown": shown }))
222        }
223        _ => respond(&mut stream, "404 Not Found", &serde_json::json!({ "error": "unknown route" })),
224    }
225}
226
227/// Open the bridge on a free loopback port. Returns None if the listener cannot be bound (the app then simply has no
228/// in-app update; the Terminal's `strata update --app` still works).
229pub fn start(app: &AppHandle, token: String) -> Option<Bridge> {
230    let listener = TcpListener::bind(("127.0.0.1", 0)).ok()?;
231    let port = listener.local_addr().ok()?.port();
232    let progress = Arc::new(Mutex::new(Progress::default()));
233    let app = app.clone();
234    let secret = token.clone();
235    std::thread::spawn(move || {
236        for stream in listener.incoming().flatten() {
237            handle(stream, &app, &secret, &progress);
238        }
239    });
240    Some(Bridge { url: format!("http://127.0.0.1:{port}"), token })
241}
242
243/// Environment for the App Host: where the bridge is, which app version this is.
244#[allow(dead_code)]
245pub fn apply_env(cmd: &mut std::process::Command, app: &AppHandle, bridge: Option<&Bridge>) {
246    cmd.env("STRATA_APP_VERSION", app.package_info().version.to_string());
247    if let Some(bridge) = bridge {
248        cmd.env("STRATA_SHELL_BRIDGE", &bridge.url).env("STRATA_SHELL_TOKEN", &bridge.token);
249    }
250}
251
252#[cfg(test)]
253mod tests {
254    use super::*;
255
256    #[test]
257    fn token_comparison_needs_every_byte() {
258        assert!(same("abc123", "abc123"));
259        assert!(!same("abc123", "abc124"));
260        assert!(!same("abc123", "abc12"));
261        assert!(!same("", "x"));
262    }
263
264    #[test]
265    fn progress_reports_idle_until_something_starts() {
266        let idle = Progress::default().json();
267        assert_eq!(idle["state"], "idle");
268        let p = Progress { state: "downloading", downloaded: 10, total: 100, version: Some("0.2.0".into()), error: None };
269        assert_eq!(p.json()["downloaded"], 10);
270        assert_eq!(p.json()["version"], "0.2.0");
271    }
272
273    #[test]
274    fn only_https_or_loopback_endpoints_may_override_the_configured_one() {
275        for (value, ok) in [
276            ("https://updates.example.com/latest.json", true),
277            ("http://127.0.0.1:19080/app/latest.json", true),
278            ("http://localhost:19080/latest.json", true),
279            ("http://example.com/latest.json", false),
280            ("file:///etc/passwd", false),
281        ] {
282            std::env::set_var(ENDPOINT_ENV, value);
283            assert_eq!(endpoint_override().is_some(), ok, "{value}");
284        }
285        std::env::remove_var(ENDPOINT_ENV);
286        assert!(endpoint_override().is_none());
287    }
288}