Split the apps and the SDK out of Fennec OS

The apps are developed apart from the OS now, each in its own repo under
gitea.bluefox.support/fennec:
- sdk: sf-app (the app contract: manifest, permissions, store rules,
  sandbox, launch; from sf-ipc), sf-ui, sf-pack, the app template, the
  developer guide. The OS depends on it by tag (v0.1.0).
- youtube, steam: store apps. netflex (native) replaces the Netflex web app.
- store: the Fennec catalog, the store source a new TV starts with.

This repo keeps the OS and its own apps (Settings, App Store, AirPlay,
Miracast). sf-ipc re-exports sf-app, so OS code is mostly unchanged.

- Store apps may register for DIAL (the `dial` permission); an official
  app with the same DIAL name wins.
- Built-in icon names are for official apps only.
- The image installs the catalog apps at build time (factory-store.toml,
  sf-update store in mkosi.postinst.chroot). Steam's system part stays in
  the image: 32-bit libraries, controller udev rules (from Valve's apt
  repo), Valve's key.
- Older TVs move over by themselves: sf-update adds the replacements to
  store.toml once, the old factory app stays until its replacement is
  installed, YouTube's and Steam's data folders move to the new ids, and
  the old sf-app-<id> packages are not installed any more.

Shell 0.3.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tamas Csikel
2026-10-25 17:58:21 +01:00
parent d7e9fe4568
commit deedf1416a
67 changed files with 393 additions and 13476 deletions

View File

