Volver al índice

src/main/java/ar/com/companeros/world/PlayerCommands.java

package ar.com.companeros.world;

import ar.com.companeros.action.ToolResult;
import com.google.gson.*;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import net.minecraft.core.GlobalPos;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.fml.loading.FMLPaths;

/** Comandos de Minecraft ejecutados por el cuerpo del jugador, con sus permisos reales. */
public final class PlayerCommands {
    private static final Set<String> FORBIDDEN = Set.of("op", "deop", "stop", "restart", "reload", "execute", "function", "schedule",
        "eval", "exec", "kubejs", "script", "scripts", "js", "javascript", "python", "py", "shell", "sh", "bash", "powershell", "cmd",
        "run", "sudo", "source", "load", "upload", "download", "debug", "jfr", "perf", "save-all", "save-on", "save-off",
        "kick", "ban", "ban-ip", "pardon", "pardon-ip", "whitelist");
    private static final Map<MinecraftServer, Map<UUID, Long>> LAST = new WeakHashMap<>();
    private static final Map<MinecraftServer, ar.com.companeros.social.ChatRepeatGuard> CHAT = new WeakHashMap<>();
    public static final String DEFAULT_JSON = """
        {
          "schemaVersion": 1,
          "enabled": true,
          "allowSelfTeleport": false,
          "allowedCommands": ["msg", "tell", "w", "me", "trigger", "teammsg", "tm", "time", "weather", "tp", "teleport", "gamemode", "difficulty", "gamerule", "effect", "enchant", "team", "scoreboard", "locate", "seed"],
          "operatorCommands": ["time", "weather", "tp", "teleport", "gamemode", "difficulty", "gamerule", "effect", "enchant", "team", "scoreboard", "locate", "seed"]
        }
        """;
    private PlayerCommands() { }

    // Texto: una sola instrucción, raíz normalizada y argumentos conservados.
    public static String normalize(String raw) {
        if (raw == null || raw.isBlank() || raw.length() > 512 || raw.codePoints().anyMatch(c -> Character.isISOControl(c) || Character.getType(c) == Character.FORMAT
                || Character.getType(c) == Character.LINE_SEPARATOR || Character.getType(c) == Character.PARAGRAPH_SEPARATOR))
            throw new IllegalArgumentException("Comando vacío, múltiple o demasiado largo");
        String command = raw.strip();
        if (command.startsWith("/")) command = command.substring(1);
        if (command.isBlank() || command.startsWith("/") || command.contains(";") || command.contains("|") || command.contains("&&")
                || command.contains("`") || command.contains("$(") || command.contains("\\") || command.contains("../")
                || command.matches("(?is).*\\b(?:[a-z]:/|file:|https?://).*")
                || command.matches("(?s).*(?:^|\\s|[\"'=])/[A-Za-z0-9_.-]+(?:/|\\b).*"))
            throw new IllegalArgumentException("No se admiten cadenas, scripts ni rutas de archivos");
        int separator = command.indexOf(' ');
        String root = (separator < 0 ? command : command.substring(0, separator)).toLowerCase(Locale.ROOT);
        if (root.length() > 80 || !root.matches("(?:[a-z0-9_.-]+:)?[a-z0-9_.-]+")) throw new IllegalArgumentException("Raíz de comando inválida");
        String leaf = root.substring(root.indexOf(':') + 1);
        String namespace = root.contains(":") ? root.substring(0, root.indexOf(':')) : "";
        if (FORBIDDEN.contains(leaf) || FORBIDDEN.contains(namespace)
                || root.matches(".*(?:kubejs|javascript|python|powershell|shell|script).*"))
            throw new IllegalArgumentException("Comando de sistema, wrapper o administración restringida");
        return root + (separator < 0 ? "" : command.substring(separator));
    }

    // Configuración: sólo el operador elige raíces conocidas; se recarga en cada uso.
    private record Settings(boolean enabled, Set<String> allowed, Set<String> operator, boolean selfTeleport) { }
    private static Settings settings() throws IOException {
        Path root = FMLPaths.CONFIGDIR.get().resolve("raps");
        Path file = root.resolve("commands.json");
        if (!Files.exists(file)) {
            Files.createDirectories(root);
            Files.writeString(file, DEFAULT_JSON, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW);
        }
        if (Files.isSymbolicLink(file) || !Files.isRegularFile(file) || Files.size(file) > 16384) throw new IOException("Configuración inválida");
        JsonObject json = JsonParser.parseString(Files.readString(file, StandardCharsets.UTF_8)).getAsJsonObject();
        if (json.get("schemaVersion").getAsInt() != 1) throw new IOException("Versión de configuración inválida");
        return new Settings(json.get("enabled").getAsBoolean(), roots(json.getAsJsonArray("allowedCommands")), roots(json.getAsJsonArray("operatorCommands")),
            json.has("allowSelfTeleport") && json.get("allowSelfTeleport").getAsBoolean());
    }
    private static Set<String> roots(JsonArray entries) {
        if (entries == null || entries.size() > 128) throw new IllegalArgumentException("Lista de comandos inválida");
        Set<String> result = new HashSet<>();
        for (JsonElement entry : entries) {
            if (!entry.isJsonPrimitive() || !entry.getAsJsonPrimitive().isString()) throw new IllegalArgumentException("Raíz inválida");
            String root = normalize(entry.getAsString());
            if (root.contains(" ") || root.length() > 80) throw new IllegalArgumentException("La lista admite sólo raíces");
            result.add(root);
        }
        return Set.copyOf(result);
    }
    private static boolean listed(Set<String> roots, String root) {
        return roots.contains(root) || root.startsWith("minecraft:") && roots.contains(root.substring(10));
    }

