Include shared profile protection for Lobby Builder

This commit is contained in:
unimatrixgit 2026-12-05 14:33:18 +01:00
commit f4f8312f71
5 changed files with 294 additions and 0 deletions

View file

@ -0,0 +1,79 @@
package com.example.dunelobby;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Set;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
/** Keeps pre-transfer local inventory snapshots subordinate to the shared profile. */
final class BuilderSharedProfiles {
private static final String SHARED_INVENTORY = "network.share-lobby-inventory";
static boolean allowTransfer(Player player, Path snapshot) {
if (Files.exists(snapshot)) return true;
if (sharingCore() == null) return true;
player.sendMessage("The build world is temporarily unavailable while shared inventories are protected.");
return false;
}
/**
* Handles shared-mode snapshots. Only local-only mode may continue into the
* original inventory and ender-chest restore.
*/
static boolean restore(Player player, Path snapshot, boolean travel, boolean inBuilder,
Set<UUID> returning) throws IOException {
JavaPlugin core = sharingCore();
if (core == null) return false;
if (!Files.exists(snapshot) || !loaded(core, player.getUniqueId())) return true;
if (inBuilder) {
if (!travel) return true;
var state = YamlConfiguration.loadConfiguration(snapshot.toFile());
var destination = state.getLocation("return");
String name = state.getString("mode");
if (destination == null || destination.getWorld() == null || name == null) return true;
GameMode mode = GameMode.valueOf(name);
returning.add(player.getUniqueId());
try {
if (!player.teleport(destination)) return true;
player.setGameMode(mode);
} finally {
returning.remove(player.getUniqueId());
}
}
quarantine(snapshot);
return true;
}
private static JavaPlugin sharingCore() {
var registered = Bukkit.getPluginManager().getPlugin("DuneCore");
if (!(registered instanceof JavaPlugin core) || !core.getConfig().getBoolean(SHARED_INVENTORY, false)) return null;
return core;
}
private static boolean loaded(JavaPlugin core, UUID player) {
if (!core.isEnabled()) return false;
try {
var database = core.getClass().getMethod("sharedDatabase").invoke(core);
return database != null && Boolean.TRUE.equals(database.getClass().getMethod("isLoaded", UUID.class)
.invoke(database, player));
} catch (ReflectiveOperationException | LinkageError unavailable) {
return false;
}
}
private static void quarantine(Path snapshot) throws IOException {
if (!Files.isRegularFile(snapshot, LinkOption.NOFOLLOW_LINKS)) {
throw new IOException("Builder recovery snapshot is not a regular file");
}
Path retained = snapshot.resolveSibling(snapshot.getFileName() + ".shared-" + UUID.randomUUID());
Files.move(snapshot, retained, StandardCopyOption.ATOMIC_MOVE);
}
}

View file

