diff --git a/docs/web-editor.md b/docs/web-editor.md new file mode 100644 index 0000000..ad28bbf --- /dev/null +++ b/docs/web-editor.md @@ -0,0 +1,29 @@ +# Free command editor + +`/rtp editor` opens a temporary web session for the existing `config.yml`. It does not register the server, require a premium plan, or require Discord. `/rtp editor cancel` stops the active session. Permission: `betterrtp.editor` (default: op), including permission to write config and reload BetterRTP. Existing `/rtp edit` is unchanged. + +## Setup + +1. Deploy the companion BetterRTP-Webapp with PostgreSQL. Apply its committed Drizzle migrations, set `EDITOR_ENABLED=true`, and set `APP_ORIGIN=https://minecentral.net`. +2. Build/install this plugin. The editor website is fixed to `https://minecentral.net`; there is no website setting or `editor.yml` resource. Any old editor.yml file is ignored. +3. Run `/rtp editor`. Open the private chat link, edit the YAML, and choose **Save and apply to server**. Download is also available. A player who started the session must remain online with permission when applying; console-created sessions use console authority. +4. The UI first shows pending. It shows applied only after the plugin has validated, backed up, written, reloaded, verified the loaded/persisted settings, and acknowledged the result. + +No inbound ports on the Minecraft server are needed. The plugin calls the website over HTTPS every three seconds while a session is active. Outbound HTTPS must be permitted. Certificate checks remain enabled, and redirects are refused. + +## Limits and failure handling + +- One active editor per running server; fifteen-minute expiry and one submitted save. Start a fresh session for further edits. Cancelling cannot undo a write already in progress. +- Only `config.yml`, at most 128 KiB. Economy, database, language and other files are not exposed. Changing `Language-File` is blocked. +- Existing setting names and structured world/group entries must remain. Values and scalar lists may change. Numeric ranges and setting types are checked, with conservative limits for preload radius and attempts. YAML tags, anchors and aliases are rejected. The conservative parser also rejects literal equals signs and encoded character escapes to prevent Bukkit object-deserialization markers; edit such unusual configs locally. This is structural validation plus selected semantic checks, not a version-complete schema for every integration. +- A file changed since the session snapshot is rejected. Do not edit the file externally during apply: external processes do not participate in the plugin's lock/checks. +- Backups are written to `plugins/BetterRTP/editor-backups/` before replacement. Maintain/rotate these backups as appropriate for your server. +- Atomic replacement is required. Reload exceptions or a detected reload mismatch restore the original file and attempt another reload. If that reload also fails, restart the server; plugins/integrations may have partially changed in-memory state. +- Network failure retries until expiry. After a local apply result, only the acknowledgement is retried, never the write. A crash/restart cancels the in-memory session; it never resumes applying queued edits. If an acknowledgement is lost or the plugin crashes after writing, the website can show pending until expiry: inspect the live config and server messages before starting over. +- Anyone with the browser link can submit its one edit until it expires. Permission is checked at creation and again before applying. Do not share links, paste them into public chat, or run them through third-party link tools. Browser tokens are in URL fragments; plugin tokens never reach the browser. + +The website is trusted with the submitted config; this protocol is not end-to-end encrypted against the hosting operator. Restrict DB access and avoid putting secrets in the main config. The one-time session grants no persistent premium server access. + +## Validation + +Run `mvn -f tests/editor/pom.xml test` for the isolated config validator/file-write suite. It uses the actual Spigot YAML implementation without requiring all of the plugin's protection integrations. Run `mvn package` for the full plugin. Before production use, test the complete flow on a staging Minecraft server, including permissions, disconnect, reload failure and Folia scheduling if applicable. diff --git a/src/main/java/me/SuperRonanCraft/BetterRTP/BetterRTP.java b/src/main/java/me/SuperRonanCraft/BetterRTP/BetterRTP.java index 6010f5a..21791e3 100644 --- a/src/main/java/me/SuperRonanCraft/BetterRTP/BetterRTP.java +++ b/src/main/java/me/SuperRonanCraft/BetterRTP/BetterRTP.java @@ -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(); diff --git a/src/main/java/me/SuperRonanCraft/BetterRTP/player/commands/RTPCommandType.java b/src/main/java/me/SuperRonanCraft/BetterRTP/player/commands/RTPCommandType.java index ee124c3..ce72837 100644 --- a/src/main/java/me/SuperRonanCraft/BetterRTP/player/commands/RTPCommandType.java +++ b/src/main/java/me/SuperRonanCraft/BetterRTP/player/commands/RTPCommandType.java @@ -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()), diff --git a/src/main/java/me/SuperRonanCraft/BetterRTP/player/commands/types/CmdEditor.java b/src/main/java/me/SuperRonanCraft/BetterRTP/player/commands/types/CmdEditor.java new file mode 100644 index 0000000..daf1a7b --- /dev/null +++ b/src/main/java/me/SuperRonanCraft/BetterRTP/player/commands/types/CmdEditor.java @@ -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 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]"); + } +} diff --git a/src/main/java/me/SuperRonanCraft/BetterRTP/references/PermissionNode.java b/src/main/java/me/SuperRonanCraft/BetterRTP/references/PermissionNode.java index db24bb7..9b4f5fc 100644 --- a/src/main/java/me/SuperRonanCraft/BetterRTP/references/PermissionNode.java +++ b/src/main/java/me/SuperRonanCraft/BetterRTP/references/PermissionNode.java @@ -22,6 +22,7 @@ public enum PermissionNode implements PermissionCheck { SIGN_CREATE("sign"), VERSION("version"), EDIT("edit"), + EDITOR("editor"), LOCATION("location"), DEVELOPER("DEVELOPER_PERM"), ; diff --git a/src/main/java/me/SuperRonanCraft/BetterRTP/references/web/editor/EditorBridge.java b/src/main/java/me/SuperRonanCraft/BetterRTP/references/web/editor/EditorBridge.java new file mode 100644 index 0000000..10120e6 --- /dev/null +++ b/src/main/java/me/SuperRonanCraft/BetterRTP/references/web/editor/EditorBridge.java @@ -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 sync; + private final Consumer reload; + private final Predicate allowed; + private final Supplier 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 sync, Consumer reload, + Predicate allowed, Supplier 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; } + } +} diff --git a/src/main/java/me/SuperRonanCraft/BetterRTP/references/web/editor/EditorConfig.java b/src/main/java/me/SuperRonanCraft/BetterRTP/references/web/editor/EditorConfig.java new file mode 100644 index 0000000..d823c7a --- /dev/null +++ b/src/main/java/me/SuperRonanCraft/BetterRTP/references/web/editor/EditorConfig.java @@ -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 result = new LinkedHashMap<>(); + for (Map.Entry entry : ((Map) value).entrySet()) result.put(entry.getKey(), tree(entry.getValue())); + return result; + } + if (value instanceof List) { + List 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); } + } +} diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 5a35cd0..87853d0 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -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 diff --git a/tests/editor/pom.xml b/tests/editor/pom.xml new file mode 100644 index 0000000..e81a60e --- /dev/null +++ b/tests/editor/pom.xml @@ -0,0 +1,18 @@ + + 4.0.0 + me.SuperRonanCraftbetterrtp-editor-tests1.0 + 8UTF-8 + spigothttps://hub.spigotmc.org/nexus/content/repositories/snapshots/ + + org.spigotmcspigot-api1.8.8-R0.1-SNAPSHOTnet.md-5bungeecord-chat + net.md-5bungeecord-chat1.16-R0.4 + junitjunit4.13.2test + + + ../../src/main/java + + org.apache.maven.pluginsmaven-compiler-plugin3.14.0**/web/editor/*.java + org.apache.maven.pluginsmaven-surefire-plugin3.5.3 + + + diff --git a/tests/editor/src/test/java/EditorConfigTest.java b/tests/editor/src/test/java/EditorConfigTest.java new file mode 100644 index 0000000..87a8e68 --- /dev/null +++ b/tests/editor/src/test/java/EditorConfigTest.java @@ -0,0 +1,69 @@ +import me.SuperRonanCraft.BetterRTP.references.web.editor.EditorConfig; +import org.junit.Test; +import static org.junit.Assert.*; +import java.nio.file.*; +import java.nio.charset.StandardCharsets; + +public class EditorConfigTest { + private final String original = "Language-File: en.yml\nSettings:\n MaxAttempts: 32\n PreloadRadius: 5\nDefault:\n MinRadius: 10\n MaxRadius: 1000\n Shape: square\n Biomes: []\n"; + private void rejected(String edited) throws Exception { + try { EditorConfig.validate(original, edited); fail("Expected rejection"); } + catch (java.io.IOException expected) { } + } + @Test public void acceptsValidChange() throws Exception { EditorConfig.validate(original, original.replace("1000", "2000")); } + @Test public void rejectsWrongTypeAndRange() throws Exception { + rejected(original.replace("1000", "false")); + rejected(original.replace("1000", "5")); + rejected(original.replace("square", "triangle")); + rejected(original.replace("PreloadRadius: 5", "PreloadRadius: 5000")); + } + @Test public void rejectsSchemaAndLanguageChanges() throws Exception { + rejected(original + "Injected: true\n"); + rejected(original.replace("en.yml", "../secrets.yml")); + rejected(original.replace(" Shape: square\n", "")); + } + @Test public void rejectsAliasesAndTags() throws Exception { + rejected(original + "Alias: &x value\n"); + rejected(original + "Tag: !!java/object foo\n"); + rejected(original + "Object:\n ==: org.bukkit.inventory.ItemStack\n"); + } + @Test public void validatesBundledConfig() throws Exception { + String bundled = new String(Files.readAllBytes(Paths.get("../../src/main/resources/config.yml")), StandardCharsets.UTF_8); + EditorConfig.validate(bundled, bundled.replace("MaxRadius: 1000\n", "MaxRadius: 2000\n")); + } + @Test public void refusesStaleWritesAndRestoresAfterReloadFailure() throws Exception { + Path dir = Files.createTempDirectory("betterrtp-editor-apply"); Path file = dir.resolve("config.yml"); + byte[] snapshot = original.getBytes(StandardCharsets.UTF_8); + try { + Files.write(file, snapshot); + String edited = original.replace("1000", "2000"); + Path backup = EditorConfig.apply(file, snapshot, edited, () -> {}); + assertArrayEquals(snapshot, Files.readAllBytes(backup)); + assertTrue(EditorConfig.equivalent(edited, new String(Files.readAllBytes(file), StandardCharsets.UTF_8))); + try { EditorConfig.apply(file, snapshot, original, () -> {}); fail("Stale overwrite"); } + catch (java.io.IOException expected) { } + byte[] current = Files.readAllBytes(file); + final int[] reloads = { 0 }; + try { + EditorConfig.apply(file, current, original, () -> { if (reloads[0]++ == 0) throw new java.io.IOException("Simulated reload failure"); }); + fail("Reload should fail"); + } catch (java.io.IOException expected) { } + assertEquals(2, reloads[0]); + assertArrayEquals(current, Files.readAllBytes(file)); + } finally { + try (java.util.stream.Stream files = Files.walk(dir)) { + files.sorted(java.util.Comparator.reverseOrder()).forEach(p -> { try { Files.delete(p); } catch (java.io.IOException e) { throw new RuntimeException(e); } }); + } + } + } + @Test public void replacesAtomicallyAndBoundsReads() throws Exception { + Path dir = Files.createTempDirectory("betterrtp-editor-test"); Path file = dir.resolve("config.yml"); + try { + Files.write(file, original.getBytes(StandardCharsets.UTF_8)); + byte[] replacement = original.replace("1000", "2000").getBytes(StandardCharsets.UTF_8); + EditorConfig.replace(file, replacement); assertArrayEquals(replacement, EditorConfig.read(file)); + Files.write(file, new byte[EditorConfig.MAX_BYTES + 1]); + try { EditorConfig.read(file); fail("Oversized read"); } catch (java.io.IOException expected) { } + } finally { Files.deleteIfExists(file); Files.deleteIfExists(dir); } + } +}