//! App manifests: one `app.toml` per folder under the apps directory. //! //! Apps come from two places: //! - factory apps (the image) and official packages (`sf-app-`, signed //! with the Fennec OS key); //! - the store: third-party apps from their own GitHub/Gitea/GitLab repos, //! published in their own repo (docs/store.md). These always run sandboxed and //! can never replace an official app. use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; use crate::settings::Settings; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum AppKind { /// Runs in the shared Chromium web runtime. Web, /// Any executable: AppImage, Rust binary, script. Exec, /// Built into the launcher (e.g. settings screen). Builtin, } /// Where an app was loaded from. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum Origin { /// The image or an official package. #[default] Official, /// A store package from a third-party repo: always sandboxed. Store, } /// What a sandboxed app may reach besides its own files and the screen /// (the Wayland socket). Shown to the user before installing. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] pub enum Permission { /// Internet and the local network. Network, /// Hardware graphics and video decoding (/dev/dri). Gpu, /// Sound output (PipeWire / PulseAudio socket). Audio, /// Game controllers: /dev/input, /dev/hidraw*, /dev/uinput. Gamepad, /// The user's D-Bus session bus (unfiltered). DbusSession, /// The system D-Bus (unfiltered). DbusSystem, /// Every device in /dev. Devices, /// Phones may start the app by casting to the TV (DIAL, e.g. the YouTube /// app's cast button). Implied by a `[dial]` section. Dial, } impl Permission { pub const ALL: [Permission; 8] = [ Permission::Network, Permission::Gpu, Permission::Audio, Permission::Gamepad, Permission::DbusSession, Permission::DbusSystem, Permission::Devices, Permission::Dial, ]; /// Name used in app.toml and store.toml. pub fn key(self) -> &'static str { match self { Permission::Network => "network", Permission::Gpu => "gpu", Permission::Audio => "audio", Permission::Gamepad => "gamepad", Permission::DbusSession => "dbus-session", Permission::DbusSystem => "dbus-system", Permission::Devices => "devices", Permission::Dial => "dial", } } pub fn from_key(key: &str) -> Option { Permission::ALL.into_iter().find(|p| p.key() == key) } /// Hungarian label for the store screen. pub fn label(self) -> &'static str { match self { Permission::Network => "Internet és helyi hálózat", Permission::Gpu => "Grafikus gyorsítás", Permission::Audio => "Hang", Permission::Gamepad => "Játékvezérlők", Permission::DbusSession => "Munkamenet D-Bus", Permission::DbusSystem => "Rendszer D-Bus", Permission::Devices => "Minden eszköz (/dev)", Permission::Dial => "Castolás telefonról (DIAL)", } } /// Worth a warning: the app can reach far outside its sandbox. pub fn risky(self) -> bool { matches!(self, Permission::DbusSession | Permission::DbusSystem | Permission::Devices) } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SandboxOptions { /// Run in a bubblewrap sandbox. Only official apps may turn it off /// (system receivers like AirPlay); store apps are always sandboxed. /// Unset: on, except for official background services. #[serde(default)] pub enabled: Option, #[serde(default)] pub permissions: Vec, } impl Default for SandboxOptions { fn default() -> Self { SandboxOptions { enabled: None, permissions: Vec::new() } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AppManifest { pub id: String, pub name: String, pub kind: AppKind, /// Package version (semver). Published as `sf-app-` when it changes; /// the newer of a factory and an installed copy wins. #[serde(default = "default_version")] pub version: String, /// Short label above the title in the hero ("Saját app", "Castolás"...). #[serde(default)] pub category: String, #[serde(default)] pub description: String, /// Web apps: start URL. May contain `${settings.}` placeholders. #[serde(default)] pub url: Option, /// Exec apps: command line. #[serde(default)] pub exec: Option>, /// Built-in icon name used by the launcher. #[serde(default)] pub icon: String, /// Accent color (hex), used for focus glow and buttons. #[serde(default = "default_accent")] pub accent: String, /// Three colors for the animated hero backdrop: highlight, mid, deep. #[serde(default)] pub palette: Vec, /// Sort order on the home row. #[serde(default)] pub order: i32, #[serde(default)] pub web: WebOptions, #[serde(default)] pub dial: Option, /// Background receiver (AirPlay, Miracast): sf-core keeps it running all /// the time and it shows its own window when something connects. The /// launcher tile only opens the details sheet. #[serde(default)] pub service: bool, #[serde(default)] pub sandbox: SandboxOptions, /// Extra environment for the app's process. #[serde(default)] pub env: BTreeMap, /// Legacy store manifest field. Older signed releases may still contain it. #[serde(default)] pub public_key: Option, /// Store apps: source code / home page, shown on the store screen. #[serde(default)] pub homepage: Option, #[serde(default)] pub author: Option, #[serde(default)] pub license: Option, /// Folder the manifest was loaded from (not serialized). #[serde(skip)] pub dir: PathBuf, #[serde(skip)] pub origin: Origin, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct WebOptions { /// Full user agent override. #[serde(default)] pub user_agent: Option, /// Appended to the default user agent. #[serde(default)] pub user_agent_suffix: Option, /// Unpacked extensions to load (paths relative to the app folder). #[serde(default)] pub extensions: Vec, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DialOptions { /// DIAL application name, e.g. "YouTube". pub name: String, } fn default_version() -> String { "0.0.0".into() } fn default_accent() -> String { "#ffffff".into() } impl AppManifest { /// Start URL with `${settings.key}` placeholders filled in. pub fn resolved_url(&self, settings: &Settings) -> Option { self.url.as_ref().map(|u| settings.expand(u)) } /// The command line with `${app}` replaced by `app_root` (where the app's /// files are: its folder, or /app inside the sandbox). A relative program /// path with a slash (`bin/hello`) is inside the app folder too; a bare /// name (`uxplay`) is looked up in PATH. pub fn resolved_exec(&self, app_root: &Path) -> Vec { let root = app_root.to_string_lossy(); let mut line: Vec = self.exec.iter().flatten().map(|a| a.replace("${app}", &root)).collect(); if let Some(first) = line.first_mut() { if first.contains('/') && !first.starts_with('/') { *first = format!("{}/{}", root.trim_end_matches('/'), first.trim_start_matches("./")); } } line } /// What the app may reach from its sandbox. Web apps always get what a /// browser needs; a `[dial]` section asks for `dial`. pub fn permissions(&self) -> Vec { let mut p = self.sandbox.permissions.clone(); if self.kind == AppKind::Web { p.extend([Permission::Network, Permission::Gpu, Permission::Audio]); } if self.dial.is_some() { p.push(Permission::Dial); } p.sort(); p.dedup(); p } /// Store apps always run sandboxed; official ones unless they opt out. pub fn sandboxed(&self) -> bool { self.origin == Origin::Store || self.sandbox.enabled.unwrap_or(!self.service) } /// An image file shipped with the app (`icon = "icon.png"`), if `icon` /// isn't one of the launcher's built-in icon names. pub fn icon_file(&self) -> Option { let lower = self.icon.to_ascii_lowercase(); if ![".png", ".svg", ".jpg", ".jpeg"].iter().any(|ext| lower.ends_with(ext)) { return None; } if self.icon.contains("..") || Path::new(&self.icon).is_absolute() { return None; } let path = self.dir.join(&self.icon); path.is_file().then_some(path) } /// Rules a store app must follow (checked by sf-update before installing /// and by the launcher when loading). pub fn check_store_rules(&self) -> Result<()> { anyhow::ensure!(is_store_id(&self.id), "store app id {:?} must be a reverse domain name (io.github.user.app)", self.id); anyhow::ensure!(self.kind != AppKind::Builtin, "store apps can't be built-in"); anyhow::ensure!(!self.service, "store apps can't be background services"); if let Some(d) = &self.dial { anyhow::ensure!(!d.name.trim().is_empty() && d.name.len() <= 64, "dial.name must be 1-64 characters"); } anyhow::ensure!(self.sandbox.enabled != Some(false), "store apps can't turn off the sandbox"); match self.kind { AppKind::Exec => anyhow::ensure!(!self.resolved_exec(Path::new("/app")).is_empty(), "exec is missing"), AppKind::Web => anyhow::ensure!(self.url.as_deref().is_some_and(|u| u.starts_with("https://")), "web apps need an https:// url"), AppKind::Builtin => {} } Ok(()) } } /// Store app ids are reverse domain names with at least one dot /// (`io.github.user.app`). Official app ids never have a dot, so a store app /// can't take the place of one. pub fn is_store_id(id: &str) -> bool { let parts: Vec<&str> = id.split('.').collect(); id.len() <= 128 && parts.len() >= 2 && parts.iter().all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')) && parts[0].bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit()) } /// Loads every `*/app.toml` under `dir`, sorted by `order` then name. pub fn load_apps(dir: &Path) -> Result> { let mut apps = Vec::new(); let entries = std::fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))?; for entry in entries.flatten() { let path = entry.path().join("app.toml"); if !path.is_file() { continue; } match load_one(&path) { Ok(app) => apps.push(app), Err(e) => log::warn!("skipping {}: {e:#}", path.display()), } } sort_apps(&mut apps); Ok(apps) } /// Loads apps from several folders (factory apps, then installed packages). /// Missing folders are skipped; of two apps with the same id the higher /// `version` wins, on a tie the later folder. pub fn load_apps_from(dirs: &[PathBuf]) -> Result> { let mut apps: Vec = Vec::new(); let mut found = false; for dir in dirs { if !dir.is_dir() { continue; } found = true; for app in load_apps(dir)? { // Official ids have no dot; a store app here (developed inside // the apps folder) belongs to the store, not the factory set. if is_store_id(&app.id) { log::info!("skipping {}: a store app id in an official apps folder", app.id); continue; } match apps.iter_mut().find(|a| a.id == app.id) { Some(old) if version_cmp(&app.version, &old.version).is_ge() => *old = app, Some(_) => {} None => apps.push(app), } } } anyhow::ensure!(found, "none of the app folders exist: {dirs:?}"); sort_apps(&mut apps); Ok(apps) } /// Official apps from `dirs` (see `load_apps_from`), plus store apps from /// `store`. A store app is skipped if it breaks the store rules or has the id /// of an official app. pub fn load_all(dirs: &[PathBuf], store: Option<&Path>) -> Result> { let mut apps = load_apps_from(dirs)?; if let Some(store) = store.filter(|d| d.is_dir()) { for mut app in load_apps(store)? { app.origin = Origin::Store; if let Err(e) = app.check_store_rules() { log::warn!("skipping store app {}: {e:#}", app.dir.display()); } else if apps.iter().any(|a| a.id == app.id) { log::warn!("skipping store app {}: an app with this id is already installed", app.id); } else { apps.push(app); } } sort_apps(&mut apps); } Ok(apps) } fn sort_apps(apps: &mut [AppManifest]) { apps.sort_by(|a, b| a.order.cmp(&b.order).then_with(|| a.name.cmp(&b.name))); } /// Compares dotted numeric versions ("1.10.0" > "1.9.2"), up to four parts /// (the Steam launcher is 1.0.0.87); anything that isn't a number compares as 0. pub fn version_cmp(a: &str, b: &str) -> std::cmp::Ordering { let parts = |v: &str| -> Vec { v.split(['.', '-', '+']).take(4).map(|p| p.parse().unwrap_or(0)).collect() }; let (a, b) = (parts(a), parts(b)); (0..4).map(|i| a.get(i).unwrap_or(&0).cmp(b.get(i).unwrap_or(&0))).find(|o| o.is_ne()).unwrap_or(std::cmp::Ordering::Equal) } fn load_one(path: &Path) -> Result { let text = std::fs::read_to_string(path)?; let mut app: AppManifest = toml::from_str(&text)?; app.dir = path.parent().unwrap_or(Path::new(".")).to_path_buf(); Ok(app) } #[cfg(test)] mod tests { use super::*; #[test] fn parses_web_manifest() { let app: AppManifest = toml::from_str( r##" id = "netflex" name = "Netflex" kind = "web" url = "${settings.netflex_server}/" accent = "#E50914" palette = ["#ff3b3b", "#7a0a10", "#0c0203"] [web] user_agent_suffix = "SMART-TV FennecOS/0.1" "##, ) .unwrap(); assert_eq!(app.kind, AppKind::Web); let mut s = Settings::default(); s.values.insert("netflex_server".into(), "http://10.0.0.5:7880".into()); assert_eq!(app.resolved_url(&s).unwrap(), "http://10.0.0.5:7880/"); assert_eq!(app.version, "0.0.0"); } #[test] fn compares_versions() { use std::cmp::Ordering::*; assert_eq!(version_cmp("1.10.0", "1.9.2"), Greater); assert_eq!(version_cmp("0.2", "0.2.0"), Equal); assert_eq!(version_cmp("0.1.9", "0.2.0"), Less); assert_eq!(version_cmp("1.0.0.87", "1.0.0.9"), Greater); assert_eq!(version_cmp("1.0.0", "1.0.0.0"), Equal); } #[test] fn store_ids() { assert!(is_store_id("io.github.user.app")); assert!(is_store_id("org.example.My_App-2")); assert!(!is_store_id("youtube")); assert!(!is_store_id("IO.github.x")); assert!(!is_store_id("io..x")); assert!(!is_store_id("io.x/../y")); assert!(!is_store_id(".io.x")); } #[test] fn exec_and_permissions() { let app: AppManifest = toml::from_str( r#" id = "io.github.fox.hello" name = "Hello" kind = "exec" exec = ["bin/hello", "--data", "${app}/share"] [sandbox] permissions = ["network", "gamepad"] "#, ) .unwrap(); assert_eq!(app.resolved_exec(Path::new("/app")), ["/app/bin/hello", "--data", "/app/share"]); assert_eq!(app.permissions(), [Permission::Network, Permission::Gamepad]); assert!(app.sandboxed()); app.check_store_rules().unwrap(); let mut bad = app.clone(); bad.sandbox.enabled = Some(false); assert!(bad.check_store_rules().is_err()); bad = app.clone(); bad.id = "youtube".into(); assert!(bad.check_store_rules().is_err()); // DIAL: allowed for store apps, and it shows up as a permission. let cast: AppManifest = toml::from_str( "id = 'io.github.fox.tube' name = 'Tube' kind = 'web' url = 'https://example.com/tv' [dial] name = 'YouTube' ", ) .unwrap(); cast.check_store_rules().unwrap(); assert!(cast.permissions().contains(&Permission::Dial)); let web: AppManifest = toml::from_str("id = 'a'\nname = 'A'\nkind = 'web'\nurl = 'https://x'\n").unwrap(); assert_eq!(web.permissions(), [Permission::Network, Permission::Gpu, Permission::Audio]); let path: AppManifest = toml::from_str("id = 'a'\nname = 'A'\nkind = 'exec'\nexec = ['uxplay', '-n']\n").unwrap(); assert_eq!(path.resolved_exec(Path::new("/x")), ["uxplay", "-n"]); } }