@ -133,6 +133,7 @@ public final class BuilderTransfer implements Listener {
private void restore(Player player, boolean travel) throws IOException {
Path file = snapshot(player);
if (!Files.exists(file)) return;
if (BuilderSharedProfiles.restore(player, file, travel, inBuilder(player.getWorld()), returning)) return;
var state = YamlConfiguration.loadConfiguration(file.toFile());
Location destination = state.getLocation("return");
GameMode mode = GameMode.valueOf(state.getString("mode"));
@ -161,6 +162,7 @@ public final class BuilderTransfer implements Listener {
restore(player, true);
return;
}
if (!BuilderSharedProfiles.allowTransfer(player, snapshot(player))) return;
World world = loadWorld();
if (world == null) {
player.sendMessage("The Arrakis build world is unavailable.");

View file

@ -0,0 +1,92 @@
package com.example.dunelobby;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Set;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class BuilderSharedProfilesTest {
private static final UUID PLAYER = UUID.fromString("00000000-0000-4000-8000-000000000101");
@TempDir Path directory;
public abstract static class TestCore extends JavaPlugin {
public abstract TestDatabase sharedDatabase();
}
public abstract static class TestDatabase {
public abstract boolean isLoaded(UUID player);
}
private org.mockito.MockedStatic<Bukkit> core(boolean enabled, boolean loaded) {
var bukkit = mockStatic(Bukkit.class);
var plugins = mock(PluginManager.class);
var plugin = mock(TestCore.class);
var database = mock(TestDatabase.class);
var config = new YamlConfiguration();
config.set("network.share-lobby-inventory", enabled);
bukkit.when(Bukkit::getPluginManager).thenReturn(plugins);
when(plugins.getPlugin("DuneCore")).thenReturn(plugin);
when(plugin.getConfig()).thenReturn(config);
when(plugin.isEnabled()).thenReturn(true);
when(plugin.sharedDatabase()).thenReturn(database);
when(database.isLoaded(PLAYER)).thenReturn(loaded);
return bukkit;
}
@Test void confirmedSharedLoadQuarantinesStaleSnapshotWithoutTouchingInventory() throws Exception {
var file = directory.resolve("snapshot.yml");
Files.writeString(file, "inventory: [stale]\nender: [stale]\n");
var stale = Files.readAllBytes(file);
var player = mock(Player.class);
when(player.getUniqueId()).thenReturn(PLAYER);
try (var ignored = core(true, true)) {
assertTrue(BuilderSharedProfiles.restore(player, file, true, false, Set.of()));
}
assertFalse(Files.exists(file));
try (var files = Files.list(directory)) {
var retained = files.toList();
assertEquals(1, retained.size());
assertArrayEquals(stale, Files.readAllBytes(retained.getFirst()));
}
verify(player).getUniqueId();
verifyNoMoreInteractions(player);
}
@Test void failedSharedLoadDoesNotRestoreOrRemoveLocalData() throws Exception {
var file = directory.resolve("snapshot.yml");
Files.writeString(file, "inventory: [stale]\n");
var stale = Files.readAllBytes(file);
var player = mock(Player.class);
when(player.getUniqueId()).thenReturn(PLAYER);
try (var ignored = core(true, false)) {
assertTrue(BuilderSharedProfiles.restore(player, file, true, true, Set.of()));
assertFalse(BuilderSharedProfiles.allowTransfer(player, directory.resolve("missing.yml")));
}
assertArrayEquals(stale, Files.readAllBytes(file));
verify(player).getUniqueId();
verify(player).sendMessage("The build world is temporarily unavailable while shared inventories are protected.");
verifyNoMoreInteractions(player);
}
@Test void localOnlyStillUsesOriginalBuilderRestoreAndEntry() throws Exception {
var file = directory.resolve("snapshot.yml");
Files.writeString(file, "inventory: [legacy]\n");
var player = mock(Player.class);
try (var ignored = core(false, false)) {
assertFalse(BuilderSharedProfiles.restore(player, file, true, false, Set.of()));
assertTrue(BuilderSharedProfiles.allowTransfer(player, directory.resolve("missing.yml")));
}
assertTrue(Files.exists(file));
verifyNoInteractions(player);
}
}

View file

@ -0,0 +1,75 @@
import java.nio.file.Files;
import java.nio.file.Path;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FrameNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.VarInsnNode;
class BuilderSharedProfilesOverlay {
private static final String OWNER = "com/example/dunelobby/BuilderTransfer";
private static final String GUARD = "com/example/dunelobby/BuilderSharedProfiles";
private static final String PLAYER = "Lorg/bukkit/entity/Player;";
private static final String PATH = "Ljava/nio/file/Path;";
public static void main(String[] args) throws Exception {
if (args.length != 2) throw new IllegalArgumentException("Expected baseline and output classes");
var reader = new ClassReader(Files.readAllBytes(Path.of(args[0])));
var retained = new ClassNode();
reader.accept(retained, 0);
if (!OWNER.equals(retained.name)) throw new IllegalArgumentException("Unexpected legacy Builder implementation");
var restore = retained.methods.stream().filter(m -> m.name.equals("restore") && m.desc.equals("(" + PLAYER + "Z)V"))
.findFirst().orElseThrow();
var transfer = retained.methods.stream().filter(m -> m.name.equals("transfer") && m.desc.equals("(" + PLAYER + ")V"))
.findFirst().orElseThrow();
var recover = snapshot();
recover.add(new VarInsnNode(Opcodes.ILOAD, 2));
recover.add(new VarInsnNode(Opcodes.ALOAD, 0));
recover.add(new VarInsnNode(Opcodes.ALOAD, 1));
recover.add(new MethodInsnNode(Opcodes.INVOKEINTERFACE, "org/bukkit/entity/Player", "getWorld",
"()Lorg/bukkit/World;", true));
recover.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, OWNER, "inBuilder", "(Lorg/bukkit/World;)Z", false));
recover.add(new VarInsnNode(Opcodes.ALOAD, 0));
recover.add(new FieldInsnNode(Opcodes.GETFIELD, OWNER, "returning", "Ljava/util/Set;"));
recover.add(new MethodInsnNode(Opcodes.INVOKESTATIC, GUARD, "restore",
"(" + PLAYER + PATH + "ZZLjava/util/Set;)Z", false));
finish(recover, Opcodes.IFEQ);
restore.instructions.insert(recover);
restore.maxStack = Math.max(restore.maxStack, 5);
var enter = snapshot();
enter.add(new MethodInsnNode(Opcodes.INVOKESTATIC, GUARD, "allowTransfer", "(" + PLAYER + PATH + ")Z", false));
finish(enter, Opcodes.IFNE);
transfer.instructions.insert(enter);
transfer.maxStack = Math.max(transfer.maxStack, 3);
var writer = new ClassWriter(reader, 0);
retained.accept(writer);
Files.write(Path.of(args[1]), writer.toByteArray());
}
private static InsnList snapshot() {
var code = new InsnList();
code.add(new VarInsnNode(Opcodes.ALOAD, 1));
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(new VarInsnNode(Opcodes.ALOAD, 1));
code.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, OWNER, "snapshot", "(" + PLAYER + ")" + PATH, false));
return code;
}
private static void finish(InsnList code, int jump) {
var old = new LabelNode();
code.add(new JumpInsnNode(jump, old));
code.add(new InsnNode(Opcodes.RETURN));
code.add(old);
code.add(new FrameNode(Opcodes.F_SAME, 0, null, 0, null));
}
}

