No chat to show

This project's files are all here to explore.

Files
src
build.gradle
Code
4 269
src/main/java/com/gatekeeper/GateKeeper.java
package com.GateKeeper.gatekeeper;

import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.java.JavaPlugin;

import javax.net.ssl.HttpsURLConnection;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

public final class GateKeeper extends JavaPlugin implements Listener {

    @Override
    public void onEnable() {
        saveDefaultConfig();
        getServer().getPluginManager().registerEvents(this, this);
        getLogger().info("GateKeeper Engine: Security Audit Module Online.");
    }

    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event) {
        Player player = event.getPlayer();
        
        final UUID uuid = player.getUniqueId();
        final String name = player.getName();
        final String webhookUrl = getConfig().getString("webhook-url");

        if (webhookUrl == null || webhookUrl.isEmpty() || webhookUrl.contains("YOUR_WEBHOOK_URL_HERE")) {
            return;
        }

        // CRITICAL TIMING FIX: 
        // Delay the scan by 2 seconds (40 ticks) using the Paper Entity Scheduler.
        // This gives the player's client enough time to send all of its mod channels over the network.
        player.getScheduler().runDelayed(this, task -> {
            
            // If the player somehow left within those 2 seconds, cancel the scan.
            if (!player.isOnline()) return; 
            
            final String brand = (player.getClientBrandName() == null) ? "Vanilla" : player.getClientBrandName();
            final Set<String> rawChannels = player.getListeningPluginChannels();
            
            // Now run the Discord web request asynchronously
            CompletableFuture.runAsync(() -> dispatchAudit(uuid, webhookUrl, name, brand, rawChannels));
            
        }, null, 40L);
    }

    private void dispatchAudit(UUID uuid, String webhookUrl, String name, String brand, Set<String> rawChannels) {
        List<String> detections = new ArrayList<>();
        List<String> channelLines = new ArrayList<>();
        List<String> illegalList = getConfig().getStringList("illegal-mods");
        ConfigurationSection mapping = getConfig().getConfigurationSection("mod-mappings");
        
        boolean threatDetected = false;

        if (rawChannels.isEmpty()) {
            channelLines.add(getConfig().getString("strings.no-channels", "• `None`"));
        } else {
            for (String ch : rawChannels) {
                channelLines.add("• `" + ch + "`");
                if (mapping != null) {
                    for (String key : mapping.getKeys(false)) {
                        if (ch.toLowerCase().contains(key.toLowerCase())) {
                            String modName = mapping.getString(key);
                            
                            // Flag as Illegal if it's on the restricted list
                            if (illegalList != null && illegalList.contains(modName)) {
                                threatDetected = true;
                                modName = "⚠️ **[ILLEGAL]** " + modName;
                            }
                            
                            if (!detections.contains(modName)) detections.add(modName);
                        }
                    }
                }
            }
        }

        if (detections.isEmpty()) detections.add(getConfig().getString("strings.no-violations", "None Detected"));

        String violationStr = "• " + String.join("\n• ", detections);
        String channelStr = String.join("\n", channelLines);
        
        // --- AUTO-KICK PROTOCOL ---
        if (threatDetected && getConfig().getBoolean("auto-kick.enabled", true)) {
            String kickMessage = getConfig().getString("auto-kick.message", "§c§lSECURITY ALERT\n\n§7Illegal client modifications detected.\n§7Please disable your cheats and rejoin.");
            
            Player target = getServer().getPlayer(uuid);
            if (target != null && target.isOnline()) {
                target.getScheduler().run(this, task -> target.kickPlayer(kickMessage), null);
            }
        }

        // Choose color and status based on threat analysis
        int color = threatDetected ? getConfig().getInt("colors.illegal", 15158332) : getConfig().getInt("embed.color", 1752220);
        String status = threatDetected ? getConfig().getString("strings.status-threat", "Threat Detected") : getConfig().getString("strings.status-safe", "Authorized");

        try {
            URL url = new URL(webhookUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("User-Agent", "GateKeeper-Audit-Node");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.setDoOutput(true);

            String encodedName = URLEncoder.encode(name, StandardCharsets.UTF_8).replace("+", "%20");
            
            // Dynamic Title parsing
            String configTitle = getConfig().getString("embed.title", "🛡️ Audit Result: %status%");
            String title = escapeJson(configTitle).replace("%status%", status);
            
            String template = getConfig().getString("embed.description", "");
            
            String finalDesc = template
                    .replace("%player%", name)
                    .replace("%violations%", violationStr)
                    .replace("%version%", getConfig().getString("strings.version-placeholder", "1.21.x"))
                    .replace("%brand%", brand)
                    .replace("%channels%", channelStr);

            String payload = "{" +
                "\"embeds\": [{" +
                    "\"title\": \"" + title + "\"," +
                    "\"color\": " + color + "," +
                    "\"thumbnail\": {\"url\": \"https://mc-heads.net/head/" + encodedName + "/100.png\"}," +
                    "\"description\": \"" + escapeJson(finalDesc).replace("\n", "\\n") + "\"," +
                    "\"footer\": {\"text\": \"" + escapeJson(getConfig().getString("embed.footer", "GateKeeper Security System")) + "\"}" +
                "}]" +
            "}";

            try (OutputStream os = conn.getOutputStream()) {
                os.write(payload.getBytes(StandardCharsets.UTF_8));
            }
            conn.getResponseCode();
            conn.disconnect();
        } catch (Exception e) {
            getLogger().severe("Audit Dispatch Failure: " + e.getMessage());
        }
    }

    private String escapeJson(String input) {
        return (input == null) ? "" : input.replace("\\", "\\\\").replace("\"", "\\\"");
    }
}