Alok Raj
📎 1 file 5,296 chars
📄
pasted-code-1795194116744.txt
txt 180 lines
▶
# PROJECT: THRONEMC – ULTIMATE ADVANCED ANTI-CHEAT SYSTEM

Develop a highly advanced, powerful, and intelligent Minecraft Anti-Cheat plugin named **ThroneGuard Anti-Cheat**, specifically designed for the ThroneMC Minecraft server.

The primary objective is to detect, prevent, and punish hackers, cheaters, ghost clients, modified clients, and unfair gameplay advantages in real time.

## 1. Core Requirements
- Support Paper 1.21.11 and newer compatible versions.
- High-performance detection with minimal CPU and RAM usage.
- Real-time player behavior monitoring.
- Advanced packet-level analysis.
- Detect both common and advanced cheating methods.
- Prevent false positives as much as technically possible.
- Work alongside popular Minecraft plugins without conflicts.

## 2. Advanced Cheat Detection

Implement detection systems for:

**Combat Hacks**
- KillAura
- AimAssist
- Aimbot
- AutoClicker
- Reach
- Hitbox
- Criticals
- Velocity / Anti-Knockback
- TriggerBot
- MultiAura
- AutoTotem
- FastBow
- FastHeal
- NoSwing
- Invalid Attack Packets

**Movement Hacks**
- Fly
- Speed
- Spider
- Jesus
- NoFall
- HighJump
- LongJump
- AirJump
- Step
- Phase
- NoSlow
- Timer
- InventoryMove
- ElytraFly
- Invalid Movement
- Unnatural Strafing

**Player & World Exploits**
- Scaffold
- Tower
- FastPlace
- Nuker
- FastBreak
- AutoMine
- X-Ray (where detectable through server-side evidence)
- ChestStealer
- Inventory Exploits
- Impossible Block Interactions
- Invalid Digging Packets

**Ghost Client & Modified Client Detection**
- Detect suspicious packet patterns associated with ghost clients.
- Identify impossible rotations and combat behavior.
- Detect abnormal interaction sequences.
- Identify suspicious client-side movement behavior.
- Detect known cheat signatures where reliable.
- Analyze behavioral patterns instead of depending only on client brand or client-reported information.
- Detect attempts to bypass normal server-side validation.

Important: Do not automatically ban players simply because they use Lunar Client, Badlion Client, or another legitimate modified client. Focus on actual cheating behavior.

## 3. Intelligent Detection Engine

Create an advanced detection engine that:
- Uses multiple independent checks.
- Tracks player violations using a configurable VL (Violation Level) system.
- Uses statistical analysis and movement prediction.
- Analyzes packet timing and player behavior.
- Detects repeated suspicious actions.
- Automatically reduces violation levels when legitimate behavior resumes.
- Uses ping, TPS, and server lag compensation.
- Avoids punishing players for lag, high latency, or server performance issues.

## 4. Automatic Punishment System

**Default punishment: 1 HOUR BAN.**

When the anti-cheat confirms cheating with sufficient evidence:
- Automatically ban the player for exactly 60 minutes.
- Display a clear ban message.
- Record the exact cheat category and detection information.
- Save player UUID, username, timestamp, violation level, and evidence.
- Prevent players from bypassing bans by reconnecting.

Example ban message:

"⚠ You have been temporarily banned from ThroneMC for cheating. Reason: Unfair Client Modifications. Duration: 1 Hour."

Add configurable punishment settings for each individual check.

IMPORTANT: Do not issue an automatic ban based on one suspicious packet or a single minor violation. Require strong, repeated, independently verified evidence before applying the ban.

## 5. Advanced Admin Alerts

Create professional real-time alerts for administrators.

Example:

[ThroneGuard] Player: Steve
Check: KillAura
Violations: 15
Ping: 42ms
Evidence: Abnormal combat rotation
Action: 1 Hour Ban

Commands:
/tg alerts
/tg info 
/tg violations 
/tg ban 
/tg unban 
/tg reload
/tg bypass 
/tg checks
/tg debug 

## 6. Ghost Client & Bypass Protection

Implement additional protection against:
- Ghost clients.
- Custom hacked clients.
- Advanced combat modifications.
- Packet manipulation.
- Timer manipulation.
- Client-side prediction abuse.
- Cheat modules that attempt to bypass traditional checks.
- Common anti-cheat bypass techniques.

The detection system should be modular and regularly configurable so new cheat patterns can be addressed without rewriting the entire plugin.

## 7. Configuration System

Provide a complete configuration file with:
- Individual check toggles.
- Violation thresholds.
- Automatic punishment duration.
- Alert permissions.
- Exempt worlds.
- Exempt permissions.
- Ping compensation.
- TPS protection.
- Debug mode.
- Ban messages.
- Per-check punishment settings.

## 8. Performance & Compatibility

- Optimize all packet listeners.
- Avoid unnecessary synchronous tasks.
- Use asynchronous processing where safe.
- Avoid excessive database queries.
- Support SQLite or MySQL.
- Ensure compatibility with LuckPerms, EssentialsX, ProtocolLib or PacketEvents, and common server management plugins.
- Never cause server crashes or severe TPS drops.
- Ensure compatibility with Paper 1.21.11.

## 9. Professional Development Standards

- Use clean Java code.
- Create a modular detection architecture.
- Include proper error handling.
- Provide detailed installation instructions.
- Include plugin configuration examples
Kodari AI
KodariFri at 5:04 pm 3
ThroneGuardAntiCheat
ThroneGuardAntiCheat is a comprehensive Minecraft anti-cheat plugin for Paper 1.21.11 that detects and prevents cheating through advanced packet analysis and behavioral monitoring. It features a modular detection engine with multiple independent checks for combat hacks, movement exploits, and ghost client modifications. The system uses configurable violation levels with lag compensation, automatic 1-hour temporary bans with evidence logging, and real-time admin alerts. Includes SQLite/MySQL storage, per-check configuration, exempt permissions/worlds, and commands for alerts, violations, bans, bypass management, and debugging. Designed for high performance with minimal resource usage and compatibility with popular server plugins.

I’ll build the monitoring, violation, alert, ban, and configuration systems first. Detection will stay conservative: unsupported packet-level and cheat-specific checks won’t be presented as working.

Built the ThroneGuard foundation with configurable alerts, violation decay, temporary bans, SQLite/MySQL storage, and admin commands.

Scope: Detection currently covers reach, attack frequency, speed, and block placement frequency. The other requested cheat checks and packet-level analysis are not implemented. Automatic bans are enabled by default; set punishment.enabled: false while tuning and reviewing alerts.

Kodari can make mistakes. Review important code before using.
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;
    }
}