1use std::{
31 path::{Path, PathBuf},
32 sync::{
33 Arc, Mutex,
34 atomic::{AtomicBool, Ordering},
35 },
36};
37
38use nsh_package::{PackageReceipt, PublicKey, TrustStore};
39
40use crate::{AppError, Bundle, LoadedPackage, Trial};
41
42pub const DIR: &str = "updates";
44pub const NEXT: &str = "next.nshpkg";
46pub const CURRENT: &str = "current.nshpkg";
48pub const TRYING: &str = "trying.nshpkg";
50const TRUST: &str = "trust";
51const PACKAGES: &str = "packages";
52
53pub fn updates_dir(support_dir: &Path, app_id: &str) -> PathBuf {
58 support_dir
59 .join(crate::app_dir_name(Some(app_id)))
60 .join(DIR)
61}
62
63#[derive(Debug, Default)]
65#[non_exhaustive]
66pub struct Launch {
67 pub bundle: Bundle,
69 pub assets: PathBuf,
72 pub package: Option<nsh_package::App>,
74}
75
76pub fn launch(shipped: Bundle, resources: &Path, support_dir: Option<&Path>) -> Launch {
84 let assets = resources.join("assets");
85 let config = std::fs::read(assets.join(nsh_updater::CONFIG_ASSET)).ok();
86 let mut shipped = shipped;
87 match package_to_run(&mut shipped, config, support_dir) {
88 Some(run) => Launch {
89 bundle: run.bundle,
90 assets: run.assets,
91 package: Some(run.app),
92 },
93 None => Launch {
94 bundle: shipped,
95 assets,
96 package: None,
97 },
98 }
99}
100
101#[derive(Debug)]
103#[non_exhaustive]
104pub struct PackageRun {
105 pub bundle: Bundle,
107 pub assets: PathBuf,
109 pub app: nsh_package::App,
111}
112
113pub fn package_to_run(
118 shipped: &mut Bundle,
119 config: Option<Vec<u8>>,
120 support_dir: Option<&Path>,
121) -> Option<PackageRun> {
122 shipped.updater_config = config.map(Arc::from);
124 let update = Shipped::read(
125 shipped.updater_config.as_deref()?,
126 shipped.app_id.as_deref(),
127 )?;
128 let dir = updates_dir(support_dir?, &update.app_id);
129 let chosen = choose(&dir, &update)?;
130 let app = chosen.loaded.app.clone();
131 log::info!(
132 "running package {} {} (build {}), shipped build {}",
133 app.id,
134 app.version,
135 app.build,
136 update.build
137 );
138 Some(PackageRun {
139 assets: chosen.loaded.assets.clone(),
140 bundle: as_shipped(chosen.loaded.bundle, shipped, chosen.trial),
141 app,
142 })
143}
144
145fn as_shipped(mut bundle: Bundle, shipped: &Bundle, trial: Option<Arc<dyn Trial>>) -> Bundle {
149 bundle.links = shipped.links.clone();
150 bundle.system_paths = shipped.system_paths.clone();
151 bundle.main_window = shipped.main_window.clone();
152 bundle.application = shipped.application;
155 bundle.updater_config = shipped.updater_config.clone();
156 bundle.policy.granted = match (&shipped.policy.granted, &shipped.policy.declared) {
159 (Some(granted), _) => Some(granted.clone()),
160 (None, declared) => declared.clone(),
161 };
162 bundle.trial = trial;
163 bundle
164}
165
166#[derive(Debug, Clone)]
168struct Shipped {
169 app_id: String,
170 build: u64,
171 roots: Vec<PublicKey>,
172}
173
174impl Shipped {
175 fn read(config: &[u8], app_id: Option<&str>) -> Option<Shipped> {
178 let config = match nsh_updater::Config::parse(config) {
179 Ok(config) => config,
180 Err(err) => {
181 log::warn!("{}: {err}", nsh_updater::CONFIG_ASSET);
182 return None;
183 }
184 };
185 if config.package_roots().is_empty() {
186 return None;
187 }
188 if app_id.is_some_and(|id| id != config.id) {
189 log::warn!(
190 "{} is for {}, the app is {app_id:?}: no packages",
191 nsh_updater::CONFIG_ASSET,
192 config.id
193 );
194 return None;
195 }
196 let roots = config
197 .package_roots()
198 .iter()
199 .filter_map(|root| PublicKey::from_base64(root).ok())
200 .collect();
201 Some(Shipped {
202 app_id: config.id,
203 build: config.build.unwrap_or(1),
204 roots,
205 })
206 }
207
208 fn trust(&self, dir: &Path) -> Result<TrustStore, String> {
209 let mut trust = TrustStore::open(dir.join(TRUST)).map_err(|e| e.to_string())?;
210 for root in &self.roots {
211 trust.add_root(*root);
212 }
213 Ok(trust)
214 }
215}
216
217struct Chosen {
219 loaded: LoadedPackage,
220 trial: Option<Arc<dyn Trial>>,
221}
222
223fn choose(dir: &Path, shipped: &Shipped) -> Option<Chosen> {
225 let (next, trying, current) = (dir.join(NEXT), dir.join(TRYING), dir.join(CURRENT));
226 if !next.exists() && !trying.exists() && !current.exists() {
227 return None;
228 }
229 let trust = match shipped.trust(dir) {
230 Ok(trust) => trust,
231 Err(err) => {
232 log::error!("updates: cannot open the trust store: {err}");
233 return None;
234 }
235 };
236 let packages = dir.join(PACKAGES);
237 if trying.exists() {
238 log::warn!(
239 "updates: the package started last never ran {}s without a fatal error; it is \
240 deleted and the app goes back",
241 crate::TRIAL_PERIOD.as_secs()
242 );
243 remove(&trying);
244 }
245 let mut chosen = None;
246 if next.exists() {
247 match open(&trust, &next, &packages, shipped) {
248 Ok(loaded) => match std::fs::rename(&next, &trying) {
249 Ok(()) => {
250 let trial = PackageTrial {
251 dir: dir.to_owned(),
252 shipped: shipped.clone(),
253 receipt: loaded.receipt.clone(),
254 done: AtomicBool::new(false),
255 lock: Mutex::new(()),
256 };
257 chosen = Some(Chosen {
258 loaded,
259 trial: Some(Arc::new(trial)),
260 });
261 }
262 Err(err) => log::error!("updates: cannot start the package's trial: {err}"),
263 },
264 Err(err) => {
265 log::warn!("updates: downloaded package refused: {err}");
266 remove(&next);
267 }
268 }
269 }
270 if chosen.is_none() && current.exists() {
271 match open(&trust, ¤t, &packages, shipped) {
272 Ok(loaded) => {
273 chosen = Some(Chosen {
274 loaded,
275 trial: None,
276 })
277 }
278 Err(err) => {
279 log::warn!("updates: the installed package does not run: {err}");
280 remove(¤t);
281 }
282 }
283 }
284 let keep = chosen.as_ref().map(|c| c.loaded.receipt.sha256.clone());
286 if let Ok(entries) = std::fs::read_dir(packages.join(&shipped.app_id)) {
287 for entry in entries.flatten() {
288 if keep.as_deref() != entry.file_name().to_str() {
289 let _ = std::fs::remove_dir_all(entry.path());
290 }
291 }
292 }
293 chosen
294}
295
296fn open(
300 trust: &TrustStore,
301 path: &Path,
302 packages: &Path,
303 shipped: &Shipped,
304) -> Result<LoadedPackage, String> {
305 let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
306 let package = trust
308 .verify(&bytes, crate::BYTECODE_VERSION)
309 .map_err(|e| e.to_string())?;
310 check_app(&package.app, shipped)?;
311 drop(package);
312 crate::verify_package(trust, &bytes, packages)
313}
314
315fn check_app(app: &nsh_package::App, shipped: &Shipped) -> Result<(), String> {
316 if app.id != shipped.app_id {
317 return Err(format!("it is {}, the app is {}", app.id, shipped.app_id));
318 }
319 if app.build <= shipped.build {
320 return Err(format!(
321 "its build {} is not newer than the app's {}",
322 app.build, shipped.build
323 ));
324 }
325 Ok(())
326}
327
328fn remove(path: &Path) {
329 if let Err(err) = std::fs::remove_file(path)
330 && err.kind() != std::io::ErrorKind::NotFound
331 {
332 log::error!("updates: cannot remove {}: {err}", path.display());
333 }
334}
335
336pub fn verify_download(
342 file: &Path,
343 dir: &Path,
344 app_id: &str,
345 roots: &[String],
346 newer_than: u64,
347) -> Result<nsh_package::App, String> {
348 let roots = roots
349 .iter()
350 .map(|root| PublicKey::from_base64(root).map_err(|e| format!("package root: {e}")))
351 .collect::<Result<Vec<_>, _>>()?;
352 if roots.is_empty() {
353 return Err("the app trusts no package roots".into());
354 }
355 let shipped = Shipped {
356 app_id: app_id.to_owned(),
357 build: newer_than,
358 roots,
359 };
360 let trust = shipped.trust(dir)?;
361 let bytes = std::fs::read(file).map_err(|e| format!("{}: {e}", file.display()))?;
362 let package = trust
363 .verify(&bytes, crate::BYTECODE_VERSION)
364 .map_err(|e| e.to_string())?;
365 check_app(&package.app, &shipped)?;
366 Ok(package.app)
367}
368
369#[derive(Debug)]
372struct PackageTrial {
373 dir: PathBuf,
374 shipped: Shipped,
375 receipt: PackageReceipt,
376 done: AtomicBool,
378 lock: Mutex<()>,
379}
380
381impl PackageTrial {
382 fn decide(&self) -> Option<std::sync::MutexGuard<'_, ()>> {
383 let guard = self.lock.lock().unwrap_or_else(|e| e.into_inner());
384 (!self.done.swap(true, Ordering::SeqCst)).then_some(guard)
385 }
386
387 fn accept(&self) -> Result<(), String> {
388 let mut trust = self.shipped.trust(&self.dir)?;
389 trust
390 .accept_receipt(&self.receipt)
391 .map_err(|e| e.to_string())?;
392 std::fs::rename(self.dir.join(TRYING), self.dir.join(CURRENT)).map_err(|e| e.to_string())
393 }
394}
395
396impl Trial for PackageTrial {
397 fn healthy(&self) {
398 let Some(_guard) = self.decide() else { return };
399 match self.accept() {
400 Ok(()) => log::info!(
401 "updates: package {} build {} is healthy: installed",
402 self.receipt.app.id,
403 self.receipt.app.build
404 ),
405 Err(err) => log::error!("updates: cannot install the healthy package: {err}"),
406 }
407 }
408
409 fn failed(&self, error: &AppError) {
410 let Some(_guard) = self.decide() else { return };
411 log::error!(
412 "updates: package {} build {} failed ({}): the next launch goes back",
413 self.receipt.app.id,
414 self.receipt.app.build,
415 error.message
416 );
417 remove(&self.dir.join(TRYING));
418 }
419}
420
421#[cfg(test)]
422mod tests {
423 use nsh_package::{Certificate, Contents, SecretKey, build, certify};
424
425 use super::*;
426 use crate::AppErrorKind;
427
428 const ID: &str = "com.example.app";
429
430 struct Keys {
431 root: SecretKey,
432 release: SecretKey,
433 cert: Certificate,
434 }
435
436 impl Keys {
437 fn new() -> Keys {
438 let root = SecretKey::generate().unwrap();
439 let release = SecretKey::generate().unwrap();
440 let cert = certify(&root, &release.public(), &[ID.into()], 0, u64::MAX);
441 Keys {
442 root,
443 release,
444 cert,
445 }
446 }
447
448 fn package(&self, id: &str, build_number: u64) -> Vec<u8> {
449 let contents = Contents {
450 app: nsh_package::App {
451 id: id.into(),
452 name: "App".into(),
453 version: format!("1.0.{build_number}"),
454 build: build_number,
455 },
456 capabilities: Some(serde_json::json!({ "clipboard": true })),
457 source: format!("globalThis.build = {build_number};"),
458 bytecode: None,
459 source_map: None,
460 assets: vec![("a.txt".into(), build_number.to_string().into_bytes())],
461 min_runtime: None,
462 };
463 let cert = if id == ID {
464 self.cert.clone()
465 } else {
466 certify(
467 &self.root,
468 &self.release.public(),
469 &["*".into()],
470 0,
471 u64::MAX,
472 )
473 };
474 build(&contents, &self.release, &cert).unwrap()
475 }
476
477 fn shipped(&self, build: u64) -> Shipped {
478 Shipped {
479 app_id: ID.into(),
480 build,
481 roots: vec![self.root.public()],
482 }
483 }
484 }
485
486 fn temp(name: &str) -> PathBuf {
487 let dir = std::env::temp_dir().join(format!("nsh-updates-{name}-{}", std::process::id()));
488 let _ = std::fs::remove_dir_all(&dir);
489 std::fs::create_dir_all(&dir).unwrap();
490 dir
491 }
492
493 fn put(dir: &Path, name: &str, bytes: &[u8]) {
494 std::fs::write(dir.join(name), bytes).unwrap();
495 }
496
497 fn chosen_build(chosen: &Option<Chosen>) -> Option<u64> {
498 chosen.as_ref().map(|c| c.loaded.app.build)
499 }
500
501 fn fatal() -> AppError {
502 AppError::new(AppErrorKind::Load, "Error: boom")
503 }
504
505 #[test]
506 fn nothing_downloaded_runs_the_shipped_bundle() {
507 let (keys, dir) = (Keys::new(), temp("none"));
508 assert!(choose(&dir, &keys.shipped(1)).is_none());
509 }
510
511 #[test]
512 fn a_new_package_runs_on_trial_and_is_installed_once_healthy() {
513 let (keys, dir) = (Keys::new(), temp("healthy"));
514 put(&dir, NEXT, &keys.package(ID, 2));
515 let chosen = choose(&dir, &keys.shipped(1));
516 assert_eq!(chosen_build(&chosen), Some(2));
517 let chosen = chosen.unwrap();
518 assert!(dir.join(TRYING).exists() && !dir.join(NEXT).exists());
519 assert_eq!(
520 std::fs::read(chosen.loaded.assets.join("a.txt")).unwrap(),
521 b"2"
522 );
523 let trial = chosen.trial.expect("on trial");
524 trial.healthy();
525 trial.failed(&fatal());
527 assert!(!dir.join(NEXT).exists() && !dir.join(TRYING).exists());
528 assert!(dir.join(CURRENT).exists());
529 let again = choose(&dir, &keys.shipped(1)).unwrap();
531 assert_eq!(again.loaded.app.build, 2);
532 assert!(again.trial.is_none());
533 let trust = keys.shipped(1).trust(&dir).unwrap();
535 assert_eq!(trust.accepted_build(ID), Some(2));
536 }
537
538 #[test]
539 fn a_package_that_crashed_is_rolled_back_to_the_installed_one() {
540 let (keys, dir) = (Keys::new(), temp("crash"));
541 put(&dir, CURRENT, &keys.package(ID, 2));
542 put(&dir, NEXT, &keys.package(ID, 3));
543 assert_eq!(chosen_build(&choose(&dir, &keys.shipped(1))), Some(3));
544 let rolled_back = choose(&dir, &keys.shipped(1));
546 assert_eq!(chosen_build(&rolled_back), Some(2));
547 assert!(!dir.join(NEXT).exists() && !dir.join(TRYING).exists());
548 let kept: Vec<_> = std::fs::read_dir(dir.join(PACKAGES).join(ID))
550 .unwrap()
551 .collect();
552 assert_eq!(kept.len(), 1);
553 }
554
555 #[test]
556 fn a_fatal_error_deletes_the_package() {
557 let (keys, dir) = (Keys::new(), temp("fatal"));
558 put(&dir, NEXT, &keys.package(ID, 2));
559 let chosen = choose(&dir, &keys.shipped(1)).unwrap();
560 let trial = chosen.trial.unwrap();
561 trial.failed(&fatal());
562 trial.healthy();
563 assert!(!dir.join(NEXT).exists() && !dir.join(TRYING).exists());
564 assert!(!dir.join(CURRENT).exists());
565 assert!(choose(&dir, &keys.shipped(1)).is_none());
566 }
567
568 #[test]
569 fn tampered_foreign_and_old_packages_are_deleted() {
570 let keys = Keys::new();
571 let mut tampered = keys.package(ID, 2);
572 let at = tampered.len() / 2;
573 tampered[at] ^= 1;
574 let untrusted = Keys::new().package(ID, 2);
575 for (name, bytes) in [
576 ("tampered", tampered),
577 ("untrusted", untrusted),
578 ("foreign", keys.package("com.example.other", 2)),
579 ("old", keys.package(ID, 1)),
580 ] {
581 let dir = temp(name);
582 put(&dir, NEXT, &bytes);
583 assert!(choose(&dir, &keys.shipped(1)).is_none(), "{name}");
584 assert!(!dir.join(NEXT).exists(), "{name}");
585 }
586 }
587
588 #[test]
589 fn a_newer_app_replaces_the_installed_package() {
590 let (keys, dir) = (Keys::new(), temp("newer-app"));
591 put(&dir, CURRENT, &keys.package(ID, 2));
592 assert_eq!(chosen_build(&choose(&dir, &keys.shipped(1))), Some(2));
593 assert!(choose(&dir, &keys.shipped(2)).is_none());
595 assert!(!dir.join(CURRENT).exists());
596 }
597
598 #[test]
599 fn an_older_download_than_the_installed_package_is_refused() {
600 let (keys, dir) = (Keys::new(), temp("older"));
601 put(&dir, NEXT, &keys.package(ID, 3));
602 choose(&dir, &keys.shipped(1))
603 .unwrap()
604 .trial
605 .unwrap()
606 .healthy();
607 put(&dir, NEXT, &keys.package(ID, 2));
608 assert_eq!(chosen_build(&choose(&dir, &keys.shipped(1))), Some(3));
609 assert!(!dir.join(NEXT).exists());
610 }
611
612 #[test]
613 fn a_download_during_a_trial_waits_for_the_next_launch() {
614 let (keys, dir) = (Keys::new(), temp("during"));
615 put(&dir, NEXT, &keys.package(ID, 2));
616 let trial = choose(&dir, &keys.shipped(1)).unwrap().trial.unwrap();
617 put(&dir, NEXT, &keys.package(ID, 3));
618 trial.healthy();
619 let trust = keys.shipped(1).trust(&dir).unwrap();
620 assert_eq!(trust.accepted_build(ID), Some(2));
621 let next = choose(&dir, &keys.shipped(1)).unwrap();
622 assert_eq!(next.loaded.app.build, 3);
623 assert!(next.trial.is_some());
624 }
625
626 #[test]
627 fn downloads_are_verified_without_being_accepted() {
628 let (keys, dir) = (Keys::new(), temp("download"));
629 let roots = [keys.root.public().to_base64()];
630 let file = dir.join("next.nshpkg.part");
631 put(&dir, "next.nshpkg.part", &keys.package(ID, 3));
632 let app = verify_download(&file, &dir, ID, &roots, 2).unwrap();
633 assert_eq!(app.build, 3);
634 assert!(verify_download(&file, &dir, ID, &roots, 3).is_err());
635 assert!(verify_download(&file, &dir, "com.example.other", &roots, 2).is_err());
636 let other = [Keys::new().root.public().to_base64()];
637 assert!(verify_download(&file, &dir, ID, &other, 2).is_err());
638 assert!(verify_download(&file, &dir, ID, &[], 2).is_err());
639 let trust = keys.shipped(1).trust(&dir).unwrap();
640 assert_eq!(trust.accepted_build(ID), None);
641 }
642
643 #[test]
644 fn packages_run_as_the_shipped_app() {
645 let (keys, dir) = (Keys::new(), temp("launch"));
646 let resources = dir.join("nsh");
647 std::fs::create_dir_all(resources.join("assets")).unwrap();
648 let config = serde_json::json!({
649 "id": ID, "version": "1.0.0", "github": "o/r", "build": 1,
650 "packages": { "roots": [keys.root.public().to_base64()] },
651 });
652 std::fs::write(
653 resources.join("assets/nsh-updater.json"),
654 config.to_string(),
655 )
656 .unwrap();
657 let data = dir.join("data");
658 let updates = updates_dir(&data, ID);
659 std::fs::create_dir_all(&updates).unwrap();
660 put(&updates, NEXT, &keys.package(ID, 2));
661 let declared =
662 crate::parse_capabilities(r#"{"network":{"hosts":["api.example.com"]}}"#).unwrap();
663 let shipped = Bundle::source("1".into())
664 .with_app_id(Some(ID))
665 .with_links(nsh_core::url_scheme::AppLinks::from_json(
666 &serde_json::json!({
667 "schemes": ["example"],
668 "links": [{ "host": "example.com", "paths": ["/orders/*"] }]
669 }),
670 ))
671 .with_main_window(Some(r#"{"defaultSize":{"width":900,"height":640}}"#))
672 .with_policy(crate::Policy {
673 declared: Some(declared),
674 ..Default::default()
675 });
676
677 assert!(shipped.main_window.is_some());
678 let launched = launch(shipped.clone(), &resources, Some(&data));
679 assert_eq!(launched.package.as_ref().map(|a| a.build), Some(2));
680 let bundle = &launched.bundle;
681 assert_eq!(bundle.links, shipped.links);
682 assert_eq!(bundle.links.web().len(), 1);
683 assert_eq!(bundle.main_window, shipped.main_window);
684 assert!(bundle.updater_config.is_some() && bundle.trial.is_some());
685 assert!(!bundle.policy.access().allows_clipboard());
687 assert!(launched.assets.join("a.txt").exists());
688
689 let plain = launch(shipped.clone(), &resources, None);
691 assert!(plain.package.is_none() && plain.bundle.updater_config.is_some());
692 assert_eq!(plain.assets, resources.join("assets"));
693 let elsewhere = dir.join("other");
694 let shipped_only = launch(shipped, &elsewhere, Some(&data));
695 assert!(shipped_only.package.is_none() && shipped_only.bundle.updater_config.is_none());
696 }
697}