223 lines
9.4 KiB
Java
223 lines
9.4 KiB
Java
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;
|
|
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.configuration.InvalidConfigurationException;
|
|
import org.bukkit.configuration.file.YamlConfiguration;
|
|
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");
|
|
verifyForwarding(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);
|
|
}
|
|
|
|
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();
|
|
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();
|
|
String admittedName = firstAdmissions.get(uuid);
|
|
if (admittedName != null) {
|
|
try {
|
|
journal.admit(uuid, admittedName);
|
|
firstAdmissions.remove(uuid);
|
|
} catch (IOException unavailable) {
|
|
return; // Retry the local receipt before admitting any network work.
|
|
}
|
|
}
|
|
if (!running || !AccountJournal.validName(liveName) || finished.contains(uuid) || !active.add(uuid)) return;
|
|
try {
|
|
executor.execute(() -> process(player, uuid, liveName));
|
|
} catch (RejectedExecutionException full) {
|
|
active.remove(uuid);
|
|
}
|
|
}
|
|
|
|
private void process(Player player, UUID uuid, String liveName) {
|
|
boolean terminal = false;
|
|
try {
|
|
AccountJournal.Entry entry = journal.read(uuid);
|
|
if (entry == null) {
|
|
terminal = true;
|
|
return;
|
|
}
|
|
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;
|
|
onMain(() -> {
|
|
active.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.
|
|
}
|
|
}
|
|
}
|

Staff