Files
src
build.gradle
manifest.kod
README.md
settings.gradle
Code
8 350
src/main/java/com/thronemc/guard/ThroneGuard.java
package com.thronemc.guard;
import com.cryptomorin.xseries.XPotion;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.*;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.player.*;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.BoundingBox;
public final class ThroneGuard extends JavaPlugin implements Listener, CommandExecutor {
private static final List<String> CHECKS = Arrays.asList("reach", "speed", "autoclicker", "fastplace");
private final Map<UUID, Profile> profiles = new HashMap<>();
private final Set<UUID> bypass = new HashSet<>();
private final Set<UUID> alertsOff = new HashSet<>();
private final Set<UUID> debug = new HashSet<>();
private Storage storage;
private static final class Profile {
final Map<String, Double> violations = new HashMap<>();
final Map<String, Long> recent = new HashMap<>();
final Deque<Long> attacks = new ArrayDeque<>();
final Deque<Long> places = new ArrayDeque<>();
long lastDecay = System.currentTimeMillis();
long graceUntil = System.currentTimeMillis() + 3000;
long lastMove;
}
@Override public void onEnable() {
saveDefaultConfig();
storage = new Storage(this);
try { storage.open(); } catch (Exception e) {
getLogger().severe("Storage unavailable; disabling ThroneGuard: " + e.getMessage());
getServer().getPluginManager().disablePlugin(this); return;
}
getServer().getPluginManager().registerEvents(this, this);
Objects.requireNonNull(getCommand("tg")).setExecutor(this);
}
@Override public void onDisable() { if (storage != null) storage.close(); }
private Profile profile(Player p) { return profiles.computeIfAbsent(p.getUniqueId(), id -> new Profile()); }
private String color(String text) { return ChatColor.translateAlternateColorCodes('&', text); }
private void tell(CommandSender s, String message) { s.sendMessage(color("&6[ThroneGuard] &7" + message)); }
private boolean enabled(String check) { return getConfig().getBoolean("checks." + check + ".enabled", true); }
private boolean eligible(Player p) {
return p.isOnline() && !p.isDead() && p.getGameMode() != GameMode.CREATIVE && p.getGameMode() != GameMode.SPECTATOR
&& !p.hasPermission(getConfig().getString("exempt-permission", "throneguard.exempt")) && !bypass.contains(p.getUniqueId())
&& !getConfig().getStringList("exempt-worlds").contains(p.getWorld().getName())
&& p.getPing() <= getConfig().getInt("protection.max-ping-ms", 250)
&& Bukkit.getTPS()[0] >= getConfig().getDouble("protection.min-tps", 18.0)
&& System.currentTimeMillis() >= profile(p).graceUntil;
}
private void decay(Profile data, long now) {
double amount = (now - data.lastDecay) / 60000.0 * Math.max(0, getConfig().getDouble("protection.violation-decay-per-minute", 2));
data.violations.replaceAll((key, value) -> Math.max(0, value - amount));
data.lastDecay = now;
}
private void flag(Player p, String check, String evidence) {
if (!enabled(check) || !eligible(p)) return;
Profile data = profile(p); long now = System.currentTimeMillis(); decay(data, now);
double vl = data.violations.merge(check, 1.0, Double::sum);
data.recent.put(check, now);
storage.evidence(p.getUniqueId(), p.getName(), check, vl, evidence);
String msg = "&e" + p.getName() + " &7check=&f" + check + " &7VL=&f" + String.format(Locale.ROOT, "%.1f", vl) + " &7ping=&f" + p.getPing() + "ms &7evidence=&f" + evidence;
for (Player admin : Bukkit.getOnlinePlayers()) if (admin.hasPermission(getConfig().getString("alert-permission", "throneguard.alerts")) && !alertsOff.contains(admin.getUniqueId())) tell(admin, msg);
if (getConfig().getBoolean("debug", false) || debug.contains(p.getUniqueId())) getLogger().info(ChatColor.stripColor(color(msg)));
long window = Math.max(1, getConfig().getLong("protection.evidence-window-seconds", 120)) * 1000L;
long independent = data.recent.entrySet().stream().filter(e -> now - e.getValue() <= window && data.violations.getOrDefault(e.getKey(), 0.0) >= 3.0).count();
double total = data.violations.values().stream().mapToDouble(Double::doubleValue).sum();
if (getConfig().getBoolean("punishment.enabled", true) && getConfig().getBoolean("checks." + check + ".punish", true)
&& vl >= Math.max(3, getConfig().getDouble("checks." + check + ".threshold", 10))
&& independent >= Math.max(2, getConfig().getInt("protection.minimum-independent-checks", 2))
&& total >= Math.max(6, getConfig().getDouble("protection.minimum-total-violations", 12))) ban(p, check + ": " + evidence);
}
private String banMessage(Storage.Ban ban) {
String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").format(new Date(ban.expires()));
return color(getConfig().getString("punishment.message", "&cTemporarily banned for cheating until {expires}").replace("{expires}", date).replace("\\n", "\n"));
}
private void ban(Player p, String reason) {
long minutes = Math.max(1, getConfig().getLong("punishment.duration-minutes", 60));
Storage.Ban ban = new Storage.Ban(p.getUniqueId(), p.getName(), System.currentTimeMillis() + minutes * 60000L, reason);
storage.ban(ban);
storage.evidence(p.getUniqueId(), p.getName(), "punishment", 0, reason);
for (Player admin : Bukkit.getOnlinePlayers()) if (admin.hasPermission(getConfig().getString("alert-permission", "throneguard.alerts")) && !alertsOff.contains(admin.getUniqueId())) tell(admin, "&c" + p.getName() + " banned for " + minutes + " minutes: " + reason);
p.kickPlayer(banMessage(ban));
}
@EventHandler(priority = EventPriority.HIGHEST) public void login(PlayerLoginEvent event) {
Storage.Ban ban = storage.getBan(event.getPlayer().getUniqueId());
if (ban != null) event.disallow(PlayerLoginEvent.Result.KICK_BANNED, banMessage(ban));
}
@EventHandler public void join(PlayerJoinEvent e) { profile(e.getPlayer()).graceUntil = System.currentTimeMillis() + getConfig().getLong("protection.teleport-grace-ms", 3000); }
@EventHandler public void quit(PlayerQuitEvent e) { UUID id = e.getPlayer().getUniqueId(); profiles.remove(id); debug.remove(id); }
@EventHandler(ignoreCancelled = true) public void teleport(PlayerTeleportEvent e) { profile(e.getPlayer()).graceUntil = System.currentTimeMillis() + getConfig().getLong("protection.teleport-grace-ms", 3000); }
@EventHandler(ignoreCancelled = true) public void velocity(PlayerVelocityEvent e) { profile(e.getPlayer()).graceUntil = System.currentTimeMillis() + getConfig().getLong("protection.teleport-grace-ms", 3000); }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void move(PlayerMoveEvent e) {
if (e instanceof PlayerTeleportEvent || e.getTo() == null) return;
Player p = e.getPlayer(); Profile data = profile(p); long now = System.currentTimeMillis();
long elapsed = now - data.lastMove; data.lastMove = now;
if (!enabled("speed") || !eligible(p) || elapsed < 40 || elapsed > 500 || p.isFlying() || p.isGliding() || p.isSwimming() || p.isInsideVehicle() || p.isRiptiding() || XPotion.matchXPotion("SPEED").map(x -> p.hasPotionEffect(x.getPotionEffectType())).orElse(false)) return;
Location from = e.getFrom(), to = e.getTo();
if (from.getWorld() != to.getWorld()) return;
double distance = Math.hypot(to.getX() - from.getX(), to.getZ() - from.getZ());
double rate = distance * 1000.0 / elapsed;
if (rate > getConfig().getDouble("checks.speed.max-blocks-per-second", 12)) flag(p, "speed", String.format(Locale.ROOT, "%.2f blocks/s", rate));
}
private int count(Deque<Long> queue, long now) { while (!queue.isEmpty() && now - queue.peekFirst() >= 1000) queue.removeFirst(); queue.addLast(now); return queue.size(); }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void attack(EntityDamageByEntityEvent e) {
if (!(e.getDamager() instanceof Player p) || !eligible(p)) return;
int count = count(profile(p).attacks, System.currentTimeMillis());
if (enabled("autoclicker") && count > getConfig().getInt("checks.autoclicker.max-attacks-per-second", 18)) flag(p, "autoclicker", count + " attacks in one second");
if (!enabled("reach") || !p.getWorld().equals(e.getEntity().getWorld())) return;
Location eye = p.getEyeLocation(); BoundingBox box = e.getEntity().getBoundingBox();
double x = Math.max(box.getMinX(), Math.min(eye.getX(), box.getMaxX()));
double y = Math.max(box.getMinY(), Math.min(eye.getY(), box.getMaxY()));
double z = Math.max(box.getMinZ(), Math.min(eye.getZ(), box.getMaxZ()));
double distance = Math.sqrt(Math.pow(eye.getX()-x, 2) + Math.pow(eye.getY()-y, 2) + Math.pow(eye.getZ()-z, 2));
double limit = getConfig().getDouble("checks.reach.max-distance", 4.5) + p.getPing() * 0.003;
if (distance > limit) flag(p, "reach", String.format(Locale.ROOT, "%.2f blocks (limit %.2f)", distance, limit));
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void place(BlockPlaceEvent e) {
Player p = e.getPlayer(); if (!enabled("fastplace") || !eligible(p)) return;
int count = count(profile(p).places, System.currentTimeMillis());
if (count > getConfig().getInt("checks.fastplace.max-places-per-second", 12)) flag(p, "fastplace", count + " placements in one second");
}
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length == 0) { tell(sender, "/tg alerts|info|violations|ban|unban|reload|bypass|checks|debug"); return true; }
String sub = args[0].toLowerCase(Locale.ROOT);
if (sub.equals("reload")) { reloadConfig(); tell(sender, "Configuration reloaded. Storage changes require a restart."); return true; }
if (sub.equals("checks")) { for (String check : CHECKS) tell(sender, check + ": " + (enabled(check) ? "enabled" : "disabled")); return true; }
if (sub.equals("alerts")) {
if (!(sender instanceof Player p)) { tell(sender, "Only players can toggle alerts."); return true; }
if (!alertsOff.add(p.getUniqueId())) { alertsOff.remove(p.getUniqueId()); tell(sender, "Alerts enabled."); } else tell(sender, "Alerts disabled."); return true;
}
if (args.length < 2) { tell(sender, "Specify a player."); return true; }
if (sub.equals("unban")) {
OfflinePlayer target = Bukkit.getOfflinePlayerIfCached(args[1]);
if (target == null) { try { target = Bukkit.getOfflinePlayer(UUID.fromString(args[1])); } catch (IllegalArgumentException ignored) {} }
if (target == null) { tell(sender, "Player not found; use their UUID if they are not cached."); return true; }
storage.unban(target.getUniqueId()); tell(sender, "Removed ThroneGuard ban for " + target.getUniqueId()); return true;
}
Player target = Bukkit.getPlayerExact(args[1]);
if (target == null) { tell(sender, "Player must be online."); return true; }
Profile data = profile(target); decay(data, System.currentTimeMillis());
switch (sub) {
case "info" -> tell(sender, target.getName() + " ping=" + target.getPing() + "ms bypass=" + bypass.contains(target.getUniqueId()) + " violations=" + data.violations);
case "violations" -> tell(sender, target.getName() + ": " + data.violations);
case "ban" -> { ban(target, "Manual ban by " + sender.getName()); tell(sender, "Player banned."); }
case "bypass" -> { if (!bypass.add(target.getUniqueId())) { bypass.remove(target.getUniqueId()); tell(sender, "Bypass disabled."); } else tell(sender, "Bypass enabled."); }
case "debug" -> { if (!debug.add(target.getUniqueId())) { debug.remove(target.getUniqueId()); tell(sender, "Debug disabled."); } else { tell(sender, "Debug enabled; violation details will be logged."); } }
default -> tell(sender, "Unknown subcommand.");
}
return true;
}
}