okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
3cabb9e3f
main
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 { 29state : &' static str , 30downloaded : u64 , 31total : u64 , 32version : Option < String >, 33error : Option < String >, 34} 35 36impl Progress { 37fn 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 { 47pub url : String , 48pub token : String , 49} 50 51fn endpoint_override () ->Option < String > { 52let url = std:: env:: var ( ENDPOINT_ENV ). ok () ?; 53if url. starts_with ( "https://" ) || url. starts_with ( "http://127.0.0.1:" ) || url. starts_with ( "http://localhost:" ) { 54Some ( url) 55} else { 56None 57} 58} 59 60fn updater_for ( app : & AppHandle ) ->Result < tauri_plugin_updater:: Updater , String > { 61match endpoint_override () { 62Some ( url) =>{ 63let 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} 66None => app. updater (). map_err ( |e| e. to_string ()), 67} 68} 69 70async fn check ( app : & AppHandle ) ->Result < serde_json:: Value , String > { 71let updater =updater_for ( app) ?; 72match updater. check (). await . map_err ( |e| e. to_string ()) ?{ 73Some ( update) =>Ok ( serde_json:: json!({ 74"available" : true , "version" : update. version , "current" : update. current_version , "notes" : update. body , 75})), 76None =>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 >>) { 81let fail = |message : String |{ 82let mut p = progress. lock (). unwrap (); 83 p. state ="error" ; 84 p. error =Some ( message); 85}; 86let updater =match updater_for ( & app) { 87Ok ( u) => u, 88Err ( e) =>return fail ( e), 89}; 90let update =match updater. check (). await { 91Ok ( Some ( update)) => update, 92Ok ( None ) =>return fail ( "There is no newer version of the Strata app." . into ()), 93Err ( e) =>return fail ( e. to_string ()), 94}; 95{ 96let mut p = progress. lock (). unwrap (); 97* p =Progress { state : "downloading" , version : Some ( update. version . clone ()), ..Default :: default () }; 98} 99let on_chunk ={ 100let progress = progress. clone (); 101move |chunk : usize , total : Option < u64 > |{ 102let mut p = progress. lock (). unwrap (); 103 p. downloaded += chunkas u64 ; 104 p. total = total. unwrap_or ( p. total ); 105} 106}; 107let on_finish ={ 108let progress = progress. clone (); 109move || 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. 115let bytes =match update. download ( on_chunk, on_finish). await { 116Ok ( bytes) => bytes, 117Err ( e) =>return fail ( e. to_string ()), 118}; 119 progress. lock (). unwrap (). state ="installing" ; 120match launch_installer ( & update. version , & bytes) { 121Ok (()) =>{ 122 progress. lock (). unwrap (). state ="done" ; 123 app. exit ( 0 ); 124} 125Err ( first) =>match update. install ( & bytes) { 126Ok (()) =>{ 127 progress. lock (). unwrap (). state ="done" ; 128 app. restart (); 129} 130Err ( 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 > { 138use std:: os:: windows:: process:: CommandExt ; 139const CREATE_BREAKAWAY_FROM_JOB : u32 =0x0100_0000 ; 140const DETACHED_PROCESS : u32 =0x0000_0008 ; 141let dir = std:: env:: temp_dir (). join ( format! ( "strata-app-update-{version}" )); 142 std:: fs:: create_dir_all ( & dir). map_err ( |e| e. to_string ()) ?; 143let 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 > { 156Err ( "not Windows" . into ()) 157} 158 159fn respond ( stream : & mut TcpStream , status : & str , body : & serde_json:: Value ) { 160let text = body. to_string (); 161let _ = stream. write_all ( 162format! ( 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 >>) { 175let _ = stream. set_read_timeout ( Some ( Duration :: from_secs ( 5 ))); 176let mut buf =Vec :: new (); 177let mut chunk =[ 0u8 ; 1024 ]; 178while !buf. windows ( 4 ). any ( |w| w ==b"\r\n\r\n" ) && buf. len () <8192 { 179match stream. read ( & mut chunk) { 180Ok ( 0 ) |Err ( _) =>break , 181Ok ( n) => buf. extend_from_slice ( & chunk[ ..n]), 182} 183} 184let head =String :: from_utf8_lossy ( & buf). to_string (); 185let mut lines = head. lines (); 186let request = lines. next (). unwrap_or_default (). to_string (); 187let 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 (); 191if !same ( & supplied, token) { 192return respond ( & mut stream, "401 Unauthorized" , & serde_json:: json!({ "error" : "not allowed" })); 193} 194let mut parts = request. split_whitespace (); 195let ( method, path) =( parts. next (). unwrap_or ( "" ), parts. next (). unwrap_or ( "" )); 196match ( method, path) { 197( "GET" , "/app-update/check" ) =>match tauri:: async_runtime:: block_on ( check ( app)) { 198Ok ( value) =>respond ( & mut stream, "200 OK" , & value), 199Err ( e) =>respond ( & mut stream, "502 Bad Gateway" , & serde_json:: json!({ "error" : e})), 200}, 201( "POST" , "/app-update/install" ) =>{ 202{ 203let mut p = progress. lock (). unwrap (); 204if p. state =="downloading" || p. state =="installing" { 205return 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 ())); 210respond ( & 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" ) =>{ 215let title =crate :: shell:: clean_text ( & crate :: shell:: query_value ( p, "title" ). unwrap_or_default (), 120 ); 216let body =crate :: shell:: clean_text ( & crate :: shell:: query_value ( p, "body" ). unwrap_or_default (), 300 ); 217# [ cfg ( not ( target_os = "linux" ))] 218let shown =crate :: shell:: notify ( app, & title, & body); 219# [ cfg ( target_os = "linux" )] 220let shown =false ; 221respond ( & 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 > { 230let listener =TcpListener :: bind (( "127.0.0.1" , 0 )). ok () ?; 231let port = listener. local_addr (). ok () ?. port (); 232let progress =Arc :: new ( Mutex :: new ( Progress :: default ())); 233let app = app. clone (); 234let secret = token. clone (); 235 std:: thread:: spawn ( move ||{ 236for streamin listener. incoming (). flatten () { 237handle ( stream, & app, & secret, & progress); 238} 239}); 240Some ( 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 ()); 247if 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{ 254use super :: * ; 255 256# [ test ] 257fn token_comparison_needs_every_byte () { 258assert! ( same ( "abc123" , "abc123" )); 259assert! ( !same ( "abc123" , "abc124" )); 260assert! ( !same ( "abc123" , "abc12" )); 261assert! ( !same ( "" , "x" )); 262} 263 264# [ test ] 265fn progress_reports_idle_until_something_starts () { 266let idle =Progress :: default (). json (); 267assert_eq! ( idle[ "state" ], "idle" ); 268let p =Progress { state : "downloading" , downloaded : 10 , total : 100 , version : Some ( "0.2.0" . into ()), error : None }; 269assert_eq! ( p. json ()[ "downloaded" ], 10 ); 270assert_eq! ( p. json ()[ "version" ], "0.2.0" ); 271} 272 273# [ test ] 274fn only_https_or_loopback_endpoints_may_override_the_configured_one () { 275for ( 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); 283assert_eq! ( endpoint_override (). is_some (), ok, "{value}" ); 284} 285 std:: env:: remove_var ( ENDPOINT_ENV ); 286assert! ( endpoint_override (). is_none ()); 287} 288}