    // Catálogo para decidir: sólo raíces existentes que este jugador puede usar, sin ejecutar comandos.
    public static String describeAvailable(ServerPlayer player) {
        if (player == null || !player.server.isSameThread()) return "Comandos Minecraft: cuerpo de jugador no disponible.";
        final Settings config;
        try { config = settings(); }
        catch (IOException | RuntimeException rejected) { return "Comandos Minecraft: configuración no disponible."; }
        if (!config.enabled()) return "Comandos Minecraft deshabilitados por el operador.";
        var source = player.createCommandSourceStack();
        var dispatcher = player.server.getCommands().getDispatcher();
        int permissionLevel = 0;
        for (int level = 4; level >= 1; level--) if (source.hasPermission(level)) { permissionLevel = level; break; }
        List<String> available = config.allowed().stream().filter(root -> {
            var node = dispatcher.getRoot().getChild(root);
            return node != null && node.canUse(source) && (!listed(config.operator(), root) || source.hasPermission(2));
        }).sorted().toList();
        StringJoiner roots = new StringJoiner(",");
        int shown = 0;
        for (String root : available) {
            if (shown >= 20 || roots.length() + root.length() + (shown == 0 ? 0 : 1) > 200) continue;
            roots.add(root); shown++;
        }
        return "Permiso real=" + permissionLevel + "; permitidos=" + (shown == 0 ? "ninguno" : roots)
            + (shown < available.size() ? " (+" + (available.size() - shown) + ")" : "")
            + ". Entrada command, ej. /msg Nombre mensaje. Minecraft valida subcomandos; intervalo 40 ticks.";
    }

    // Ejecución: Brigadier recibe la fuente del jugador; nunca se eleva su permiso.
    public static ToolResult execute(ServerPlayer player, UUID invocation, String raw) {
        MinecraftServer server = player.server;
        if (!server.isSameThread()) return result(player, invocation, ToolResult.Status.BLOCKED, ToolResult.Reason.CONDITIONS_CHANGED, "command_server_thread_required");
        final String command;
        try { command = normalize(raw); }
        catch (IllegalArgumentException rejected) { return result(player, invocation, ToolResult.Status.BLOCKED, ToolResult.Reason.INVALID_ARGUMENT, "command_rejected"); }
        String root = command.split(" ", 2)[0];
        final Settings config;
        try { config = settings(); }
        catch (IOException | RuntimeException rejected) { return result(player, invocation, ToolResult.Status.BLOCKED, ToolResult.Reason.CONDITIONS_CHANGED, "command_config_invalid"); }
        if (!config.enabled() || !listed(config.allowed(), root))
            return result(player, invocation, ToolResult.Status.BLOCKED, ToolResult.Reason.PERMISSION_DENIED, "command_not_allowed:" + root);
        var source = player.createCommandSourceStack();
        var dispatcher = server.getCommands().getDispatcher();
        var node = dispatcher.getRoot().getChild(root);
        if (node == null) return result(player, invocation, ToolResult.Status.BLOCKED, ToolResult.Reason.UNSUPPORTED, "command_unknown:" + root);
        if (!node.canUse(source) || listed(config.operator(), root) && !source.hasPermission(2))
            return result(player, invocation, ToolResult.Status.BLOCKED, ToolResult.Reason.PERMISSION_DENIED, "command_permission_denied:" + root);
        long now = server.overworld().getGameTime();
        String leaf = root.substring(root.indexOf(':') + 1);
        String[] whisper = Set.of("msg", "tell", "w").contains(leaf) ? command.split("\\s+", 3) : new String[0];
        var repeat = CHAT.computeIfAbsent(server, ignored -> new ar.com.companeros.social.ChatRepeatGuard());
        if (whisper.length == 3 && repeat.duplicate(player.getUUID(), "private", whisper[1], whisper[2], now))
            return result(player, invocation, ToolResult.Status.SUCCEEDED, ToolResult.Reason.NO_CHANGE, "private_duplicate_suppressed: already delivered");
        Map<UUID, Long> calls = LAST.computeIfAbsent(server, ignored -> new LinkedHashMap<>());
        Long previous = calls.get(player.getUUID());
        if (previous != null && now - previous < 40)
            return result(player, invocation, ToolResult.Status.BLOCKED, ToolResult.Reason.CONDITIONS_CHANGED, "command_cooldown");
        if (calls.size() >= 2048 && !calls.containsKey(player.getUUID())) calls.remove(calls.keySet().iterator().next());
        calls.put(player.getUUID(), now);
        try {
            int outcome = dispatcher.execute(dispatcher.parse(command, source));
            if (outcome > 0 && whisper.length == 3) {
                repeat.record(player.getUUID(), "private", whisper[1], whisper[2], now);
                return result(player, invocation, ToolResult.Status.SUCCEEDED, ToolResult.Reason.NONE,
                    "private_sent to=" + whisper[1] + " text=" + whisper[2]);
            }
            boolean delivered = whisper.length != 3 || outcome > 0;
            return result(player, invocation, delivered ? ToolResult.Status.SUCCEEDED : ToolResult.Status.BLOCKED,
                delivered ? ToolResult.Reason.NONE : ToolResult.Reason.NO_CHANGE,
                "player_command:" + root + ":return=" + Math.max(-1000000, Math.min(1000000, outcome)));
        } catch (CommandSyntaxException rejected) {
            return result(player, invocation, ToolResult.Status.BLOCKED, ToolResult.Reason.INVALID_ARGUMENT, "command_denied_or_invalid:" + root);
        } catch (RuntimeException rejected) {
            return result(player, invocation, ToolResult.Status.FAILED, ToolResult.Reason.INTERNAL_ERROR, "command_failed:" + root);
        }
    }

