web editor

This commit is contained in:
Ronan committed 2026-10-30 20:53:02 +01:00
1 parent 4697f06163
commit 66fe5b9001
10 files changed
+491

No files matched your search

@@ -47,12 +47,17 @@ public class BetterRTP extends JavaPlugin {
@Getter private boolean PlaceholderAPI;
@Getter private final RTPLogger rtpLogger = new RTPLogger();
@Getter private final FoliaHandler foliaHandler = new FoliaHandler();
@Getter private me.SuperRonanCraft.BetterRTP.references.web.editor.EditorBridge editorBridge;
@Override
public void onEnable() {
instance = this;
registerDependencies();
loadAll();
editorBridge = new me.SuperRonanCraft.BetterRTP.references.web.editor.EditorBridge(
this, me.SuperRonanCraft.BetterRTP.versions.AsyncHandler::sync, this::reload,
me.SuperRonanCraft.BetterRTP.references.PermissionNode.EDITOR::check,
() -> me.SuperRonanCraft.BetterRTP.references.file.FileOther.FILETYPE.CONFIG.getConfig().saveToString());
new Updater(this);
new Metrics(this);
listener.registerEvents(this);
@@ -66,6 +71,7 @@ public class BetterRTP extends JavaPlugin {
@Override
public void onDisable() {
if (editorBridge != null) editorBridge.close();
invs.closeAll();
queue.unload();
rtpLogger.unload();
@@ -5,6 +5,7 @@ import me.SuperRonanCraft.BetterRTP.player.commands.types.*;
public enum RTPCommandType {
BIOME(new CmdBiome()),
EDIT(new CmdEdit()),
EDITOR(new CmdEditor()),
HELP(new CmdHelp()),
INFO(new CmdInfo()),
LOCATION(new CmdLocation()),
@@ -0,0 +1,23 @@
package me.SuperRonanCraft.BetterRTP.player.commands.types;
import me.SuperRonanCraft.BetterRTP.BetterRTP;
import me.SuperRonanCraft.BetterRTP.player.commands.RTPCommand;
import me.SuperRonanCraft.BetterRTP.player.commands.RTPCommandHelpable;
import me.SuperRonanCraft.BetterRTP.references.PermissionNode;
import org.bukkit.command.CommandSender;
import java.util.Collections;
import java.util.List;
public class CmdEditor implements RTPCommand, RTPCommandHelpable {
public String getName() { return "editor"; }
public PermissionNode permission() { return PermissionNode.EDITOR; }
public String getHelp() { return "&7Open a private web config editor: &f/rtp editor &7(or cancel)"; }
public List<String> tabComplete(CommandSender sender, String[] args) {
return args.length == 2 && "cancel".startsWith(args[1].toLowerCase()) ? Collections.singletonList("cancel") : Collections.emptyList();
}
public void execute(CommandSender sender, String label, String[] args) {
if (args.length == 1) BetterRTP.getInstance().getEditorBridge().open(sender);
else if (args.length == 2 && "cancel".equalsIgnoreCase(args[1])) BetterRTP.getInstance().getEditorBridge().cancel(sender);
else sender.sendMessage("Usage: /" + label + " editor [cancel]");
}
}
@@ -22,6 +22,7 @@ public enum PermissionNode implements PermissionCheck {
SIGN_CREATE("sign"),
VERSION("version"),
EDIT("edit"),
EDITOR("editor"),
LOCATION("location"),
DEVELOPER("DEVELOPER_PERM"),
;
@@ -0,0 +1,184 @@
package me.SuperRonanCraft.BetterRTP.references.web.editor;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.chat.ClickEvent;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
/** One active session per server, all HTTP on a dedicated daemon worker. No inbound server port. */
public final class EditorBridge {
private static final String WEBSITE = "https://minecentral.net";
private final JavaPlugin plugin;
private final Consumer<Runnable> sync;
private final Consumer<CommandSender> reload;
private final Predicate<CommandSender> allowed;
private final Supplier<String> loadedConfig;
private final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor(r -> {
Thread thread = new Thread(r, "BetterRTP-editor"); thread.setDaemon(true); return thread;
});
private volatile Session current;
private volatile boolean stopped;
public EditorBridge(JavaPlugin plugin, Consumer<Runnable> sync, Consumer<CommandSender> reload,
Predicate<CommandSender> allowed, Supplier<String> loadedConfig) {
this.plugin = plugin;
this.sync = sync;
this.reload = reload;
this.allowed = allowed;
this.loadedConfig = loadedConfig;
worker.scheduleWithFixedDelay(this::poll, 3, 3, TimeUnit.SECONDS);
}
public void close() { stopped = true; current = null; worker.shutdownNow(); }
public void open(CommandSender sender) {
if (!allowed.test(sender)) return;
try {
if (current != null) throw new IOException("An editor is already active. Use /rtp editor cancel first.");
byte[] bytes = EditorConfig.read(configPath());
String content = new String(bytes, StandardCharsets.UTF_8); EditorConfig.parse(content);
Session session = new Session(content, bytes, sender instanceof Player ? ((Player) sender).getUniqueId() : null);
current = session;
sender.sendMessage("§7Creating a private BetterRTP editor session…");
worker.execute(() -> {
try {
JsonObject body = new JsonObject(); body.addProperty("protocol", 1);
body.addProperty("version", plugin.getDescription().getVersion()); body.addProperty("content", content);
JsonObject result = request(session, "POST", "/api/editor/sessions", body);
session.pluginToken = result.get("pluginToken").getAsString();
String browserToken = result.get("browserToken").getAsString();
if (!session.pluginToken.matches("[a-f0-9]{64}") || !browserToken.matches("[a-f0-9]{64}")) throw new IOException("Invalid relay response.");
session.expires = Math.min(session.expires, result.get("expiresAt").getAsLong());
if (current != session || stopped) { revoke(session); return; }
sync.accept(() -> {
if (current != session || stopped) return;
CommandSender recipient = recipient(session);
if (recipient == null || !allowed.test(recipient)) { cancelSession(session); return; }
String url = WEBSITE + "/editor/session#" + browserToken;
recipient.sendMessage("§ePrivate editor link: expires in 15 minutes, one save. Do not share it.");
if (recipient instanceof Player) {
TextComponent link = new TextComponent("§a[Open BetterRTP editor]");
link.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, url));
((Player) recipient).spigot().sendMessage(link);
} else recipient.sendMessage(url);
});
} catch (Exception error) {
if (current == session) current = null;
message(session, "Could not reach the MineCentral editor. Please try again later.");
}
});
} catch (Exception error) { sender.sendMessage("§cEditor: " + error.getMessage()); }
}
public void cancel(CommandSender sender) {
if (!allowed.test(sender)) return;
Session session = current;
if (session != null) cancelSession(session);
sender.sendMessage("§7Editor session cancelled. Changes already applied cannot be undone by cancelling.");
}
private void cancelSession(Session session) {
if (current == session) current = null;
if (!stopped) worker.execute(() -> revoke(session));
}
private void revoke(Session session) {
if (session.pluginToken != null) try { request(session, "DELETE", "/api/editor/session", null); } catch (Exception ignored) { }
}
private Path configPath() { return plugin.getDataFolder().toPath().resolve("config.yml"); }
private CommandSender recipient(Session session) { return session.player == null ? Bukkit.getConsoleSender() : Bukkit.getPlayer(session.player); }
private void message(Session session, String text) {
if (!stopped) sync.accept(() -> {
CommandSender sender = recipient(session); if (sender != null) sender.sendMessage("§eEditor: " + text);
});
}
private void poll() {
Session session = current;
if (stopped || session == null || session.pluginToken == null || session.applying) return;
if (System.currentTimeMillis() >= session.expires) { current = null; revoke(session); message(session, "Session expired. Run /rtp editor again."); return; }
try {
if (session.result != null) {
JsonObject ack = new JsonObject(); ack.addProperty("state", session.result);
request(session, "POST", "/api/editor/result", ack);
if (current == session) current = null;
return;
}
JsonObject response = request(session, "GET", "/api/editor/session", null);
if ("pending".equals(response.get("state").getAsString())) {
String edited = response.get("content").getAsString();
try { EditorConfig.validate(session.original, edited); }
catch (Exception invalid) {
session.result = "rejected";
message(session, "Configuration rejected: " + invalid.getMessage());
return;
}
session.applying = true;
sync.accept(() -> apply(session, edited));
}
} catch (Exception error) {
// Network failures are retried until expiry; never reapply after a recorded local result.
}
}
private void apply(Session session, String edited) {
try {
if (stopped || current != session || System.currentTimeMillis() >= session.expires) return;
CommandSender sender = recipient(session);
if (sender == null || !allowed.test(sender)) throw new IOException("Command sender must be online and still have betterrtp.editor.");
Path backup = EditorConfig.apply(configPath(), session.bytes, edited, () -> {
reload.accept(sender);
String loaded = loadedConfig.get();
String persisted = new String(EditorConfig.read(configPath()), StandardCharsets.UTF_8);
if (!EditorConfig.equivalent(persisted, loaded))
throw new IOException("Loaded configuration does not match the saved settings.");
});
session.result = "applied";
sender.sendMessage("§aEditor changes applied. Backup: " + backup.getFileName());
} catch (Exception error) {
session.result = "rejected"; message(session, "Not applied: " + error.getMessage());
} finally { session.applying = false; }
}
private JsonObject request(Session session, String method, String path, JsonObject body) throws IOException {
HttpURLConnection connection = (HttpURLConnection) new URL(WEBSITE + path).openConnection();
connection.setConnectTimeout(5000); connection.setReadTimeout(10000); connection.setInstanceFollowRedirects(false);
connection.setRequestMethod(method); connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("X-Editor-Actor", "plugin");
if (session.pluginToken != null) connection.setRequestProperty("Authorization", "Bearer " + session.pluginToken);
try {
if (body != null) {
byte[] bytes = body.toString().getBytes(StandardCharsets.UTF_8);
connection.setDoOutput(true); connection.setFixedLengthStreamingMode(bytes.length);
connection.setRequestProperty("Content-Type", "application/json");
try (OutputStream out = connection.getOutputStream()) { out.write(bytes); }
}
int status = connection.getResponseCode();
if (status < 200 || status >= 300) throw new IOException("Relay HTTP " + status);
try (InputStream in = connection.getInputStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
byte[] chunk = new byte[8192]; int count;
while ((count = in.read(chunk)) != -1) {
if (buffer.size() + count > EditorConfig.MAX_BYTES * 6 + 4096) throw new IOException("Relay response too large.");
buffer.write(chunk, 0, count);
}
return new JsonParser().parse(new String(buffer.toByteArray(), StandardCharsets.UTF_8)).getAsJsonObject();
}
} finally { connection.disconnect(); }
}
private static final class Session {
final String original; final byte[] bytes; final UUID player;
volatile String pluginToken, result;
volatile boolean applying;
volatile long expires = System.currentTimeMillis() + 15 * 60 * 1000;
Session(String original, byte[] bytes, UUID player) { this.original = original; this.bytes = bytes; this.player = player; }
}
}
@@ -0,0 +1,156 @@
package me.SuperRonanCraft.BetterRTP.references.web.editor;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
/** Validation is deliberately stricter than the local file loader. No new schema keys in protocol 1. */
public final class EditorConfig {
public static final int MAX_BYTES = 128 * 1024;
private static final Pattern TOKENS = Pattern.compile("(^|[\\s\\[\\]{},])[!&*]", Pattern.MULTILINE);
private EditorConfig() { }
public static YamlConfiguration parse(String text) throws Exception {
// Bukkit supports object deserialization through the reserved == key. Reject equals
// and encoded character escapes before invoking its parser, not only after parsing.
if (text.indexOf('=') >= 0 || Pattern.compile("\\\\[xuU]").matcher(text).find())
throw new IOException("Object serialization markers and encoded character escapes are not supported.");
if (text.getBytes(StandardCharsets.UTF_8).length > MAX_BYTES || TOKENS.matcher(text).find())
throw new IOException("Configuration too large, or YAML tags/anchors/aliases present.");
int lines = 0, flow = 0;
for (String line : text.split("\\n")) {
if (++lines > 4000 || line.matches("^ {65}.*")) throw new IOException("Configuration is too complex.");
for (char c : line.toCharArray()) if (c == '[' || c == '{') flow++;
}
if (flow > 128) throw new IOException("Too many flow collections.");
YamlConfiguration parsed = new YamlConfiguration();
parsed.loadFromString(text);
if (!parsed.isConfigurationSection("Settings") || !parsed.isConfigurationSection("Default"))
throw new IOException("Missing Settings or Default section.");
return parsed;
}
public static void validate(String original, String edited) throws Exception {
YamlConfiguration before = parse(original), after = parse(edited);
if (!Objects.equals(before.get("Language-File"), after.get("Language-File")))
throw new IOException("Change Language-File locally, not through the web editor.");
compare(before, after, "config", 0);
}
private static Object normalize(Object value) {
return value instanceof ConfigurationSection ? ((ConfigurationSection) value).getValues(false) : value;
}
private static void compare(Object oldValue, Object newValue, String path, int depth) throws IOException {
if (depth > 32) throw new IOException("Configuration nesting is too deep.");
oldValue = normalize(oldValue); newValue = normalize(newValue);
if (oldValue instanceof Map) {
if (!(newValue instanceof Map)) throw new IOException("Expected section: " + path);
Map<?, ?> oldMap = (Map<?, ?>) oldValue, newMap = (Map<?, ?>) newValue;
if (!oldMap.keySet().equals(newMap.keySet())) throw new IOException("Keep existing setting names: " + path);
for (Object key : oldMap.keySet()) compare(oldMap.get(key), newMap.get(key), path + "." + key, depth + 1);
checkRange(newMap, "MinRadius", "MaxRadius", path, true);
checkRange(newMap, "MinY", "MaxY", path, false);
} else if (oldValue instanceof List) {
if (!(newValue instanceof List)) throw new IOException("Expected list: " + path);
List<?> oldList = (List<?>) oldValue, newList = (List<?>) newValue;
if (newList.size() > 1000) throw new IOException("List too long: " + path);
boolean structured = oldList.stream().anyMatch(v -> normalize(v) instanceof Map);
if (structured && oldList.size() != newList.size()) throw new IOException("Keep existing world/group entries: " + path);
for (int i = 0; i < newList.size(); i++) {
Object baseline = structured ? oldList.get(i) : oldList.isEmpty() ? "" : oldList.get(0);
compare(baseline, newList.get(i), path + "[" + i + "]", depth + 1);
}
} else if (oldValue instanceof Number) {
if (!(newValue instanceof Number)) throw new IOException("Expected number: " + path);
double n = ((Number) newValue).doubleValue();
if (!Double.isFinite(n) || n < Integer.MIN_VALUE || n > Integer.MAX_VALUE ||
((oldValue instanceof Integer || oldValue instanceof Long) && n != Math.rint(n)))
throw new IOException("Invalid number: " + path);
if (path.endsWith("Radius") && (n < 0 || n > 30000000)) throw new IOException("Invalid radius: " + path);
if ((path.endsWith(".Time") || path.endsWith(".LockAfter")) && n < 0) throw new IOException("Negative time: " + path);
if (path.endsWith(".PreloadRadius") && (n < 0 || n > 16)) throw new IOException("PreloadRadius must be 0–16.");
if (path.endsWith(".MaxAttempts") && (n < 1 || n > 10000)) throw new IOException("MaxAttempts must be 1–10000.");
} else if (oldValue instanceof Boolean) {
if (!(newValue instanceof Boolean)) throw new IOException("Expected boolean: " + path);
} else if (oldValue instanceof String) {
if (!(newValue instanceof String)) throw new IOException("Expected text: " + path);
if (path.endsWith(".Shape") && !Arrays.asList("square", "circle").contains(((String) newValue).toLowerCase(Locale.ROOT)))
throw new IOException("Shape must be square or circle.");
} else if (!Objects.equals(oldValue, newValue)) throw new IOException("Unsupported setting: " + path);
}
private static void checkRange(Map<?, ?> map, String min, String max, String path, boolean strict) throws IOException {
if (map.get(min) instanceof Number && map.get(max) instanceof Number) {
double a = ((Number) map.get(min)).doubleValue(), b = ((Number) map.get(max)).doubleValue();
if (strict ? a >= b : a > b) throw new IOException("Invalid " + min + "/" + max + " range: " + path);
}
}
@FunctionalInterface
public interface Reload { void run() throws Exception; }
public static Path apply(Path file, byte[] snapshot, String edited, Reload reload) throws Exception {
validate(new String(snapshot, StandardCharsets.UTF_8), edited);
if (!Arrays.equals(read(file), snapshot)) throw new IOException("config.yml changed; start a new session.");
Path backups = file.getParent().resolve("editor-backups");
Files.createDirectories(backups);
Path backup = backups.resolve("config-" + System.currentTimeMillis() + "-" + UUID.randomUUID() + ".yml");
Files.write(backup, snapshot, StandardOpenOption.CREATE_NEW);
if (!Arrays.equals(read(file), snapshot)) throw new IOException("Configuration changed during save.");
replace(file, edited.getBytes(StandardCharsets.UTF_8));
try {
reload.run();
if (!equivalent(edited, new String(read(file), StandardCharsets.UTF_8)))
throw new IOException("Saved configuration does not match the submission.");
return backup;
} catch (Exception failure) {
replace(file, snapshot);
try { reload.run(); }
catch (Exception rollback) {
IOException error = new IOException("Original file restored but reload failed; restart the server.", failure);
error.addSuppressed(rollback); throw error;
}
throw new IOException("Reload failed; original configuration restored.", failure);
}
}
public static boolean equivalent(String expected, String actual) throws Exception {
return tree(parse(expected)).equals(tree(parse(actual)));
}
private static Object tree(Object value) {
value = normalize(value);
if (value instanceof Map) {
Map<Object, Object> result = new LinkedHashMap<>();
for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) result.put(entry.getKey(), tree(entry.getValue()));
return result;
}
if (value instanceof List) {
List<Object> result = new ArrayList<>();
for (Object item : (List<?>) value) result.add(tree(item));
return result;
}
return value;
}
public static byte[] read(Path file) throws IOException {
if (Files.size(file) > MAX_BYTES) throw new IOException("config.yml exceeds 128 KiB.");
byte[] result = Files.readAllBytes(file);
if (result.length > MAX_BYTES) throw new IOException("config.yml exceeds 128 KiB.");
return result;
}
public static void replace(Path file, byte[] bytes) throws IOException {
Path temp = Files.createTempFile(file.getParent(), ".editor-", ".tmp");
try {
Files.write(temp, bytes);
// Fail closed if this filesystem cannot atomically replace the configuration.
Files.move(temp, file, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
} finally { Files.deleteIfExists(temp); }
}
}
+4
View File
@@ -91,3 +91,7 @@ permissions:
betterrtp.edit:
description: Edit a custom/default world rtp center/radius
default: op
betterrtp.editor:
description: Open or cancel a temporary web editor with config write and reload access
default: op