Files
src
build.gradle
CHANGELOG.md
manifest.kod
README.md
settings.gradle
TESTING.md
Code
15 939
src/main/java/com/rehanlive/antialt/AntiAlt.java
package com.rehanlive.antialt;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
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 org.geysermc.floodgate.api.FloodgateApi;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.InetAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public final class AntiAlt extends JavaPlugin implements Listener {
private Database database;
private Network network;
private FileConfiguration messages, discord;
private byte[] key;
private final Set<UUID> muted = ConcurrentHashMap.newKeySet();
private final Map<String, Deque<Long>> attempts = new HashMap<>();
private final Map<String, Long> cooldowns = new HashMap<>();
private final Map<String, Long> notifications = new HashMap<>();
@Override public void onEnable() {
saveDefaultConfig();
for (String file : List.of("messages.yml", "database.yml", "discord.yml")) {
if (!new java.io.File(getDataFolder(), file).exists()) saveResource(file, false);
}
loadSettings();
try {
Path path = getDataFolder().toPath().resolve("ip-hmac.key");
if (!Files.exists(path)) {
byte[] random = new byte[32]; new SecureRandom().nextBytes(random);
Files.write(path, random, java.nio.file.StandardOpenOption.CREATE_NEW);
}
key = Files.readAllBytes(path);
if (key.length != 32) throw new IllegalStateException("IP association key must contain 32 bytes");
database = new Database(this, YamlConfiguration.loadConfiguration(new java.io.File(getDataFolder(), "database.yml")));
} catch (Exception e) {
getLogger().severe("Could not initialize security storage: " + e.getClass().getSimpleName());
getServer().getPluginManager().disablePlugin(this); return;
}
network = new Network(this);
Admin admin = new Admin(this);
Objects.requireNonNull(getCommand("antialt")).setExecutor(admin);
Objects.requireNonNull(getCommand("antialt")).setTabCompleter(admin);
getServer().getPluginManager().registerEvents(this, this);
getServer().getPluginManager().registerEvents(admin, this);
database.initialize().whenComplete((ignored, error) -> main(() -> {
if (error != null) {
getLogger().severe("Database initialization failed; disabling AntiAlt. Check database settings and JDBC driver packaging.");
getServer().getPluginManager().disablePlugin(this);
} else getLogger().info("Database connection and schema initialized.");
}));
database.cleanup(System.currentTimeMillis() - days("history.retention-days", 30) * 86400000L)
.exceptionally(e -> { storageError(); return null; });
getLogger().info("AntiAlt 1.0.1 starting; database operations run asynchronously.");
}
@Override public void onDisable() {
if (network != null) network.close();
if (database != null) database.close();
getLogger().info("AntiAlt stopped.");
}
public void loadSettings() {
reloadConfig();
messages = YamlConfiguration.loadConfiguration(new java.io.File(getDataFolder(), "messages.yml"));
discord = YamlConfiguration.loadConfiguration(new java.io.File(getDataFolder(), "discord.yml"));
for (String path : List.of("detection.max-accounts-per-ip", "detection.detection-window-seconds", "detection.alert-cooldown-seconds", "login-protection.max-attempts", "login-protection.time-window-seconds", "login-protection.cooldown-seconds", "lockdown.duration-seconds", "vpn-detection.timeout-millis", "vpn-detection.cache-minutes", "history.retention-days", "detection.trusted-max-accounts")) {
if (!getConfig().isInt(path) || getConfig().getInt(path) < 1 || getConfig().getInt(path) > 1000000) getLogger().warning("Invalid " + path + "; using a safe default.");
}
for (String path : List.of("detection.high-action", "vpn-detection.action")) {
if (!List.of("ALERT", "KICK", "IGNORE").contains(getConfig().getString(path, "ALERT").toUpperCase(Locale.ROOT))) getLogger().warning("Invalid " + path + "; using ALERT.");
}
}
public int number(String path, int fallback) {
int n = getConfig().getInt(path, fallback);
return n < 1 || n > 1000000 ? fallback : n;
}
private int days(String path, int fallback) { return number(path, fallback); }
public FileConfiguration discord() { return discord; }
public Database database() { return database; }
public String text(String path) { return format(messages.getString(path, "")); }
public String format(String value) {
try { return LegacyComponentSerializer.legacySection().serialize(MiniMessage.miniMessage().deserialize(ChatColor.translateAlternateColorCodes('&', value))); }
catch (RuntimeException e) { return ChatColor.translateAlternateColorCodes('&', value); }
}
public void send(org.bukkit.command.CommandSender sender, String path) { sender.sendMessage(text("prefix") + text(path)); }
public void storageError() { getLogger().warning("Database operation failed; security checks requiring storage are unavailable."); }
public void main(Runnable task) {
if (!isEnabled()) return;
try { Bukkit.getScheduler().runTask(this, task); }
catch (org.bukkit.plugin.IllegalPluginAccessException ignored) { }
}
public boolean toggle(UUID uuid) { if (muted.remove(uuid)) return true; muted.add(uuid); return false; }
private boolean bypass(Player p, String specific) { return p.hasPermission("antialt.bypass") || p.hasPermission("antialt.bypass." + specific); }
private String hash(InetAddress address) {
try {
Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(key, "HmacSHA256"));
return HexFormat.of().formatHex(mac.doFinal(address.getAddress()));
} catch (Exception e) { throw new IllegalStateException(e); }
}
private boolean isBedrock(UUID uuid) {
try { return Bukkit.getPluginManager().isPluginEnabled("floodgate") && FloodgateApi.getInstance().isFloodgatePlayer(uuid); }
catch (LinkageError | RuntimeException e) { return false; }
}
private String action(String path) {
String action = getConfig().getString(path, "ALERT").toUpperCase(Locale.ROOT);
return List.of("ALERT", "KICK", "IGNORE").contains(action) ? action : "ALERT";
}
@EventHandler public void onJoin(PlayerJoinEvent event) {
if (!getConfig().getBoolean("general.enabled", true)) return;
Player player = event.getPlayer();
Bukkit.getScheduler().runTaskLater(this, () -> clientJoinAlert(player), 40L);
if (player.getAddress() == null || player.getAddress().getAddress() == null) return;
InetAddress address = player.getAddress().getAddress();
String hash = hash(address);
UUID uuid = player.getUniqueId();
String name = player.getName();
boolean bedrock = isBedrock(uuid);
String associationHash = bedrock ? hashBedrock(hash) : hash;
boolean configuredTrusted = getConfig().getStringList("detection.trusted-uuids").stream().anyMatch(s -> s.equalsIgnoreCase(uuid.toString()));
boolean shared = getConfig().getStringList("detection.shared-networks").contains(hash);
boolean skipAlt = bypass(player, "alt"), skipRate = bypass(player, "ratelimit"), skipVpn = bypass(player, "vpn");
long window = number("detection.detection-window-seconds", 300) * 1000L;
database.record(uuid, name, associationHash, window).thenCombine(database.restriction(hash), (account, restriction) -> new Object[]{account, restriction})
.whenComplete((result, error) -> main(() -> {
if (error != null) { storageError(); return; }
Database.Account account = (Database.Account) result[0];
boolean trusted = account.trusted() || configuredTrusted;
if (!trusted && !skipRate && getConfig().getBoolean("login-protection.enabled", true) && rateLimited(hash, (Long) result[1])) {
alert(new Database.Detection(name, uuid.toString(), "LOGIN", "HIGH", "Connection rate exceeded", account.linked(), System.currentTimeMillis()));
if (player.isOnline()) player.kickPlayer(text("kick.rate"));
return;
}
if (!player.isOnline()) return;
if (!trusted && !skipAlt && !bedrock && !shared && getConfig().getBoolean("detection.enabled", true) && account.linked() > 1) {
int limit = number("detection.max-accounts-per-ip", 3);
String severity = account.linked() > limit ? "HIGH" : account.recent() > 1 ? "MEDIUM" : "LOW";
String reason = severity.equals("HIGH") ? "Account threshold exceeded" : severity.equals("MEDIUM") ? "Accounts seen within detection window" : "Accounts share a network";
String action = severity.equals("HIGH") ? action("detection.high-action") : "ALERT";
if (!action.equals("IGNORE")) alert(new Database.Detection(name, uuid.toString(), "ALT", severity, reason, account.linked(), System.currentTimeMillis()));
if (severity.equals("HIGH") && action.equals("KICK") && !getConfig().getBoolean("detection.shared-network-protection", true)) { player.kickPlayer(text("kick.alt")); return; }
}
if (!trusted && !skipVpn && getConfig().getBoolean("vpn-detection.enabled", false)) network.checkVpn(address, flagged -> main(() -> {
if (!player.isOnline() || !flagged) return;
String action = action("vpn-detection.action");
if (!action.equals("IGNORE")) alert(new Database.Detection(name, uuid.toString(), "VPN", "MEDIUM", "VPN or proxy provider flagged connection", account.linked(), System.currentTimeMillis()));
if (action.equals("KICK")) player.kickPlayer(text("kick.vpn"));
}));
}));
}
private void clientJoinAlert(Player player) {
if (!player.isOnline()) return;
String brand;
try { brand = player.getClientBrandName(); }
catch (LinkageError e) { brand = null; }
if (brand == null || brand.isBlank()) brand = "Unknown";
brand = brand.replaceAll("[\\p{Cntrl}§]", "");
if (brand.length() > 80) brand = brand.substring(0, 80);
if (brand.isBlank()) brand = "Unknown";
String version = isBedrock(player.getUniqueId()) ? "Unknown (Bedrock)" : clientVersion(player.getUniqueId());
String prefix = text("prefix");
String template = format(messages.getString("client-join", "<gray>{player} joined using <aqua>{brand}</aqua> (hover for version)</gray>"));
String hover = format(messages.getString("client-version-hover", "<gray>Minecraft version: <white>{version}</white></gray>"));
Component message = LegacyComponentSerializer.legacySection().deserialize(prefix + template.replace("{player}", player.getName()).replace("{brand}", brand))
.hoverEvent(LegacyComponentSerializer.legacySection().deserialize(hover.replace("{version}", version)));
for (Player staff : Bukkit.getOnlinePlayers()) {
if ((staff.isOp() || staff.hasPermission("antialt.alerts")) && !muted.contains(staff.getUniqueId())) staff.sendMessage(message);
}
getLogger().info("[CLIENT] " + player.getName() + " joined using " + brand + " (Minecraft " + version + ")");
}
private String clientVersion(UUID uuid) {
org.bukkit.plugin.Plugin via = Bukkit.getPluginManager().getPlugin("ViaVersion");
if (via == null || !via.isEnabled()) return "Unknown (ViaVersion unavailable)";
try {
ClassLoader loader = via.getClass().getClassLoader();
Class<?> viaClass = Class.forName("com.viaversion.viaversion.api.Via", true, loader);
Class<?> apiClass = Class.forName("com.viaversion.viaversion.api.ViaAPI", true, loader);
Object api = viaClass.getMethod("getAPI").invoke(null);
int protocol = (int) apiClass.getMethod("getPlayerVersion", UUID.class).invoke(api, uuid);
if (protocol < 0) return "Unknown";
Class<?> versions = Class.forName("com.viaversion.viaversion.api.protocol.version.ProtocolVersion", true, loader);
Object version = versions.getMethod("getProtocol", int.class).invoke(null, protocol);
return (String) versions.getMethod("getName").invoke(version);