    // Concesión explícita del operador: sólo /minecraft:tp @s a tres coordenadas numéricas.
    // La fuente elevada vive en esta llamada fija; no otorga OP ni acepta selectores o texto del agente.
    public static ToolResult teleportSelf(ServerPlayer player, UUID invocation, int x, int y, int z) {
        if (!player.server.isSameThread() || !player.isAlive() || player.isRemoved())
            return result(player, invocation, ToolResult.Status.BLOCKED, ToolResult.Reason.CONDITIONS_CHANGED, "teleport_body_unavailable");
        final Settings config;
        try { config = settings(); }
        catch (IOException | RuntimeException rejected) { return result(player, invocation, ToolResult.Status.BLOCKED, ToolResult.Reason.CONDITIONS_CHANGED, "command_config_invalid"); }
        if (!config.enabled() || !config.selfTeleport())
            return result(player, invocation, ToolResult.Status.BLOCKED, ToolResult.Reason.PERMISSION_DENIED, "self_teleport_disabled");
        var pos = new net.minecraft.core.BlockPos(x, y, z);
        if (y < player.level().getMinBuildHeight() || y >= player.level().getMaxBuildHeight()
                || Math.abs((long)x) > 30_000_000 || Math.abs((long)z) > 30_000_000 || !player.level().getWorldBorder().isWithinBounds(pos))
            return result(player, invocation, ToolResult.Status.BLOCKED, ToolResult.Reason.INVALID_ARGUMENT, "teleport_outside_world");
        try {
            if (ar.com.companeros.body.PlayerSessions.isAgent(player.server, player.getUUID()))
                ar.com.companeros.body.PlayerSessions.setMovementIntent(player.server, player.getUUID(), 0, 0, false);
            var source = player.createCommandSourceStack().withPermission(2).withSuppressedOutput();
            var dispatcher = player.server.getCommands().getDispatcher();
            // Forge añade el alias namespaced en producción; GameTest conserva la raíz vanilla.
            String root = dispatcher.getRoot().getChild("minecraft:tp") != null ? "minecraft:tp" : "tp";
            String command = root + " @s " + (x + .5) + " " + y + " " + (z + .5);
            int changed = dispatcher.execute(dispatcher.parse(command, source));
            boolean arrived = changed > 0 && player.blockPosition().equals(pos);
            return result(player, invocation, arrived ? ToolResult.Status.SUCCEEDED : ToolResult.Status.BLOCKED,
                arrived ? ToolResult.Reason.NONE : ToolResult.Reason.NO_CHANGE, "self_teleport actual=" + player.blockPosition().toShortString());
        } catch (CommandSyntaxException | RuntimeException failure) {
            return result(player, invocation, ToolResult.Status.BLOCKED, ToolResult.Reason.CONDITIONS_CHANGED, "self_teleport_failed");
        }
    }
    // Resultado acotado: conserva estado y raíz, sin copiar susurros ni argumentos privados.
    private static ToolResult result(ServerPlayer player, UUID invocation, ToolResult.Status status, ToolResult.Reason reason, String detail) {
        return ToolResult.immediate(invocation, status, reason, GlobalPos.of(player.level().dimension(), player.blockPosition()), Map.of(), List.of(detail));
    }
}