Include the standalone Lobby account module
All checks were successful
Lobby Account Provisioning Build / lobby-account (push) Successful in 38s
DuneRealms Plugin CI / plugins (push) Successful in 2m51s

This commit is contained in:
unimatrixgit 2026-12-02 11:33:51 +01:00
commit b2036dfdc3
6 changed files with 491 additions and 0 deletions

View file

@ -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<JavaCompile> { options.encoding = "UTF-8" }

View file

@ -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];
}
}

View file

@ -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<UUID> active = new HashSet<>();
private final Set<UUID> finished = new HashSet<>();
private final Map<UUID, String> 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<Boolean>();
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.
}
}
}

View file

@ -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<String> 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(); }
}

View file

@ -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

View file

@ -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;
}
}