diff --git a/CHANGELOG.md b/CHANGELOG.md index c22ef93..e6c1b12 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 0.6.0 + +- **Adults' words masked for kids** (D233, D235). A new `mask-for-viewers` setting in `filter.yml`, off by default. With it on, a player with `mayor.filter.bypass` writes freely, and anyone without the bypass sees each blocked word as `****` in that player's chat and private messages, while players with the bypass see them as written. A player without the bypass counts as filtered, so one whose permissions aren't known yet is filtered too. +- Filtered players get their own copy of the chat line, rendered the same way. A signed chat message carries its original words even when it's displayed differently, so changing only how it looks wasn't enough. +- Signs, books and item names are stored once for everyone, so with the setting on an adult's blocked words in them are saved as `****`. Showing them per viewer is planned. +- Players without the bypass are still stopped and told kindly when they use a blocked word, as before. +- Tested: 48 unit tests, 6 of them new, and on throwaway Paper 26.3 with bots 75/75 live checks, 8 of them new. Signs and anvil renames weren't tested, and it hasn't been seen in a real game client. + ## 0.5.0 - **A new name: Mayor** (D198). The mayor sets how folks in town talk to each other. How it works is unchanged. As the owner asked (D196), no old names are kept: the package, plugin, jar, commands, permissions and data folder all use Mayor. diff --git a/README.md b/README.md index cc36ea4..f68fed5 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Chat rules for family and community Paper servers. Players hear people in the same world, plus anyone who shares a "circle" with them, so groups such as families or age groups keep their own conversations across every world. -**Status:** pre-release. It passes its acceptance tests on throwaway Paper 26.2 and 26.3 servers, using protocol bots with LuckPerms: chat and private messages for every pair of players, replies, blocked commands, the word filter and its bypass, books, `/circles`, reloads, a broken config, and 20 bots chatting at once. BlueMapMini's share was tested with a stand-in plugin here; the real BlueMapMini 0.3.0 and Mayor 0.5.0 haven't been run together yet. Signs and anvil renames weren't tested. It hasn't been seen in a real game client yet, so the wording and colours haven't been checked by a person. See [the live tests](test/live/README.md) and the [test audit](docs/test-audit.md). +**Status:** pre-release. It passes its acceptance tests on throwaway Paper 26.2 and 26.3 servers, using protocol bots with LuckPerms: chat and private messages for every pair of players, replies, blocked commands, the word filter and its bypass, masking adults' words for kids, books, `/circles`, reloads, a broken config, and 20 bots chatting at once. BlueMapMini's share was tested with a stand-in plugin here; the real BlueMapMini 0.3.0 and Mayor 0.5.0 haven't been run together yet. Signs and anvil renames weren't tested. It hasn't been seen in a real game client yet, so the wording and colours haven't been checked by a person. See [the live tests](test/live/README.md) and the [test audit](docs/test-audit.md). - Requires Paper 26.1 or newer and Java 25. Paper 1.21.11 and older aren't supported. - With no circles set up it changes nothing about who hears whom, so it's safe to install first and configure after. @@ -28,7 +28,9 @@ Otherwise they can't. A world group is a world with its Nether and End (`surviva **Blocked commands.** Any command can be turned off, each with its own message. `sort` also blocks `anyplugin:sort`, in any letter case. -**Word filter.** `filter.yml` lists words and phrases to keep out of chat, private messages, signs, books and item names. It matches whole words, so "class" and "Scunthorpe" are fine, and it sees through `sh1t`, `$` for s and stretched letters. Spaced-out spellings get through. Blocked text is never logged or stored: the player is told kindly and can try again. Players with `mayor.filter.bypass`, such as an adults-only group, aren't filtered anywhere. +**Word filter.** `filter.yml` lists words and phrases to keep out of chat, private messages, signs, books and item names. It matches whole words, so "class" and "Scunthorpe" are fine, and it sees through `sh1t`, `$` for s and stretched letters. Spaced-out spellings get through. Blocked text is never logged or stored: the player is told kindly and can try again. Players with `mayor.filter.bypass`, such as an adults group, aren't filtered anywhere. + +**Masking for kids.** Where adults and kids play together, set `mask-for-viewers: true` in `filter.yml`. Adults (players with `mayor.filter.bypass`) write freely, and everyone else sees each blocked word in their chat and private messages as `****`, while other adults see it as written. A player without the bypass counts as filtered, so a new account is masked until someone adds it to the adults group. Signs, books and item names are stored once for everyone, so an adult's blocked words in them are saved as `****`. **Nobody heard you.** If you chat and nobody online can hear you, you get a light-hearted note, such as "A squid nods politely. It didn't understand a word." There are 75 in `quips.yml`, and you see them all before any comes round again. At most one every 3 minutes. @@ -65,7 +67,7 @@ Every `/mayor` command also takes `--json ` at the end, for scripts and the | `mayor.circles` | everyone | `/circles`. | | `mayor.circles.names` | everyone | Names in `/circles`. Without it, only a count. | | `mayor.bypass` | nobody, ops included | Reaching and being reached by everyone, for moderators. It doesn't show anyone else's chat. | -| `mayor.filter.bypass` | nobody, ops included | Skipping the word filter everywhere it applies, for adult groups. It doesn't change who hears whom. | +| `mayor.filter.bypass` | nobody, ops included | Skipping the word filter everywhere it applies, for adult groups. It doesn't change who hears whom. With `mask-for-viewers` on, it's also what lets a player read other adults' words as written. | | `mayor.admin` | ops | `/mayor`, and config warnings on joining. | ## For other plugins diff --git a/build.gradle.kts b/build.gradle.kts index a94386d..7f86ac7 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -4,7 +4,7 @@ plugins { } group = "com.extantape" -version = "0.5.0" +version = "0.6.0" java { toolchain.languageVersion.set(JavaLanguageVersion.of(25)) diff --git a/docs/test-audit.md b/docs/test-audit.md index 7fc660c..5ae638e 100644 --- a/docs/test-audit.md +++ b/docs/test-audit.md @@ -53,3 +53,9 @@ Each promise in the README, and the test that holds it to it. "Live" is `test/li **Skipped, with reasons:** - Sign text and anvil renames: bots can't place and edit signs or use an anvil. They're on the real-client list. - `ReachService` "safe from any thread": it reads the rules from one snapshot that a reload swaps in whole (a `volatile` field with `final` contents), plus the two players' own permissions and world, the same reads async chat already makes. A dedicated concurrency test would be overkill; the live load test exercises the same path from the async chat thread with 20 bots. + + +## 2026-11-16: masking for kids (0.6.0, D233, D235) + +- **Covered:** `WordFilter.mask` (only blocked words change, phrases masked whole, the allow list, spacing kept, the mask length gives nothing away, nothing blocked gives the same text), the setting off by default and read from `filter.yml`, private messages adult to kid masked and adult to adult as written, kids still stopped. Live on 26.3: chat masked for a player without the bypass and as written for one with it, private messages both ways, clean text unchanged, a kid's own word still stopped, an adult's book saved masked (read back from the server). +- **Skipped:** signs and anvil renames, for the same reason as before (bots can't). Item names and signs share the masking code with books. Live 26.2 wasn't rerun; the change uses no version-specific API. diff --git a/src/main/java/com/extantape/mayor/config/Settings.java b/src/main/java/com/extantape/mayor/config/Settings.java index ba7f673..b36cfd4 100644 --- a/src/main/java/com/extantape/mayor/config/Settings.java +++ b/src/main/java/com/extantape/mayor/config/Settings.java @@ -23,7 +23,7 @@ public String filterSummary() { } /** Which kinds of text the word filter checks. */ - public record Filtered(boolean chat, boolean messages, boolean signs, boolean books, boolean itemNames) { + public record Filtered(boolean chat, boolean messages, boolean signs, boolean books, boolean itemNames, boolean maskForViewers) { } /** The note players get when nobody could hear their chat. */ diff --git a/src/main/java/com/extantape/mayor/config/SettingsLoader.java b/src/main/java/com/extantape/mayor/config/SettingsLoader.java index a45e7c6..bd4748b 100644 --- a/src/main/java/com/extantape/mayor/config/SettingsLoader.java +++ b/src/main/java/com/extantape/mayor/config/SettingsLoader.java @@ -139,14 +139,15 @@ public Result load(String config, String filterText, String quips) { WordFilter filter = filterOn ? WordFilter.of(strings(FILTER, words, "words"), strings(FILTER, words, "allow")) : WordFilter.NONE; Settings.Filtered filtered = new Settings.Filtered( bool(FILTER, words, "check.chat", true), bool(FILTER, words, "check.private-messages", true), - bool(FILTER, words, "check.signs", true), bool(FILTER, words, "check.books", true), bool(FILTER, words, "check.item-names", true)); + bool(FILTER, words, "check.signs", true), bool(FILTER, words, "check.books", true), bool(FILTER, words, "check.item-names", true), + bool(FILTER, words, "mask-for-viewers", false)); List quipList = new ArrayList<>(); for (String note : strings(QUIPS, notes, "notes")) if (!note.isBlank()) quipList.add(note); if (nobodyHeard.enabled() && quipList.isEmpty()) warnings.add(QUIPS + ": there are no notes, so nobody-heard stays quiet."); Reach reach = new Reach(circles, circleOnly, groupOf, suffixes); - CommandRules commands = new CommandRules(reach, filter, filtered.messages(), + CommandRules commands = new CommandRules(reach, filter, filtered.messages(), filtered.maskForViewers(), Set.copyOf(strings(CONFIG, base, "private-message-commands")), Set.copyOf(strings(CONFIG, base, "reply-commands")), Set.copyOf(strings(CONFIG, base, "broadcast-commands")), blocked); if (!errors.isEmpty()) return new Result(null, List.copyOf(errors), List.copyOf(warnings)); diff --git a/src/main/java/com/extantape/mayor/listen/ChatListener.java b/src/main/java/com/extantape/mayor/listen/ChatListener.java index 0d4d5fc..c410e9e 100644 --- a/src/main/java/com/extantape/mayor/listen/ChatListener.java +++ b/src/main/java/com/extantape/mayor/listen/ChatListener.java @@ -6,7 +6,10 @@ import com.extantape.mayor.rules.Subject; import com.extantape.mayor.rules.WordFilter; import com.extantape.mayor.text.Messages; +import io.papermc.paper.chat.ChatRenderer; import io.papermc.paper.event.player.AsyncChatEvent; +import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.text.Component; import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; import org.bukkit.Bukkit; import org.bukkit.entity.Player; @@ -14,6 +17,8 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; +import java.util.ArrayList; +import java.util.List; import java.util.Map; /** Public chat goes only to the players the speaker can reach. Runs on the async chat thread and never blocks it. */ @@ -56,4 +61,36 @@ public void onChat(AsyncChatEvent event) { // A tick later, so the note shows under the player's own line. if (note != null) Bukkit.getScheduler().runTask(plugin, () -> from.sendMessage(Messages.parse(note, Map.of()))); } + + /** + * With mask-for-viewers on, an unfiltered speaker's blocked words reach filtered players as ****, and everyone + * with the bypass sees the line as written. A player without the bypass, including one whose permissions aren't + * known, counts as filtered. The console sees it as written. + * + * Runs last, once nothing else will cancel the line or change who hears it. Filtered players are taken off the + * line's viewers and sent their own copy, rendered the same way with the masked text. A signed chat message + * carries the original words even when it's displayed differently, so it isn't enough to change the rendering. + */ + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void maskForViewers(AsyncChatEvent event) { + MayorPlugin.State state = plugin.state(); + if (state == null) return; + Settings settings = state.settings(); + Player from = event.getPlayer(); + if (!settings.filtered().chat() || !settings.filtered().maskForViewers() || !from.hasPermission(WordFilter.BYPASS)) return; + String plain = PlainTextComponentSerializer.plainText().serialize(event.message()); + String masked = settings.filter().mask(plain); + if (masked.equals(plain)) return; + Component hidden = Component.text(masked); + ChatRenderer renderer = event.renderer(); + List filtered = new ArrayList<>(); + for (Audience viewer : event.viewers()) if (viewer instanceof Player p && !seesAsWritten(p)) filtered.add(p); + if (filtered.isEmpty()) return; + event.viewers().removeAll(filtered); + for (Player p : filtered) p.sendMessage(renderer.render(from, from.displayName(), hidden, p)); + } + + static boolean seesAsWritten(Audience viewer) { + return !(viewer instanceof Player p) || p.hasPermission(WordFilter.BYPASS); + } } diff --git a/src/main/java/com/extantape/mayor/listen/CommandListener.java b/src/main/java/com/extantape/mayor/listen/CommandListener.java index 500be95..7e3ce3b 100644 --- a/src/main/java/com/extantape/mayor/listen/CommandListener.java +++ b/src/main/java/com/extantape/mayor/listen/CommandListener.java @@ -49,6 +49,7 @@ public void onCommand(PlayerCommandPreprocessEvent event) { } else plugin.tell(from, decision.key(), decision.vars()); } case DELIVER -> { + if (decision.rewrite() != null) event.setMessage(decision.rewrite()); UUID to = decision.partner().id(); plugin.partners().put(from.getUniqueId(), to); plugin.partners().put(to, from.getUniqueId()); diff --git a/src/main/java/com/extantape/mayor/listen/TextListener.java b/src/main/java/com/extantape/mayor/listen/TextListener.java index b785c73..9fd5bf0 100644 --- a/src/main/java/com/extantape/mayor/listen/TextListener.java +++ b/src/main/java/com/extantape/mayor/listen/TextListener.java @@ -46,6 +46,13 @@ public void onSign(SignChangeEvent event) { if (refusal != null) { event.setCancelled(true); plugin.tell(event.getPlayer(), refusal); + return; + } + WordFilter mask = masker(event.getPlayer(), Settings.Filtered::signs); + if (mask == null) return; + for (int i = 0; i < lines.size(); i++) { + String masked = mask.mask(lines.get(i)); + if (!masked.equals(lines.get(i))) event.line(i, Component.text(masked)); } } @@ -59,7 +66,28 @@ public void onBook(PlayerEditBookEvent event) { if (refusal != null) { event.setCancelled(true); plugin.tell(event.getPlayer(), refusal); + return; + } + WordFilter mask = masker(event.getPlayer(), Settings.Filtered::books); + if (mask == null) return; + boolean changed = false; + List pages = new ArrayList<>(); + List plainPages = new ArrayList<>(); + for (Component page : book.pages()) { + String plain = PLAIN.serialize(page), masked = mask.mask(plain); + changed |= !masked.equals(plain); + pages.add(masked.equals(plain) ? page : Component.text(masked)); + plainPages.add(masked); } + if (event.isSigning() && book.hasTitle()) { + String plain = PLAIN.serialize(book.title()), masked = mask.mask(plain); + if (!masked.equals(plain)) { book.title(Component.text(masked)); changed = true; } + } + if (!changed) return; + // An unsigned book keeps plain-text pages; a signed one keeps formatted pages. + if (event.isSigning()) book.pages(pages); + else book.setPages(plainPages); + event.setNewBookMeta(book); } @EventHandler(priority = EventPriority.HIGH) @@ -68,7 +96,18 @@ public void onAnvil(PrepareAnvilEvent event) { String name = view.getRenameText(); if (event.getResult() == null || name == null || name.isBlank() || !(view.getPlayer() instanceof Player player)) return; String refusal = refusal(player, List.of(name), Settings.Filtered::itemNames, "filtered-item-name"); - if (refusal == null) return; + if (refusal == null) { + WordFilter mask = masker(player, Settings.Filtered::itemNames); + String masked = mask == null ? name : mask.mask(name); + if (masked.equals(name)) return; + org.bukkit.inventory.ItemStack result = event.getResult().clone(); + org.bukkit.inventory.meta.ItemMeta meta = result.getItemMeta(); + if (meta == null) return; + meta.customName(Component.text(masked)); + result.setItemMeta(meta); + event.setResult(result); + return; + } event.setResult(null); long now = System.currentTimeMillis(); Long last = anvilNotes.get(player.getUniqueId()); @@ -78,6 +117,19 @@ public void onAnvil(PrepareAnvilEvent event) { } } + /** + * With mask-for-viewers on, signs, books and item names are stored once for everyone, so an unfiltered writer's + * blocked words are saved as **** and filtered players never see them. Returns the filter to mask with, or null + * when nothing should change. + */ + private WordFilter masker(Player player, java.util.function.Predicate check) { + MayorPlugin.State state = plugin.state(); + if (state == null) return null; + Settings settings = state.settings(); + if (!settings.filtered().maskForViewers() || !check.test(settings.filtered()) || !player.hasPermission(WordFilter.BYPASS)) return null; + return settings.filter(); + } + /** The message key explaining why this text can't be written, or null if it's fine. */ private String refusal(Player player, List text, java.util.function.Predicate check, String filteredKey) { MayorPlugin.State state = plugin.state(); diff --git a/src/main/java/com/extantape/mayor/rules/CommandRules.java b/src/main/java/com/extantape/mayor/rules/CommandRules.java index 132cc5e..7ff3c27 100644 --- a/src/main/java/com/extantape/mayor/rules/CommandRules.java +++ b/src/main/java/com/extantape/mayor/rules/CommandRules.java @@ -25,21 +25,23 @@ public enum Kind { PASS, BLOCK, DELIVER } /** * The outcome. For BLOCK, either {@code key} names a message in messages, or {@code text} is the message itself. - * For DELIVER, {@code partner} is who the message goes to, remembered for replies. + * For DELIVER, {@code partner} is who the message goes to, remembered for replies, and {@code rewrite}, when not + * null, is the command line to run instead: the same message with blocked words masked, because an unfiltered + * player is writing to a filtered one. */ - public record Decision(Kind kind, String key, String text, Map vars, Subject partner) { - static final Decision PASS = new Decision(Kind.PASS, null, null, Map.of(), null); + public record Decision(Kind kind, String key, String text, Map vars, Subject partner, String rewrite) { + static final Decision PASS = new Decision(Kind.PASS, null, null, Map.of(), null, null); static Decision block(String key, Map vars) { - return new Decision(Kind.BLOCK, key, null, vars, null); + return new Decision(Kind.BLOCK, key, null, vars, null, null); } static Decision blockText(String text) { - return new Decision(Kind.BLOCK, null, text, Map.of(), null); + return new Decision(Kind.BLOCK, null, text, Map.of(), null, null); } - static Decision deliver(Subject partner) { - return new Decision(Kind.DELIVER, null, null, Map.of(), partner); + static Decision deliver(Subject partner, String rewrite) { + return new Decision(Kind.DELIVER, null, null, Map.of(), partner, rewrite); } public boolean blocked() { @@ -50,16 +52,18 @@ public boolean blocked() { private final Reach reach; private final WordFilter filter; private final boolean filterMessages; + private final boolean maskForViewers; private final Set messageCommands; private final Set replyCommands; private final Set broadcastCommands; private final List blocked; - public CommandRules(Reach reach, WordFilter filter, boolean filterMessages, Set messageCommands, + public CommandRules(Reach reach, WordFilter filter, boolean filterMessages, boolean maskForViewers, Set messageCommands, Set replyCommands, Set broadcastCommands, List blocked) { this.reach = reach; this.filter = filter; this.filterMessages = filterMessages; + this.maskForViewers = maskForViewers; this.messageCommands = lower(messageCommands); this.replyCommands = lower(replyCommands); this.broadcastCommands = lower(broadcastCommands); @@ -96,7 +100,8 @@ public Decision decide(Subject from, String line, boolean paused, Function= args.length || !sender.has(WordFilter.BYPASS) || to.has(WordFilter.BYPASS)) return null; + String text = String.join(" ", Arrays.copyOfRange(args, from, args.length)); + String masked = filter.mask(text); + return masked.equals(text) ? null : masked; + } + + private static String slash(String line) { + return line.startsWith("/") ? "/" : ""; + } + static boolean matches(Set entries, String label) { if (entries.contains(label)) return true; int colon = label.indexOf(':'); diff --git a/src/main/java/com/extantape/mayor/rules/WordFilter.java b/src/main/java/com/extantape/mayor/rules/WordFilter.java index 752320f..b4eb2c0 100644 --- a/src/main/java/com/extantape/mayor/rules/WordFilter.java +++ b/src/main/java/com/extantape/mayor/rules/WordFilter.java @@ -6,6 +6,7 @@ import java.util.List; import java.util.Locale; import java.util.Set; +import java.util.regex.Matcher; import java.util.regex.Pattern; /** @@ -19,6 +20,10 @@ public final class WordFilter { public static final WordFilter NONE = new WordFilter(List.of(), Set.of()); private static final Pattern SPLIT = Pattern.compile("[^\\p{L}\\p{N}@$]+"); private static final Pattern MARKS = Pattern.compile("\\p{M}+"); + /** The same words {@link #SPLIT} leaves between its separators, with their places in the text. */ + private static final Pattern WORD = Pattern.compile("[\\p{L}\\p{N}@$]+"); + /** What a blocked word becomes, whatever its length, so the length gives nothing away. */ + public static final String MASK = "****"; private final List> phrases; private final Set allow; @@ -67,6 +72,49 @@ public boolean flags(String text) { return false; } + /** + * The text with every blocked word or phrase replaced by {@link #MASK}, and everything else left exactly as + * written. Text with nothing blocked comes back unchanged. Used to show an adult's words to players who are + * filtered. + */ + public String mask(String text) { + if (phrases.isEmpty() || text == null || text.isBlank()) return text; + List spans = new ArrayList<>(); + List tokens = new ArrayList<>(); + Matcher m = WORD.matcher(text); + while (m.find()) { + String token = normalize(m.group()); + if (token.isEmpty()) continue; + spans.add(new int[]{m.start(), m.end()}); + tokens.add(token); + } + boolean[] hit = new boolean[tokens.size()]; + boolean any = false; + for (int start = 0; start < tokens.size(); start++) { + for (List phrase : phrases) { + if (start + phrase.size() > tokens.size()) continue; + boolean match = true; + for (int i = 0; i < phrase.size() && match; i++) { + String token = tokens.get(start + i); + match = !allow.contains(token) && phrase.get(i).matcher(token).matches(); + } + if (match) { + for (int i = 0; i < phrase.size(); i++) hit[start + i] = true; + any = true; + } + } + } + if (!any) return text; + StringBuilder out = new StringBuilder(text.length()); + int at = 0; + for (int i = 0; i < spans.size(); i++) { + if (!hit[i]) continue; + out.append(text, at, spans.get(i)[0]).append(MASK); + at = spans.get(i)[1]; + } + return out.append(text.substring(at)).toString(); + } + static List tokens(String text) { List out = new ArrayList<>(); for (String raw : SPLIT.split(text)) { diff --git a/src/main/resources/filter.yml b/src/main/resources/filter.yml index 20a6327..66d2327 100644 --- a/src/main/resources/filter.yml +++ b/src/main/resources/filter.yml @@ -13,6 +13,11 @@ # This list is a starting point. Change it to suit your players. enabled: true +# Where adults and kids play together: players with mayor.filter.bypass write freely, and everyone without it +# sees their blocked words as ****, in chat and private messages. Signs, books and item names are saved masked +# for everyone. A player without the bypass counts as filtered. +mask-for-viewers: false + check: chat: true private-messages: true diff --git a/src/test/java/com/extantape/mayor/config/SettingsLoaderTest.java b/src/test/java/com/extantape/mayor/config/SettingsLoaderTest.java index 9b8af6c..25e21d6 100644 --- a/src/test/java/com/extantape/mayor/config/SettingsLoaderTest.java +++ b/src/test/java/com/extantape/mayor/config/SettingsLoaderTest.java @@ -74,4 +74,12 @@ void messagesOverrideDefaults() { void filterCanBeTurnedOff() { assertTrue(load(null, "enabled: false", null).settings().filter().isEmpty()); } + + @Test + void maskForViewersIsOffByDefaultAndReadFromFilterYml() { + assertFalse(load(null, null, null).settings().filtered().maskForViewers()); + SettingsLoader.Result on = load(null, "words: [heck]\nmask-for-viewers: true\n", null); + assertTrue(on.ok(), on.errors().toString()); + assertTrue(on.settings().filtered().maskForViewers()); + } } diff --git a/src/test/java/com/extantape/mayor/rules/CommandRulesTest.java b/src/test/java/com/extantape/mayor/rules/CommandRulesTest.java index 630f3c7..c627645 100644 --- a/src/test/java/com/extantape/mayor/rules/CommandRulesTest.java +++ b/src/test/java/com/extantape/mayor/rules/CommandRulesTest.java @@ -16,7 +16,7 @@ class CommandRulesTest { private final Reach reach = new Reach(List.of("red"), Set.of("hall"), Map.of(), List.of("_nether")); - private final CommandRules rules = new CommandRules(reach, WordFilter.of(List.of("heck"), List.of()), true, + private final CommandRules rules = new CommandRules(reach, WordFilter.of(List.of("heck"), List.of()), true, false, Set.of("msg", "tell", "w"), Set.of("r", "reply"), Set.of("me"), List.of(new CommandRules.Blocked(Set.of("/Sort", "other:only"), "Sorting stays on."))); private final Map online = new HashMap<>(); @@ -110,4 +110,34 @@ void pausedBlocksMessagesButNotOtherCommands() { assertEquals(CommandRules.Kind.PASS, rules.decide(alex, "/spawn", true, n -> null, null, id -> null).kind()); assertNull(rules.decide(alex, "/spawn", true, n -> null, null, id -> null).key()); } + + // D230: where adults and kids play together, an adult's message reaches a kid with blocked words masked, and an adult as written. + private final CommandRules masking = new CommandRules(new Reach(List.of(), Set.of(), Map.of(), List.of()), + WordFilter.of(List.of("heck"), List.of()), true, true, Set.of("msg", "tell"), Set.of("r"), Set.of(), List.of()); + + private CommandRules.Decision mask(Subject from, String line, UUID partner) { + return masking.decide(from, line, false, n -> online.get(n.toLowerCase()), partner, + id -> online.values().stream().filter(s -> s.id().equals(id)).findFirst().orElse(null)); + } + + @Test + void adultToKidIsMaskedAdultToAdultIsNot() { + Subject adult = add(player("Adult", "forest", WordFilter.BYPASS)); + Subject adult2 = add(player("Adult2", "forest", WordFilter.BYPASS)); + Subject kid = add(player("Kid", "forest")); + CommandRules.Decision d = mask(adult, "/msg Kid what the heck now", null); + assertEquals(CommandRules.Kind.DELIVER, d.kind()); + assertEquals("/msg Kid what the **** now", d.rewrite()); + assertEquals("/r what the ****", mask(adult, "/r what the heck", kid.id()).rewrite()); + assertNull(mask(adult, "/msg Adult2 what the heck", null).rewrite(), "an adult reads it as written"); + assertNull(mask(adult, "/msg Kid hello", null).rewrite(), "nothing blocked, nothing changed"); + assertEquals("filtered-message", mask(kid, "/msg Adult heck", null).key(), "kids are still stopped, as before"); + } + + @Test + void maskingIsOffUnlessTurnedOn() { + Subject adult = add(player("Adult", "forest", WordFilter.BYPASS)); + add(player("Kid", "forest")); + assertNull(run(adult, "/msg Kid heck").rewrite()); + } } diff --git a/src/test/java/com/extantape/mayor/rules/WordFilterTest.java b/src/test/java/com/extantape/mayor/rules/WordFilterTest.java index a696bf8..24af831 100644 --- a/src/test/java/com/extantape/mayor/rules/WordFilterTest.java +++ b/src/test/java/com/extantape/mayor/rules/WordFilterTest.java @@ -5,6 +5,7 @@ import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -70,4 +71,28 @@ private static WordFilter defaults() { var settings = new SettingsLoader(n -> SettingsLoader.class.getResourceAsStream("/" + n)).load(null, null, null).settings(); return settings.filter(); } + + @Test + void maskHidesOnlyBlockedWordsAndKeepsTheRest() { + assertEquals("you ****!", small.mask("you ass!")); + assertEquals("**** it, ****", small.mask("Darned it, H3CK")); + assertEquals("well **** **** **** then", small.mask("well go away now then"), "every word of a phrase"); + assertEquals("a first class pass", small.mask("a first class pass")); + assertEquals("darnation stays", small.mask("darnation stays"), "the allow list"); + assertEquals(" **** spaced ", small.mask(" @sss spaced "), "spacing is kept"); + assertEquals("**** and ****", small.mask("hééck and heck")); + } + + @Test + void maskLengthGivesNothingAway() { + assertEquals(small.mask("ass"), small.mask("asssssssss")); + } + + @Test + void maskWithNothingBlockedIsTheSameText() { + String s = "nothing to see"; + assertEquals(s, small.mask(s)); + assertEquals(s, WordFilter.NONE.mask(s)); + assertEquals("", small.mask("")); + } } diff --git a/test/live/README.md b/test/live/README.md index 125d974..64cd13b 100644 --- a/test/live/README.md +++ b/test/live/README.md @@ -43,6 +43,7 @@ It takes about 4 minutes. The summary lists failures and skipped checks. The ful | Commands | Blocked commands in plain, namespaced and mixed-case forms, unlisted ones passing, `/me` off except with bypass. | | Replies | `/r` with nobody to reply to, and after the other player moves out of reach. | | Word filter | Chat and private messages with a blocked word aren't delivered; "Scunthorpe has a classic assassin" is. | +| Masking for kids | With `mask-for-viewers` on, an adult's blocked word reaches a player without the bypass as `****` in chat and private messages and as written to another adult; clean text is unchanged; a kid's own blocked word is still stopped; an adult's book is saved masked (checked on the server, since the bot sees only its own copy). | | Filter bypass | Granted with LuckPerms, a player's chat and private messages aren't filtered while another player's still are; removed, they're filtered again straight away, with no relog. | | Books | A clean edit is kept; a filtered one, or one in a circle-only world with no circle, is refused with an explanation. A filtered word is kept for a player with `mayor.filter.bypass`. | | Nobody heard you | A note from `quips.yml`, a different one next time, and none when someone heard. | diff --git a/test/live/suite.js b/test/live/suite.js index 06ad4df..ab230f1 100644 --- a/test/live/suite.js +++ b/test/live/suite.js @@ -195,6 +195,49 @@ async function filter() { check('removing it filters again straight away', !bots.R2.heard('sh1t again', k) && bots.R1.heard("a word we don't use here", told)); } +async function maskForViewers() { + section('D230: an adult\'s blocked words reach filtered players as **** (mask-for-viewers)'); + const fpath = s.path('plugins/Mayor/filter.yml'); + const before = fs.readFileSync(fpath, 'utf8'); + fs.writeFileSync(fpath, before.replace(/\s*$/, '\n') + 'mask-for-viewers: true\n'); + const r = await reload(); + check('reload with mask-for-viewers on', r && /Reloaded/.test(r[0]), r && r[0]); + await lp('user R1 permission set mayor.filter.bypass true'); + try { + let k = bots.R2.mark(); bots.R1.say('what the fuk now'); await sleep(1200); + check('a filtered player (no bypass, as an unknown one) sees the word as ****', bots.R2.heard('what the **** now', k) && !bots.R2.heard('fuk', k), bots.R2.lines(k)); + k = bots.R2.mark(); bots.R1.say('Scunthorpe stays whole'); await sleep(1200); + check('clean text from an adult is unchanged', bots.R2.heard('Scunthorpe stays whole', k), bots.R2.lines(k)); + k = bots.R2.mark(); bots.R1.say('/msg R2 oh fuk it'); await sleep(1200); + check('an adult\'s private message reaches a filtered player masked', bots.R2.heard('oh **** it', k) && !bots.R2.heard('fuk', k), bots.R2.lines(k)); + await lp('user R2 permission set mayor.filter.bypass true'); + k = bots.R2.mark(); bots.R1.say('fuk again, adults'); await sleep(1200); + check('another adult sees it as written', bots.R2.heard('fuk again, adults', k), bots.R2.lines(k)); + k = bots.R2.mark(); bots.R1.say('/msg R2 fuk between adults'); await sleep(1200); + check('an adult\'s private message to an adult is as written', bots.R2.heard('fuk between adults', k), bots.R2.lines(k)); + await lp('user R2 permission unset mayor.filter.bypass'); + k = bots.R1.mark(); const own = bots.R2.mark(); bots.R2.say('fuk from a kid'); await sleep(1200); + check('a filtered player\'s own blocked word is still stopped and explained', !bots.R1.heard('from a kid', k) && bots.R2.heard("a word we don't use here", own), bots.R2.lines(own)); + // Books are stored once for everyone, so an adult's blocked word is saved as ****. + await s.run('mt give R1 writable_book', /HRT give/); + for (let i = 0; i < 40 && !bots.R1.bot.inventory.slots[36]; i++) await sleep(100); + try { + await Promise.race([bots.R1.bot.writeBook(36, ['a fuk book']).catch(() => {}), sleep(2500)]); + await sleep(3000); + // The bot only sees its own copy, so ask the server what it saved. + const saved = await s.run('data get entity R1 Inventory[{Slot:0b}]', /R1 has the following entity data: [^\n]*/, 10000); + const text = saved ? saved[0] : ''; + if (!saved) skip('an adult\'s book is saved masked', 'the server did not report the book'); + else check('an adult\'s book is saved masked', text.includes('a **** book') && !text.includes('fuk'), text.slice(0, 200)); + } catch (e) { skip('an adult\'s book is saved masked', 'the bot could not edit a book: ' + e.message); } + } finally { + await lp('user R1 permission unset mayor.filter.bypass'); + await lp('user R2 permission unset mayor.filter.bypass'); + fs.writeFileSync(fpath, before); + await reload(); + } +} + async function writing() { section('Signs, books and item names'); // Book: give a writable book and edit it, as the client does. @@ -384,6 +427,7 @@ async function pausedOnBrokenStart() { await blockedCommands(); await replies(); await filter(); + await maskForViewers(); await writing(); await nobodyHeard(); await share();