Files
src
build.gradle
settings.gradle
Code
5 263
src/main/java/com/ultronai/UltronAI.java
package com.ultronai;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
public final class UltronAI extends JavaPlugin {
private static final int MAX_RESPONSE = 262144;
private final Deque<String> logs = new ArrayDeque<>();
private BukkitTask task;
private Handler logHandler;
private volatile Settings settings;
@Override
public void onEnable() {
saveDefaultConfig();
logHandler = new Handler() {
@Override
public void publish(LogRecord record) {
if (record == null || record.getMessage() == null) return;
synchronized (logs) {
if (logs.size() >= 200) logs.removeFirst();
String line = record.getLevel() + ": " + record.getMessage();
logs.addLast(line.length() > 1000 ? line.substring(0, 1000) : line);
}
}
@Override public void flush() { }
@Override public void close() { }
};
getServer().getLogger().addHandler(logHandler);
startBridge();
}
@Override
public void onDisable() {
if (task != null) task.cancel();
if (logHandler != null) getServer().getLogger().removeHandler(logHandler);
}
private void startBridge() {
if (task != null) task.cancel();
task = null;
String url = getConfig().getString("bridge.url", "").trim();
String token = getConfig().getString("key", "").trim();
if (token.isEmpty()) token = getConfig().getString("bridge.token", "").trim();
List<String> commands = new ArrayList<>();
for (String name : getConfig().getStringList("commands.allowed")) {
commands.add(name.toLowerCase(Locale.ROOT));
}
settings = new Settings(url.replaceAll("/+$", ""), token,
Math.max(1000, getConfig().getInt("bridge.connect-timeout-ms", 5000)),
Math.max(1000, getConfig().getInt("bridge.read-timeout-ms", 10000)),
getConfig().getBoolean("bridge.send-logs"), getConfig().getBoolean("commands.enabled"),
commands, getConfig().getBoolean("files.enabled"),
getConfig().getString("files.root", "plugins/UltronAI/shared"),
Math.max(1, Math.min(131072, getConfig().getInt("files.max-bytes", 65536))));
if (!getConfig().getBoolean("bridge.enabled")) return;
if (!url.startsWith("https://") || token.isEmpty() || token.equals("change-me")) {
getLogger().warning("Bridge disabled: configure an HTTPS URL and a secret token.");
return;
}
long period = Math.max(1, getConfig().getLong("bridge.poll-seconds", 5)) * 20L;
Settings current = settings;
task = getServer().getScheduler().runTaskTimerAsynchronously(this, () -> poll(current), 20L, period);
}
private void poll(Settings s) {
if (s != settings || !isEnabled()) return;
try {
Properties request = new Properties();
request.setProperty("server", getServer().getName());
if (s.sendLogs) {
synchronized (logs) {
request.setProperty("logs", String.join("\n", logs));
}
}
Properties job = exchange(s, "/api/bridge/poll", request);
if (s.sendLogs) {
synchronized (logs) {
String sent = request.getProperty("logs", "");
int count = sent.isEmpty() ? 0 : sent.split("\n", -1).length;
while (count-- > 0 && !logs.isEmpty()) logs.removeFirst();
}
}
String id = job.getProperty("id", "").trim();
if (id.isEmpty()) return;
Properties result = new Properties();
result.setProperty("id", id);
try {
if (s != settings || !isEnabled()) return;
result.setProperty("output", execute(s, job));
result.setProperty("ok", "true");
} catch (Exception e) {
result.setProperty("ok", "false");
result.setProperty("output", e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage());
}
exchange(s, "/api/bridge/result", result);
} catch (Exception e) {
getLogger().warning("Bridge request failed: " + e.getClass().getSimpleName());
}
}
private Properties exchange(Settings s, String endpoint, Properties data) throws IOException {
URL url = new URL(s.url + endpoint);
if (!"https".equalsIgnoreCase(url.getProtocol())) throw new IOException("HTTPS required");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(false);
connection.setConnectTimeout(s.connectTimeout);
connection.setReadTimeout(s.readTimeout);
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", "Bearer " + s.token);
connection.setRequestProperty("Content-Type", "text/x-java-properties; charset=ISO-8859-1");
connection.setDoOutput(true);
ByteArrayOutputStream body = new ByteArrayOutputStream();
data.store(body, null);
try {
try (java.io.OutputStream out = connection.getOutputStream()) {
out.write(body.toByteArray());
}
int status = connection.getResponseCode();
if (status < 200 || status >= 300) throw new IOException("HTTP " + status);
byte[] bytes;
try (InputStream in = connection.getInputStream()) {
bytes = in.readNBytes(MAX_RESPONSE + 1);
}
if (bytes.length > MAX_RESPONSE) throw new IOException("Response too large");
Properties response = new Properties();
response.load(new ByteArrayInputStream(bytes));
return response;
} finally {
connection.disconnect();
}
}
private String execute(Settings s, Properties job) throws Exception {
String type = job.getProperty("type", "");
if (type.equals("command")) {
if (!s.commandsEnabled) throw new IOException("Remote commands are disabled");
String command = job.getProperty("command", "").trim();
if (command.startsWith("/")) command = command.substring(1);
if (command.isEmpty() || command.contains("\n") || command.contains("\r")) throw new IOException("Invalid command");
String name = command.split("\\s+", 2)[0].toLowerCase(Locale.ROOT);
if (!s.commands.contains(name)) throw new IOException("Command not allowed");
final String dispatch = command;
return getServer().getScheduler().callSyncMethod(this, () -> {
if (s != settings || !isEnabled()) return "Bridge configuration changed";
return getServer().dispatchCommand(getServer().getConsoleSender(), dispatch)
? "Command dispatched; output appears in server logs" : "Command was not handled";
}).get(30, TimeUnit.SECONDS);
}
if (!s.filesEnabled) throw new IOException("Remote file access is disabled");
if (!type.equals("list") && !type.equals("read") && !type.equals("write")) throw new IOException("Unknown job type");
Path server = getServer().getWorldContainer().toPath().toRealPath();
Path configured = server.resolve(s.fileRoot).normalize();
if (!configured.startsWith(server) || configured.equals(server)) throw new IOException("Invalid file root");
Files.createDirectories(configured);
Path root = configured.toRealPath();
if (!root.startsWith(server) || root.equals(server)) throw new IOException("File root resolves outside the server directory");
String relative = job.getProperty("path", "");
Path target = root.resolve(relative).normalize();
if (!target.startsWith(root)) throw new IOException("Path outside file root");
Path existing = target;
while (existing != null && !Files.exists(existing, LinkOption.NOFOLLOW_LINKS)) existing = existing.getParent();
if (existing == null || !existing.toRealPath().startsWith(root)) throw new IOException("Path resolves outside file root");
if (Files.isSymbolicLink(target)) throw new IOException("Symbolic links are not supported");
if (type.equals("list")) {
try (java.util.stream.Stream<Path> stream = Files.list(target)) {
return String.join("\n", stream.limit(500).map(p -> p.getFileName().toString()).toList());
}
}
if (type.equals("read")) {
try (InputStream in = Files.newInputStream(target)) {
byte[] bytes = in.readNBytes(s.maxBytes + 1);
if (bytes.length > s.maxBytes) throw new IOException("File too large");
return new String(bytes, StandardCharsets.UTF_8);
}
}
byte[] content = job.getProperty("content", "").getBytes(StandardCharsets.UTF_8);