Merge pull request #1009 from ludovic111/feat/server-config-command

🤖 Agent: merged after verify and CI parity passed (40 server tests; the whole create → start → join → whitelist → backup → restore → update → stop flow ran on the Mac mini and the ThinkPad). Adds `horizon-server config`, `backups --json`, `update --check --json`; fixes whitelisting on offline servers and updates as root in containers.
This commit is contained in:
Ludovic Marie
2026-10-19 16:21:56 +02:00
committed by GitHub
8 changed files with 446 additions and 13 deletions
+17 -2
View File
@@ -303,9 +303,24 @@ pub fn backup(dir: &Path, name: Option<&str>) -> Result<(), String> {
Ok(())
}
/// `backups`: the backups, newest first.
pub fn backups(dir: &Path) -> Result<(), String> {
/// `backups [--json]`: the backups, newest first.
pub fn backups(dir: &Path, as_json: bool) -> Result<(), String> {
let all = backup::list(dir);
if as_json {
let list: Vec<Value> = all
.iter()
.map(|b| {
let modified = std::fs::metadata(dir.join(backup::DIR).join(&b.name))
.and_then(|m| m.modified())
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_secs());
json!({ "name": b.name, "bytes": b.bytes, "modified": modified })
})
.collect();
println!("{}", Value::Array(list));
return Ok(());
}
if all.is_empty() {
println!("No backups yet: `horizon-server backup` makes one.");
}
+10 -2
View File
@@ -446,10 +446,18 @@ pub fn sync_back(dir: &Path, written: &[(String, String)]) -> Result<Vec<String>
/// Sets one typed setting in `server.toml` (`whitelist on`), keeping the owner's comments.
pub fn update(dir: &Path, section: &str, field: &str, value: toml::Value) -> Result<(), String> {
update_all(dir, &[(section.to_owned(), field.to_owned(), value)])
}
/// Sets settings in `server.toml`, keeping the owner's comments; nothing is written unless the result is
/// a valid configuration.
pub fn update_all(dir: &Path, changes: &[(String, String, toml::Value)]) -> Result<(), String> {
let path = dir.join(FILE);
let text = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
let mut doc: toml_edit::DocumentMut = text.parse().map_err(|e| format!("{e}"))?;
set(&mut doc, section, field, &value);
for (section, field, value) in changes {
set(&mut doc, section, field, value);
}
let updated = doc.to_string();
Config::parse(&updated)?;
std::fs::write(&path, updated).map_err(|e| e.to_string())
@@ -503,7 +511,7 @@ fn typed_value(text: &str, like: &toml::Value) -> Option<toml::Value> {
}
/// A server.properties value for `[properties]`: a boolean or a number when it reads back the same.
fn loose_value(text: &str) -> toml::Value {
pub fn loose_value(text: &str) -> toml::Value {
match text {
"true" => toml::Value::Boolean(true),
"false" => toml::Value::Boolean(false),
+38
View File
@@ -1,6 +1,11 @@
//! `op`, `deop` and `whitelist`. While the server runs, the game owns the lists: the command goes to its
//! console. While it is stopped, they edit vanilla's files with the code the game reads them with
//! (horizon-server-files) and answer with vanilla's console messages.
//!
//! One exception: `whitelist add` on a running offline server. The game asks Mojang for the name first, as
//! vanilla does, so a name someone owns gets that account's UUID, and the player, who joins under the
//! offline UUID, is still refused. There the offline entry is written to whitelist.json and the game
//! reloads it (`whitelist reload`), as it would be written while the server is stopped.
use crate::{config, supervisor};
use horizon_server_files::user_lists::{NameAndId, OpEntry, OpList, WhiteEntry, WhiteList};
@@ -10,6 +15,12 @@ pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> {
let config = config::Config::load(dir)?;
// Holding the folder's lock keeps the server from starting halfway through.
let Ok(_lock) = supervisor::lock(dir) else {
if let ("whitelist", [add, name]) = (command, args)
&& add == "add"
&& !config.server.online_mode
{
return add_offline(dir, name);
}
let mut words = vec![command.to_owned()];
words.extend_from_slice(args);
return crate::cli::command(dir, &words);
@@ -99,6 +110,26 @@ pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> {
Ok(())
}
/// `whitelist add` on a running offline server: the offline entry, then the game reloads the list.
fn add_offline(dir: &Path, name: &str) -> Result<(), String> {
if crate::api::Client::open(dir)?.is_none() {
return Err(format!("no server is running in {}", dir.display()));
}
let user = account(name, false)?;
let mut white = load(WhiteList::new(dir.join("whitelist.json")))?;
if white.contains(&user) {
println!("Player is already whitelisted");
return Ok(());
}
white.add(WhiteEntry { user });
white
.save()
.map_err(|e| format!("{}: {e}", white.file.display()))?;
crate::cli::command(dir, &["whitelist".to_owned(), "reload".to_owned()])?;
println!("Added {name} to the whitelist");
Ok(())
}
/// The profile a running server would store for `name`: the offline one, or in online mode the account the
/// services know by that name.
pub fn account(name: &str, online: bool) -> Result<NameAndId, String> {
@@ -161,12 +192,19 @@ mod tests {
// A running server owns the lists: without its API, nothing changes.
let lock = supervisor::lock(&dir).unwrap();
assert!(run(&dir, "op", &s(&["Alex"])).is_err());
config::update(&dir, "server", "online_mode", toml::Value::Boolean(false)).unwrap();
assert!(run(&dir, "whitelist", &s(&["add", "Kai"])).is_err());
drop(lock);
assert!(
!std::fs::read_to_string(dir.join("ops.json"))
.unwrap()
.contains("Alex")
);
assert!(
!std::fs::read_to_string(dir.join("whitelist.json"))
.unwrap()
.contains("Kai")
);
std::fs::remove_dir_all(&dir).unwrap();
}
}
+12 -3
View File
@@ -11,6 +11,7 @@ mod init;
mod lists;
mod panel;
mod service;
mod settings;
mod signals;
mod supervisor;
mod update;
@@ -37,7 +38,8 @@ Usage: horizon-server [--dir DIR] <command>
The last N lines of the log (default 50); -f follows it
backup [NAME]
Zip the world and the settings into backups/ (a running server saves first and stays up)
backups List the backups
backups [--json]
List the backups
restore BACKUP [--yes]
Put a backup's world in place (the current one is kept in backups/); a running
server restarts with it
@@ -46,11 +48,17 @@ Usage: horizon-server [--dir DIR] <command>
with sudo), a launchd agent on macOS, a task at logon on Windows
panel A one-time login link for the web panel ([panel] in server.toml; 127.0.0.1:8130 by
default)
update [--check] [--version TAG] [--timeout SECONDS]
update [--check [--json]] [--version TAG] [--timeout SECONDS]
Install the newest release (checked against GitHub's SHA-256), back up the world and
restart on it; goes back by itself if the game isn't up within the timeout (300 s).
--archive FILE --version NAME installs an archive you have
rollback Back to the release used before the update
config [--json]
The settings in server.toml
config set KEY=VALUE... [--json]
Change settings (for example world.difficulty=hard server.max_players=10), checked first;
a running server takes the difficulty, default game mode and whitelist at once, the rest
at its next start
import FILE Write server.toml from a vanilla server.properties
op NAME, deop NAME
whitelist on|off|list, whitelist add|remove NAME
@@ -91,13 +99,14 @@ fn main() -> ExitCode {
Some("logs") => logs(&dir, &args[1..]),
Some("panel") => cli::panel(&dir),
Some("backup") => cli::backup(&dir, args.get(1).map(String::as_str)),
Some("backups") => cli::backups(&dir),
Some("backups") => cli::backups(&dir, args[1..].iter().any(|a| a == "--json")),
Some("service") => service::command(&dir, &args[1..]),
Some("restore") => match args.get(1) {
Some(name) => cli::restore(&dir, name, args[2..].iter().any(|a| a == "--yes")),
None => Err("restore needs a backup (`horizon-server backups` lists them)".into()),
},
Some("import") => import(&dir, &args[1..]),
Some("config") => settings::command(&dir, &args[1..]),
Some("update") => update::command(&dir, &args[1..]),
Some("rollback") => update::rollback(&dir, &args[1..]),
Some(command @ ("op" | "deop" | "whitelist")) => lists::run(&dir, command, &args[1..]),
+330
View File
@@ -0,0 +1,330 @@
//! `horizon-server config`: read server.toml's settings, and change them the way the server checks them
//! (docs/server.md, section 4). A running server takes what vanilla can change live through its console
//! (difficulty, the default game mode, the whitelist) at once; the rest applies at the next start.
use crate::{api::Client, config};
use serde_json::{Value, json};
use std::path::Path;
/// `config [--json]` and `config set KEY=VALUE... [--json]`.
pub fn command(dir: &Path, args: &[String]) -> Result<(), String> {
let as_json = args.iter().any(|a| a == "--json");
let args: Vec<&str> = args
.iter()
.map(String::as_str)
.filter(|a| *a != "--json")
.collect();
match args.as_slice() {
[] => show(dir, as_json),
["set", changes @ ..] if !changes.is_empty() => {
let outcome = set(dir, changes)?;
if as_json {
println!("{}", outcome.to_json());
} else {
print!("{}", outcome.describe());
}
Ok(())
}
_ => Err(
"config takes no arguments, or `set KEY=VALUE...` (for example: config set world.difficulty=hard)"
.into(),
),
}
}
fn show(dir: &Path, as_json: bool) -> Result<(), String> {
let cfg = config::Config::load(dir)?;
let table = toml::Table::try_from(&cfg).map_err(|e| e.to_string())?;
if as_json {
println!(
"{}",
serde_json::to_value(&table).map_err(|e| e.to_string())?
);
return Ok(());
}
for (section, values) in &table {
for (key, value) in values.as_table().into_iter().flatten() {
println!("{section}.{key} = {value}");
}
}
Ok(())
}
/// What `config set` did.
#[derive(Debug, Default, PartialEq)]
pub struct Outcome {
/// Every setting written to server.toml.
pub saved: Vec<String>,
/// Those the running server took at once.
pub applied: Vec<String>,
/// Those that wait for the game's next start, while it runs.
pub restart: Vec<String>,
pub running: bool,
}
impl Outcome {
fn to_json(&self) -> Value {
json!({
"saved": self.saved,
"applied": self.applied,
"restart": self.restart,
"running": self.running,
})
}
fn describe(&self) -> String {
if !self.running {
return format!(
"Saved {}: the server uses them from its next start.\n",
self.saved.join(", ")
);
}
let mut out = String::new();
if !self.applied.is_empty() {
out += &format!("Applied now: {}\n", self.applied.join(", "));
}
if !self.restart.is_empty() {
out += &format!(
"Saved; restart the server to apply: {} (`horizon-server restart`)\n",
self.restart.join(", ")
);
}
out
}
}
/// One `KEY=VALUE`: the section, the field and the value as server.toml types it.
pub fn parse_change(
current: &toml::Table,
change: &str,
) -> Result<(String, String, toml::Value), String> {
let (key, text) = change
.split_once('=')
.ok_or_else(|| format!("{change:?}: write KEY=VALUE, like world.difficulty=hard"))?;
let (section, field) = key
.trim()
.split_once('.')
.ok_or_else(|| format!("{key:?}: name a setting as section.name, like server.port"))?;
let text = text.trim();
let value = if section == "properties" {
config::loose_value(text)
} else {
let like = current
.get(section)
.and_then(|s| s.get(field))
.ok_or_else(|| {
format!("{key} is not a setting (`horizon-server config` lists them)")
})?;
match like {
toml::Value::Boolean(_) => toml::Value::Boolean(match text {
"true" | "on" | "yes" => true,
"false" | "off" | "no" => false,
_ => return Err(format!("{key} is on or off: use true or false")),
}),
toml::Value::Integer(_) => toml::Value::Integer(
text.parse()
.map_err(|_| format!("{key} is a number, not {text:?}"))?,
),
_ => toml::Value::String(text.to_owned()),
}
};
if let (Some(range), toml::Value::Integer(n)) = (range(section, field), &value)
&& !range.contains(n)
{
return Err(format!(
"{key} is {n}: use {} to {}",
range.start(),
range.end()
));
}
Ok((section.to_owned(), field.to_owned(), value))
}
/// The values vanilla uses for the numbers it clamps (`ChunkMap` keeps both distances within 2 to 32).
fn range(section: &str, field: &str) -> Option<std::ops::RangeInclusive<i64>> {
match (section, field) {
("server", "view_distance" | "simulation_distance") => Some(2..=32),
("server", "max_players") => Some(1..=1000),
("backups", "keep") => Some(1..=1000),
_ => None,
}
}
/// The console command that applies a setting to a running game, if vanilla has one; `Some("")` for the
/// settings the supervisor itself reads every time (backups, updates).
pub fn live_command(section: &str, field: &str, value: &toml::Value) -> Option<String> {
let text = match value {
toml::Value::String(s) => s.clone(),
other => other.to_string(),
};
match (section, field) {
("world", "difficulty") => Some(format!("difficulty {text}")),
("world", "game_mode") => Some(format!("defaultgamemode {text}")),
("server", "whitelist") => Some(format!(
"whitelist {}",
if value.as_bool() == Some(true) {
"on"
} else {
"off"
}
)),
("backups" | "updates", _) => Some(String::new()),
_ => None,
}
}
pub fn set(dir: &Path, changes: &[&str]) -> Result<Outcome, String> {
let current = toml::Table::try_from(config::Config::load(dir)?).map_err(|e| e.to_string())?;
let parsed = changes
.iter()
.map(|c| parse_change(&current, c))
.collect::<Result<Vec<_>, _>>()?;
config::update_all(dir, &parsed)?;
let mut outcome = Outcome {
saved: parsed.iter().map(|(s, f, _)| format!("{s}.{f}")).collect(),
..Outcome::default()
};
let Some(client) = Client::open(dir)? else {
return Ok(outcome);
};
outcome.running = true;
let up = client
.call("GET", "/api/v1/status", None)
.is_ok_and(|s| s["phase"] == "running");
for (section, field, value) in &parsed {
let key = format!("{section}.{field}");
let unchanged = current.get(section).and_then(|s| s.get(field)) == Some(value);
match live_command(section, field, value) {
_ if unchanged => {}
Some(line) if line.is_empty() => outcome.applied.push(key),
Some(line)
if up
&& client
.call("POST", "/api/v1/command", Some(&json!({ "line": line })))
.is_ok() =>
{
outcome.applied.push(key)
}
_ => outcome.restart.push(key),
}
}
Ok(outcome)
}
#[cfg(test)]
mod tests {
use super::*;
fn table() -> toml::Table {
toml::Table::try_from(config::Config::default()).unwrap()
}
#[test]
fn changes_take_the_settings_types() {
let t = table();
assert_eq!(
parse_change(&t, "server.max_players=8").unwrap(),
(
"server".into(),
"max_players".into(),
toml::Value::Integer(8)
)
);
assert_eq!(
parse_change(&t, "server.whitelist=off").unwrap().2,
toml::Value::Boolean(false)
);
assert_eq!(
parse_change(&t, "server.motd= Friends only ").unwrap().2,
toml::Value::String("Friends only".into())
);
assert_eq!(
parse_change(&t, "properties.spawn-protection=0").unwrap(),
(
"properties".into(),
"spawn-protection".into(),
toml::Value::Integer(0)
)
);
for (bad, says) in [
("server.view_distance=40", "use 2 to 32"),
("server.max_players=many", "is a number"),
("server.online_mode=maybe", "use true or false"),
("server.colour=red", "is not a setting"),
("difficulty=hard", "section.name"),
("world.difficulty", "KEY=VALUE"),
] {
let e = parse_change(&t, bad).unwrap_err();
assert!(e.contains(says), "{bad}: {e}");
}
}
#[test]
fn vanilla_changes_these_live() {
let s = |v: &str| toml::Value::String(v.into());
assert_eq!(
live_command("world", "difficulty", &s("hard")).as_deref(),
Some("difficulty hard")
);
assert_eq!(
live_command("world", "game_mode", &s("creative")).as_deref(),
Some("defaultgamemode creative")
);
assert_eq!(
live_command("server", "whitelist", &toml::Value::Boolean(false)).as_deref(),
Some("whitelist off")
);
assert_eq!(
live_command("backups", "every", &s("1h")).as_deref(),
Some("")
);
assert_eq!(
live_command("server", "view_distance", &toml::Value::Integer(8)),
None
);
}
#[test]
fn a_stopped_server_saves_and_keeps_comments() {
let dir =
std::env::temp_dir().join(format!("horizon-server-config-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join(config::FILE), config::TEMPLATE).unwrap();
let outcome = set(
&dir,
&[
"world.difficulty=hard",
"server.max_players=5",
"backups.every=0",
],
)
.unwrap();
assert_eq!(
outcome,
Outcome {
saved: vec![
"world.difficulty".into(),
"server.max_players".into(),
"backups.every".into()
],
..Outcome::default()
}
);
let text = std::fs::read_to_string(dir.join(config::FILE)).unwrap();
assert!(
text.contains("difficulty = \"hard\" # peaceful, easy, normal or hard"),
"{text}"
);
let cfg = config::Config::load(&dir).unwrap();
assert_eq!(
(cfg.server.max_players, cfg.backups.every.as_str()),
(5, "0")
);
// Checked as the server checks it: nothing is written.
assert!(set(&dir, &["world.difficulty=impossible"]).is_err());
assert!(set(&dir, &["world.name=a/b", "server.port=1"]).is_err());
assert_eq!(config::Config::load(&dir).unwrap(), cfg);
std::fs::remove_dir_all(&dir).unwrap();
}
}
+18 -1
View File
@@ -368,8 +368,11 @@ pub fn unpack(install: &Install, archive: &Path, tag: &str) -> Result<PathBuf, S
.and_then(|mut z| z.extract(&scratch))
.map_err(|e| format!("{}: {e}", archive.display()))?;
} else if name.ends_with(".tar.gz") || name.ends_with(".tgz") {
// tar is on every Linux and macOS, and on Windows 10 and later.
// tar is on every Linux and macOS, and on Windows 10 and later. The files are the
// user's, not the archive's owners: as root in a user namespace (an unprivileged LXC
// or rootless container) taking those fails, and as plain root they'd be strangers'.
let status = Command::new("tar")
.arg("--no-same-owner")
.arg("-xzf")
.arg(archive)
.arg("-C")
@@ -455,6 +458,7 @@ pub fn backup_name(tag: &str) -> String {
/// `update [--check] [--version TAG] [--archive FILE --version TAG] [--timeout SECONDS]`.
pub fn command(dir: &Path, args: &[String]) -> Result<(), String> {
let mut check = false;
let mut as_json = false;
let mut version = None;
let mut archive = None;
let mut timeout = crate::api::UPDATE_TIMEOUT;
@@ -467,6 +471,7 @@ pub fn command(dir: &Path, args: &[String]) -> Result<(), String> {
};
match arg.as_str() {
"--check" => check = true,
"--json" => as_json = true,
"--version" => version = Some(value()?),
"--archive" => archive = Some(PathBuf::from(value()?)),
"--timeout" => timeout = seconds(&value()?)?,
@@ -486,6 +491,18 @@ pub fn command(dir: &Path, args: &[String]) -> Result<(), String> {
}
None => {
let release = release(version.as_deref())?;
if check && as_json {
println!(
"{}",
json!({
"installed": current,
"newest": release.tag,
"available": newer(&release.tag, &current),
"previous": install.previous(),
})
);
return Ok(());
}
if check {
if newer(&release.tag, &current) {
println!(
+14 -2
View File
@@ -13,7 +13,10 @@ plan are in [docs/server.md](https://github.com/ludovic111/horizon/blob/main/doc
- **Names you add are accounts** (release v2026.10.17.14 and newer). `init --player`, `horizon-server
whitelist add` and `op`, and the console's `whitelist add`, `op` and `ban` look a name up the way vanilla
does: players already seen (kept in `usercache.json`), then Mojang's profile service. In online mode a name
with no account is refused. So you can whitelist friends before they first join.
with no account is refused. So you can whitelist friends before they first join. On an offline server,
`horizon-server whitelist add` always writes the offline UUID, the one the player joins with, also while
the server runs (it writes the entry and the game reloads the list): the console's own `whitelist add`
takes the account's UUID when someone owns that name, as vanilla does, and that player is then refused.
- **Horizon's own client can't sign in to a Microsoft account yet.** That needs an Azure app registration and
Mojang's approval, which the project doesn't have
([docs/microsoft-account.md](https://github.com/ludovic111/horizon/blob/main/docs/microsoft-account.md)).
@@ -199,11 +202,13 @@ horizon-server op|deop NAME
horizon-server whitelist on|off|list
horizon-server whitelist add|remove NAME
horizon-server backup [NAME] back up now
horizon-server backups list the backups
horizon-server backups [--json] list the backups
horizon-server restore BACKUP [--yes]
horizon-server service install|uninstall|print [--system]
horizon-server panel a one-time login link for the web panel
horizon-server import FILE server.toml from a vanilla server.properties
horizon-server config [--json] the settings in server.toml
horizon-server config set KEY=VALUE... change settings, checked first (below)
horizon-server update [--check] install the newest release and restart on it (below)
horizon-server rollback back to the release before
```
@@ -212,6 +217,13 @@ While the server runs, `op`, `whitelist` and `cmd` go to the game's console, so
console commands do. While it's stopped, they edit vanilla's files directly. Any console command works through
`cmd`: `horizon-server cmd ban Griefer`, `horizon-server cmd say Restarting in 5 minutes`.
`config set` changes `server.toml` without opening it: `horizon-server config set world.difficulty=hard
server.max_players=10`. Each key is a section and a name from the file (`properties.spawn-protection=0` for any
other vanilla key). The values are checked as the server checks them, and nothing is written if one is wrong.
A running server takes the difficulty, the default game mode, the whitelist and the backup settings at once;
the rest applies at its next start, and `config set` says which. `--json` prints that as `saved`, `applied`
and `restart`.
The server restarts the game by itself if it crashes: after 5 s, then waiting longer each time, up to 5
minutes. It keeps the crash report and gives up after 5 crashes in 10 minutes, and `status` says why.
+7 -3
View File
@@ -308,9 +308,12 @@ a typed key set again under `[properties]` and values vanilla would refuse. Plan
After it stops, the supervisor compares the file with what it wrote and copies any changed keys back into
`server.toml`, so an in-game change survives the next start. Edits go through `toml_edit`, so the owner's
comments and order are kept.
- **Reload (planned).** The four lists already reload through the engine (`whitelist reload`). `reload` will
send what can change live and say which settings need a restart. A real hot reload (view distance, MOTD) needs engine
support and comes later.
- **Changes without opening the file.** `horizon-server config set KEY=VALUE...` (the launcher's Servers
page uses it) writes through `toml_edit`, checks the result as `server.toml` is checked, and writes nothing
if a value is wrong. On a running server it sends what vanilla changes live through its console:
`difficulty`, `defaultgamemode` and `whitelist on|off`; the backup settings apply at once because the
supervisor reads them each time. Everything else waits for the next start, and the command says which. A
real hot reload (view distance, MOTD) needs engine support and comes later.
- `server.properties`, `ops.json`, `whitelist.json`, `banned-*.json` and `world/` keep vanilla's names and
formats. A vanilla server folder works as is, and so does going back to vanilla.
@@ -327,6 +330,7 @@ horizon-server op|deop <player>
horizon-server whitelist on|off|list|add|remove [player]
horizon-server backup [NAME] backups restore <backup> [--yes]
horizon-server import <server.properties>
horizon-server config [--json] config set KEY=VALUE... [--json]
horizon-server service install|uninstall|print [--system]
horizon-server panel the panel's address and a one-time login link
horizon-server update [--check] [--version vX.Y.Z] [--timeout S] rollback [--timeout S]