From cd4d04b7f8981c766b55fa834771c8ffc0018683 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:33:41 +0100 Subject: [PATCH 1/4] Provision accounts from authenticated first Lobby joins --- .forgejo/workflows/lobby-account.yml | 43 ++++++++++++++++++++++++++++ .forgejo/workflows/plugins.yml | 2 +- tools/install-plugin-fleet.py | 23 +++++++++++++-- tools/test_plugin_ci_policy.py | 4 +-- tools/test_plugin_fleet_install.py | 11 +++++++ 5 files changed, 78 insertions(+), 5 deletions(-) create mode 100644 .forgejo/workflows/lobby-account.yml diff --git a/.forgejo/workflows/lobby-account.yml b/.forgejo/workflows/lobby-account.yml new file mode 100644 index 00000000..61436ebb --- /dev/null +++ b/.forgejo/workflows/lobby-account.yml @@ -0,0 +1,43 @@ +name: Lobby Account Provisioning Build +on: + workflow_dispatch: + push: + branches: ['feat/lobby-first-join-account-*'] + +jobs: + lobby-account: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Build and verify the standalone Lobby module + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p DuneLobbyAccount test jar + python3 tools/test_plugin_fleet_install.py -v + mkdir lobby-account-artifacts + cp DuneLobbyAccount/build/libs/DuneLobbyAccount.jar lobby-account-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > lobby-account-artifacts/SOURCE_COMMIT + python3 tools/write-plugin-manifest.py lobby-account-artifacts "$GITHUB_SHA" + cp tools/{install-plugin-fleet,plugin_menu_pack,plugin_backend_abi,plugin_fleet_rollback,plugin_pack_properties,plugin_pillager_abi}.py lobby-account-artifacts/ + (cd lobby-account-artifacts && sha256sum -- *.jar *.json *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Lobby-Account + path: lobby-account-artifacts/ + if-no-files-found: error diff --git a/.forgejo/workflows/plugins.yml b/.forgejo/workflows/plugins.yml index bda888c0..a99015eb 100644 --- a/.forgejo/workflows/plugins.yml +++ b/.forgejo/workflows/plugins.yml @@ -28,7 +28,7 @@ jobs: shell: bash run: | set -euo pipefail - modules=(DuneEss DuneLobby DuneNPC DuneRealms-minecraft-only DuneRealmsGUI DuneTerrain JarvisConnector DuneMenus) + modules=(DuneEss DuneLobby DuneLobbyAccount DuneNPC DuneRealms-minecraft-only DuneRealmsGUI DuneTerrain JarvisConnector DuneMenus) mkdir -p plugin-artifacts for module in "${modules[@]}"; do gradle --no-daemon -p "$module" test jar diff --git a/tools/install-plugin-fleet.py b/tools/install-plugin-fleet.py index fdd60803..74896fe3 100644 --- a/tools/install-plugin-fleet.py +++ b/tools/install-plugin-fleet.py @@ -75,10 +75,11 @@ def verify_dunechest_fleet_target(sid, root, unit, incoming, installed): def plan(artifacts, inventory, expected_source): mode=inventory.get('mode') - if mode not in {'gui-preserve-backends','pillager-preserve-economy','arrakis-crysknife','navigator','planet-dunechest','fleet-dunechest','arrakis-raw-spice','arrakis-jerboa','compact-menus','lobby-food'}: + if mode not in {'gui-preserve-backends','pillager-preserve-economy','arrakis-crysknife','navigator','planet-dunechest','fleet-dunechest','arrakis-raw-spice','arrakis-jerboa','compact-menus','lobby-food','lobby-account'}: raise ValueError('An explicit supported rollout mode is required') compact_menus=mode=='compact-menus' lobby_food=mode=='lobby-food' + lobby_account=mode=='lobby-account' jerboa=mode=='arrakis-jerboa' raw_spice=mode=='arrakis-raw-spice' pillager=mode=='pillager-preserve-economy' @@ -97,6 +98,10 @@ def plan(artifacts, inventory, expected_source): allowed_names={'DuneMenus'} if inventory.get('menuPack') is not None: raise ValueError('Compact menus require retaining the current resource pack') + if lobby_account: + allowed_names={'DuneLobbyAccount'} + if inventory.get('menuPack') is not None or inventory.get('privatePrerequisites'): + raise ValueError('Lobby account rollout must retain the current resource pack and runtimes') if jerboa: allowed_names={'DuneTerrain'} if raw_spice or lobby_food: @@ -169,7 +174,7 @@ def plan(artifacts, inventory, expected_source): uses_menu=not compact_menus and ('dunemenus' in wanted or bool(menu and menu.get('unified') and not (crysknife or dunechest or jerboa))) if menu and menu.get('unified') and not (crysknife or dunechest or jerboa) and 'dunerealmsgui' not in wanted: raise ValueError('Unified pack rollout must select its matching DunerealmsGUI adapter') - if not (pillager or crysknife or navigator or dunechest or raw_spice or jerboa or lobby_food) and wanted - {'dunemenus','dunerealmsgui','dunenpc','dunelobby','mcgui'}: + if not (pillager or crysknife or navigator or dunechest or raw_spice or jerboa or lobby_food or lobby_account) and wanted - {'dunemenus','dunerealmsgui','dunenpc','dunelobby','mcgui'}: raise ValueError('GUI rollout must retain working Ess/JARVIS/Core/Terrain binaries') if compact_menus: expected_root = Path('/opt/dunerealms/lobby') if sid == 'lobby' else Path('/opt/dunerealms/servers') / sid @@ -185,6 +190,9 @@ def plan(artifacts, inventory, expected_source): if lobby_food and (sid != 'lobby' or root != Path('/opt/dunerealms/lobby') or unit != 'dune-lobby.service' or wanted != {'jarvistranslator'} or selected_prerequisites): raise ValueError('Lobby food rollout may only replace JARVIS on Lobby') + if lobby_account and (sid != 'lobby' or root != Path('/opt/dunerealms/lobby') or unit != 'dune-lobby.service' + or wanted != {'dunelobbyaccount'} or selected_prerequisites): + raise ValueError('Account provisioning may only install the standalone plugin on Lobby') if crysknife and ( sid != 'arrakis' or unit != 'dune-arrakis.service' or root != ARRAKIS_ROOT @@ -379,6 +387,17 @@ def plan(artifacts, inventory, expected_source): replaced = {entry['filename'] for entry in previous} retained = [{'filename': path.name, 'sha256': digest(path), 'metadata': metadata(path)} for path in sorted(plugins.glob('*.jar')) if path.name not in replaced] + if lobby_account: + credential = Path('/etc/dunerealms/lobby-account.token') + if (credential.is_symlink() or not credential.is_file() or + metadata(credential)['mode'] != 0o600 or credential.stat().st_uid != plugins.stat().st_uid): + raise ValueError('Expected the private service-owned Lobby account token') + installed = existing_paths.get('dunelobbyaccount') + if installed is not None and digest(installed) != chosen[0]['sha256']: + raise ValueError('Unexpected prior Lobby account plugin') + replaced = {entry['filename'] for entry in previous} + retained = [{'filename': path.name, 'sha256': digest(path), 'metadata': metadata(path)} + for path in sorted(plugins.glob('*.jar')) if path.name not in replaced] configurations = [] if uses_menu or crysknife or dunechest or jerboa: if menu is None: diff --git a/tools/test_plugin_ci_policy.py b/tools/test_plugin_ci_policy.py index 975f9f6b..0ddd1d77 100644 --- a/tools/test_plugin_ci_policy.py +++ b/tools/test_plugin_ci_policy.py @@ -29,10 +29,10 @@ def validate(text): raise ValueError('Missing exact-source build: ' + command) modules = re.search(r'^\s*modules=\(([^)]+)\)', text, re.M) if not modules or set(modules[1].split()) != { - 'DuneEss', 'DuneLobby', 'DuneNPC', 'DuneRealms-minecraft-only', + 'DuneEss', 'DuneLobby', 'DuneLobbyAccount', 'DuneNPC', 'DuneRealms-minecraft-only', 'DuneRealmsGUI', 'DuneTerrain', 'JarvisConnector', 'DuneMenus', }: - raise ValueError('All eight source modules must retain tests and compilation') + raise ValueError('All nine source modules must retain tests and compilation') for script in CHECKS: if 'python3 tools/' + script + ' -v' not in text: raise ValueError('Missing release regression check: ' + script) diff --git a/tools/test_plugin_fleet_install.py b/tools/test_plugin_fleet_install.py index 7ccd48c5..d9a0e368 100644 --- a/tools/test_plugin_fleet_install.py +++ b/tools/test_plugin_fleet_install.py @@ -89,6 +89,17 @@ class FleetInstallerTests(unittest.TestCase): with self.assertRaises(ValueError): self.deployment() + def test_account_artifact_cannot_install_on_a_planet(self): + candidate = self.artifacts / 'DuneLobbyAccount.jar' + jar(candidate, 'DuneLobbyAccount') + entry = dict(installer.identity(candidate), filename=candidate.name, sha256=installer.digest(candidate)) + (self.artifacts / 'release-manifest.json').write_text(json.dumps({'sourceCommit': SOURCE, 'plugins': [entry]})) + server = self.inventory['servers'][0] + server.update(id='arrakis', serviceUnit='dune-arrakis.service', artifacts=[candidate.name]) + self.inventory['mode'] = 'lobby-account' + with self.assertRaisesRegex(ValueError, 'standalone plugin on Lobby'): + self.deployment() + def test_replaces_by_identity_and_preserves_backend_and_third_party(self): preserved = {n: (self.plugins / n).read_bytes() for n in ('DuneNPC.jar', 'MCGUI.jar')} service = Service() -- 2.53.0 From b2036dfdc3870f8745e4b7ed6fc4058c5d577071 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:33:51 +0100 Subject: [PATCH 2/4] Include the standalone Lobby account module --- DuneLobbyAccount/build.gradle.kts | 20 ++ .../lobbyaccount/AccountJournal.java | 86 ++++++++ .../lobbyaccount/DuneLobbyAccount.java | 196 ++++++++++++++++++ .../lobbyaccount/LobbyAccountApi.java | 107 ++++++++++ .../src/main/resources/plugin.yml | 5 + .../LobbyAccountContractTest.java | 77 +++++++ 6 files changed, 491 insertions(+) create mode 100644 DuneLobbyAccount/build.gradle.kts create mode 100644 DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/AccountJournal.java create mode 100644 DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/DuneLobbyAccount.java create mode 100644 DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/LobbyAccountApi.java create mode 100644 DuneLobbyAccount/src/main/resources/plugin.yml create mode 100644 DuneLobbyAccount/src/test/java/com/dunerealms/lobbyaccount/LobbyAccountContractTest.java diff --git a/DuneLobbyAccount/build.gradle.kts b/DuneLobbyAccount/build.gradle.kts new file mode 100644 index 00000000..c4267ebb --- /dev/null +++ b/DuneLobbyAccount/build.gradle.kts @@ -0,0 +1,20 @@ +plugins { java } +group = "com.dunerealms" +version = "1.0.0" + +repositories { + mavenCentral() + maven("https://repo.papermc.io/repository/maven-public/") +} + +dependencies { + compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") + testImplementation("com.google.code.gson:gson:2.11.0") + testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") +} + +java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) } +tasks.test { useJUnitPlatform() } +tasks.jar { archiveFileName.set("DuneLobbyAccount.jar") } +tasks.withType { options.encoding = "UTF-8" } diff --git a/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/AccountJournal.java b/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/AccountJournal.java new file mode 100644 index 00000000..6b112aaf --- /dev/null +++ b/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/AccountJournal.java @@ -0,0 +1,86 @@ +package com.dunerealms.lobbyaccount; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.UUID; + +final class AccountJournal { + enum Phase { PENDING, ACK, DONE, HELD } + + record Entry(UUID player, UUID request, String name, Phase phase) { + Entry advance(Phase next) { + return new Entry(player, request, name, next); + } + } + + private final Path folder; + private final boolean posix; + + AccountJournal(Path folder) throws IOException { + this.folder = folder.toAbsolutePath().normalize(); + posix = folder.getFileSystem().supportedFileAttributeViews().contains("posix"); + Files.createDirectories(this.folder, permissions("rwx------")); + if (!this.folder.toRealPath().equals(this.folder)) throw new IOException("Invalid provisioning journal directory"); + if (posix && !Files.getPosixFilePermissions(this.folder).equals(PosixFilePermissions.fromString("rwx------"))) { + throw new IOException("Provisioning journal directory must be private"); + } + } + + Entry read(UUID player) throws IOException { + Path path = path(player); + if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) return null; + if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS) || Files.size(path) > 256) + throw new IOException("Invalid provisioning receipt"); + try { + var rows = Files.readAllLines(path, StandardCharsets.UTF_8); + if (rows.size() != 4 || !player.equals(UUID.fromString(rows.get(0))) || !validName(rows.get(2))) + throw new IllegalArgumentException(); + return new Entry(player, UUID.fromString(rows.get(1)), rows.get(2), Phase.valueOf(rows.get(3))); + } catch (IllegalArgumentException invalid) { + throw new IOException("Invalid provisioning receipt"); + } + } + + void write(Entry entry) throws IOException { + if (!validName(entry.name())) throw new IOException("Invalid verified player name"); + Path tmp = Files.createTempFile(folder, ".receipt-", ".tmp", permissions("rw-------")); + try { + String text = entry.player() + "\n" + entry.request() + "\n" + entry.name() + "\n" + entry.phase() + "\n"; + try (FileChannel output = FileChannel.open(tmp, StandardOpenOption.WRITE)) { + ByteBuffer buffer = StandardCharsets.UTF_8.encode(text); + while (buffer.hasRemaining()) output.write(buffer); + output.force(true); + } + Files.move(tmp, path(entry.player()), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + if (posix) { + try (FileChannel directory = FileChannel.open(folder, StandardOpenOption.READ)) { + directory.force(true); + } + } + } finally { + Files.deleteIfExists(tmp); + } + } + + static boolean validName(String name) { + return name != null && name.matches("[A-Za-z0-9_.-]{1,32}"); + } + + private Path path(UUID player) { + return folder.resolve(player + ".receipt"); + } + + private FileAttribute[] permissions(String mode) { + return posix ? new FileAttribute[]{PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(mode))} + : new FileAttribute[0]; + } +} diff --git a/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/DuneLobbyAccount.java b/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/DuneLobbyAccount.java new file mode 100644 index 00000000..8e43f79c --- /dev/null +++ b/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/DuneLobbyAccount.java @@ -0,0 +1,196 @@ +package com.dunerealms.lobbyaccount; + +import static com.dunerealms.lobbyaccount.AccountJournal.Phase.*; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import net.kyori.adventure.text.Component; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.plugin.java.JavaPlugin; + +public final class DuneLobbyAccount extends JavaPlugin implements Listener { + private static final Path LOBBY = Path.of("/opt/dunerealms/lobby"); + private static final Path TOKEN = Path.of("/etc/dunerealms/lobby-account.token"); + private static final Component HELP = Component.text("Visit cp.dunerealms.com to link or recover your account."); + + private final Set active = new HashSet<>(); + private final Set finished = new HashSet<>(); + private final Map firstAdmissions = new HashMap<>(); + private volatile boolean running; + private ThreadPoolExecutor executor; + private AccountJournal journal; + private LobbyAccountApi api; + + @Override public void onEnable() { + try { + Path root = getDataFolder().toPath().toAbsolutePath().normalize().getParent().getParent(); + if (!LOBBY.equals(root) || !LOBBY.equals(root.toRealPath())) throw new IOException("Invalid Lobby root"); + api = new LobbyAccountApi(TOKEN); + api.verifyCredential(); + journal = new AccountJournal(getDataFolder().toPath().resolve("receipts")); + } catch (IOException | RuntimeException unavailable) { + getLogger().warning("Lobby account provisioning is disabled. Check the Lobby installation and credential."); + getServer().getPluginManager().disablePlugin(this); + return; + } + executor = new ThreadPoolExecutor(2, 2, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(96), task -> { + Thread worker = new Thread(task, "DuneLobbyAccount"); + worker.setDaemon(true); + return worker; + }); + running = true; + getServer().getPluginManager().registerEvents(this, this); + getServer().getScheduler().runTaskTimer(this, () -> Bukkit.getOnlinePlayers().forEach(this::attempt), 600, 600); + } + + @Override public void onDisable() { + running = false; + if (executor != null) executor.shutdownNow(); + if (api != null) api.close(); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void joined(PlayerJoinEvent event) { + Player player = event.getPlayer(); + if (!player.hasPlayedBefore() && AccountJournal.validName(player.getName())) { + firstAdmissions.putIfAbsent(player.getUniqueId(), player.getName()); + } + attempt(player); + } + + private void attempt(Player player) { + UUID uuid = player.getUniqueId(); + String liveName = player.getName(); + if (!running || !AccountJournal.validName(liveName) || finished.contains(uuid) || !active.add(uuid)) return; + String admittedName = firstAdmissions.get(uuid); + try { + executor.execute(() -> process(player, uuid, liveName, admittedName)); + } catch (RejectedExecutionException full) { + active.remove(uuid); + } + } + + private void process(Player player, UUID uuid, String liveName, String admittedName) { + boolean terminal = false; + boolean recorded = false; + try { + AccountJournal.Entry entry = journal.read(uuid); + if (entry == null) { + if (admittedName == null) { + terminal = true; + return; + } + entry = new AccountJournal.Entry(uuid, UUID.randomUUID(), admittedName, PENDING); + journal.write(entry); + } + recorded = true; + if (entry.phase() == DONE || entry.phase() == HELD) { + terminal = true; + return; + } + terminal = advance(player, liveName, entry); + } catch (InterruptedException stopped) { + Thread.currentThread().interrupt(); + } catch (IOException | TimeoutException | ExecutionException unavailable) { + // An uncertain response is retried using the same durable request on the next timer or join. + } finally { + boolean complete = terminal, hasReceipt = recorded; + onMain(() -> { + active.remove(uuid); + if (hasReceipt) firstAdmissions.remove(uuid); + if (complete) finished.add(uuid); + }); + } + } + + private boolean advance(Player player, String liveName, AccountJournal.Entry entry) + throws IOException, InterruptedException, TimeoutException, ExecutionException { + AccountJournal.Entry next = entry; + try { + if (next.phase() == PENDING) { + if (!next.name().equals(liveName)) return hold(player, liveName, next); + LobbyAccountApi.Reply reply = api.send(next, false); + boolean sent = deliver(player, liveName, next.player(), reply); + if (!sent) return false; + if (!reply.state().equals("created")) { + journal.write(next.advance(DONE)); + return true; + } + next = next.advance(ACK); + journal.write(next); + } + api.send(next, true); + journal.write(next.advance(DONE)); + return true; + } catch (LobbyAccountApi.Rejected rejected) { + return hold(player, liveName, next); + } + } + + private boolean hold(Player player, String name, AccountJournal.Entry entry) throws IOException { + journal.write(entry.advance(HELD)); + onMain(() -> { if (sameOnlineSession(player, entry.player(), name)) player.sendMessage(HELP); }); + return true; + } + + private boolean deliver(Player player, String name, UUID uuid, LobbyAccountApi.Reply reply) + throws InterruptedException, ExecutionException, TimeoutException { + var delivered = new CompletableFuture(); + onMain(() -> { + if (delivered.isDone()) return; + try { + if (!sameOnlineSession(player, uuid, name)) { + delivered.complete(false); + return; + } + switch (reply.state()) { + case "created" -> player.sendMessage(Component.text("DuneRealms account at cp.dunerealms.com\n" + + "Username: " + reply.username() + "\nTemporary password: " + reply.password() + + "\nChange your password after signing in.")); + case "existing" -> player.sendMessage(Component.text("Your DuneRealms account is already linked.")); + case "manual_link_required", "recovery_required" -> player.sendMessage(HELP); + default -> { } + } + delivered.complete(true); + } catch (RuntimeException failed) { + delivered.complete(false); + } + }); + try { + return delivered.get(10, TimeUnit.SECONDS); + } finally { + delivered.cancel(false); + } + } + + private boolean sameOnlineSession(Player player, UUID uuid, String name) { + return running && player.isOnline() && Bukkit.getPlayer(uuid) == player + && uuid.equals(player.getUniqueId()) && name.equals(player.getName()); + } + + private void onMain(Runnable action) { + if (!running) return; + try { + getServer().getScheduler().runTask(this, action); + } catch (org.bukkit.plugin.IllegalPluginAccessException disabled) { + // Receipts remain durable for the next plugin start. + } + } +} diff --git a/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/LobbyAccountApi.java b/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/LobbyAccountApi.java new file mode 100644 index 00000000..e54fb2e8 --- /dev/null +++ b/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/LobbyAccountApi.java @@ -0,0 +1,107 @@ +package com.dunerealms.lobbyaccount; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.time.Duration; +import java.util.Set; + +final class LobbyAccountApi implements AutoCloseable { + private static final URI ENDPOINT = URI.create("https://cp.dunerealms.com/internal/game/lobby-account"); + private static final int MAX_RESPONSE = 4096; + private static final Set PROVISION_STATES = Set.of( + "created", "existing", "delivered", "manual_link_required", "recovery_required"); + + record Reply(String state, String username, String password) { + @Override public String toString() { return "Provisioning reply: " + state; } + } + + static final class Rejected extends IOException { + Rejected() { super("Provisioning request rejected"); } + } + + private final Path tokenPath; + private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)) + .followRedirects(HttpClient.Redirect.NEVER).build(); + + LobbyAccountApi(Path tokenPath) { this.tokenPath = tokenPath; } + + void verifyCredential() throws IOException { credential(); } + + Reply send(AccountJournal.Entry entry, boolean ack) throws IOException, InterruptedException { + JsonObject payload = request(entry, ack); + var request = HttpRequest.newBuilder(ENDPOINT).timeout(Duration.ofSeconds(12)) + .header("Authorization", "Bearer " + credential()) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(payload.toString())).build(); + var response = http.send(request, HttpResponse.BodyHandlers.ofInputStream()); + try (var stream = response.body()) { + if (response.statusCode() == 403 || response.statusCode() == 409) throw new Rejected(); + if (response.statusCode() != 200 && response.statusCode() != 201) throw unavailable(); + byte[] body = stream.readNBytes(MAX_RESPONSE + 1); + if (body.length > MAX_RESPONSE) throw unavailable(); + return parse(new String(body, StandardCharsets.UTF_8), entry, ack); + } + } + + static JsonObject request(AccountJournal.Entry entry, boolean ack) { + var payload = new JsonObject(); + payload.addProperty("schema", 1); + payload.addProperty("action", ack ? "ack" : "provision"); + payload.addProperty("requestId", entry.request().toString()); + payload.addProperty("uuid", entry.player().toString()); + if (!ack) payload.addProperty("name", entry.name()); + return payload; + } + + static Reply parse(String body, AccountJournal.Entry entry, boolean ack) throws IOException { + try { + JsonObject data = JsonParser.parseString(body).getAsJsonObject(); + if (!data.getAsJsonPrimitive("ok").isBoolean() || !data.get("ok").getAsBoolean() + || !data.getAsJsonPrimitive("schema").isNumber() || !data.get("schema").getAsString().equals("1") + || !(ack ? "ack" : "provision").equals(string(data, "action")) + || !entry.request().toString().equals(string(data, "requestId")) + || !entry.player().toString().equals(string(data, "uuid"))) throw unavailable(); + String state = string(data, "state"); + if (ack ? !"delivered".equals(state) : state == null || !PROVISION_STATES.contains(state)) throw unavailable(); + String username = string(data, "username"); + String password = string(data, "password"); + if (username != null && !username.matches("[a-z0-9_]{1,64}")) throw unavailable(); + if ("created".equals(state)) { + if (username == null || password == null || !password.matches("[!-~]{20,128}")) throw unavailable(); + } else if (data.has("password")) { + throw unavailable(); + } + return new Reply(state, username, password); + } catch (RuntimeException invalid) { + throw unavailable(); + } + } + + private static String string(JsonObject data, String key) { + var value = data.get(key); + return value != null && value.isJsonPrimitive() && value.getAsJsonPrimitive().isString() ? value.getAsString() : null; + } + + private String credential() throws IOException { + if (!Files.isRegularFile(tokenPath, LinkOption.NOFOLLOW_LINKS) || Files.size(tokenPath) > 1024 + || !Files.getPosixFilePermissions(tokenPath).equals(PosixFilePermissions.fromString("rw-------"))) + throw unavailable(); + String token = Files.readString(tokenPath, StandardCharsets.US_ASCII).strip(); + if (!token.matches("[A-Za-z0-9._~+/-]{32,512}={0,2}")) throw unavailable(); + return token; + } + + private static IOException unavailable() { return new IOException("Provisioning service unavailable"); } + + @Override public void close() { http.shutdownNow(); } +} diff --git a/DuneLobbyAccount/src/main/resources/plugin.yml b/DuneLobbyAccount/src/main/resources/plugin.yml new file mode 100644 index 00000000..5b2667b4 --- /dev/null +++ b/DuneLobbyAccount/src/main/resources/plugin.yml @@ -0,0 +1,5 @@ +name: DuneLobbyAccount +version: 1.0.0 +main: com.dunerealms.lobbyaccount.DuneLobbyAccount +api-version: '1.21.8' +description: Provisions ordinary DuneRealms accounts from authenticated first Lobby joins diff --git a/DuneLobbyAccount/src/test/java/com/dunerealms/lobbyaccount/LobbyAccountContractTest.java b/DuneLobbyAccount/src/test/java/com/dunerealms/lobbyaccount/LobbyAccountContractTest.java new file mode 100644 index 00000000..5608e0ad --- /dev/null +++ b/DuneLobbyAccount/src/test/java/com/dunerealms/lobbyaccount/LobbyAccountContractTest.java @@ -0,0 +1,77 @@ +package com.dunerealms.lobbyaccount; + +import static com.dunerealms.lobbyaccount.AccountJournal.Phase.*; +import static org.junit.jupiter.api.Assertions.*; + +import com.google.gson.JsonNull; +import com.google.gson.JsonObject; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Set; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class LobbyAccountContractTest { + private final AccountJournal.Entry request = new AccountJournal.Entry(UUID.randomUUID(), UUID.randomUUID(), ".Bedrock-Name", PENDING); + private static final String PASSWORD = "TestSecretNeverInReceipt_123"; + + @Test void journalSurvivesRestartAndNeverStoresPassword(@TempDir Path temp) throws Exception { + Path folder = temp.resolve("receipts"); + var first = new AccountJournal(folder); + assertNull(first.read(request.player())); + first.write(request); + var restarted = new AccountJournal(folder); + assertEquals(request, restarted.read(request.player())); + restarted.write(request.advance(ACK)); + assertEquals(request.advance(ACK), first.read(request.player())); + String text = Files.readString(folder.resolve(request.player() + ".receipt")); + assertFalse(text.contains(PASSWORD)); + assertEquals(4, text.lines().count()); + assertThrows(IOException.class, () -> restarted.write(new AccountJournal.Entry(request.player(), request.request(), "x\ny", PENDING))); + } + + @Test void requestAndAcknowledgementHaveExactWireFields() { + JsonObject provision = LobbyAccountApi.request(request, false); + assertEquals(Set.of("action", "schema", "requestId", "uuid", "name"), provision.keySet()); + assertEquals(request.name(), provision.get("name").getAsString()); + JsonObject ack = LobbyAccountApi.request(request.advance(ACK), true); + assertEquals(Set.of("action", "schema", "requestId", "uuid"), ack.keySet()); + assertEquals(provision.get("requestId"), ack.get("requestId")); + assertEquals(provision.get("uuid"), ack.get("uuid")); + } + + @Test void onlyExactBoundCreatedResponseMayExposePassword() throws Exception { + JsonObject reply = response(false, "created"); + reply.addProperty("username", "bedrock_name"); + reply.addProperty("password", PASSWORD); + assertEquals(PASSWORD, LobbyAccountApi.parse(reply.toString(), request, false).password()); + assertFalse(LobbyAccountApi.parse(reply.toString(), request, false).toString().contains(PASSWORD)); + reply.addProperty("requestId", UUID.randomUUID().toString()); + assertThrows(IOException.class, () -> LobbyAccountApi.parse(reply.toString(), request, false)); + reply.addProperty("requestId", request.request().toString()); + reply.addProperty("uuid", UUID.randomUUID().toString()); + assertThrows(IOException.class, () -> LobbyAccountApi.parse(reply.toString(), request, false)); + } + + @Test void existingRecoveryAndAcknowledgementDoNotAcceptSecrets() throws Exception { + for (String state : Set.of("existing", "manual_link_required", "recovery_required", "delivered")) { + JsonObject reply = response(false, state); + reply.add("username", JsonNull.INSTANCE); + assertNull(LobbyAccountApi.parse(reply.toString(), request, false).password()); + reply.addProperty("password", PASSWORD); + assertThrows(IOException.class, () -> LobbyAccountApi.parse(reply.toString(), request, false)); + } + assertEquals("delivered", LobbyAccountApi.parse(response(true, "delivered").toString(), request, true).state()); + assertThrows(IOException.class, () -> LobbyAccountApi.parse(response(true, "created").toString(), request, true)); + } + + private JsonObject response(boolean ack, String state) { + JsonObject reply = LobbyAccountApi.request(request, ack); + reply.remove("name"); + reply.addProperty("ok", true); + reply.addProperty("state", state); + return reply; + } +} -- 2.53.0 From 840af6cb002ae3f2ad490f9c22c9f14fe97aa7dd Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:37:06 +0100 Subject: [PATCH 3/4] Require authenticated Velocity forwarding before provisioning --- .../lobbyaccount/DuneLobbyAccount.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/DuneLobbyAccount.java b/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/DuneLobbyAccount.java index 8e43f79c..3fd90985 100644 --- a/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/DuneLobbyAccount.java +++ b/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/DuneLobbyAccount.java @@ -3,6 +3,7 @@ package com.dunerealms.lobbyaccount; import static com.dunerealms.lobbyaccount.AccountJournal.Phase.*; import java.io.IOException; +import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; import java.util.HashSet; @@ -18,6 +19,8 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -42,6 +45,7 @@ public final class DuneLobbyAccount extends JavaPlugin implements Listener { try { Path root = getDataFolder().toPath().toAbsolutePath().normalize().getParent().getParent(); if (!LOBBY.equals(root) || !LOBBY.equals(root.toRealPath())) throw new IOException("Invalid Lobby root"); + verifyForwarding(root); api = new LobbyAccountApi(TOKEN); api.verifyCredential(); journal = new AccountJournal(getDataFolder().toPath().resolve("receipts")); @@ -60,6 +64,28 @@ public final class DuneLobbyAccount extends JavaPlugin implements Listener { getServer().getScheduler().runTaskTimer(this, () -> Bukkit.getOnlinePlayers().forEach(this::attempt), 600, 600); } + private void verifyForwarding(Path root) throws IOException { + Path config = root.resolve("config/paper-global.yml"); + Path spigot = root.resolve("spigot.yml"); + if (!"127.0.0.1".equals(getServer().getIp()) || !Files.isRegularFile(config) || !Files.isRegularFile(spigot)) + throw new IOException("Expected the local authenticated Lobby backend"); + var velocity = readConfig(config).getConfigurationSection("proxies.velocity"); + if (velocity == null || !velocity.getBoolean("enabled") || !velocity.getBoolean("online-mode") + || velocity.getString("secret", "").isBlank() + || readConfig(spigot).getBoolean("settings.bungeecord", true)) + throw new IOException("Expected authenticated Velocity forwarding"); + } + + private static YamlConfiguration readConfig(Path path) throws IOException { + var config = new YamlConfiguration(); + try { + config.load(path.toFile()); + } catch (InvalidConfigurationException invalid) { + throw new IOException("Invalid Lobby forwarding configuration"); + } + return config; + } + @Override public void onDisable() { running = false; if (executor != null) executor.shutdownNow(); -- 2.53.0 From 67d36049c1ba494a2b3cab87e40672919f607491 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:41:10 +0100 Subject: [PATCH 4/4] Accept the historical account manual-link response --- .../main/java/com/dunerealms/lobbyaccount/LobbyAccountApi.java | 1 + .../com/dunerealms/lobbyaccount/LobbyAccountContractTest.java | 3 +++ 2 files changed, 4 insertions(+) diff --git a/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/LobbyAccountApi.java b/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/LobbyAccountApi.java index e54fb2e8..feaf5a76 100644 --- a/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/LobbyAccountApi.java +++ b/DuneLobbyAccount/src/main/java/com/dunerealms/lobbyaccount/LobbyAccountApi.java @@ -75,6 +75,7 @@ final class LobbyAccountApi implements AutoCloseable { if (ack ? !"delivered".equals(state) : state == null || !PROVISION_STATES.contains(state)) throw unavailable(); String username = string(data, "username"); String password = string(data, "password"); + if ("manual_link_required".equals(state) && "".equals(username)) username = null; if (username != null && !username.matches("[a-z0-9_]{1,64}")) throw unavailable(); if ("created".equals(state)) { if (username == null || password == null || !password.matches("[!-~]{20,128}")) throw unavailable(); diff --git a/DuneLobbyAccount/src/test/java/com/dunerealms/lobbyaccount/LobbyAccountContractTest.java b/DuneLobbyAccount/src/test/java/com/dunerealms/lobbyaccount/LobbyAccountContractTest.java index 5608e0ad..f1082d91 100644 --- a/DuneLobbyAccount/src/test/java/com/dunerealms/lobbyaccount/LobbyAccountContractTest.java +++ b/DuneLobbyAccount/src/test/java/com/dunerealms/lobbyaccount/LobbyAccountContractTest.java @@ -65,6 +65,9 @@ class LobbyAccountContractTest { } assertEquals("delivered", LobbyAccountApi.parse(response(true, "delivered").toString(), request, true).state()); assertThrows(IOException.class, () -> LobbyAccountApi.parse(response(true, "created").toString(), request, true)); + JsonObject manual = response(false, "manual_link_required"); + manual.addProperty("username", ""); + assertNull(LobbyAccountApi.parse(manual.toString(), request, false).username()); } private JsonObject response(boolean ack, String state) { -- 2.53.0