@@ -1,459 +1,110 @@
//! 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-<id>`, 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.
//! App manifests: the Fennec SDK's `sf_app::manifest`, plus what only the OS
//! decides: which factory apps became store apps, and how a TV moves over.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use anyhow::Result;
use crate::settings::Settings;
pub use sf_app::manifest::*;
#[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,
/// The Fennec catalog: the store source with the Bluefox apps.
pub const FENNEC_CATALOG: &str = "https://gitea.bluefox.support/fennec/store";
/// A factory app that became a store app (its own repo, Fennec catalog).
pub struct Retired {
/// The old official id (`apps/<id>`, `sf-app-<id>`).
pub id: &'static str,
/// The store app that replaces it.
pub replacement: &'static str,
/// Its repo (canonical https URL, as in store.toml).
pub source: &'static str,
/// What it asks for; the old app had the same, so it is approved.
pub permissions: &'static [Permission],
/// The old app's data folder (logins, Chromium profile) moves over.
pub move_data: bool,
}
/// 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,
pub const RETIRED: &[Retired] = &[
Retired {
// The Netflex web app; the native app keeps its own login.
id: "netflex",
replacement: "support.bluefox.netflex",
source: "https://gitea.bluefox.support/fennec/netflex",
permissions: &[Permission::Network, Permission::Gpu, Permission::Audio],
move_data: false,
},
Retired {
id: "youtube",
replacement: "support.bluefox.youtube",
source: "https://gitea.bluefox.support/fennec/youtube",
permissions: &[Permission::Network, Permission::Gpu, Permission::Audio, Permission::Dial],
move_data: true,
},
Retired {
id: "steam",
replacement: "support.bluefox.steam",
source: "https://gitea.bluefox.support/fennec/steam",
permissions: &[Permission::Network, Permission::Gpu, Permission::Audio, Permission::Gamepad, Permission::DbusSession],
move_data: true,
},
];
pub fn retired(id: &str) -> Option<&'static Retired> {
RETIRED.iter().find(|r| r.id == id)
}
/// 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,
pub fn is_retired(id: &str) -> bool {
retired(id).is_some()
}
impl Permission {
pub const ALL: [Permission; 7] = [
Permission::Network,
Permission::Gpu,
Permission::Audio,
Permission::Gamepad,
Permission::DbusSession,
Permission::DbusSystem,
Permission::Devices,
];
/// 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",
}
}
pub fn from_key(key: &str) -> Option<Permission> {
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)",
}
}
/// 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<bool>,
#[serde(default)]
pub permissions: Vec<Permission>,
}
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-<id>` 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.<key>}` placeholders.
#[serde(default)]
pub url: Option<String>,
/// Exec apps: command line.
#[serde(default)]
pub exec: Option<Vec<String>>,
/// 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<String>,
/// Sort order on the home row.
#[serde(default)]
pub order: i32,
#[serde(default)]
pub web: WebOptions,
#[serde(default)]
pub dial: Option<DialOptions>,
/// 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<String, String>,
/// Legacy store manifest field. Older signed releases may still contain it.
#[serde(default)]
pub public_key: Option<String>,
/// Store apps: source code / home page, shown on the store screen.
#[serde(default)]
pub homepage: Option<String>,
#[serde(default)]
pub author: Option<String>,
#[serde(default)]
pub license: Option<String>,
/// 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<String>,
/// Appended to the default user agent.
#[serde(default)]
pub user_agent_suffix: Option<String>,
/// Unpacked extensions to load (paths relative to the app folder).
#[serde(default)]
pub extensions: Vec<String>,
}
#[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<String> {
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<String> {
let root = app_root.to_string_lossy();
let mut line: Vec<String> = 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.
pub fn permissions(&self) -> Vec<Permission> {
let mut p = self.sandbox.permissions.clone();
if self.kind == AppKind::Web {
p.extend([Permission::Network, Permission::Gpu, Permission::Audio]);
}
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<PathBuf> {
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");
anyhow::ensure!(self.dial.is_none(), "store apps can't register for DIAL");
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<Vec<AppManifest>> {
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<Vec<AppManifest>> {
let mut apps: Vec<AppManifest> = 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.
/// `sf_app::manifest::load_all`, where a retired official app (the old
/// factory copy in an older image, or its `sf-app-<id>` package) stays only
/// until its store replacement is installed: the TV never loses the app.
pub fn load_all(dirs: &[PathBuf], store: Option<&Path>) -> Result<Vec<AppManifest>> {
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);
let apps = sf_app::manifest::load_all(dirs, store)?;
let replaced = |id: &str| retired(id).is_some_and(|r| apps.iter().any(|a| a.origin == Origin::Store && a.id == r.replacement));
let keep: Vec<bool> = apps.iter().map(|a| a.origin == Origin::Store || !replaced(&a.id)).collect();
Ok(apps.into_iter().zip(keep).filter_map(|(a, k)| k.then_some(a)).collect())
}
/// Moves the data folder of a retired app to its replacement, once the
/// replacement is installed and has no data yet (runs as the TV user).
pub fn migrate_data(apps: &[AppManifest]) {
for r in RETIRED.iter().filter(|r| r.move_data) {
if !apps.iter().any(|a| a.origin == Origin::Store && a.id == r.replacement) {
continue;
}
let (old, new) = (sf_app::paths::app_data_dir(r.id), sf_app::paths::app_data_dir(r.replacement));
if old.is_dir() && std::fs::symlink_metadata(&new).is_err() {
match std::fs::rename(&old, &new) {
Ok(()) => log::info!("moved the data of {} to {}", r.id, r.replacement),
Err(e) => log::warn!("moving {} to {}: {e}", old.display(), new.display()),
}
}
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<u64> { 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<AppManifest> {
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");
fn write(dir: &Path, id: &str, body: &str) {
std::fs::create_dir_all(dir.join(id)).unwrap();
std::fs::write(dir.join(id).join("app.toml"), format!("id = \"{id}\"\nname = \"{id}\"\n{body}")).unwrap();
}
#[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());
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"]);
fn retired_app_stays_until_replaced() {
let base = std::env::temp_dir().join(format!("sf-ipc-retired-{}", std::process::id()));
let (factory, store) = (base.join("factory"), base.join("store"));
write(&factory, "youtube", "kind = \"web\"\nurl = \"https://www.youtube.com/tv\"\n");
write(&factory, "settings", "kind = \"builtin\"\n");
let ids = |apps: Vec<AppManifest>| apps.into_iter().map(|a| a.id).collect::<Vec<_>>();
assert_eq!(ids(load_all(&[factory.clone()], Some(&store)).unwrap()), ["settings", "youtube"]);
write(&store, "support.bluefox.youtube", "kind = \"web\"\nurl = \"https://www.youtube.com/tv\"\n");
let mut got = ids(load_all(&[factory.clone()], Some(&store)).unwrap());
got.sort();
assert_eq!(got, ["settings", "support.bluefox.youtube"]);
std::fs::remove_dir_all(&base).unwrap();
}
}