Commands follow the world's Allow Commands (#372)
The single-player owner was always at permission level 4. Like IntegratedServer.getProfilePermissions, the owner now gets OWNER (4) only when the world allows commands, else ALL (0): /gamemode, /give and friends answer "Unknown or incomplete command" and are not suggested (the client's tree only holds usable nodes, Commands.sendCommands). allowCommands is read from level.dat, set by World Options, and worlds made without the Create New World screen take its default (Creative only). The server console, the command harness and horizon-ctl `command` keep the owner's level. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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) => {
|
||||
|
||||
@@ -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<String> = 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()));
|
||||
|
||||
@@ -1005,8 +1005,6 @@ struct Game<'a> {
|
||||
chat_capture: Option<Vec<horizon_client::text::Text>>,
|
||||
/// 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(),
|
||||
|
||||
@@ -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() => {
|
||||
|
||||
@@ -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<T>(&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<String> {
|
||||
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 }
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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<bool>,
|
||||
/// Game rule values by name without namespace (`keep_inventory`, ...).
|
||||
pub game_rules: BTreeMap<String, i32>,
|
||||
@@ -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<String, i32> = GAME_RULES
|
||||
.iter()
|
||||
.map(|(k, v)| ((*k).to_owned(), *v))
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user