View file

@ -0,0 +1,46 @@
"""Graft the shared inventory guard onto the retained Lobby Builder JAR."""
import argparse
import os
from pathlib import Path
import subprocess
from tempfile import TemporaryDirectory
from plugin_wild_update import digest, read_archive, write_archive
PREFIX = "com/example/dunelobby/"
BUILDER = PREFIX + "BuilderTransfer.class"
GUARD = PREFIX + "BuilderSharedProfiles.class"
BASELINE = "18f8878b18f249ff97728542a63effedb1d19f473168b9ab7ec8ef8f11c25538"
def assemble(baseline, donor, donor_sha, output, classpath):
existing = baseline.read_bytes()
compiled = donor.read_bytes()
if digest(existing) != BASELINE or digest(compiled) != donor_sha:
raise ValueError("Unexpected Builder baseline or donor checksum")
archive = read_archive(existing)
payload = read_archive(compiled)
if GUARD in archive:
raise ValueError("Builder already contains the shared profile guard")
java_home = os.environ.get("JAVA_HOME")
executable = "java.exe" if os.name == "nt" else "java"
java = str(Path(java_home) / "bin" / executable) if java_home else executable
helper = Path(__file__).with_name("BuilderSharedProfilesOverlay.java")
with TemporaryDirectory() as temp:
old, new = (Path(temp) / name for name in ("retained.class", "guarded.class"))
old.write_bytes(archive[BUILDER])
subprocess.run([java, "--class-path", classpath, str(helper), str(old), str(new)], check=True)
archive[BUILDER] = new.read_bytes()
archive[GUARD] = payload[GUARD]
with output.open("xb") as candidate:
candidate.write(write_archive(archive))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("baseline", type=Path)
parser.add_argument("donor", type=Path)
parser.add_argument("donor_sha")
parser.add_argument("output", type=Path)
parser.add_argument("classpath", help="ASM core and tree JARs")
assemble(**vars(parser.parse_args()))