diff --git a/crates/horizon-client/src/command/mod.rs b/crates/horizon-client/src/command/mod.rs index 79041beb5..728c1f716 100644 --- a/crates/horizon-client/src/command/mod.rs +++ b/crates/horizon-client/src/command/mod.rs @@ -941,8 +941,12 @@ impl Dispatcher { let start = start.min(cursor); let truncated = &parse.input[..cursor.min(parse.input.len())]; let mut all = Vec::new(); - // Brigadier lists every child, whatever its requirement. + // Brigadier lists every child, but the client's tree only holds the + // nodes the player may use (Commands.sendCommands prunes by canUse). for &child in &self.nodes[parent].children { + if self.nodes[child].permission > reg.permission { + continue; + } let mut builder = SuggestionsBuilder::new(truncated, start); match &self.nodes[child].kind { NodeKind::Literal(l) => { diff --git a/crates/horizon-client/src/command/tests.rs b/crates/horizon-client/src/command/tests.rs index ea29da523..1d136059a 100644 --- a/crates/horizon-client/src/command/tests.rs +++ b/crates/horizon-client/src/command/tests.rs @@ -185,6 +185,34 @@ fn vanilla_error_messages() { assert_eq!(e.message.plain(), "argument.block.property.invalid"); } #[test] +fn commands_need_allow_commands() { + // IntegratedServer.getProfilePermissions: the owner of a world without + // Allow Commands is at LevelBasedPermissionSet.ALL. + let reg = Registries { + permission: 0, + ..reg() + }; + let d = vanilla::game_dispatcher(); + let e = d.parse("gamemode creative", ®).executable().unwrap_err(); + assert_eq!(e.message.plain(), "command.unknown.command"); + assert!(d.parse("me waves", ®).executable().is_ok()); + let parse = d.parse("", ®); + let root: Vec = d + .suggestions(&parse, 0, ®) + .1 + .into_iter() + .map(|s| s.text) + .collect(); + // Commands.java with CommandSelection.INTEGRATED: seed and version need no level. + assert_eq!( + root, + [ + "help", "list", "me", "msg", "random", "seed", "teammsg", "tell", "tm", "trigger", + "version", "w" + ] + ); +} +#[test] fn suggestions_like_vanilla() { let root = suggestions(""); assert!(root.contains(&"gamemode".to_owned()) && root.contains(&"tp".to_owned())); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 862138198..9eebc586b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1005,8 +1005,6 @@ struct Game<'a> { chat_capture: Option>, /// State of `/spectate`, `/posteffect`, `/debug`, `/waypoint` and friends. cmds: commands::extra::CommandExtras, - /// Allow Cheats: whether guests may be given commands. - cheats: bool, ui: chat::UiState, combat: combat::CombatTracker, mount: mounts::MountState, @@ -6184,6 +6182,11 @@ impl Game<'_> { level.allow_commands = Some(o.commands(creative)); horizon_client::save::write_world_gen_settings(&save_root, level.seed, o.world_gen())?; } + // Worlds made without the Create New World screen (--world, the + // control socket) take its default: commands on for Creative only. + if created { + level.allow_commands.get_or_insert(creative); + } horizon_client::crash::set_detail("World", format!("{} (saves/{folder})", level.name)); if let Some(d) = &self.options.dimension { level.dimension = d.clone(); @@ -10065,7 +10068,6 @@ pub fn run() -> Result<()> { lan_acting: None, chat_capture: None, cmds: Default::default(), - cheats: true, ui: Default::default(), combat: Default::default(), mount: Default::default(), diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index fcfd5ff3d..13a31b2d5 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -1465,7 +1465,7 @@ impl Game<'_> { self.send_chat(&command); return ok(json!({ "ok": true })); } - self.handle_chat_input(&command); + self.as_console(|g| g.handle_chat_input(&command)); ok(json!({ "ok": true, "chat": self.ui.chat.recent_lines(5) })) } "respawn" if self.remote.is_none() => { diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 169148dcb..aec8db56b 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -90,10 +90,28 @@ pub struct UiState { } impl Game<'_> { + /// `PlayerList.isOp` for the single-player owner: the world's Allow Commands. + pub(super) fn allow_commands(&self) -> bool { + self.level.allow_commands == Some(true) + } + /// `IntegratedServer.setWorldAllowCommands`, then `updatePermissions`. + pub(super) fn set_allow_commands(&mut self, allow: bool) { + self.level.allow_commands = Some(allow); + self.ui.registries.permission = owner_permission(allow); + } + /// Commands the game issues itself (the server console, harnesses, the + /// control socket) run at the owner's level whatever Allow Commands says. + pub(super) fn as_console(&mut self, f: impl FnOnce(&mut Self) -> T) -> T { + let level = std::mem::replace(&mut self.ui.registries.permission, 4); + let out = f(self); + self.ui.registries.permission = level; + out + } /// Registry contents for argument parsing (built when a world opens). pub(super) fn build_registries(&mut self) { + let permission = owner_permission(self.allow_commands()); let reg = &mut self.ui.registries; - reg.permission = 4; + reg.permission = permission; { let dir = |sub: &str| -> Vec { let root = self.options.resources.join("data/minecraft").join(sub); @@ -861,3 +879,9 @@ fn write_difficulty(world: &std::path::Path, difficulty: u8) -> horizon_client:: std::fs::write(&path, Compression::Gzip.encode(&out)?)?; Ok(()) } + +/// `IntegratedServer.getProfilePermissions` for the owner: `OWNER` (4) when +/// commands are allowed, else `ALL` (0). +fn owner_permission(allow_commands: bool) -> u8 { + if allow_commands { 4 } else { 0 } +} diff --git a/crates/horizon-client/src/game/command_harness.rs b/crates/horizon-client/src/game/command_harness.rs index 0409b410c..ed3f8b336 100644 --- a/crates/horizon-client/src/game/command_harness.rs +++ b/crates/horizon-client/src/game/command_harness.rs @@ -89,7 +89,9 @@ impl Game<'_> { let command = op["cmd"].as_str().unwrap_or(""); self.chat_capture = Some(Vec::new()); self.cmds.results = Some(Vec::new()); - self.run_command(command.strip_prefix('/').unwrap_or(command)); + self.as_console(|g| { + g.run_command(command.strip_prefix('/').unwrap_or(command)) + }); let messages = self.chat_capture.take().unwrap_or_default(); let results = self.cmds.results.take().unwrap_or_default(); if op["record"].as_bool() != Some(false) { diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index e73de6988..cd7744d87 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -915,7 +915,7 @@ impl Game<'_> { _ => { // The game's dispatcher, captured for the console. self.chat_capture = Some(Vec::new()); - self.run_command(line); + self.as_console(|g| g.run_command(line)); for text in self.chat_capture.take().unwrap_or_default() { self.console_reply(text); } diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 7faba7f6c..b5ed904bc 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -564,7 +564,7 @@ impl Game<'_> { ); return; } - if !host.settings.guest_commands || !self.cheats { + if !host.settings.guest_commands || !self.allow_commands() { host.hub.send_to( conn, &C::SystemChat(play::SystemChat { diff --git a/crates/horizon-client/src/game/lan_screen.rs b/crates/horizon-client/src/game/lan_screen.rs index f0eb57b3e..b9ba56c5e 100644 --- a/crates/horizon-client/src/game/lan_screen.rs +++ b/crates/horizon-client/src/game/lan_screen.rs @@ -170,7 +170,7 @@ impl Game<'_> { let mut options = WorldOptions { default_mode: self.level.mode(), personal_mode: self.mode_id(), - cheats: self.cheats, + cheats: self.allow_commands(), difficulty: self.ui.difficulty, lan, port, @@ -360,7 +360,7 @@ impl Game<'_> { fn apply_world_options(&mut self, before: &Snapshot, wanted: &Snapshot) { if wanted.difficulty != before.difficulty { let name = DIFFICULTIES[usize::from(wanted.difficulty) & 3]; - self.run_command(&format!("difficulty {name}")); + self.as_console(|g| g.run_command(&format!("difficulty {name}"))); } if wanted.default_mode != before.default_mode { self.set_default_game_mode(wanted.default_mode); @@ -368,7 +368,9 @@ impl Game<'_> { if wanted.personal_mode != before.personal_mode { self.set_mode_id(wanted.personal_mode); } - self.cheats = wanted.cheats; + if wanted.cheats != before.cheats { + self.set_allow_commands(wanted.cheats); + } let settings_changed = wanted.guest_commands != before.guest_commands || wanted.force != before.force; if wanted.lan != before.lan || (wanted.lan && wanted.port != before.port) { diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 9660d237e..94ab7646d 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -2107,8 +2107,8 @@ pub struct Level { pub world_spawn: Option<[i32; 3]>, pub difficulty: String, pub hardcore: bool, - /// `allowCommands` chosen on the Create New World screen; unset keeps - /// the saved value (off for a new world). + /// `allowCommands`: read from `level.dat` or chosen on the Create New + /// World screen; unset is written as off. pub allow_commands: Option, /// Game rule values by name without namespace (`keep_inventory`, ...). pub game_rules: BTreeMap, @@ -2170,6 +2170,7 @@ impl Level { level.difficulty = text(d.get("difficulty")).unwrap_or_else(|| "normal".into()); level.hardcore = n(d.get("hardcore")) != 0; } + level.allow_commands = Some(n(data.get("allowCommands")) != 0); let mut rules: BTreeMap = GAME_RULES .iter() .map(|(k, v)| ((*k).to_owned(), *v)) diff --git a/tools/test_save_roundtrip_parity.py b/tools/test_save_roundtrip_parity.py index a9a718340..068fba3d4 100644 --- a/tools/test_save_roundtrip_parity.py +++ b/tools/test_save_roundtrip_parity.py @@ -346,7 +346,7 @@ def horizon_resave(source, destination, bin_dir): if launch.returncode: sys.exit('horizon failed to launch: ' + launch.stdout + launch.stderr) steps = [['wait-ready', '240']] - steps += [['chat', f'/gamerule {rule} {new}'] for rule, (_, new) in HORIZON_RULES.items()] + steps += [['command', f'gamerule {rule} {new}'] for rule, (_, new) in HORIZON_RULES.items()] steps += [['save-all'], ['quit']] for step in steps: result = subprocess.run(ctl + step, cwd=destination, env=env, capture_output=True, text=True)