From 186022581a0edf4e08bde847ae62206c6cea25af Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:30:22 +0100 Subject: [PATCH 1/4] Integrate DuneChat with verified private channel membership --- .forgejo/workflows/dunechat.yml | 41 ++++ DuneChat/README.md | 36 ++++ DuneChat/build.gradle.kts | 21 ++ DuneChat/settings.gradle.kts | 1 + .../java/com/example/dunechat/ChatLogic.java | 146 +++++++++++++ .../com/example/dunechat/DiscordPrivacy.java | 24 +++ .../java/com/example/dunechat/DuneChat.java | 196 ++++++++++++++++++ DuneChat/src/main/resources/config.yml | 8 + DuneChat/src/main/resources/plugin.yml | 31 +++ .../com/example/dunechat/ChatLogicTest.java | 92 ++++++++ .../main/java/com/dunerealms/gui/DuneGUI.java | 10 +- 11 files changed, 604 insertions(+), 2 deletions(-) create mode 100644 .forgejo/workflows/dunechat.yml create mode 100644 DuneChat/README.md create mode 100644 DuneChat/build.gradle.kts create mode 100644 DuneChat/settings.gradle.kts create mode 100644 DuneChat/src/main/java/com/example/dunechat/ChatLogic.java create mode 100644 DuneChat/src/main/java/com/example/dunechat/DiscordPrivacy.java create mode 100644 DuneChat/src/main/java/com/example/dunechat/DuneChat.java create mode 100644 DuneChat/src/main/resources/config.yml create mode 100644 DuneChat/src/main/resources/plugin.yml create mode 100644 DuneChat/src/test/java/com/example/dunechat/ChatLogicTest.java diff --git a/.forgejo/workflows/dunechat.yml b/.forgejo/workflows/dunechat.yml new file mode 100644 index 00000000..f186b53c --- /dev/null +++ b/.forgejo/workflows/dunechat.yml @@ -0,0 +1,41 @@ +name: DuneChat Build +on: + workflow_dispatch: + push: + branches: ['feat/dunechat-*'] + +jobs: + dunechat: + 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 test DuneChat and its GUI identity hook + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p DuneChat test jar + gradle --no-daemon -p DuneRealmsGUI test jar + mkdir dunechat-artifacts + cp DuneChat/build/libs/DuneChat.jar DuneRealmsGUI/build/libs/DunerealmsGUI.jar dunechat-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > dunechat-artifacts/SOURCE_COMMIT + (cd dunechat-artifacts && sha256sum -- *.jar SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-DuneChat + path: dunechat-artifacts/ + if-no-files-found: error diff --git a/DuneChat/README.md b/DuneChat/README.md new file mode 100644 index 00000000..1be2ccb4 --- /dev/null +++ b/DuneChat/README.md @@ -0,0 +1,36 @@ +# DuneChat + +Chat prefixes and private channels. Built on canonical main `5d727d7`. Not pushed. Not tested in game. + +## What players see +Public chat: `[STAFF]/[VIP] [Race] [CLAN TAG] [Company] Name: message`. Order is `prefix-order` in config.yml. Race colour follows the house colour used by the nameplates. + +| Command | Does | +|---|---| +| `/cc ` (`/clanchat`) | one message to your clan. `/cc` alone toggles clan chat mode | +| `/coc ` (`/companychat`) | same for your company | +| `/sc ` (`/staffchat`) | staff only, permission `dunechat.staff` | +| `/g` (`/gc`) | back to public chat | +| `/chatspy` | staff with `dunechat.spy` also see clan and company chat | + +You can be in one clan and one company at the same time; each has its own private channel. Private chat is logged to the console (`log-private-chat`). + +## Where the data comes from +The same central briefing the nameplates use (`briefing.identity`: staff, vip, clans, companies), pushed in by a 5-line hook in DuneRealmsGUI (`DuneGUI.pushChatIdentity`, reflection, no hard dependency). Group membership keys on the central id when the briefing carries one, otherwise on the name, so please confirm the briefing includes ids. + +## Safety +- Names and tags are stripped of `& § % < >` and control characters before they reach a prefix; the message itself is never colour-parsed. +- Never un-cancels chat: a mute or filter from another plugin still wins. +- Leaving a clan or company while in its channel drops you back to public chat. + +## Install +1. Build: `gradle -p DuneChat build` -> `build/libs/DuneChat.jar`. +2. Apply the DuneRealmsGUI change (DuneGUI.java, plugin.yml softdepend), rebuild DuneRealmsGUI. +3. Grant `dunechat.staff` / `dunechat.spy` through LuckPerms. + +## Verified / not verified +CI: DuneChat compiles; 7 unit tests (parsing, prefix order, injection, group isolation, staff rules). The DuneRealmsGUI edit was not compiled in CI (that module needs another module missing from the cut-down CI tree; the errors seen were unrelated). Not tested: real chat events, other chat plugins (LuckPerms prefixes, DuneEss, DuneMenus chat prompts), Bedrock clients. + +## Limits +- Per server only: planets are separate servers, so clan/company/staff chat does not cross servers. A proxy relay would be a separate piece. +- No mute, filter, cooldown or channel history. diff --git a/DuneChat/build.gradle.kts b/DuneChat/build.gradle.kts new file mode 100644 index 00000000..bfedb910 --- /dev/null +++ b/DuneChat/build.gradle.kts @@ -0,0 +1,21 @@ +plugins { java } +group = "com.example" +version = "1.0.0" +repositories { + mavenCentral() + maven("https://repo.papermc.io/repository/maven-public/") + maven("https://nexus.scarsz.me/content/groups/public/") { + content { includeModule("com.discordsrv", "discordsrv") } + } +} +dependencies { + compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") + compileOnly("com.discordsrv:discordsrv:1.30.5") { isTransitive = false } + testImplementation("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") + testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") +} +java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) } +tasks.withType { options.encoding = "UTF-8" } +tasks.test { useJUnitPlatform() } +tasks.jar { archiveFileName.set("DuneChat.jar") } diff --git a/DuneChat/settings.gradle.kts b/DuneChat/settings.gradle.kts new file mode 100644 index 00000000..c94dd473 --- /dev/null +++ b/DuneChat/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "DuneChat" diff --git a/DuneChat/src/main/java/com/example/dunechat/ChatLogic.java b/DuneChat/src/main/java/com/example/dunechat/ChatLogic.java new file mode 100644 index 00000000..125cd848 --- /dev/null +++ b/DuneChat/src/main/java/com/example/dunechat/ChatLogic.java @@ -0,0 +1,146 @@ +package com.example.dunechat; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +/** Pure chat rules: identity parsing, prefixes and who may read a channel. No Bukkit types. */ +final class ChatLogic { + enum Channel { GLOBAL, CLAN, COMPANY, STAFF } + + /** Group keys are exact central membership UUIDs. Blank means no authorized membership. */ + record Identity(String faction, String race, boolean staff, boolean vip, + String clanKey, String clanTag, String companyKey, String companyName) { + static final Identity NONE = new Identity("", "", false, false, "", "", "", ""); + } + + static String clean(String value, int max) { + String safe = value == null ? "" : value.replaceAll("[&§%<>\\p{Cntrl}]", "").strip(); + return safe.substring(0, Math.min(Math.max(0, max), safe.length())); + } + + static String color(String faction) { + return switch (faction == null ? "" : faction) { + case "atreides" -> "&a"; case "harkonnen" -> "&c"; case "corrino" -> "&6"; + case "ordos" -> "&e"; case "fremen" -> "&b"; default -> "&f"; + }; + } + + private static boolean flag(JsonObject o, String k) { + return o != null && o.has(k) && o.get(k).isJsonPrimitive() && o.get(k).getAsJsonPrimitive().isBoolean() && o.get(k).getAsBoolean(); + } + + private static String text(JsonObject o, String k) { + JsonElement e = o == null ? null : o.get(k); + return e != null && e.isJsonPrimitive() ? e.getAsString() : ""; + } + + /** First object in an array field, or null. Only the first group counts: one clan and one company per player. */ + private static JsonObject first(JsonObject o, String k) { + JsonElement e = o == null ? null : o.get(k); + if (e == null || !e.isJsonArray()) return null; + JsonArray a = e.getAsJsonArray(); + return a.isEmpty() || !a.get(0).isJsonObject() ? null : a.get(0).getAsJsonObject(); + } + + /** Reads the same central briefing the nameplates use: briefing.identity.{staff,vip,clans[],companies[]}. */ + static Identity parse(JsonObject data, String faction, String race, int max) { + JsonObject id = null; + if (data != null && data.has("briefing") && data.get("briefing").isJsonObject()) { + JsonObject b = data.getAsJsonObject("briefing"); + if (b.has("identity") && b.get("identity").isJsonObject()) id = b.getAsJsonObject("identity"); + } + JsonObject clan = first(id, "clans"), company = first(id, "companies"); + String clanName = text(clan, "name"), clanTag = text(clan, "tag"); + String companyName = text(company, "name"); + return new Identity(faction == null ? "" : faction, clean(race, max), flag(id, "staff"), flag(id, "vip"), + "", clean(clanTag.isBlank() ? clanName : clanTag, max), "", clean(companyName, max)); + } + + record Membership(String clan, String company, long observedAt) { + static final Membership NONE = new Membership("", "", 0); + } + + static Membership memberships(JsonObject data, UUID actor, long now) { + if (data == null || !flag(data, "ok") || !"1".equals(text(data, "schema"))) return Membership.NONE; + long observedAt = data.get("observedAt").getAsLong(); + if (observedAt < now - 45_000 || observedAt > now + 5_000) return Membership.NONE; + return new Membership(memberId(data.getAsJsonArray("clans"), actor), + memberId(data.getAsJsonArray("companies"), actor), observedAt); + } + + private static String memberId(JsonArray rows, UUID actor) { + if (rows == null || rows.size() > 512) return ""; + String found = ""; + for (JsonElement element : rows) { + JsonObject row = element.getAsJsonObject(); + if (!"active".equals(text(row, "lifecycle"))) continue; + JsonArray members = row.getAsJsonArray("members"); + if (members == null || members.size() > 5_000) continue; + for (JsonElement member : members) { + if (!actor.toString().equals(text(member.getAsJsonObject(), "uuid"))) continue; + String id = canonicalId(text(row, "id")); + if (id.isEmpty() || !found.isEmpty() && !found.equals(id)) return ""; + found = id; + } + } + return found; + } + + private static String canonicalId(String id) { + try { + String canonical = UUID.fromString(id).toString(); + return canonical.equalsIgnoreCase(id) ? canonical : ""; + } catch (IllegalArgumentException invalid) { + return ""; + } + } + + static Identity withMembership(Identity identity, Membership membership, long now) { + if (membership.observedAt() < now - 45_000) return identity; + return new Identity(identity.faction(), identity.race(), identity.staff(), identity.vip(), + membership.clan(), identity.clanTag(), membership.company(), identity.companyName()); + } + + static boolean inGroup(Channel c, Identity i) { + return switch (c) { + case CLAN -> !i.clanKey().isBlank(); + case COMPANY -> !i.companyKey().isBlank(); + default -> true; + }; + } + + static boolean canSend(Channel c, Identity sender, boolean staffPerm) { + return switch (c) { case STAFF -> staffPerm; case CLAN, COMPANY -> inGroup(c, sender); case GLOBAL -> true; }; + } + + /** Whether {@code viewer} sees a message sent in {@code c} by {@code sender}. */ + static boolean receives(Channel c, Identity sender, Identity viewer, boolean viewerStaff, boolean viewerSpy) { + return switch (c) { + case GLOBAL -> true; + case STAFF -> viewerStaff; + case CLAN -> inGroup(c, viewer) && viewer.clanKey().equals(sender.clanKey()) || viewerSpy; + case COMPANY -> inGroup(c, viewer) && viewer.companyKey().equals(sender.companyKey()) || viewerSpy; + }; + } + + /** Public prefix as legacy ampersand text, in the configured order. Only cleaned values are inserted. */ + static String prefix(Identity i, List order) { + List parts = new ArrayList<>(); + String c = color(i.faction()); + for (String key : order) { + switch (key) { + case "staff" -> { if (i.staff()) parts.add("&c&l[STAFF]&r"); else if (i.vip()) parts.add("&6&l[VIP]&r"); } + case "race" -> { if (!i.race().isBlank()) parts.add(c + "[" + i.race() + "]&r"); } + case "clan" -> { if (!i.clanTag().isBlank()) parts.add("&6[" + i.clanTag() + "]&r"); } + case "company" -> { if (!i.companyName().isBlank()) parts.add("&3[" + i.companyName() + "]&r"); } + default -> { } + } + } + return String.join(" ", parts); + } +} diff --git a/DuneChat/src/main/java/com/example/dunechat/DiscordPrivacy.java b/DuneChat/src/main/java/com/example/dunechat/DiscordPrivacy.java new file mode 100644 index 00000000..fa7d12cf --- /dev/null +++ b/DuneChat/src/main/java/com/example/dunechat/DiscordPrivacy.java @@ -0,0 +1,24 @@ +package com.example.dunechat; + +import github.scarsz.discordsrv.DiscordSRV; +import github.scarsz.discordsrv.api.Subscribe; +import github.scarsz.discordsrv.api.events.GameChatMessagePreProcessEvent; + +/** Leave the existing public relay in place and prevent it from processing private messages. */ +public final class DiscordPrivacy implements AutoCloseable { + private final DuneChat chat; + + DiscordPrivacy(DuneChat chat) { + this.chat = chat; + DiscordSRV.api.subscribe(this); + } + + @Subscribe + public void beforeRelay(GameChatMessagePreProcessEvent event) { + if (event.getPlayer() != null && chat.isPrivate(event.getPlayer())) event.setCancelled(true); + } + + @Override public void close() { + DiscordSRV.api.unsubscribe(this); + } +} diff --git a/DuneChat/src/main/java/com/example/dunechat/DuneChat.java b/DuneChat/src/main/java/com/example/dunechat/DuneChat.java new file mode 100644 index 00000000..31a4eb5c --- /dev/null +++ b/DuneChat/src/main/java/com/example/dunechat/DuneChat.java @@ -0,0 +1,196 @@ +package com.example.dunechat; + +import com.example.dunechat.ChatLogic.Channel; +import com.example.dunechat.ChatLogic.Identity; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import io.papermc.paper.event.player.AsyncChatEvent; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import org.bukkit.Bukkit; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +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.PlayerQuitEvent; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Chat prefixes (race, clan, company) and private clan, company and staff channels. + * Identity comes from the central JARVIS briefing, pushed in by DuneRealmsGUI through {@link #identity}. + * Chat is per server; there is no cross-server relay. + */ +public final class DuneChat extends JavaPlugin implements Listener, CommandExecutor { + private static final LegacyComponentSerializer LEGACY = LegacyComponentSerializer.legacyAmpersand(); + private final Map identities = new ConcurrentHashMap<>(); + private final Map memberships = new ConcurrentHashMap<>(); + private final Map mode = new ConcurrentHashMap<>(); + private record CommandMessage(UUID sender, Channel channel) {} + private final ThreadLocal commandMessage = new ThreadLocal<>(); + private DiscordPrivacy discordPrivacy; + private final Set spies = ConcurrentHashMap.newKeySet(); + private List order = List.of("staff", "race", "clan", "company"); + private int max = 16; + + @Override public void onEnable() { + saveDefaultConfig(); + order = getConfig().getStringList("prefix-order"); + max = Math.max(4, getConfig().getInt("max-prefix-length", 16)); + if (getServer().getPluginManager().isPluginEnabled("DiscordSRV")) { + try { + discordPrivacy = new DiscordPrivacy(this); + } catch (RuntimeException | LinkageError unavailable) { + getLogger().warning("DiscordSRV privacy hook failed; private channels are unavailable."); + } + } + getServer().getPluginManager().registerEvents(this, this); + for (String c : List.of("clanchat", "companychat", "staffchat", "globalchat", "chatspy")) { + var cmd = getCommand(c); + if (cmd != null) cmd.setExecutor(this); + } + } + + @Override public void onDisable() { + if (discordPrivacy != null) discordPrivacy.close(); + } + + /** Called by DuneRealmsGUI (by reflection) whenever the central briefing for a player changes. */ + public void identity(UUID player, String briefingJson, String faction, String race) { + Identity next = Identity.NONE; + try { + if (briefingJson != null) next = ChatLogic.parse(JsonParser.parseString(briefingJson).getAsJsonObject(), faction, race, max); + } catch (RuntimeException malformed) { getLogger().warning("Ignored malformed identity for " + player); } + identities.put(player, next); + } + + /** Called with an authenticated JARVIS organisation-list response for this player. */ + public void memberships(UUID player, String json) { + ChatLogic.Membership membership = ChatLogic.Membership.NONE; + try { + if (json != null) membership = ChatLogic.memberships( + JsonParser.parseString(json).getAsJsonObject(), player, System.currentTimeMillis()); + } catch (RuntimeException invalid) { + getLogger().warning("Ignored malformed chat membership projection"); + } + memberships.put(player, membership); + } + + private Identity of(Player p) { + UUID id = p.getUniqueId(); + return ChatLogic.withMembership(identities.getOrDefault(id, Identity.NONE), + memberships.getOrDefault(id, ChatLogic.Membership.NONE), System.currentTimeMillis()); + } + private boolean staff(Player p) { return p.hasPermission("dunechat.staff"); } + private Channel channel(Player player) { + var command = commandMessage.get(); + return command != null && command.sender().equals(player.getUniqueId()) + ? command.channel() : mode.getOrDefault(player.getUniqueId(), Channel.GLOBAL); + } + boolean isPrivate(Player player) { return channel(player) != Channel.GLOBAL; } + + private boolean privateReady() { + return discordPrivacy != null || !getServer().getPluginManager().isPluginEnabled("DiscordSRV"); + } + + @EventHandler public void onQuit(PlayerQuitEvent e) { + UUID id = e.getPlayer().getUniqueId(); identities.remove(id); memberships.remove(id); mode.remove(id); spies.remove(id); + } + + /** Never un-cancels: if another plugin cancelled the chat (mute, filter), we leave it alone. */ + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onChat(AsyncChatEvent e) { + Player p = e.getPlayer(); + Channel c = channel(p); + Identity me = of(p); + if (c != Channel.GLOBAL) { + if (!privateReady() || !ChatLogic.canSend(c, me, staff(p))) { + e.setCancelled(true); + p.sendMessage(Component.text("Your private channel is unavailable. Use /g to return to public chat.", NamedTextColor.RED)); + return; + } + } + final Channel channel = c; + if (channel != Channel.GLOBAL) { + e.viewers().removeIf(v -> !(v instanceof Player vp) || !ChatLogic.receives(channel, me, of(vp), staff(vp), spies.contains(vp.getUniqueId()) && vp.hasPermission("dunechat.spy"))); + } + e.renderer((source, name, message, viewer) -> render(channel, me, name, message)); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void logAcceptedPrivateChat(AsyncChatEvent event) { + Channel channel = channel(event.getPlayer()); + if (channel != Channel.GLOBAL) logPrivate(channel, event.getPlayer(), event.message()); + } + + private Component render(Channel c, Identity me, Component name, Component message) { + Component sep = Component.text(": ", NamedTextColor.GRAY); + if (c == Channel.GLOBAL) { + String prefix = ChatLogic.prefix(me, order); + Component head = prefix.isEmpty() ? Component.empty() : LEGACY.deserialize(prefix).append(Component.space()); + return head.append(name).append(sep).append(message); + } + String label = switch (c) { + case CLAN -> getConfig().getString("clan-chat-label", "CLAN") + (me.clanTag().isBlank() ? "" : " " + me.clanTag()); + case COMPANY -> getConfig().getString("company-chat-label", "COMPANY") + (me.companyName().isBlank() ? "" : " " + me.companyName()); + default -> getConfig().getString("staff-chat-label", "STAFF"); + }; + NamedTextColor color = c == Channel.CLAN ? NamedTextColor.GOLD : c == Channel.COMPANY ? NamedTextColor.DARK_AQUA : NamedTextColor.RED; + return Component.text("[" + ChatLogic.clean(label, 40) + "] ", color).append(name).append(sep).append(message.color(NamedTextColor.WHITE)); + } + + private void logPrivate(Channel c, Player p, Component message) { + if (getConfig().getBoolean("log-private-chat", false)) + getLogger().info("[" + c + "] " + p.getName() + ": " + net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText().serialize(message)); + } + + @Override public boolean onCommand(CommandSender s, Command cmd, String label, String[] a) { + if (!(s instanceof Player p)) { s.sendMessage("Players only."); return true; } + Channel c = switch (cmd.getName()) { + case "clanchat" -> Channel.CLAN; case "companychat" -> Channel.COMPANY; case "staffchat" -> Channel.STAFF; + case "globalchat" -> Channel.GLOBAL; default -> null; + }; + if (cmd.getName().equals("chatspy")) { + if (!p.hasPermission("dunechat.spy")) { p.sendMessage(Component.text("No permission.", NamedTextColor.RED)); return true; } + boolean on = spies.add(p.getUniqueId()); if (!on) spies.remove(p.getUniqueId()); + p.sendMessage(Component.text("Chat spy " + (on ? "on" : "off") + ".", NamedTextColor.GOLD)); return true; + } + if (c == null) return false; + Identity me = of(p); + if (c == Channel.GLOBAL) { mode.remove(p.getUniqueId()); p.sendMessage(Component.text("Public chat.", NamedTextColor.GOLD)); return true; } + if (!privateReady()) { + p.sendMessage(Component.text("Private channels are unavailable.", NamedTextColor.RED)); + return true; + } + if (!ChatLogic.canSend(c, me, staff(p))) { + p.sendMessage(Component.text(c == Channel.STAFF ? "No permission." : "You are not in a " + (c == Channel.CLAN ? "clan" : "company") + ".", NamedTextColor.RED)); return true; + } + if (a.length == 0) { + boolean off = mode.get(p.getUniqueId()) == c; + if (off) mode.remove(p.getUniqueId()); else mode.put(p.getUniqueId(), c); + p.sendMessage(Component.text(off ? "Public chat." : c + " chat on. /g to leave.", NamedTextColor.GOLD)); return true; + } + String message = String.join(" ", a).strip(); + if (message.isEmpty() || message.length() > 256 || message.startsWith("/") + || message.chars().anyMatch(ch -> ch == '§' || Character.isISOControl(ch))) { + p.sendMessage(Component.text("Enter ordinary chat text of up to 256 characters.", NamedTextColor.RED)); + return true; + } + commandMessage.set(new CommandMessage(p.getUniqueId(), c)); + try { + p.chat(message); + } finally { + commandMessage.remove(); + } + return true; + } +} diff --git a/DuneChat/src/main/resources/config.yml b/DuneChat/src/main/resources/config.yml new file mode 100644 index 00000000..132da669 --- /dev/null +++ b/DuneChat/src/main/resources/config.yml @@ -0,0 +1,8 @@ +# Prefix order in public chat. Remove an entry to hide it. +prefix-order: [staff, race, clan, company] +max-prefix-length: 16 +clan-chat-label: "CLAN" +company-chat-label: "COMPANY" +staff-chat-label: "STAFF" +# Staff with dunechat.spy can opt in using /chatspy. Private messages stay out of the console by default. +log-private-chat: false diff --git a/DuneChat/src/main/resources/plugin.yml b/DuneChat/src/main/resources/plugin.yml new file mode 100644 index 00000000..4cfec2a5 --- /dev/null +++ b/DuneChat/src/main/resources/plugin.yml @@ -0,0 +1,31 @@ +name: DuneChat +version: 1.0.0 +main: com.example.dunechat.DuneChat +api-version: '1.21.8' +softdepend: [DiscordSRV] +description: Chat prefixes for race, clan and company, plus private clan, company and staff channels. +commands: + clanchat: + aliases: [cc] + description: Send to your private clan chat, or toggle it + usage: /cc [message] + companychat: + aliases: [coc] + description: Send to your private company chat, or toggle it + usage: /coc [message] + staffchat: + aliases: [sc] + description: Staff-only chat + usage: /sc [message] + globalchat: + aliases: [gc, g] + description: Return to public chat + usage: /g + chatspy: + description: Staff - watch clan and company chats + usage: /chatspy +permissions: + dunechat.staff: + default: op + dunechat.spy: + default: op diff --git a/DuneChat/src/test/java/com/example/dunechat/ChatLogicTest.java b/DuneChat/src/test/java/com/example/dunechat/ChatLogicTest.java new file mode 100644 index 00000000..729db560 --- /dev/null +++ b/DuneChat/src/test/java/com/example/dunechat/ChatLogicTest.java @@ -0,0 +1,92 @@ +package com.example.dunechat; + +import com.example.dunechat.ChatLogic.Channel; +import com.example.dunechat.ChatLogic.Identity; +import com.google.gson.JsonParser; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +class ChatLogicTest { + private static Identity parse(String briefing, String house, String race) { + return ChatLogic.parse(JsonParser.parseString(briefing).getAsJsonObject(), house, race, 16); + } + private static final String CLAN = "aaaaaaaa-0000-0000-0000-000000000001"; + private static final String COMPANY = "bbbbbbbb-0000-0000-0000-000000000001"; + private static final String OTHER = "aaaaaaaa-0000-0000-0000-000000000002"; + private static final java.util.UUID ACTOR = java.util.UUID.fromString("cccccccc-0000-0000-0000-000000000001"); + + private static Identity proof(Identity display, String clan, String company) { + return ChatLogic.withMembership(display, new ChatLogic.Membership(clan, company, 100000L), 100001L); + } + + private static final String DATA = "{\"briefing\":{\"identity\":{\"staff\":false,\"vip\":true,\"clans\":[{\"id\":\"c1\",\"name\":\"Sand Hawks\",\"tag\":\"HAWK\"},{\"name\":\"Second\"}],\"companies\":[{\"id\":\"k1\",\"name\":\"Spice Co\"}]}}}"; + + @Test void parsesClanCompanyAndUsesOnlyTheFirstOfEach() { + Identity i = proof(parse(DATA, "fremen", "Fremen"), CLAN, COMPANY); + assertEquals(CLAN, i.clanKey()); assertEquals("HAWK", i.clanTag()); + assertEquals(COMPANY, i.companyKey()); assertEquals("Spice Co", i.companyName()); + assertTrue(i.vip()); assertFalse(i.staff()); + } + + @Test void prefixFollowsConfiguredOrderAndSkipsMissingParts() { + Identity i = proof(parse(DATA, "fremen", "Fremen"), CLAN, COMPANY); + assertEquals("&6&l[VIP]&r &b[Fremen]&r &6[HAWK]&r &3[Spice Co]&r", ChatLogic.prefix(i, List.of("staff", "race", "clan", "company"))); + assertEquals("&3[Spice Co]&r &b[Fremen]&r", ChatLogic.prefix(i, List.of("company", "race"))); + assertEquals("", ChatLogic.prefix(Identity.NONE, List.of("staff", "race", "clan", "company"))); + } + + @Test void colourAndMarkupCannotBeInjectedThroughNames() { + Identity i = parse("{\"briefing\":{\"identity\":{\"clans\":[{\"tag\":\"&4EVIL§k\"}]}}}", "atreides", "&cRace%"); + assertFalse(ChatLogic.prefix(i, List.of("race", "clan")).contains("§")); + assertEquals("4EVILredk", i.clanTag(), "markup characters are removed, nothing is interpreted"); + assertEquals("cRace", i.race()); + } + + @Test void privateChannelsReachOnlyTheSameGroup() { + Identity me = proof(parse(DATA, "fremen", "Fremen"), CLAN, COMPANY); + Identity mate = proof(parse(DATA, "fremen", "Fremen"), CLAN, COMPANY); + Identity otherClan = proof(Identity.NONE, OTHER, COMPANY); + assertTrue(ChatLogic.receives(Channel.CLAN, me, mate, false, false)); + assertFalse(ChatLogic.receives(Channel.CLAN, me, otherClan, false, false)); + assertTrue(ChatLogic.receives(Channel.COMPANY, me, otherClan, false, false), "same company, different clan"); + assertFalse(ChatLogic.receives(Channel.CLAN, me, Identity.NONE, false, false)); + assertTrue(ChatLogic.receives(Channel.CLAN, me, Identity.NONE, true, true), "spy sees it"); + } + + @Test void aClanAndACompanyAreIndependent() { + Identity onlyCompany = proof(Identity.NONE, "", COMPANY); + assertFalse(ChatLogic.canSend(Channel.CLAN, onlyCompany, false)); + assertTrue(ChatLogic.canSend(Channel.COMPANY, onlyCompany, false)); + } + + @Test void staffChatNeedsThePermissionToSendAndToRead() { + assertFalse(ChatLogic.canSend(Channel.STAFF, Identity.NONE, false)); + assertTrue(ChatLogic.canSend(Channel.STAFF, Identity.NONE, true)); + assertTrue(ChatLogic.receives(Channel.STAFF, Identity.NONE, Identity.NONE, true, false)); + assertFalse(ChatLogic.receives(Channel.STAFF, Identity.NONE, Identity.NONE, false, true), "spy alone is not staff chat"); + } + + @Test void missingBriefingGivesNoPrefixAndNoGroups() { + Identity i = ChatLogic.parse(null, null, null, 16); + assertEquals("", ChatLogic.prefix(i, List.of("race", "clan", "company"))); + assertFalse(ChatLogic.inGroup(Channel.CLAN, i)); + } + + @Test void onlyFreshExplicitMembershipAuthorizesPrivateChat() { + var display = parse(DATA, "fremen", "Fremen"); + assertFalse(ChatLogic.canSend(Channel.CLAN, display, false), "public label alone grants nothing"); + var response = JsonParser.parseString(""" + {"ok":true,"schema":1,"observedAt":100000,"clans":[ + {"id":"%s","lifecycle":"active","canManage":true,"members":[]}, + {"id":"%s","lifecycle":"active","members":[{"uuid":"%s"}]} + ],"companies":[]} + """.formatted(OTHER, CLAN, ACTOR)).getAsJsonObject(); + var membership = ChatLogic.memberships(response, ACTOR, 100001L); + assertEquals(CLAN, membership.clan()); + assertTrue(ChatLogic.canSend(Channel.CLAN, ChatLogic.withMembership(display, membership, 100001L), false)); + assertFalse(ChatLogic.canSend(Channel.CLAN, ChatLogic.withMembership(display, membership, 145001L), false)); + } +} diff --git a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/DuneGUI.java b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/DuneGUI.java index 9bdbae99..e2839a24 100644 --- a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/DuneGUI.java +++ b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/DuneGUI.java @@ -212,13 +212,19 @@ public final class DuneGUI extends JavaPlugin implements Listener,CommandExecuto } private void refreshSidebar(Player p){ UUID owner=p.getUniqueId();if(requests.containsKey(owner))return;UUID operation=UUID.randomUUID();requests.put(owner,operation); + boolean chatEnabled=Bukkit.getPluginManager().isPluginEnabled("DuneChat"); Bukkit.getScheduler().runTaskAsynchronously(this,()->{JsonObject result=null;try{result=bridge.request(owner,null,0,null);}catch(Exception unavailable){}JsonObject received=result;if(!isEnabled())return; + JsonObject memberships=null;if(chatEnabled)try{memberships=bridge.organisations(owner);}catch(Exception unavailable){} + JsonObject chatMemberships=memberships; Bukkit.getScheduler().runTask(this,()->{if(!operation.equals(requests.get(owner)))return;requests.remove(owner);if(!p.isOnline())return; - if(received!=null){records.put(owner,received);updateSidebar(p,received);}else{records.remove(owner);sidebar.update(p,null,null);nameplates.update(p,null,null,null);} + if(chatEnabled)pushChatMemberships(owner,chatMemberships); + if(received!=null){records.put(owner,received);updateSidebar(p,received);}else{records.remove(owner);sidebar.update(p,null,null);nameplates.update(p,null,null,null);pushChatIdentity(p,null,null,null);} }); }); } - private void updateSidebar(Player p,JsonObject data){String house=selection(data),label=house==null?null:houseName(data,house);sidebar.update(p,data,label);nameplates.update(p,data,house,label);} + private void updateSidebar(Player p,JsonObject data){String house=selection(data),label=house==null?null:houseName(data,house);sidebar.update(p,data,label);nameplates.update(p,data,house,label);pushChatIdentity(p,data,house,label);} + private void pushChatIdentity(Player p,JsonObject data,String house,String race){var chat=Bukkit.getPluginManager().getPlugin("DuneChat");if(chat==null||!chat.isEnabled())return;try{chat.getClass().getMethod("identity",UUID.class,String.class,String.class,String.class).invoke(chat,p.getUniqueId(),data==null?null:data.toString(),house,race);}catch(ReflectiveOperationException|RuntimeException unavailable){}} + private void pushChatMemberships(UUID uuid,JsonObject data){var chat=Bukkit.getPluginManager().getPlugin("DuneChat");if(chat==null||!chat.isEnabled())return;try{chat.getClass().getMethod("memberships",UUID.class,String.class).invoke(chat,uuid,data==null?null:data.toString());}catch(ReflectiveOperationException|RuntimeException unavailable){}} private void toggleSidebar(Player p){sidebar.toggle(p);p.sendMessage(Component.text(sidebar.enabled(p)?"Personal scoreboard enabled.":"Personal scoreboard hidden.",NamedTextColor.GOLD));if(sidebar.enabled(p)){JsonObject data=records.get(p.getUniqueId());if(data!=null)updateSidebar(p,data);refreshSidebar(p);}} @EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=false) public void organisationContact(org.bukkit.event.player.PlayerInteractEntityEvent event){String marker=event.getRightClicked().getPersistentDataContainer().get(new NamespacedKey("dunerealms","organisation_home_npc"),PersistentDataType.STRING);if(marker==null)return;event.setCancelled(true);if(event.getHand()!=org.bukkit.inventory.EquipmentSlot.HAND)return;String[] parts=marker.split(":",2);if(parts.length!=2||!Set.of("clan","company").contains(parts[0]))return;try{String id=UUID.fromString(parts[1]).toString();organisations.openHomeNpc(event.getPlayer(),parts[0].equals("clan")?"clans":"companies",id,event.getRightClicked().getUniqueId());}catch(IllegalArgumentException ignored){}} @EventHandler public void scoreboardCommand(PlayerCommandPreprocessEvent e){String command=e.getMessage().trim();if(command.equalsIgnoreCase("/scoreboard")){e.setCancelled(true);toggleSidebar(e.getPlayer());}} -- 2.53.0 From a5813cc270eedc3d805936eb5dc7741b77143eda Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:33:21 +0100 Subject: [PATCH 2/4] Read chat authority through retained JARVIS without replacing GUI --- .forgejo/workflows/dunechat.yml | 5 +- .../example/dunechat/ChatIdentitySource.java | 28 ++++++++++ .../java/com/example/dunechat/ChatLogic.java | 13 +++++ .../java/com/example/dunechat/DuneChat.java | 53 +++++++++++-------- DuneChat/src/main/resources/plugin.yml | 1 + 5 files changed, 75 insertions(+), 25 deletions(-) create mode 100644 DuneChat/src/main/java/com/example/dunechat/ChatIdentitySource.java diff --git a/.forgejo/workflows/dunechat.yml b/.forgejo/workflows/dunechat.yml index f186b53c..e69deb19 100644 --- a/.forgejo/workflows/dunechat.yml +++ b/.forgejo/workflows/dunechat.yml @@ -24,14 +24,13 @@ jobs: - uses: gradle/actions/setup-gradle@v4 with: gradle-version: '9.2.1' - - name: Build and test DuneChat and its GUI identity hook + - name: Build and test DuneChat shell: bash run: | set -euo pipefail gradle --no-daemon -p DuneChat test jar - gradle --no-daemon -p DuneRealmsGUI test jar mkdir dunechat-artifacts - cp DuneChat/build/libs/DuneChat.jar DuneRealmsGUI/build/libs/DunerealmsGUI.jar dunechat-artifacts/ + cp DuneChat/build/libs/DuneChat.jar dunechat-artifacts/ printf '%s\n' "$(git rev-parse HEAD)" > dunechat-artifacts/SOURCE_COMMIT (cd dunechat-artifacts && sha256sum -- *.jar SOURCE_COMMIT > SHA256SUMS) - uses: actions/upload-artifact@v3 diff --git a/DuneChat/src/main/java/com/example/dunechat/ChatIdentitySource.java b/DuneChat/src/main/java/com/example/dunechat/ChatIdentitySource.java new file mode 100644 index 00000000..de431390 --- /dev/null +++ b/DuneChat/src/main/java/com/example/dunechat/ChatIdentitySource.java @@ -0,0 +1,28 @@ +package com.example.dunechat; + +import com.google.gson.JsonObject; +import java.lang.reflect.Method; +import java.util.UUID; +import org.bukkit.plugin.Plugin; + +/** Reuse the installed JARVIS reads without replacing the GUI or the central service. */ +final class ChatIdentitySource { + private final Plugin jarvis; + private final Method house; + private final Method organisations; + + ChatIdentitySource(Plugin jarvis) throws ReflectiveOperationException { + this.jarvis = jarvis; + if (jarvis == null || !jarvis.isEnabled()) throw new IllegalStateException("JARVIS unavailable"); + house = jarvis.getClass().getMethod("requestHouse", UUID.class, String.class, int.class, UUID.class); + organisations = jarvis.getClass().getMethod("requestOrganisations", UUID.class); + } + + JsonObject house(UUID player) throws ReflectiveOperationException { + return (JsonObject) house.invoke(jarvis, player, null, 0, null); + } + + JsonObject organisations(UUID player) throws ReflectiveOperationException { + return (JsonObject) organisations.invoke(jarvis, player); + } +} diff --git a/DuneChat/src/main/java/com/example/dunechat/ChatLogic.java b/DuneChat/src/main/java/com/example/dunechat/ChatLogic.java index 125cd848..14ab3bac 100644 --- a/DuneChat/src/main/java/com/example/dunechat/ChatLogic.java +++ b/DuneChat/src/main/java/com/example/dunechat/ChatLogic.java @@ -61,6 +61,19 @@ final class ChatLogic { "", clean(clanTag.isBlank() ? clanName : clanTag, max), "", clean(companyName, max)); } + static Identity house(JsonObject data, int max) { + if (data == null) return Identity.NONE; + String faction = text(data, "selection"); + JsonArray choices = data.getAsJsonArray("choices"); + if (!faction.isBlank() && choices != null) { + for (JsonElement element : choices) { + JsonObject choice = element.getAsJsonObject(); + if (faction.equals(text(choice, "id"))) return parse(data, faction, text(choice, "name"), max); + } + } + return parse(data, "", "", max); + } + record Membership(String clan, String company, long observedAt) { static final Membership NONE = new Membership("", "", 0); } diff --git a/DuneChat/src/main/java/com/example/dunechat/DuneChat.java b/DuneChat/src/main/java/com/example/dunechat/DuneChat.java index 31a4eb5c..d4edf650 100644 --- a/DuneChat/src/main/java/com/example/dunechat/DuneChat.java +++ b/DuneChat/src/main/java/com/example/dunechat/DuneChat.java @@ -2,8 +2,6 @@ package com.example.dunechat; import com.example.dunechat.ChatLogic.Channel; import com.example.dunechat.ChatLogic.Identity; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; import io.papermc.paper.event.player.AsyncChatEvent; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; @@ -17,6 +15,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.plugin.java.JavaPlugin; import java.util.List; @@ -27,13 +26,15 @@ import java.util.concurrent.ConcurrentHashMap; /** * Chat prefixes (race, clan, company) and private clan, company and staff channels. - * Identity comes from the central JARVIS briefing, pushed in by DuneRealmsGUI through {@link #identity}. + * Identity and private membership come from the installed JARVIS read APIs. * Chat is per server; there is no cross-server relay. */ public final class DuneChat extends JavaPlugin implements Listener, CommandExecutor { private static final LegacyComponentSerializer LEGACY = LegacyComponentSerializer.legacyAmpersand(); private final Map identities = new ConcurrentHashMap<>(); private final Map memberships = new ConcurrentHashMap<>(); + private final Map refreshing = new ConcurrentHashMap<>(); + private ChatIdentitySource identitySource; private final Map mode = new ConcurrentHashMap<>(); private record CommandMessage(UUID sender, Channel channel) {} private final ThreadLocal commandMessage = new ThreadLocal<>(); @@ -46,6 +47,11 @@ public final class DuneChat extends JavaPlugin implements Listener, CommandExecu saveDefaultConfig(); order = getConfig().getStringList("prefix-order"); max = Math.max(4, getConfig().getInt("max-prefix-length", 16)); + try { + identitySource = new ChatIdentitySource(getServer().getPluginManager().getPlugin("JarvisTranslator")); + } catch (ReflectiveOperationException | IllegalStateException unavailable) { + getLogger().warning("JARVIS identity unavailable; organisation channels are unavailable."); + } if (getServer().getPluginManager().isPluginEnabled("DiscordSRV")) { try { discordPrivacy = new DiscordPrivacy(this); @@ -54,6 +60,7 @@ public final class DuneChat extends JavaPlugin implements Listener, CommandExecu } } getServer().getPluginManager().registerEvents(this, this); + getServer().getScheduler().runTaskTimer(this, () -> Bukkit.getOnlinePlayers().forEach(this::refresh), 20L, 400L); for (String c : List.of("clanchat", "companychat", "staffchat", "globalchat", "chatspy")) { var cmd = getCommand(c); if (cmd != null) cmd.setExecutor(this); @@ -64,25 +71,27 @@ public final class DuneChat extends JavaPlugin implements Listener, CommandExecu if (discordPrivacy != null) discordPrivacy.close(); } - /** Called by DuneRealmsGUI (by reflection) whenever the central briefing for a player changes. */ - public void identity(UUID player, String briefingJson, String faction, String race) { - Identity next = Identity.NONE; - try { - if (briefingJson != null) next = ChatLogic.parse(JsonParser.parseString(briefingJson).getAsJsonObject(), faction, race, max); - } catch (RuntimeException malformed) { getLogger().warning("Ignored malformed identity for " + player); } - identities.put(player, next); - } + @EventHandler public void onJoin(PlayerJoinEvent event) { refresh(event.getPlayer()); } - /** Called with an authenticated JARVIS organisation-list response for this player. */ - public void memberships(UUID player, String json) { - ChatLogic.Membership membership = ChatLogic.Membership.NONE; - try { - if (json != null) membership = ChatLogic.memberships( - JsonParser.parseString(json).getAsJsonObject(), player, System.currentTimeMillis()); - } catch (RuntimeException invalid) { - getLogger().warning("Ignored malformed chat membership projection"); - } - memberships.put(player, membership); + private void refresh(Player player) { + UUID id = player.getUniqueId(); + if (identitySource == null || refreshing.putIfAbsent(id, player) != null) return; + getServer().getScheduler().runTaskAsynchronously(this, () -> { + Identity display = Identity.NONE; + ChatLogic.Membership membership = ChatLogic.Membership.NONE; + try { display = ChatLogic.house(identitySource.house(id), max); } + catch (ReflectiveOperationException | RuntimeException unavailable) { /* Default display. */ } + try { membership = ChatLogic.memberships(identitySource.organisations(id), id, System.currentTimeMillis()); } + catch (ReflectiveOperationException | RuntimeException unavailable) { /* Private access fails closed. */ } + Identity nextDisplay = display; + ChatLogic.Membership nextMembership = membership; + if (!isEnabled()) return; + getServer().getScheduler().runTask(this, () -> { + if (!refreshing.remove(id, player) || Bukkit.getPlayer(id) != player || !player.isOnline()) return; + identities.put(id, nextDisplay); + memberships.put(id, nextMembership); + }); + }); } private Identity of(Player p) { @@ -103,7 +112,7 @@ public final class DuneChat extends JavaPlugin implements Listener, CommandExecu } @EventHandler public void onQuit(PlayerQuitEvent e) { - UUID id = e.getPlayer().getUniqueId(); identities.remove(id); memberships.remove(id); mode.remove(id); spies.remove(id); + UUID id = e.getPlayer().getUniqueId(); identities.remove(id); memberships.remove(id); refreshing.remove(id, e.getPlayer()); mode.remove(id); spies.remove(id); } /** Never un-cancels: if another plugin cancelled the chat (mute, filter), we leave it alone. */ diff --git a/DuneChat/src/main/resources/plugin.yml b/DuneChat/src/main/resources/plugin.yml index 4cfec2a5..787b4821 100644 --- a/DuneChat/src/main/resources/plugin.yml +++ b/DuneChat/src/main/resources/plugin.yml @@ -3,6 +3,7 @@ version: 1.0.0 main: com.example.dunechat.DuneChat api-version: '1.21.8' softdepend: [DiscordSRV] +depend: [JarvisTranslator] description: Chat prefixes for race, clan and company, plus private clan, company and staff channels. commands: clanchat: -- 2.53.0 From 19200b07ade4cd44a194e68035bcf13e078ebe0d Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:33:51 +0100 Subject: [PATCH 3/4] Keep deployed GUI bytes out of the DuneChat change --- DuneChat/README.md | 39 +++++-------------- .../main/java/com/dunerealms/gui/DuneGUI.java | 10 +---- 2 files changed, 12 insertions(+), 37 deletions(-) diff --git a/DuneChat/README.md b/DuneChat/README.md index 1be2ccb4..2dfebc9c 100644 --- a/DuneChat/README.md +++ b/DuneChat/README.md @@ -1,36 +1,17 @@ # DuneChat -Chat prefixes and private channels. Built on canonical main `5d727d7`. Not pushed. Not tested in game. +DuneChat formats public Minecraft chat and provides local private channels. -## What players see -Public chat: `[STAFF]/[VIP] [Race] [CLAN TAG] [Company] Name: message`. Order is `prefix-order` in config.yml. Race colour follows the house colour used by the nameplates. - -| Command | Does | +| Command | Action | |---|---| -| `/cc ` (`/clanchat`) | one message to your clan. `/cc` alone toggles clan chat mode | -| `/coc ` (`/companychat`) | same for your company | -| `/sc ` (`/staffchat`) | staff only, permission `dunechat.staff` | -| `/g` (`/gc`) | back to public chat | -| `/chatspy` | staff with `dunechat.spy` also see clan and company chat | +| /cc [message] | Toggle clan chat or send one message | +| /coc [message] | Toggle company chat or send one message | +| /sc [message] | Toggle staff chat or send one message | +| /g | Return to public chat | +| /chatspy | Toggle clan and company visibility with the explicit spy permission | -You can be in one clan and one company at the same time; each has its own private channel. Private chat is logged to the console (`log-private-chat`). +Public prefixes use the existing JARVIS House briefing. Private clan and company delivery requires matching organisation UUIDs and current, explicit membership in the authenticated organisation roster. Public display labels grant no chat access. Staff commands require dunechat.staff. Chat spy requires dunechat.spy. -## Where the data comes from -The same central briefing the nameplates use (`briefing.identity`: staff, vip, clans, companies), pushed in by a 5-line hook in DuneRealmsGUI (`DuneGUI.pushChatIdentity`, reflection, no hard dependency). Group membership keys on the central id when the briefing carries one, otherwise on the name, so please confirm the briefing includes ids. +The plugin uses Paper's chat pipeline so menu prompts and existing chat cancellation handlers retain precedence. DiscordSRV keeps its public route. The privacy hook suppresses private messages before Discord forwarding. Deploy with DiscordSRV configured to use modern Paper events and respect event cancellation, including menu prompt input. Private console logging defaults off. -## Safety -- Names and tags are stripped of `& § % < >` and control characters before they reach a prefix; the message itself is never colour-parsed. -- Never un-cancels chat: a mute or filter from another plugin still wins. -- Leaving a clan or company while in its channel drops you back to public chat. - -## Install -1. Build: `gradle -p DuneChat build` -> `build/libs/DuneChat.jar`. -2. Apply the DuneRealmsGUI change (DuneGUI.java, plugin.yml softdepend), rebuild DuneRealmsGUI. -3. Grant `dunechat.staff` / `dunechat.spy` through LuckPerms. - -## Verified / not verified -CI: DuneChat compiles; 7 unit tests (parsing, prefix order, injection, group isolation, staff rules). The DuneRealmsGUI edit was not compiled in CI (that module needs another module missing from the cut-down CI tree; the errors seen were unrelated). Not tested: real chat events, other chat plugins (LuckPerms prefixes, DuneEss, DuneMenus chat prompts), Bedrock clients. - -## Limits -- Per server only: planets are separate servers, so clan/company/staff chat does not cross servers. A proxy relay would be a separate piece. -- No mute, filter, cooldown or channel history. +Build with gradle -p DuneChat test jar. The release artifact contains DuneChat.jar. Existing GUI and JARVIS archives are retained. diff --git a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/DuneGUI.java b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/DuneGUI.java index e2839a24..9bdbae99 100644 --- a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/DuneGUI.java +++ b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/DuneGUI.java @@ -212,19 +212,13 @@ public final class DuneGUI extends JavaPlugin implements Listener,CommandExecuto } private void refreshSidebar(Player p){ UUID owner=p.getUniqueId();if(requests.containsKey(owner))return;UUID operation=UUID.randomUUID();requests.put(owner,operation); - boolean chatEnabled=Bukkit.getPluginManager().isPluginEnabled("DuneChat"); Bukkit.getScheduler().runTaskAsynchronously(this,()->{JsonObject result=null;try{result=bridge.request(owner,null,0,null);}catch(Exception unavailable){}JsonObject received=result;if(!isEnabled())return; - JsonObject memberships=null;if(chatEnabled)try{memberships=bridge.organisations(owner);}catch(Exception unavailable){} - JsonObject chatMemberships=memberships; Bukkit.getScheduler().runTask(this,()->{if(!operation.equals(requests.get(owner)))return;requests.remove(owner);if(!p.isOnline())return; - if(chatEnabled)pushChatMemberships(owner,chatMemberships); - if(received!=null){records.put(owner,received);updateSidebar(p,received);}else{records.remove(owner);sidebar.update(p,null,null);nameplates.update(p,null,null,null);pushChatIdentity(p,null,null,null);} + if(received!=null){records.put(owner,received);updateSidebar(p,received);}else{records.remove(owner);sidebar.update(p,null,null);nameplates.update(p,null,null,null);} }); }); } - private void updateSidebar(Player p,JsonObject data){String house=selection(data),label=house==null?null:houseName(data,house);sidebar.update(p,data,label);nameplates.update(p,data,house,label);pushChatIdentity(p,data,house,label);} - private void pushChatIdentity(Player p,JsonObject data,String house,String race){var chat=Bukkit.getPluginManager().getPlugin("DuneChat");if(chat==null||!chat.isEnabled())return;try{chat.getClass().getMethod("identity",UUID.class,String.class,String.class,String.class).invoke(chat,p.getUniqueId(),data==null?null:data.toString(),house,race);}catch(ReflectiveOperationException|RuntimeException unavailable){}} - private void pushChatMemberships(UUID uuid,JsonObject data){var chat=Bukkit.getPluginManager().getPlugin("DuneChat");if(chat==null||!chat.isEnabled())return;try{chat.getClass().getMethod("memberships",UUID.class,String.class).invoke(chat,uuid,data==null?null:data.toString());}catch(ReflectiveOperationException|RuntimeException unavailable){}} + private void updateSidebar(Player p,JsonObject data){String house=selection(data),label=house==null?null:houseName(data,house);sidebar.update(p,data,label);nameplates.update(p,data,house,label);} private void toggleSidebar(Player p){sidebar.toggle(p);p.sendMessage(Component.text(sidebar.enabled(p)?"Personal scoreboard enabled.":"Personal scoreboard hidden.",NamedTextColor.GOLD));if(sidebar.enabled(p)){JsonObject data=records.get(p.getUniqueId());if(data!=null)updateSidebar(p,data);refreshSidebar(p);}} @EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=false) public void organisationContact(org.bukkit.event.player.PlayerInteractEntityEvent event){String marker=event.getRightClicked().getPersistentDataContainer().get(new NamespacedKey("dunerealms","organisation_home_npc"),PersistentDataType.STRING);if(marker==null)return;event.setCancelled(true);if(event.getHand()!=org.bukkit.inventory.EquipmentSlot.HAND)return;String[] parts=marker.split(":",2);if(parts.length!=2||!Set.of("clan","company").contains(parts[0]))return;try{String id=UUID.fromString(parts[1]).toString();organisations.openHomeNpc(event.getPlayer(),parts[0].equals("clan")?"clans":"companies",id,event.getRightClicked().getUniqueId());}catch(IllegalArgumentException ignored){}} @EventHandler public void scoreboardCommand(PlayerCommandPreprocessEvent e){String command=e.getMessage().trim();if(command.equalsIgnoreCase("/scoreboard")){e.setCancelled(true);toggleSidebar(e.getPlayer());}} -- 2.53.0 From 2f700ae7cc970cea76db02917f7a82df621d152d Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:35:14 +0100 Subject: [PATCH 4/4] Guard Arrakis chat cutover and keep private prompts out of relay --- .forgejo/workflows/dunechat.yml | 4 +++- tools/install-plugin-fleet.py | 41 ++++++++++++++++++++++++++++----- tools/plugin_dunechat.py | 34 +++++++++++++++++++++++++++ tools/plugin_fleet_rollback.py | 4 +++- tools/test_plugin_dunechat.py | 20 ++++++++++++++++ 5 files changed, 95 insertions(+), 8 deletions(-) create mode 100644 tools/plugin_dunechat.py create mode 100644 tools/test_plugin_dunechat.py diff --git a/.forgejo/workflows/dunechat.yml b/.forgejo/workflows/dunechat.yml index e69deb19..c474ed6a 100644 --- a/.forgejo/workflows/dunechat.yml +++ b/.forgejo/workflows/dunechat.yml @@ -29,10 +29,12 @@ jobs: run: | set -euo pipefail gradle --no-daemon -p DuneChat test jar + python3 tools/test_plugin_dunechat.py -v mkdir dunechat-artifacts cp DuneChat/build/libs/DuneChat.jar dunechat-artifacts/ + cp tools/{plugin_dunechat,install-plugin-fleet,write-plugin-manifest,plugin_menu_pack,plugin_backend_abi,plugin_fleet_rollback,plugin_pack_properties,plugin_pillager_abi}.py dunechat-artifacts/ printf '%s\n' "$(git rev-parse HEAD)" > dunechat-artifacts/SOURCE_COMMIT - (cd dunechat-artifacts && sha256sum -- *.jar SOURCE_COMMIT > SHA256SUMS) + (cd dunechat-artifacts && sha256sum -- *.jar *.py SOURCE_COMMIT > SHA256SUMS) - uses: actions/upload-artifact@v3 with: name: DuneRealms-DuneChat diff --git a/tools/install-plugin-fleet.py b/tools/install-plugin-fleet.py index 2862617a..3d845e48 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','lobby-account','arrakis-dunegroups'}: + 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','arrakis-dunegroups','arrakis-dunechat'}: raise ValueError('An explicit supported rollout mode is required') compact_menus=mode=='compact-menus' dunegroups=mode=='arrakis-dunegroups' + dunechat=mode=='arrakis-dunechat' lobby_food=mode=='lobby-food' lobby_account=mode=='lobby-account' jerboa=mode=='arrakis-jerboa' @@ -113,6 +114,12 @@ def plan(artifacts, inventory, expected_source): allowed_names={'JarvisTranslator','DuneGroups'} if inventory.get('menuPack') is not None or inventory.get('privatePrerequisites'): raise ValueError('DuneGroups must retain pack configuration and unrelated runtimes') + if dunechat: + from plugin_dunechat import verify_artifact + allowed_names={'DuneChat'} + if inventory.get('menuPack') is not None or inventory.get('privatePrerequisites'): + raise ValueError('DuneChat must retain pack configuration and unrelated runtimes') + verify_artifact(artifacts, expected_source) files, names = {}, set() for entry in manifest['plugins']: name = entry['filename'] @@ -179,7 +186,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 or lobby_account or dunegroups) 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 or dunegroups or dunechat) 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 @@ -195,6 +202,9 @@ def plan(artifacts, inventory, expected_source): if dunegroups and (sid != 'arrakis' or root != ARRAKIS_ROOT or unit != 'dune-arrakis.service' or wanted != {'jarvistranslator','dunegroups'} or selected_prerequisites): raise ValueError('DuneGroups canary requires the exact Arrakis service and approved plugin pair') + if dunechat and (sid != 'arrakis' or root != ARRAKIS_ROOT or unit != 'dune-arrakis.service' + or wanted != {'dunechat'} or selected_prerequisites): + raise ValueError('DuneChat canary requires the exact Arrakis service and standalone plugin') 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') @@ -407,6 +417,22 @@ def plan(artifacts, inventory, expected_source): 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 dunechat: + from plugin_dunechat import DISCORD_CONFIG, DISCORD_JAR, enable_modern_discord + discord = existing_paths.get('discordsrv') + if (discord is None or discord.name != 'DiscordSRV.jar' or digest(discord) != DISCORD_JAR + or not {'jarvistranslator', 'dunegroups'} <= existing_paths.keys() + or 'medievalfactions' in existing_paths or 'dunechat' in existing_paths): + raise ValueError('DuneChat requires the reviewed Discord relay, retained JARVIS and DuneGroups') + config = plugins/'DiscordSRV/config.yml' + if config.is_symlink() or config.parent.is_symlink() or digest(config) != DISCORD_CONFIG: + raise ValueError('Unexpected private Arrakis DiscordSRV config revision') + updated = enable_modern_discord(config.read_bytes().decode('utf-8')).encode('utf-8') + configurations.append({'path': 'DiscordSRV/config.yml', 'transform': 'enable-modern-discord', + 'sha256': hashlib.sha256(updated).hexdigest(), + 'previousSha256': DISCORD_CONFIG, 'previousMetadata': metadata(config)}) + retained = [{'filename': path.name, 'sha256': digest(path), 'metadata': metadata(path)} + for path in sorted(plugins.glob('*.jar'))] if dunegroups: from plugin_dunegroups import CONFIG_BASELINE, VENDORS, enable_backend, transition, verify_artifact incoming = {entry['name'].casefold(): entry for entry in chosen} @@ -537,11 +563,14 @@ def apply(deployment, backup_root, control=systemctl): target.parent.mkdir(parents=True, exist_ok=True) if new_parent: set_owner(target.parent, plugins.stat(), 0o750) - if config.get('transform') == 'enable-dunegroups': - from plugin_dunegroups import enable_backend + if config.get('transform') in {'enable-dunegroups', 'enable-modern-discord'}: + if config['transform'] == 'enable-dunegroups': + from plugin_dunegroups import enable_backend as update + else: + from plugin_dunechat import enable_modern_discord as update if digest(target) != config['previousSha256']: - raise ValueError('Private JARVIS config changed after service stop') - target.write_bytes(enable_backend(target.read_bytes().decode('utf-8')).encode('utf-8')) + raise ValueError('Private configuration changed after service stop') + target.write_bytes(update(target.read_bytes().decode('utf-8')).encode('utf-8')) restore_metadata(target, config['previousMetadata']) else: target.write_bytes(config['content'].encode()) diff --git a/tools/plugin_dunechat.py b/tools/plugin_dunechat.py new file mode 100644 index 00000000..d20296b7 --- /dev/null +++ b/tools/plugin_dunechat.py @@ -0,0 +1,34 @@ +"""Verify the DuneChat artifact and prepare the Arrakis public relay.""" + +import hashlib +import re + + +DISCORD_CONFIG = 'ea5460f59766315e47e343e0a6d88deb71232df065f7bde0074ab742c8f65b4d' +DISCORD_JAR = 'ef2fa1f2eb146c7c77412b7190a7dd33f1fc91282683fe45407739554c8aefef' + + +def enable_modern_discord(config): + setting = re.compile(r'(?m)^(UseModernPaperChatEvent:[ \t]*)false([ \t]*(?:#[^\r\n]*)?)(\r?\n)') + matches = list(setting.finditer(config)) + if len(matches) != 1 or len(re.findall(r'(?m)^UseModernPaperChatEvent\s*:', config)) != 1: + raise ValueError('Expected exactly one disabled modern Discord chat setting') + if re.search(r'(?m)^RespectChatPlugins\s*:', config): + raise ValueError('Discord cancellation policy differs from the reviewed config') + return setting.sub(r'\g<1>true\g<2>\g<3>RespectChatPlugins: true\g<3>', config) + + +def verify_artifact(artifact, source): + expected = { + 'DuneChat.jar', 'SOURCE_COMMIT', 'plugin_dunechat.py', 'install-plugin-fleet.py', + 'write-plugin-manifest.py', 'plugin_menu_pack.py', 'plugin_backend_abi.py', + 'plugin_fleet_rollback.py', 'plugin_pack_properties.py', 'plugin_pillager_abi.py', + } + lines = (artifact / 'SHA256SUMS').read_text().splitlines() + sums = dict(line.split(' ', 1)[::-1] for line in lines) + if len(lines) != len(sums) or sums.keys() != expected or any( + hashlib.sha256((artifact / name).read_bytes()).hexdigest() != sha for name, sha in sums.items() + ): + raise ValueError('Unexpected DuneChat archive manifest') + if (artifact / 'SOURCE_COMMIT').read_text().strip() != source: + raise ValueError('DuneChat archive source differs from the selected commit') diff --git a/tools/plugin_fleet_rollback.py b/tools/plugin_fleet_rollback.py index 4e52a532..7734702e 100644 --- a/tools/plugin_fleet_rollback.py +++ b/tools/plugin_fleet_rollback.py @@ -56,7 +56,9 @@ def rollback_receipt(receipt_path, expected_source, apply=False, run=control, le relative=entry['path'] private_jarvis = (relative == 'JarvisTranslator/config.yml' and entry.get('transform') == 'enable-dunegroups' and server['id'] == 'arrakis' and root == Path('/opt/dunerealms/servers/arrakis')) - if relative not in ('MCGUI/config.yml','DunerealmsGUI/menu-pack.yml') and not private_jarvis: + private_discord = (relative == 'DiscordSRV/config.yml' and entry.get('transform') == 'enable-modern-discord' + and server['id'] == 'arrakis' and root == Path('/opt/dunerealms/servers/arrakis')) + if relative not in ('MCGUI/config.yml','DunerealmsGUI/menu-pack.yml') and not (private_jarvis or private_discord): raise ValueError('Unsafe rollback configuration path') current=plugins/relative if current.is_symlink() or current.parent.is_symlink():raise ValueError('Symlinked rollback configuration') diff --git a/tools/test_plugin_dunechat.py b/tools/test_plugin_dunechat.py new file mode 100644 index 00000000..d3fd3a96 --- /dev/null +++ b/tools/test_plugin_dunechat.py @@ -0,0 +1,20 @@ +import unittest + +from plugin_dunechat import enable_modern_discord + + +class DiscordConfigTest(unittest.TestCase): + def test_only_the_two_reviewed_settings_change(self): + source = 'Channels: {}\r\nUseModernPaperChatEvent: false # Paper\r\nBotToken: example\r\n' + expected = source.replace('false # Paper\r\n', 'true # Paper\r\nRespectChatPlugins: true\r\n') + self.assertEqual(enable_modern_discord(source), expected) + + def test_unexpected_settings_are_rejected(self): + for source in ('UseModernPaperChatEvent: true\n', + 'UseModernPaperChatEvent: false\nRespectChatPlugins: false\n'): + with self.subTest(source=source), self.assertRaises(ValueError): + enable_modern_discord(source) + + +if __name__ == '__main__': + unittest.main() -- 2.53.0