diff --git a/docs/web-editor.md b/docs/web-editor.md index bdcd957..a9b3ca6 100644 --- a/docs/web-editor.md +++ b/docs/web-editor.md @@ -1,45 +1,41 @@ # 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. +`/rtp editor` creates a private, 24-hour web session for `config.yml`. It requires a player with `betterrtp.editor` (default: op), but no Discord login or premium. `/rtp editor cancel` revokes the current session and all its saved tokens; only its creator may cancel it. One session is active per running server. Existing `/rtp edit` is unchanged. -## Setup +## Setup and use -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. +1. Deploy the companion website with PostgreSQL and apply its migrations using `pnpm db:deploy`. Protocol 2 requires migration `0002_editor_command_sync`. Set `APP_ORIGIN` to the deployed website origin. The editor API is available by default. +2. Install the matching plugin build and restart Minecraft. Normal builds target `https://minecentral.net`; staging builds target the test website below. There is no website setting or `editor.yml` resource. +3. As a player, run `/rtp editor` and open the private link. The website displays the target label and `config.yml` as read-only context. +4. Edit and click **Save and get sync command**. This stores an immutable version; nothing is applied to Minecraft yet. +5. Run `/betterrtp editorsync ` as the same player on the same server. The plugin downloads that version over HTTPS, checks permission again, validates it, backs up the current file, atomically replaces it, and reloads BetterRTP. -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. +There are no inbound Minecraft connections and no automatic polling. Allow outbound HTTPS. TLS certificate validation remains enabled and redirects are refused. Never publish editor links or command tokens; Minecraft command logging plugins may capture sync commands. -## Limits and failure handling +## Expiry, versions, and errors -- 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. +- Editor sessions expire 24 hours after creation without activity extending them. Each save has an independent 15-minute, single-use sync token. Saving again does not invalidate previous tokens, and syncing does not close the editor session. +- Expiring an editor stops new saves; existing save tokens retain their own deadlines. To replace the current session before its final tokens expire, its creator must use `/rtp editor cancel` first. Cancelling revokes all remaining tokens. +- Session expiry preserves the browser text for download. The personal config library and Discord login are not implemented yet. +- Tokens are consumed atomically when downloaded. If a response is lost, local validation fails, or the player disconnects before application, save again for a fresh token. The plugin does not retry writes. Minecraft reports the apply outcome; the website does not report generated commands as applied. +- The creator must still be online and hold `betterrtp.editor` at apply time. Restarting/disabling the plugin discards its in-memory session, so old tokens cannot be applied by that plugin instance after restart. +- Invalid content is rejected before any file change. Validation preserves the existing setting structure and types, checks selected numeric ranges, blocks Language-File changes and unsafe Bukkit YAML constructs, and limits config size to 128 KiB. This is conservative validation, not a complete schema for every integration. +- Intervening edits to the Minecraft config do not block syncing: applying a saved version can overwrite those edits. A backup of the current file is created in `plugins/BetterRTP/editor-backups/`; rotate backups as appropriate. +- If writing succeeds but reload fails, the new file stays in place and a reload error is reported. There is no automatic rollback. Check Minecraft's console and reload after resolving the failure. +- The website trusts the plugin-supplied target label for display only. The private plugin-session capability and player UUID bind redemption to the original session; browser target fields cannot redirect a write. -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. +Protocol 1 automatic-apply clients are intentionally incompatible with protocol 2. The website migration closes existing protocol 1 sessions. Update website/database and plugin together for testing. ## Production and staging builds -The normal `mvn clean package` build embeds `https://minecentral.net` and produces -`target/BetterRTP-3.6.13.jar`. Use `mvn clean package -Pstaging` to embed -`https://n2nm1thopoojau1ggnalixvr.minecentral.net` and produce -`target/BetterRTP-3.6.13-staging.jar` for the test Minecraft server. +Run `mvn clean package` for `target/BetterRTP-3.6.13.jar`, targeting `https://minecentral.net`. +Run `mvn clean package -Pstaging` for `target/BetterRTP-3.6.13-staging.jar`, targeting +`https://n2nm1thopoojau1ggnalixvr.minecentral.net`. -The address is filtered into internal JAR metadata at build time. It is not read -from `editor.yml`, a server-side file, or an environment variable. Upload only one -BetterRTP JAR to a server's plugins directory. The staging website should use its -own origin as `APP_ORIGIN` and have the editor enabled and migrations applied. +The address is internal JAR build metadata, not a server configuration or environment setting. Upload only one BetterRTP JAR to the plugins directory. Use the staging website origin as its `APP_ORIGIN` and apply the database migration there. -This profile changes only the destination website. The implementation described -above still uses the original polling protocol; the agreed `editorsync` command, -24-hour sessions, and independent 15-minute save tokens remain implementation work. +## Validation + +Run `mvn -f tests/editor/pom.xml test` for configuration validation/file-write tests and `mvn package -Pstaging` for the full staging plugin. The web repository's `pnpm test` exercises version isolation, atomic single-use redemption, creator/server binding, independent expiry, cancellation, validation, and limits against embedded PostgreSQL. + +Before production use, test the complete flow on the staging Minecraft server, including wrong-player denial, permission loss, disconnect, expiry, repeated saves, intervening local changes, reload errors, restart, and Folia scheduling if applicable. Local automated checks do not substitute for this staging run. 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 ce72837..948d86e 100644 --- a/src/main/java/me/SuperRonanCraft/BetterRTP/player/commands/RTPCommandType.java +++ b/src/main/java/me/SuperRonanCraft/BetterRTP/player/commands/RTPCommandType.java @@ -6,6 +6,7 @@ public enum RTPCommandType { BIOME(new CmdBiome()), EDIT(new CmdEdit()), EDITOR(new CmdEditor()), + EDITOR_SYNC(new CmdEditorSync()), HELP(new CmdHelp()), INFO(new CmdInfo()), LOCATION(new CmdLocation()), diff --git a/src/main/java/me/SuperRonanCraft/BetterRTP/player/commands/types/CmdEditorSync.java b/src/main/java/me/SuperRonanCraft/BetterRTP/player/commands/types/CmdEditorSync.java new file mode 100644 index 0000000..3edede5 --- /dev/null +++ b/src/main/java/me/SuperRonanCraft/BetterRTP/player/commands/types/CmdEditorSync.java @@ -0,0 +1,21 @@ +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 me.SuperRonanCraft.BetterRTP.references.messages.MessagesHelp; +import org.bukkit.command.CommandSender; +import java.util.Collections; +import java.util.List; + +public class CmdEditorSync implements RTPCommand, RTPCommandHelpable { + public String getName() { return "editorsync"; } + public PermissionNode permission() { return PermissionNode.EDITOR; } + public List tabComplete(CommandSender sender, String[] args) { return Collections.emptyList(); } + public void execute(CommandSender sender, String label, String[] args) { + if (args.length == 2) BetterRTP.getInstance().getEditorBridge().redeem(sender, args[1]); + else sender.sendMessage("Usage: /" + label + " editorsync "); + } + public String getHelp() { return MessagesHelp.EDITOR_SYNC.get(); } +} diff --git a/src/main/java/me/SuperRonanCraft/BetterRTP/references/messages/MessagesHelp.java b/src/main/java/me/SuperRonanCraft/BetterRTP/references/messages/MessagesHelp.java index e5c6a43..fe2df48 100644 --- a/src/main/java/me/SuperRonanCraft/BetterRTP/references/messages/MessagesHelp.java +++ b/src/main/java/me/SuperRonanCraft/BetterRTP/references/messages/MessagesHelp.java @@ -9,6 +9,7 @@ public enum MessagesHelp implements MessageData { BIOME("Biome"), EDIT("Edit"), EDITOR("Editor"), + EDITOR_SYNC("EditorSync"), HELP("Help"), INFO("Info"), PLAYER("Player"), 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 index 8f9105b..3d7b661 100644 --- a/src/main/java/me/SuperRonanCraft/BetterRTP/references/web/editor/EditorBridge.java +++ b/src/main/java/me/SuperRonanCraft/BetterRTP/references/web/editor/EditorBridge.java @@ -55,22 +55,28 @@ public final class EditorBridge { this.reload = reload; this.allowed = allowed; this.loadedConfig = loadedConfig; - worker.scheduleWithFixedDelay(this::poll, 3, 3, TimeUnit.SECONDS); + // Saved versions are fetched only by an explicit editorsync command. } public void close() { stopped = true; current = null; worker.shutdownNow(); } public void open(CommandSender sender) { if (!allowed.test(sender)) return; + if (!(sender instanceof Player)) { sender.sendMessage("§cEditor sessions must be created by a player."); return; } try { + if (current != null && System.currentTimeMillis() >= current.expires + 15 * 60 * 1000) current = null; 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); + final String serverName = Bukkit.getServer().getServerName(); current = session; sender.sendMessage("§7Creating a private BetterRTP editor session…"); worker.execute(() -> { try { - JsonObject body = new JsonObject(); body.addProperty("protocol", 1); + JsonObject body = new JsonObject(); body.addProperty("protocol", 2); + body.addProperty("playerId", session.player.toString()); + body.addProperty("serverName", serverName); + body.addProperty("configFile", "config.yml"); 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(); @@ -83,7 +89,7 @@ public final class EditorBridge { 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."); + recipient.sendMessage("§ePrivate editor link: expires in 24 hours. Save online, then run the sync command here. 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)); @@ -92,7 +98,8 @@ public final class EditorBridge { }); } catch (Exception error) { if (current == session) current = null; - message(session, "Could not reach the MineCentral editor. Please try again later."); + plugin.getLogger().warning("Editor session creation failed (" + error.getClass().getSimpleName() + "). Check website/database availability."); + message(session, "Could not create an editor session. " + safeError(error)); } }); } catch (Exception error) { sender.sendMessage("§cEditor: " + error.getMessage()); } @@ -101,6 +108,9 @@ public final class EditorBridge { public void cancel(CommandSender sender) { if (!allowed.test(sender)) return; Session session = current; + if (session != null && (!(sender instanceof Player) || !session.player.equals(((Player) sender).getUniqueId()))) { + sender.sendMessage("§cOnly the player who created the editor session can cancel it."); return; + } if (session != null) cancelSession(session); sender.sendMessage("§7Editor session cancelled. Changes already applied cannot be undone by cancelling."); } @@ -118,39 +128,48 @@ public final class EditorBridge { CommandSender sender = recipient(session); if (sender != null) sender.sendMessage("§eEditor: " + text); }); } - private void poll() { + public void redeem(CommandSender sender, String token) { + if (!allowed.test(sender)) return; 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. + if (!(sender instanceof Player) || session == null || !session.player.equals(((Player) sender).getUniqueId())) { + sender.sendMessage("§cOnly the player who created this server's editor session can sync it."); return; } + if (!token.matches("[a-f0-9]{64}")) { sender.sendMessage("§cInvalid sync token. Copy the command from the editor."); return; } + if (session.pluginToken == null || session.applying) { sender.sendMessage("§eAn editor request is already in progress."); return; } + if (System.currentTimeMillis() >= session.expires + 15 * 60 * 1000) { + sender.sendMessage("§cSession expired. Run /rtp editor again."); return; + } + session.applying = true; + sender.sendMessage("§7Downloading your saved configuration…"); + worker.execute(() -> { + try { + JsonObject response = request(session, "GET", "/api/editor/sync", null, token); + if (!session.player.toString().equals(response.get("playerId").getAsString()) || + !"config.yml".equals(response.get("configFile").getAsString())) throw new IOException("Invalid sync target."); + String edited = response.get("content").getAsString(); + long expires = response.get("expiresAt").getAsLong(); + EditorConfig.validate(session.original, edited); + sync.accept(() -> apply(session, edited, expires)); + } catch (Exception error) { + session.applying = false; + message(session, "Sync failed: " + safeError(error) + " Save online again for a new command if this token was consumed."); + } + }); } - private void apply(Session session, String edited) { + private static String safeError(Exception error) { + // Do not log URLs, headers, raw responses, tokens, or config contents. + if (error instanceof IOException && error.getMessage() != null && error.getMessage().startsWith("Relay HTTP ")) + return error.getMessage(); + return "Request or validation failed (" + error.getClass().getSimpleName() + ")."; + } + + private void apply(Session session, String edited, long tokenExpires) { try { - if (stopped || current != session || System.currentTimeMillis() >= session.expires) return; + if (stopped || current != session) return; + if (System.currentTimeMillis() >= tokenExpires) throw new IOException("Sync token expired before apply."); CommandSender sender = recipient(session); - if (sender == null || !allowed.test(sender)) throw new IOException("Command sender must be online and still have betterrtp.editor."); + if (sender == null || !allowed.test(sender)) throw new IOException("The session creator must be online and still have betterrtp.editor."); Path backup = EditorConfig.apply(configPath(), session.bytes, edited, () -> { reload.accept(sender); String loaded = loadedConfig.get(); @@ -158,18 +177,28 @@ public final class EditorBridge { 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()); + sender.sendMessage("§aEditor changes applied and reloaded. Backup: " + backup.getFileName()); + } catch (EditorConfig.ReloadFailure error) { + message(session, "Configuration saved, but reload failed. The new file remains in place. Check the console and reload BetterRTP."); + plugin.getLogger().warning("Editor config was written but reload failed; no rollback was performed."); } catch (Exception error) { - session.result = "rejected"; message(session, "Not applied: " + error.getMessage()); + message(session, "Sync not applied: " + error.getMessage()); } finally { session.applying = false; } } private JsonObject request(Session session, String method, String path, JsonObject body) throws IOException { + return request(session, method, path, body, null); + } + private JsonObject request(Session session, String method, String path, JsonObject body, String syncToken) 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"); + connection.setRequestProperty("User-Agent", "BetterRTP-Editor/2"); + if (syncToken != null) { + connection.setRequestProperty("X-Editor-Sync-Token", syncToken); + connection.setRequestProperty("X-Editor-Player", session.player.toString()); + } if (session.pluginToken != null) connection.setRequestProperty("Authorization", "Bearer " + session.pluginToken); try { if (body != null) { @@ -192,9 +221,9 @@ public final class EditorBridge { } private static final class Session { final String original; final byte[] bytes; final UUID player; - volatile String pluginToken, result; + volatile String pluginToken; volatile boolean applying; - volatile long expires = System.currentTimeMillis() + 15 * 60 * 1000; + volatile long expires = System.currentTimeMillis() + 24 * 60 * 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 index d823c7a..e028f95 100644 --- a/src/main/java/me/SuperRonanCraft/BetterRTP/references/web/editor/EditorConfig.java +++ b/src/main/java/me/SuperRonanCraft/BetterRTP/references/web/editor/EditorConfig.java @@ -96,27 +96,24 @@ public final class EditorConfig { 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."); + // Back up the current file, but intentionally allow intervening local changes. + Files.write(backup, read(file), StandardOpenOption.CREATE_NEW); 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); + throw new ReloadFailure(failure); } + return backup; + } + + public static final class ReloadFailure extends IOException { + public ReloadFailure(Exception cause) { super("Configuration written, but reload failed. No rollback was performed.", cause); } } public static boolean equivalent(String expected, String actual) throws Exception { diff --git a/src/main/resources/lang/en.yml b/src/main/resources/lang/en.yml index ed43402..a7e5f9b 100644 --- a/src/main/resources/lang/en.yml +++ b/src/main/resources/lang/en.yml @@ -39,6 +39,7 @@ Help: Main: ' &7- &e/%command% &7- Randomly teleports you!' Biome: ' &7- &e/%command% biome &7- Randomly teleport withing these biomes' Edit: ' &7- &e/%command% edit [args...] &7- Edit some plugin settings' + EditorSync: ' &7- &e/%command% editorsync &7- Apply your saved web editor configuration' Editor: ' &7- &e/%command% editor &7- Initialize an online config editor for easier configuration' Help: ' &7- &e/%command% help &7- Shows help list' Info: ' &7- &e/%command% info [world/particles/shapes/potion_effects] &7- View specific information about plugin parameters' diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 87853d0..6f645c7 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -93,5 +93,5 @@ permissions: default: op betterrtp.editor: - description: Open or cancel a temporary web editor with config write and reload access + description: Open, cancel, or sync a temporary web editor with config write and reload access default: op diff --git a/tests/editor/src/test/java/EditorConfigTest.java b/tests/editor/src/test/java/EditorConfigTest.java index 87a8e68..b915156 100644 --- a/tests/editor/src/test/java/EditorConfigTest.java +++ b/tests/editor/src/test/java/EditorConfigTest.java @@ -31,7 +31,7 @@ public class EditorConfigTest { 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 { + @Test public void allowsStaleWritesAndKeepsNewFileAfterReloadFailure() throws Exception { Path dir = Files.createTempDirectory("betterrtp-editor-apply"); Path file = dir.resolve("config.yml"); byte[] snapshot = original.getBytes(StandardCharsets.UTF_8); try { @@ -40,16 +40,21 @@ public class EditorConfigTest { 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) { } + // The original snapshot is now stale; applying it is intentionally allowed. + EditorConfig.apply(file, snapshot, original, () -> {}); + assertArrayEquals(snapshot, Files.readAllBytes(file)); 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"); }); + EditorConfig.apply(file, current, edited, () -> { reloads[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)); + assertEquals(1, reloads[0]); + assertArrayEquals(edited.getBytes(StandardCharsets.UTF_8), Files.readAllBytes(file)); + byte[] unchanged = Files.readAllBytes(file); + try { EditorConfig.apply(file, snapshot, "broken: [", () -> fail("Must not reload")); fail("Must reject invalid config"); } + catch (Exception expected) { } + assertArrayEquals(unchanged, 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); } });