diff --git a/docs/launcher-commands.md b/docs/launcher-commands.md index 9dc4382f4..7c9562441 100644 --- a/docs/launcher-commands.md +++ b/docs/launcher-commands.md @@ -323,7 +323,7 @@ Search for packs Horizon loads. - `TEXT` - `--kind` (mod, resource, modpack) - `--everything`: Also what was made for other versions or runs only partly, each marked -- `--source` (modrinth, curseforge) +- `--source` (modrinth, curseforge, horizon) MCP: `mods_search`. @@ -335,7 +335,7 @@ Say how well a Java mod runs in Horizon: its jar is downloaded (checksum checked - `PROJECT` - `--everything`: Allow a version made for another Minecraft version (1.21 and later) -- `--source` (modrinth, curseforge) +- `--source` (modrinth, curseforge, horizon) MCP: `mods_check`. @@ -347,7 +347,7 @@ Install a pack and what it needs, by its id or slug (checksums checked); a Java - `PROJECT` - `--everything`: Allow a version made for another Minecraft version -- `--source` (modrinth, curseforge) +- `--source` (modrinth, curseforge, horizon) MCP: `mods_install`. @@ -372,6 +372,26 @@ Remove a pack the browser installed. MCP: `mods_remove`, needs `confirm: true`. +## `horizon-launcher mods enable` + +Turn on a mod the browser installed (horizon-mods.txt, as the game's Options > Mods does). + + horizon-launcher mods enable + +- `PROJECT` + +MCP: `mods_enable`. + +## `horizon-launcher mods disable` + +Turn off a mod the browser installed; it stays installed. + + horizon-launcher mods disable + +- `PROJECT` + +MCP: `mods_disable`. + ## `horizon-launcher servers list` The servers, their folder and whether they run. diff --git a/docs/mod-browser.md b/docs/mod-browser.md index 7a000cb6c..6c961fd42 100644 --- a/docs/mod-browser.md +++ b/docs/mod-browser.md @@ -149,6 +149,25 @@ horizon-launcher mods remove faithful-32x ## Sources +**Horizon's registry.** Mods (`.hmod`) and resource packs made for Horizon, reviewed as pull requests in +[ludovic111/horizon-mods](https://github.com/ludovic111/horizon-mods) ([api/mod-index.md](api/mod-index.md)). The +launcher reads its `index.json` (`browser/horizon.rs`; `HORIZON_MOD_INDEX=` reads a test +registry instead, whose files may then be on disk) at most every ten minutes, and keeps the last copy in +`mod-browser/horizon-index.json`. Before a result is installed it shows whether its files are signed and, for a mod, +what it may do, in the words of the game's Options > Mods. A download goes to `mod-browser/downloads/` and is moved +into place only after `horizon_mods::index::check_file` passes (size, SHA-256, the author's signature when the project +has a key, the file's own manifest against the index). A mod becomes `horizon-mods/.hmod`, turned on; +`mods disable` and `mods enable` switch it in `horizon-mods.txt`. When the index takes a file down, the launcher turns +it off the next time it reads the index or starts the game, says why, and refuses to install it or turn it back on. +Horizon modpacks (`.hpack`) and shader packs are listed by the index but not installed by this launcher yet. + +```sh +horizon-launcher mods search --source horizon --kind mod coords # with whether it is signed and what it may do +horizon-launcher mods install --source horizon coords_hud +horizon-launcher mods disable coords_hud +``` + + **Modrinth.** The public API (`api.modrinth.com/v2`) needs no key. The launcher names itself in its user agent, as Modrinth asks. diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index 104a086a5..957994f16 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -1636,6 +1636,7 @@ pub fn need_prepared(tag: &str) -> Result<(), String> { pub fn client(tag: &str) -> Result { need_prepared(tag)?; complete_packs(tag); + crate::browser::horizon::before_play(&game_home()); let mut cmd = client_command(tag); // A sign-in that can't be renewed (no network, expired) still lets the game start, offline. if let Err(e) = crate::account::attach_session(&mut cmd, &game_home()) { diff --git a/launcher/src/browser/horizon.rs b/launcher/src/browser/horizon.rs index a54bca17f..53e426ab0 100644 --- a/launcher/src/browser/horizon.rs +++ b/launcher/src/browser/horizon.rs @@ -1,12 +1,13 @@ //! Horizon's own registry (docs/api/mod-index.md): mods, modpacks and resource packs made for //! Horizon, reviewed as pull requests in ludovic111/horizon-mods. One file lists them all, -//! `index.json`: this is the browser source that searches it and downloads its files, checked -//! against the SHA-256 it lists. Versions the index says were taken down are blocked. +//! `index.json`; every download is checked against it before it reaches the game folder +//! (`horizon_mods::index::check_file`: size, SHA-256, the author's signature, the file's own +//! manifest), and files the index says were taken down are refused and turned off. use super::{ details::{Details, Link}, - download, FileRef, Kind, Project, Query, Source, SourceId, Version, GAME, + download, installed, java, FileRef, Kind, Project, Query, Source, SourceId, Version, GAME, }; -use horizon_mods::index::{self, Index}; +use horizon_mods::index::{self, Index, Trust}; use std::fs; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; @@ -110,6 +111,32 @@ fn kind_of(kind: &index::Kind) -> Option { } } +/// What the player reads about a registry project before installing it: whether its files are +/// signed, and for a mod what it may do, in the game's words (Options > Mods). +pub fn trust_and_capabilities(id: &str) -> Vec { + let Ok(index) = index() else { + return Vec::new(); + }; + let Some(p) = index.project(id) else { + return Vec::new(); + }; + let mut lines = vec![match &p.key { + Some(_) => "Signed by its author: the launcher checks the signature".to_owned(), + None => "Unsigned: the launcher checks its checksum only".to_owned(), + }]; + if let Some(v) = p.versions.first().filter(|_| p.kind == index::Kind::Mod) { + lines.extend( + v.capabilities + .iter() + .map(|c| format!("May {}", c.describe())), + ); + if v.capabilities.is_empty() { + lines.push("Asks for nothing beyond its own log".into()); + } + } + lines +} + fn project_of(p: &index::Project) -> Option { let mut game_versions: Vec = p.versions.iter().map(|v| v.game.clone()).collect(); game_versions.dedup(); @@ -276,5 +303,172 @@ fn fetch( } } +/// What the registry adds to an installed entry. +fn trust_label(trust: Trust) -> &'static str { + match trust { + Trust::Verified => "Verified", + Trust::Unsigned => "Unsigned", + } +} + +/// The game folder path a registry project's file goes to. +fn relative(kind: Kind, id: &str, file_name: &str) -> Result { + match kind { + Kind::Mod => Ok(format!("{}/{id}.hmod", java::MODS_DIR)), + Kind::ResourcePack => Ok(format!("resourcepacks/{file_name}")), + Kind::Modpack => { + Err("Modpacks from Horizon's registry install from the Modpacks page.".into()) + } + } +} + +/// Installs a registry project into the game folder `home`: its newest version for this game, +/// downloaded into `mod-browser/downloads/`, checked against the index, then moved into place. +/// A mod is `horizon-mods/.hmod`, turned on in `horizon-mods.txt`. +pub fn install( + project: &Project, + home: &Path, + progress: &dyn Fn(&str, f32), +) -> Result, String> { + install_from(&*index()?, local(), project, home, progress) +} + +fn install_from( + index: &Index, + local: bool, + project: &Project, + home: &Path, + progress: &dyn Fn(&str, f32), +) -> Result, String> { + let p = index + .project(&project.id) + .ok_or_else(|| format!("{} isn't in Horizon's registry.", project.title))?; + let v = p + .versions + .iter() + .find(|v| v.game == GAME && index.revoked(&p.id, &v.file.sha256).is_none()) + .ok_or_else(|| format!("{} has no version for {GAME} to install.", project.title))?; + let relative = relative(project.kind, &p.id, &v.file.name)?; + let mut list = installed::Installed::load(home); + let ours = |e: &installed::Entry| e.source == SourceId::Horizon && e.project == p.id; + let old = list.entries.iter().find(|e| ours(e)).cloned(); + if old.as_ref().is_some_and(|o| o.version == v.version) { + return Ok(vec![old.expect("checked")]); + } + let target = home.join(&relative); + let taken_by = list.entries.iter().find(|e| !ours(e) && e.file == relative); + let folder_mod = home.join(java::MODS_DIR).join(&p.id); + if let Some(other) = taken_by { + return Err(format!( + "{relative} belongs to {}: remove it first.", + other.title + )); + } + if (target.exists() && old.as_ref().is_none_or(|o| o.file != relative)) || folder_mod.exists() { + return Err(format!( + "A mod with the id {} is already in {}: move it away first.", + p.id, + java::MODS_DIR + )); + } + let line = format!("{} {}", p.name, v.version); + let file = &version_of(index, p, v).files[0]; + let staging = home.join("mod-browser/downloads"); + let path = fetch(file, &staging, local, &|f| progress(&line, f))?; + let trust = index::check_file(index, p, v, &path).inspect_err(|_| { + let _ = fs::remove_file(&path); + })?; + if let Some(dir) = target.parent() { + fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + } + fs::rename(&path, &target).map_err(|e| format!("{}: {e}", target.display()))?; + if let Some(old) = old.as_ref().filter(|o| o.file != relative) { + let _ = fs::remove_file(home.join(&old.file)); + } + if project.kind == Kind::Mod { + java::set_enabled(home, &p.id, true)?; + } + let entry = installed::Entry { + source: SourceId::Horizon, + project: p.id.clone(), + slug: p.id.clone(), + title: p.name.clone(), + kind: project.kind, + version: v.version.clone(), + number: v.version.clone(), + file: relative, + checksum: format!("SHA-256:{}", v.file.sha256), + page: project.page.clone(), + dependency: false, + verdict: Some(trust_label(trust).into()), + skipped: Vec::new(), + namespaces: Vec::new(), + }; + list.entries.retain(|e| !ours(e)); + list.entries.push(entry.clone()); + list.save(home)?; + Ok(vec![entry]) +} + +/// The mod id of an installed mod (`horizon-mods/` or `horizon-mods/.hmod`). +pub fn mod_id(entry: &installed::Entry) -> Option<&str> { + let rest = entry.file.strip_prefix(java::MODS_DIR)?.strip_prefix('/')?; + Some(rest.strip_suffix(".hmod").unwrap_or(rest)) +} + +/// Turns the registry's files that were taken down off in the game folder `home`, and says +/// which. Their files stay, so the player sees them and can remove them. +pub fn turn_off_revoked(index: &Index, home: &Path) -> Vec { + let mut out = Vec::new(); + for e in installed::Installed::load(home).entries { + let hash = e.checksum.strip_prefix("SHA-256:").unwrap_or_default(); + let Some(r) = (e.source == SourceId::Horizon) + .then(|| index.revoked(&e.project, hash)) + .flatten() + else { + continue; + }; + if let (Kind::Mod, Some(id)) = (e.kind, mod_id(&e)) { + if java::is_enabled(home, id) && java::set_enabled(home, id, false).is_ok() { + out.push(format!( + "{} was taken down and is off: {}", + e.title, r.reason + )); + } + } else if e.kind == Kind::ResourcePack { + out.push(format!( + "{} was taken down: {} Remove it.", + e.title, r.reason + )); + } + } + out +} + +/// Before the game starts: registry files taken down are turned off, by the index kept last +/// time (no waiting on the network), and the index is fetched again in the background for the +/// next start. Nothing happens when nothing came from the registry. +pub fn before_play(home: &Path) { + let from_registry = installed::Installed::load(home) + .entries + .iter() + .any(|e| e.source == SourceId::Horizon); + if !from_registry { + return; + } + let kept = fs::read_to_string(home.join(CACHE)).ok(); + if let Some(index) = kept.and_then(|t| Index::parse(&t).ok()) { + for line in turn_off_revoked(&index, home) { + eprintln!("{line}"); + } + } + let home = home.to_owned(); + std::thread::spawn(move || { + if let Ok(index) = index() { + turn_off_revoked(&index, &home); + } + }); +} + #[cfg(test)] mod tests; diff --git a/launcher/src/browser/horizon/tests.rs b/launcher/src/browser/horizon/tests.rs index 1ca0cf3ee..b46d7061d 100644 --- a/launcher/src/browser/horizon/tests.rs +++ b/launcher/src/browser/horizon/tests.rs @@ -19,6 +19,16 @@ fn sample() -> Index { index } +fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "horizon-launcher-registry-{name}-{}", + std::process::id() + )); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir +} + fn hud(index: &Index) -> Project { project_of(index.project("coords_hud").unwrap()).unwrap() } @@ -43,6 +53,80 @@ fn searches_by_kind_and_words() { assert_eq!(p.page, "https://playhorizon.dev/mods/coords_hud"); } +#[test] +fn installs_checked_turns_on_and_removes() { + let index = sample(); + let home = scratch("install"); + let p = hud(&index); + let done = install_from(&index, true, &p, &home, &|_, _| {}).unwrap(); + assert_eq!(done[0].file, "horizon-mods/coords_hud.hmod"); + assert_eq!(done[0].verdict.as_deref(), Some("Verified")); + assert!(done[0].checksum.starts_with("SHA-256:e1135345")); + assert!(home.join("horizon-mods/coords_hud.hmod").is_file()); + let list = fs::read_to_string(home.join("horizon-mods.txt")).unwrap(); + assert_eq!(list, "mod.coords_hud:true\n"); + assert_eq!( + fs::read_dir(home.join("mod-browser/downloads")) + .unwrap() + .count(), + 0 + ); + // Installed already: nothing to do. + let again = install_from(&index, true, &p, &home, &|_, _| {}).unwrap(); + assert_eq!(again, done); + + let mut revoked = index.clone(); + revoked.revoked.push(index::Revoked { + id: "coords_hud".into(), + sha256: None, + reason: "Test.".into(), + date: String::new(), + }); + let said = turn_off_revoked(&revoked, &home); + assert_eq!(said, ["Coordinates HUD was taken down and is off: Test."]); + assert_eq!( + fs::read_to_string(home.join("horizon-mods.txt")).unwrap(), + "" + ); + + installed::remove(&home, "coords_hud").unwrap(); + assert!(!home.join("horizon-mods/coords_hud.hmod").exists()); + assert!(installed::Installed::load(&home).entries.is_empty()); + fs::remove_dir_all(&home).unwrap(); +} + +#[test] +fn refuses_a_changed_file_a_taken_id_and_local_files_from_the_real_registry() { + let index = sample(); + let p = hud(&index); + + let home = scratch("tampered"); + let mut tampered = index.clone(); + let cozy = tampered.projects[1].versions[0].file.url.clone(); + tampered.projects[0].versions[0].file.url = cozy; + let e = install_from(&tampered, true, &p, &home, &|_, _| {}).unwrap_err(); + assert!(e.contains("larger than its source says"), "{e}"); + assert!(!home.join("horizon-mods").exists()); + + let e = install_from(&index, false, &p, &home, &|_, _| {}).unwrap_err(); + assert!(e.contains("file servers"), "{e}"); + + fs::create_dir_all(home.join("horizon-mods/coords_hud")).unwrap(); + let e = install_from(&index, true, &p, &home, &|_, _| {}).unwrap_err(); + assert!(e.contains("already in horizon-mods"), "{e}"); + + let mut taken_down = index.clone(); + taken_down.revoked.push(index::Revoked { + id: "coords_hud".into(), + sha256: Some(index.projects[0].versions[0].file.sha256.clone()), + reason: "Test.".into(), + date: String::new(), + }); + let e = install_from(&taken_down, true, &p, &home, &|_, _| {}).unwrap_err(); + assert!(e.contains("no version"), "{e}"); + fs::remove_dir_all(&home).unwrap(); +} + #[test] fn registry_versions_run_when_made_for_this_game() { use super::super::{pick, support, Support}; diff --git a/launcher/src/browser/installed.rs b/launcher/src/browser/installed.rs index 451bdd43e..c866dd26d 100644 --- a/launcher/src/browser/installed.rs +++ b/launcher/src/browser/installed.rs @@ -170,6 +170,9 @@ pub fn install( home: &Path, progress: &dyn Fn(&str, f32), ) -> Result, String> { + if project.source == SourceId::Horizon { + return super::horizon::install(project, home, progress); + } if project.kind == Kind::Mod { return super::java::install(source, project, everything, home, progress); } @@ -248,7 +251,7 @@ pub fn remove(home: &Path, name: &str) -> Result { .lookup(name) .cloned() .ok_or_else(|| format!("{name} wasn't installed by the browser."))?; - if entry.kind == Kind::Mod { + if entry.kind == Kind::Mod && entry.source != SourceId::Horizon { super::java::remove(home, &entry)?; } else { match fs::remove_file(home.join(&entry.file)) { @@ -257,6 +260,9 @@ pub fn remove(home: &Path, name: &str) -> Result { Err(e) => return Err(format!("{}: {e}", entry.file)), } } + if let Some(id) = super::horizon::mod_id(&entry).filter(|_| entry.source == SourceId::Horizon) { + super::java::set_enabled(home, id, false)?; + } installed .entries .retain(|e| !(e.source == entry.source && e.project == entry.project)); diff --git a/launcher/src/browser/java.rs b/launcher/src/browser/java.rs index 62122d1f5..4ac7ae084 100644 --- a/launcher/src/browser/java.rs +++ b/launcher/src/browser/java.rs @@ -110,6 +110,16 @@ pub fn check_project( Ok((version, check)) } +/// Whether mod `id` is on in `horizon-mods.txt`. +pub fn is_enabled(home: &Path, id: &str) -> bool { + let key = format!("mod.{id}"); + fs::read_to_string(home.join(MODS_LIST)) + .unwrap_or_default() + .lines() + .filter_map(|l| l.split_once(':')) + .any(|(k, v)| k.trim() == key && v.trim() == "true") +} + /// Turns mod `id` on (or off) in `horizon-mods.txt`, keeping the other lines. pub fn set_enabled(home: &Path, id: &str, on: bool) -> Result<(), String> { let path = home.join(MODS_LIST); diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index d104fe7eb..4dd5d2d20 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -199,6 +199,10 @@ enum ModsCmd { }, /// Remove a pack the browser installed Remove { project: String }, + /// Turn on a mod the browser installed (horizon-mods.txt, as the game's Options > Mods does) + Enable { project: String }, + /// Turn off a mod the browser installed; it stays installed + Disable { project: String }, } #[derive(Clone, Copy, clap::ValueEnum)] @@ -213,6 +217,8 @@ enum SourceArg { Modrinth, /// CurseForge support is coming soon Curseforge, + /// Horizon's own registry: mods, modpacks and resource packs made for Horizon, reviewed + Horizon, } impl SourceArg { @@ -221,6 +227,7 @@ impl SourceArg { let id = match self { SourceArg::Modrinth => SourceId::Modrinth, SourceArg::Curseforge => SourceId::CurseForge, + SourceArg::Horizon => SourceId::Horizon, }; browser::source(id).ok_or_else(|| browser::CURSEFORGE_SOON.into()) } @@ -1064,11 +1071,23 @@ fn servers(action: ServersCmd, as_json: bool) -> Result<(), String> { } fn mods(action: ModsCmd, as_json: bool) -> Result<(), String> { - use horizon_launcher::browser::{installed, Kind, Query}; + use horizon_launcher::browser::{horizon, installed, Kind, Query, SourceId}; use horizon_launcher::modpacks; let home = backend::game_home(); let entry_json = |e: &installed::Entry| serde_json::to_value(e).unwrap_or_default(); let line = |label: &str, f: f32| progress(label.to_string())(f); + let from_registry = installed::Installed::load(&home) + .entries + .iter() + .any(|e| e.source == SourceId::Horizon); + if from_registry { + if let Ok(index) = horizon::index() { + for said in horizon::turn_off_revoked(&index, &home) { + eprintln!("{said}"); + } + } + } + let on = matches!(action, ModsCmd::Enable { .. }); match action { ModsCmd::List => { let list = installed::Installed::load(&home).entries; @@ -1114,11 +1133,19 @@ fn mods(action: ModsCmd, as_json: bool) -> Result<(), String> { "id": p.id, "slug": p.slug, "title": p.title, "summary": p.summary, "author": p.author, "downloads": p.downloads, "page": p.page, "license": p.license, "support": support.label(), "reason": support.reason(), + "about": if p.source == SourceId::Horizon { horizon::trust_and_capabilities(&p.id) } else { Vec::new() }, }) }).collect()); } else { for p in &found { let support = p.support(); + if p.source == SourceId::Horizon { + println!("{} ({}) {}\n {}", p.title, p.slug, p.author, p.summary); + for line in horizon::trust_and_capabilities(&p.id) { + println!(" {line}"); + } + continue; + } let unchecked = p.kind == Kind::Mod && support.installable(); println!( "{} ({}) {} ยท {} downloads\n {}", @@ -1251,6 +1278,29 @@ fn mods(action: ModsCmd, as_json: bool) -> Result<(), String> { let e = installed::remove(&home, &project)?; println!("Removed {} ({}).", e.title, e.file); } + ModsCmd::Enable { project } | ModsCmd::Disable { project } => { + let e = installed::Installed::load(&home) + .lookup(&project) + .cloned() + .ok_or_else(|| format!("{project} wasn't installed by the browser."))?; + let id = horizon::mod_id(&e) + .filter(|_| e.kind == Kind::Mod) + .ok_or_else(|| format!("{} isn't a mod: only mods turn on and off.", e.title))?; + if on { + if let Some(r) = horizon::index() + .ok() + .filter(|_| e.source == SourceId::Horizon) + .and_then(|i| { + i.revoked(&e.project, e.checksum.trim_start_matches("SHA-256:")) + .cloned() + }) + { + return Err(format!("{} was taken down: {}", e.title, r.reason)); + } + } + horizon_launcher::browser::java::set_enabled(&home, id, on)?; + println!("{} is {}.", e.title, if on { "on" } else { "off" }); + } } Ok(()) }