Files
src
build.gradle
README.md
settings.gradle
Code
6 368
src/main/java/com/kodari/modblocker/ModBlocker.java
package com.kodari.modblocker;
import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.command.SimpleCommand;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.connection.PluginMessageEvent;
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
import com.velocitypowered.api.event.proxy.ProxyShutdownEvent;
import com.velocitypowered.api.plugin.Plugin;
import com.velocitypowered.api.plugin.annotation.DataDirectory;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ConsoleCommandSource;
import com.velocitypowered.api.proxy.ProxyServer;
import com.velocitypowered.api.proxy.messages.MinecraftChannelIdentifier;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.slf4j.Logger;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import com.google.inject.Inject;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
@Plugin(id = "modblocker", name = "ModBlocker", version = "1.0.0")
public final class ModBlocker {
private static final MinecraftChannelIdentifier CHANNEL = MinecraftChannelIdentifier.create("modblocker", "mods");
private static final LegacyComponentSerializer LEGACY = LegacyComponentSerializer.legacyAmpersand();
private static final String CONFIG_FILE = "config.yml";
private static final String MESSAGE_FILE = "message.yml";
private static final String DEFAULT_PREFIX = "&8[&cModBlocker&8] &r";
private static final List<String> DEFAULT_KICK_LINES = List.of(
"&cBlocked mod detected!",
"",
"&7Detected mod: &e%mod%",
"&7Please remove this mod and reconnect."
);
private final ProxyServer server;
private final Logger logger;
private final Path dataDirectory;
private volatile Snapshot snapshot;
@Inject
public ModBlocker(ProxyServer server, Logger logger, @DataDirectory Path dataDirectory) {
this.server = server;
this.logger = logger;
this.dataDirectory = dataDirectory;
}
@Subscribe
public void onProxyInitialize(ProxyInitializeEvent event) {
try {
Files.createDirectories(dataDirectory);
copyDefaultIfMissing(CONFIG_FILE);
copyDefaultIfMissing(MESSAGE_FILE);
snapshot = loadSnapshot(dataDirectory.resolve(CONFIG_FILE), dataDirectory.resolve(MESSAGE_FILE));
} catch (Exception exception) {
logger.error("Invalid ModBlocker configuration; using bundled defaults: {}", conciseError(exception));
snapshot = loadBundledDefaults();
}
server.getChannelRegistrar().register(CHANNEL);
server.getEventManager().register(this, this);
registerCommand();
}
@Subscribe
public void onPluginMessage(PluginMessageEvent event) {
if (!CHANNEL.equals(event.getIdentifier())) {
return;
}
event.setResult(PluginMessageEvent.ForwardResult.handled());
if (!(event.getSource() instanceof Player player)) {
return;
}
Snapshot current = snapshot;
if (current == null || current.bypassedUsers().contains(normalize(player.getUsername()))) {
return;
}
String payload = new String(event.getData(), StandardCharsets.UTF_8);
for (String reportedId : payload.split("[,\\r\\n]")) {
String blockedDisplayName = current.blockedMods().get(normalize(reportedId));
if (blockedDisplayName == null) {
continue;
}
player.disconnect(createKickMessage(current, blockedDisplayName));
logger.info("Kicked {} for blocked mod {}", player.getUsername(), blockedDisplayName);
return;
}
}
@Subscribe
public void onProxyShutdown(ProxyShutdownEvent event) {
server.getChannelRegistrar().unregister(CHANNEL);
snapshot = null;
}
private void registerCommand() {
SimpleCommand command = new SimpleCommand() {
@Override
public void execute(Invocation invocation) {
if (!hasPermission(invocation)) {
invocation.source().sendMessage(Component.text("You do not have permission to do that."));
return;
}
String[] arguments = invocation.arguments();
if (arguments.length != 1 || !arguments[0].equalsIgnoreCase("reload")) {
invocation.source().sendMessage(Component.text("Usage: /modblocker reload"));
return;
}
try {
Snapshot replacement = loadSnapshot(dataDirectory.resolve(CONFIG_FILE), dataDirectory.resolve(MESSAGE_FILE));
snapshot = replacement;
invocation.source().sendMessage(Component.text("ModBlocker configuration reloaded."));
} catch (Exception exception) {
logger.warn("ModBlocker reload failed; keeping the last valid configuration: {}", conciseError(exception));
invocation.source().sendMessage(Component.text("Reload failed; the previous configuration remains active."));
}
}
@Override
public boolean hasPermission(Invocation invocation) {
CommandSource source = invocation.source();
return source instanceof ConsoleCommandSource
|| (source instanceof Player player && player.hasPermission("modblocker.reload"));
}
};
server.getCommandManager().register(
server.getCommandManager().metaBuilder("modblocker").plugin(this).build(),
command
);
}
private Component createKickMessage(Snapshot current, String detectedMod) {
List<String> lines = new ArrayList<>(current.kickLines());
for (int index = 0; index < lines.size(); index++) {
lines.set(index, lines.get(index).replace("%mod%", detectedMod));
}
if (!current.prefix().isEmpty()) {
lines.set(0, current.prefix() + lines.get(0));
}
String message = String.join("\n", lines);
if (message.isBlank()) {
message = String.join("\n", DEFAULT_KICK_LINES).replace("%mod%", detectedMod);
if (!DEFAULT_PREFIX.isEmpty()) {
message = DEFAULT_PREFIX + message;
}
}
return LEGACY.deserialize(message);
}
private Snapshot loadSnapshot(Path configPath, Path messagePath) throws IOException {
try (InputStream configInput = Files.newInputStream(configPath);
InputStream messageInput = Files.newInputStream(messagePath)) {
return parseSnapshot(configInput, messageInput, CONFIG_FILE, MESSAGE_FILE);
}
}
private Snapshot loadBundledDefaults() {
try (InputStream configInput = resource(CONFIG_FILE);
InputStream messageInput = resource(MESSAGE_FILE)) {
return parseSnapshot(configInput, messageInput, CONFIG_FILE, MESSAGE_FILE);
} catch (IOException exception) {
throw new IllegalStateException("Could not read bundled ModBlocker defaults", exception);
}
}
private Snapshot parseSnapshot(InputStream configInput, InputStream messageInput, String configName, String messageName) {
Map<?, ?> config = loadYaml(configInput, configName);
Map<?, ?> messages = loadYaml(messageInput, messageName);
Map<String, String> blockedMods = new LinkedHashMap<>();
for (String displayName : readStringList(config, "Mod-Blocked", configName, false)) {
blockedMods.putIfAbsent(normalize(displayName), displayName);
}
Set<String> bypassedUsers = new LinkedHashSet<>();
for (String username : readStringList(config, "Bypass", configName, false)) {
bypassedUsers.add(normalize(username));
}
Object prefixValue = messages.get("Prefix");