diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9c3f1ea..552c058 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,28 @@
# Changelog
+## 0.11.3
+
+- **Read this before upgrading with home worlds on: an adult circle with no entry becomes restricted until it gets `unlimited: true`.** Before, a player in any circle without an entry was never moved.
+- **Every circle has its own setting.** An entry lists `worlds`, or says `unlimited: true` for no limits. A player in any unlimited circle has no limits. Anyone else may be in every world listed by any of their circles. A circle with no entry adds nothing and lifts nothing, so putting a kid in a new circle can't free them. A player whose circles all add nothing is treated like a player in no circle. An entry with both keys, neither, `unlimited` set to anything but `true`, an empty or unreadable `worlds`, or a circle written twice adds nothing and is named in a warning. Most of those were config errors before. A section with only such entries stays on. `no-circle` always needs `worlds` and can't be unlimited. Startup and reload name every circle with no entry, and `/posse status` (also with `--json`, under `settings`) shows each circle's setting. `config.yml` has a commented example.
+- **Home worlds now sends players only to the lobby.** A player found outside the worlds their group may be in, on join, respawn or world change, goes to the server's lobby only if it's named, loaded and in their group's worlds (the `no-circle` list for players in no circle). Otherwise they're disconnected with "Sorry, we couldn't get you to your world. Please join again." and no join or leave line goes out. Before, they were moved to a per-circle fallback, and a fallback that wasn't loaded led to the main world's spawn, which also left a player already there where they were. The main world is now used only if it is the named, allowed lobby. A move that ends in an error now disconnects too. The log says why and names no player.
+- **New `lobby-world` setting** (default `""` for none). `no-circle` now takes a `worlds` list. `/posse status` shows the lobby, and the config warns when no lobby is set with home worlds on, or when the lobby is missing from a group's list. New message `home-lobby`; `home-moved` is gone.
+- **Teleports, portals and rides into a forbidden world are refused.** With home worlds on, a teleport or portal that would take a player somewhere they may not be is cancelled, as is moving a boat, minecart or mount that carries them. It is also refused when Posse can't work out the answer. The player isn't told, and the log notes only a refusal caused by an error, once. Posse's own lobby move still goes through. If a start couldn't read the config, only `posse.bypass` can teleport until a good reload.
+- **The look after a world change is a safety net with no open gap.** A player who arrives where they may not be is pending from the moment of the world change. Before, that began only after the move. A Posse move that reports success but leaves the player somewhere forbidden disconnects them. If their rules or permissions can't be read, they're disconnected.
+- **A pending player is out of the game.** While a move or the first-join check is pending, and while a disconnect is being retried, nobody sees the player's character, name tag or Tab entry, and they see no other player's. They can't move, chat, run commands, interact, change blocks, take or deal damage, drop or pick up items (arrows too), or use inventories. They're taken off what they ride and their inventory is closed. Everything is restored when the move lands. A move that can't start, fails, breaks or takes more than ten seconds disconnects them. A check that breaks disconnects too.
+- **A refusal another plugin takes back is put back.** After every other priority, Posse cancels the teleport again and points it back at where it started, and does the same if a plugin changed an allowed destination to a forbidden one. The log notes this once.
+- **No `no-circle` entry now means lobby only.** With home worlds on, a player in no circle, including one whose groups aren't reported, may be only in the lobby, and is disconnected if there is none. Before, they were never moved. **Add `no-circle` with a `worlds` list before upgrading if staff or others in no circle need more.** Startup warns when the entry is missing.
+- **A reload applies to people already online.** After `/posse reload`, and when Posse starts with players online, everyone is checked and anyone in a forbidden world goes to the lobby or is disconnected.
+- **A start with a config that can't be read now refuses joins** without `posse.bypass`, operators included, with "The server's safety rules didn't load, so joining is paused. Please try again later." Before, nobody was moved while paused. This applies with or without home worlds, and has no setting. Fix the file and run `posse reload` from the console. The login check uses `PlayerLoginEvent` at HIGHEST, which Paper has deprecated, and Paper changes how it handles logins while a plugin listens to it, so it's registered only until startup has finished with working rules. A second check at join catches a login another plugin allowed again.
+- **A startup that fails keeps the door shut.** The join check is registered before anything else, and no startup error escapes to Paper, which would disable the plugin along with its checks. A later failure leaves Posse enabled with joins paused until a restart. If the join check can't be registered, the server is shut down. An error while Java loads the plugin class itself can't be caught.
+- **A cancelled disconnect no longer leaves a player loose.** If another plugin cancels the kick, Posse retries every 10 ticks and holds the player meanwhile: movement, teleports, interaction, blocks, chat, commands, writing, damage, items and inventories are cancelled at HIGHEST, and they reach nobody. A warning is logged once, only if the player is still there at a retry, and names nobody.
+- **Respawn:** when a player must be disconnected while respawning, the respawn point is set back to the world they died in if their group may be there. If neither world is allowed, Paper's API can't stop the position being saved; the player is held until gone and checked at the next join.
+- **API:** `ReachService.inSharedCircle(viewer, to)`, a circles-only check for things such as map dots. True for yourself, a shared circle or either side's `posse.bypass`; the same world doesn't count; true with no circles set up; false while paused, for a player being placed or disconnected, or on an error. Chat is unchanged.
+- **Upgrading with home worlds on:** set `lobby-world` and add it to each group's `worlds`, or anyone found outside their worlds is disconnected. That includes someone with no bed who dies in their own world and would respawn in the main world. The old `fallback` lines never choose a destination. The config loads, warns until they're removed, and doesn't show that entry's `message` meanwhile. A `no-circle` entry with only a `fallback` still allows that world until you write it under `worlds`. A circle entry needs `worlds` or `unlimited: true`; without either it adds nothing and a warning names it. A circle fallback that isn't in its worlds used to be an error and now only warns, since it grants nothing.
+- An existing `config.yml` loads and keeps its own message wording. The built-in `home-lobby` wording is used when it's missing, and a leftover `home-moved` message is not used. The built-in `admin-paused` and `admin-reload-failed-paused` messages now mention joining.
+- Tested: `./gradlew build` (268 unit tests, none skipped), then the bot suites on throwaway Paper servers with LuckPerms. `home-worlds.js` passed 194/194, `reach-leaks.js` 64/64 and `book-authors.js` 18/18 on 26.1.2, 26.2 and 26.3. `suite.js` passed 87/87 on 26.1.2 and 26.2 and 86/87 on 26.3. `presence-messages.js` passed 6/6 on 26.1.2 and 26.2 and 3/6 on 26.3. `home-worlds.js` now uses a real nether portal with a boat, a minecart, a horse and a thrown pearl, and `suite.js` makes startup fail with a stand-in BlueMapMini.
+- **Leave lines on Paper 26.3 build 272 (`d749869`):** every 26.3 failure is a missing leave line. No server log from the 26.3 runs has one, `presence: everyone` included, and the released 0.11.2 jar fails the same three `presence-messages.js` checks. 0.11.2 passed them on an earlier 26.3 build. That build wasn't tried without Posse, so the cause isn't known. On this build, checks that expect no leave line prove nothing. Look into this before moving a server to it.
+- **Not tested:** `suite.js` skips sign text, anvil renames and graves (no LanternGraves jar). No bot check covers walking or damage while pending, because the bots send no movement and the test helper cancels damage. None covers stacked riders, a teleport check that can't be decided, unreadable permissions at a world change, a circle written twice, an unlimited `no-circle`, the missing-circle warning at startup, or `start()` with players online. Bots on 26.3 can't use blocks. The calls to the online re-check from `reload()` and `start()` have no unit test, and neither does the plugin's own startup wiring. `inSharedCircle` has no bot check here; BlueMapMini's dot suite uses it. No real game client has seen this version.
+
## 0.11.2
- **Death and advancement lines follow circles** (K832). While circles are in use, whatever `presence` says, a line the server would send to everyone about a player goes only to players Posse says may reach that player, and to the console and log. A death line that names whoever dealt the last blow needs both players in reach. Before, a kid's death line reached every adult online, and the other way round. If Posse can't decide (the config couldn't be read at startup, or a player can't be read), only the player themself and players with `posse.bypass` get the line. The player who died still sees the cause on the death screen. Posse acts last (MONITOR), on the line as other plugins left it, so a line another plugin removed stays removed. A team's death message setting and the `show_death_messages` game rule still apply.
diff --git a/README.md b/README.md
index 55c7705..9cd0c33 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. Version 0.11.2 (death and advancement lines, Tab, `/list` and the server list follow circles) passed the unit tests and every bot suite on throwaway Paper 26.1.2, 26.2 and 26.3, including a new one for those leaks, which 0.11.1 fails. Before that, it passed 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, who sees whom in the player list and join messages (`presence: reach`), home worlds on rejoin, respawn and teleport, 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 Posse 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. Version 0.11.3 closes gaps where home worlds and a paused start failed open, makes the lobby the only place home worlds sends anyone, and adds a circles-only check for other plugins. It passed the unit tests and, on throwaway Paper 26.1.2 and 26.2, every bot suite, apart from the sign, anvil and graves checks, which are skipped. On 26.3 build 272, no leave line was logged in any run, so the checks that expect one fail (the released 0.11.2 does the same there) and the checks that expect none prove nothing. Everything else passed. Walking and damage while a player is held have no bot check. Version 0.11.2 (death and advancement lines, Tab, `/list` and the server list follow circles) passed the unit tests and every bot suite on throwaway Paper 26.1.2, 26.2 and 26.3, including a new one for those leaks, which 0.11.1 fails. Before that, it passed 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, who sees whom in the player list and join messages (`presence: reach`), home worlds on rejoin, respawn and teleport, 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 Posse 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.
@@ -37,15 +37,34 @@ Otherwise they can't. A world group is a world with its Nether and End (`surviva
**Names on Tab.** While circles are in use, pressing Tab in any command offers only the names of players you may reach. That covers `/msg`, `/tell`, `/w` and their namespaced forms such as `minecraft:msg`, and every plugin command that offers online players. It's checked on the finished list the server is about to send, so it doesn't matter which plugin made it. A suggestion that isn't a player but is spelled like the name of one out of reach, such as a warp, is left out too. A game also offers the names it already knows without asking the server, which is what `presence: reach` above closes. With `presence: everyone` every game knows every name, as in vanilla.
-**Home worlds (optional).** For a server where a kids' group must never end up in an adults' world. Players rejoin where they logged out, and a world plugin often checks access only when you teleport, not when you join. With a `home-worlds` section in `config.yml`, Posse steps in when someone is in a world their circle doesn't allow:
-
-- A circle with an entry lists its worlds and a fallback. A player there who is somewhere else is moved to the fallback's spawn, on join, on respawn, and after any world change. A kid who logged out in a kids' world stays where they were.
-- A player in any circle with no entry is never moved. That covers adult groups and a visitor who is in both a kids' and an adults' circle.
-- A player in no circle goes to the `no-circle` fallback, such as a circle-only station, and is sent back if they leave it.
-- A fallback world that doesn't exist fails closed: the player goes to the main world's spawn, the log warns, and `/posse status` names the missing world. They are never left where they were.
-- Only the moved player gets a short line, such as "Welcome back! You're in the kids' world." (set per entry with `message`). Nobody else is told.
-
-It is off unless the section is there, and it needs at least one circle. A mistake in the section is a config error, so nothing half-applies. Not covered: the first tick before the move, and a world that Posse can't see because another plugin loads it after the player joins. While chat is paused because the config couldn't be read at startup, home worlds are paused too, because Posse can't tell who is in which circle.
+**Home worlds (optional).** For a server where a kids' group must never end up in an adults' world. Players rejoin where they logged out, and a world plugin often checks access only when you teleport, not when you join. With a `home-worlds` section in `config.yml`, Posse keeps players out of worlds their circle doesn't allow:
+
+- **Upgrading: a circle with no entry is now restricted.** Before this version, players in such a circle, usually your adults, were left alone. **Your adults stay restricted until their circle gets `unlimited: true`.** Add it before you upgrade.
+- **Give every circle its own entry**, with one of two lines. `worlds: [first_world, second_world]` limits its players to those worlds. `unlimited: true` means no limits, so its players are never moved. To change a circle, edit its entry and run `/posse reload`.
+
+ ```yaml
+ home-worlds:
+ kids:
+ worlds: [kids_world, kids_world_nether, lobby_world]
+ adults:
+ unlimited: true
+ no-circle:
+ worlds: [station, lobby_world]
+ ```
+
+- A player in any unlimited circle has no limits, even if they're in a limited one too. Anyone else may be in every world listed by any of their circles. A kid who logged out in one of them stays where they were.
+- A circle with no entry adds no worlds and lifts no limits. So does an entry with both lines, neither line, or `unlimited` set to anything but `true`, and a circle written twice. A new circle you add to a kid therefore can't free them. A player whose circles all add nothing is treated like a player in no circle. The log names each such circle at startup and on reload, and `/posse status` shows what every circle has.
+- A player in no circle may be in the worlds of the `no-circle` entry, such as a circle-only station. **With no `no-circle` entry they may be only in the lobby**, and with no lobby they are disconnected. That includes a player whose groups your permissions plugin doesn't report. Posse warns at startup when the entry is missing. If staff or adults are in no circle, add `no-circle` with the worlds they need before you upgrade.
+- **Refused at the door.** A teleport or portal that would take a player somewhere they may not be is cancelled. So is moving a boat, minecart or mount that carries them, where the server tells plugins about it. If Posse can't work out the answer, it's refused. Posse sends no message of its own for this. If another plugin takes the refusal back or changes the destination afterwards, Posse looks again after the other plugins and refuses it again.
+- **Everyone is checked again** after `/posse reload`, so a tighter list applies to people already online. Joins and respawns are checked too, and so is every world change, in case something got past the refusal.
+- **Out of the game while a move is pending.** From the moment Posse finds a player somewhere they may not be, or holds a new player for the first-join check, until they're somewhere they may be: nobody sees their character, name tag or Tab entry, and they see no other player's. They can't move, chat, run commands, use or change anything, take or deal damage, drop or pick up items, or use inventories. They're taken off whatever they ride and their open inventory is closed. A move that hasn't finished after ten seconds disconnects them.
+- **One lobby.** Name your server's lobby with `lobby-world`. A player found anywhere they may not be goes to the lobby's spawn only if the lobby is loaded and in the worlds their group may be in (their circles' lists, or the `no-circle` list). Put the lobby in each list. Posse never sends anyone to any other world. The main world is used only if it is that lobby. A kid with no bed who dies in their own world usually respawns in the main world, so they go to the lobby too.
+- Otherwise they are disconnected with "Sorry, we couldn't get you to your world. Please join again." That includes the default, `lobby-world: ""`, which names no lobby. Nobody is told they joined or left, and they are never left where they are. The log says why, and `/posse status` names any world that doesn't exist before anyone needs it. A move that doesn't go through disconnects the player too.
+- **Upgrading.** Each entry's `fallback` line from earlier versions does nothing now. The config still loads and Posse warns until you remove it. That entry's `message` isn't shown while the line is there, because it was written for the old move. A `no-circle` entry that has only a `fallback` still allows that one world until you write it under `worlds`. Set `lobby-world` and add it to each list, or anyone outside their worlds is disconnected.
+- If another plugin cancels that disconnect, Posse tries again twice a second until the player has gone. Until then they are held: hidden from everyone, with everyone hidden from them, and unable to move, teleport, chat, send messages or commands, write, use or change blocks, take or deal damage through the usual events, drop or pick up items, or use inventories. They reach nobody.
+- Only the moved player gets a short line, such as "Welcome! You're in the lobby." (set per entry with `message`). Nobody else is told.
+
+It is off unless the `home-worlds` section is there with something in it, and it needs at least one circle. A section whose only entries can't be used stays on. A mistake in a circle's own entry makes that entry add nothing, with a warning. A circle name that isn't in `circles`, a section or `no-circle` entry that can't be read, and a bad `lobby-world` are config errors, so nothing half-applies. `no-circle` always needs `worlds`. `unlimited` there is ignored with a warning. Not covered: a pending player's screen still shows the world around them, with its signs, builds and animals. The hold works through the server's events, so anything another plugin does for a player without those events isn't stopped. A plugin that also gets in after Posse's last look at a teleport can let it through; the check after the world change then catches it, just after it happens. **If Posse is disabled or removed while the server runs, none of these rules apply.** Posse also can't see a world that another plugin loads after the player joins. A respawn can't be cancelled. If a player has to be disconnected while respawning, Posse points the respawn back at the world they died in when their group may be there. If neither world is allowed, the server may save them where it respawned them. They're held until they leave and checked again when they next join. If the config can't be read at startup, Posse can't tell who is in which circle, so it refuses joins (see below).
**Book authors.** A written book shows its author only to the author, players who share a circle with them, and players with `posse.bypass`. Everyone else sees "Unknown" (`book-authors.shown-as`), and a title that holds the author's name shows `****` for it. That includes the BetonQuest quest journal, which carries its owner's name. Same world doesn't count, only circles, so a kid and an adult standing together still don't see each other's names. It is on by default; set `book-authors.hide: false` to turn it off. With no circles set up nothing is hidden.
@@ -73,7 +92,11 @@ Every message players read is in `config.yml`, in [MiniMessage](https://docs.adv
Permission changes take effect straight away, with no relog.
-If the config can't be read when the server starts, there are no rules to follow, so chat and private messages are paused, and admins are told when they join. Fix the file and run `/posse reload`. A reload with mistakes keeps the rules that were working, and says what's wrong.
+If the config can't be read when the server starts, there are no rules to follow, so chat and private messages are paused and **nobody can join** without `posse.bypass`. This applies whether or not you use home worlds, and there is no setting to turn it off. Operators don't have `posse.bypass` unless you give it to them. A refused player reads "The server's safety rules didn't load, so joining is paused. Please try again later.", and the log says so at most once a minute. Fix the file and run `posse reload` from the console. Admins who can join are told about the pause. Join messages are checked a second time: if another plugin lets a refused login through, the player is held and disconnected, and nobody is told they joined or left. A reload with mistakes keeps the rules that were working, and says what's wrong.
+
+The same join check goes in before anything else at startup. If a later startup step fails, Posse stays enabled with joins paused, and you need to fix the cause and restart the server. Don't count on its other rules, including the ones for players with `posse.bypass`, after such a failure. If the join check itself can't be set up, Posse shuts the server down. A failure that stops Java loading the plugin at all happens before any of Posse's code runs, so it can't guard against that.
+
+Up to 0.11.2 your `config.yml` has its own copy of the `admin-paused` and `admin-reload-failed-paused` messages, which don't mention joining. Posse keeps your wording.
## Commands
@@ -109,6 +132,8 @@ if (rules == null || rules.mayReach(from, to)) { /* send it */ }
`mayReach(from, to)` and `maySpeak(player)` follow exactly the same rules as chat, and are safe from any thread.
+`inSharedCircle(viewer, to)` is the circles-only check, added in 0.11.3, for things such as map dots. It's true for yourself, when the two share a circle, or when either has `posse.bypass`. Being in the same world doesn't count. With no circles set up it's true. It's false while Posse is paused and when it can't be worked out. While circles are in use, it's also false between two different players if either is still being placed or is being disconnected. It doesn't change chat.
+
`sharesCircle(viewerHas, to)` is for a viewer who isn't in game, such as someone on a web map. It's true only when they share a circle with `to`. World, world group and bypass don't count, and with no circles set up it's always false. The caller passes the viewer's permissions, read while they're offline, and anything it can't check should answer false.
`mayKnow(viewer, owner, world)` says whether a player may know who left something in a world, such as a grave's name. It's stricter than chat, so it fails closed: the owner, either side's `posse.bypass`, a shared circle, or both players standing in that world's group right now (unless it's circle-only). An offline owner counts only through a circle or bypass, from what Posse last saw of them. With no circles set up, nobody but the owner may, and it answers false for anyone Posse has never seen. Call it from the main thread. For that, Posse keeps `known-players.yml`: each player's ID with the circle names they held and whether they had `posse.bypass`, updated when they join and leave and on /posse reload. Nothing else about them is stored. If you take someone out of a circle while they're offline, Posse still uses their old circles until they next join; delete their line from the file (with the server stopped) to make it take effect at once.
diff --git a/build.gradle.kts b/build.gradle.kts
index a7a6c8e..7a11fc3 100644
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ -4,7 +4,7 @@ plugins {
}
group = "com.extantape"
-version = "0.11.2"
+version = "0.11.3"
java {
toolchain.languageVersion.set(JavaLanguageVersion.of(25))
diff --git a/docs/decisions.md b/docs/decisions.md
index 50086c0..a41fda8 100644
--- a/docs/decisions.md
+++ b/docs/decisions.md
@@ -16,6 +16,23 @@ Owner decisions for HouseRules, newest first.
| 2026-11-07 | Every list is in config, including circles, circle-only worlds, world groups, the dimension suffixes, message and reply commands, blocked commands and every message. With no circles, chat is vanilla. | Generic and publishable, with no server's names in the code. |
- **BlueMinimap (2026-11-08, owner rename of BlueMapHUD):** 0.2.0 listens for `com.extantape.blueminimap.api.CoordinateShareEvent` when BlueMinimap is installed, and still for the old `com.extantape.bluemaphud.api` event when only BlueMapHUD 0.1.x is, for one release. Released together with BlueMinimap 0.2.0, which turns sharing off when HouseRules is older than 0.2, so no order of upgrades lets a share skip the circles.
+## 2026-11-30: Home worlds and a paused start fail closed (0.11.3)
+
+From the Trust and Safety design for these gaps, its safety review, and the owner's lobby rule. This replaces what the D290 entry of 2026-11-25 says about fallback worlds, including its last sentence about a missing one.
+
+- **The lobby rule** (D368, owner, 2026-11-30, relayed by the Head of Games): "each server names its lobby. Posse sends the player there only if their group is allowed in it. If they aren't, or no lobby is set or loaded, they're disconnected. Players in no group follow the same rule using the no-group list. The main world is used only if it is that named, allowed lobby." It wins over any older per-group fallback. It applies whenever a governed player is outside the worlds their group may be in. Posse sends nobody to any other world and never leaves them where they are. The setting is `lobby-world`, empty by default. The no-group list is `no-circle.worlds`.
+- **The old `fallback` key** (how this build applies D368) never chooses a destination. A config that still has it loads with a warning, and that entry's `message` isn't shown while the key is there, because it described the old move. A `no-circle` entry with only a `fallback` keeps that one world allowed, so an upgrade neither opens nor closes a world for those players, and it warns until `worlds` is written.
+- **Who it covers.** A player in no circle is always covered when home worlds is on. With no `no-circle` entry, their list is just the lobby, and with no lobby set or loaded they're disconnected. This follows D368 and the owner's "lobby only" answer for players in no group (2026-11-30, relayed by the Head of Games). It covers a player whose groups can't be read. It replaces what D290 allowed for players in no circle on a server with no `no-circle` entry. What happens to a circle with no entry is the next point.
+- **Every circle has its own setting** (owner, 2026-11-30, relayed by the Head of Games: "More granular but easily configurable is best so either every circle or recommended depending on that"). Design from the Head of Games: each circle's entry either lists `worlds` or says `unlimited: true`, a separate true-or-false key and never a special world name. A circle with no entry adds no worlds and lifts no limit, and a player whose circles all lack one is handled like a player in no circle. A player in any unlimited circle has no limits. Otherwise their worlds are those of all their listed circles together. An entry with both keys, neither, or a value other than `true` adds nothing and is named in a warning. This replaces D290's rule that a player in any circle without an entry is never moved. **On upgrade, an adult circle with no entry is restricted until it gets `unlimited: true`.**
+- **How this build applies that design** (choices for the Head of Games to review). "Like no circle" means the `no-circle` list when there is one, and only the lobby when there isn't. `no-circle` can't be unlimited, so one line can't free everyone whose groups can't be read. A circle written twice in different letter case uses neither. An empty or unreadable circle entry is a warning that adds nothing, where it was a config error before. A circle name that isn't in `circles` is still an error. A section with only unusable entries stays on.
+- **Pending means out of the game** (from an independent safety review, relayed by the Head of Games, 2026-11-30). While a move is pending, the player isn't seen and sees no player, and can't move or act, until the move lands or they're disconnected. Teleporting is left to the destination check, because Posse's own move is a teleport. A move that hasn't finished in ten seconds disconnects.
+- **A refusal stays a refusal** (same review). Posse looks at each teleport again after the other plugins and puts back a refusal that was taken back. Its listeners are registered again one tick after startup so that look comes late.
+- **A start with a config that can't be read refuses joins** without `posse.bypass`. The owner has confirmed this. When the config can't be read, Posse can't tell whether home worlds were set, so this applies to every server. There is no switch. A failed reload still keeps the rules that were working.
+- **A failed startup fails closed too.** The join check goes in first and no startup error escapes. If the check can't be registered, the server is shut down, because nothing would be left to keep players out.
+- **Refuse first, then check** (design from an Opus kids' safety review, relayed by the Head of Games, 2026-11-30). Teleports, portals and rides into a forbidden world are cancelled at HIGHEST. The check after a world change stays as the backstop, and the player is pending from the event itself. Rules are applied again to everyone online after a reload and at start. Anything that can't be decided is a refusal, and unreadable rules or permissions disconnect someone already there. A move that reports success into a forbidden world disconnects.
+- **A disconnect must happen.** If another plugin cancels it, Posse keeps trying and holds the player until they've gone.
+- **Map dots and the like use a circles-only check.** `inSharedCircle` doesn't count the same world, so players in different circles never pass it. Chat keeps its own rule.
+
## 2026-11-14
- **Map plugin's new name (owner, D194, D196):** the share hook follows BlueMapMini only. No hooks or stand-ins for its earlier names are kept.
diff --git a/docs/test-audit.md b/docs/test-audit.md
index 73c45d5..96fbf79 100644
--- a/docs/test-audit.md
+++ b/docs/test-audit.md
@@ -3,6 +3,46 @@
Kept by this repo's owning session (Minecraft: Plugins Lead), per `~/Code/CLAUDE.md`, "Test self-audits". Newest first.
+## 2026-11-30: home worlds and a paused start fail closed (0.11.3)
+
+All rows are fail-closed checks. The 268 unit tests pass. The bot suites ran on 26.1.2, 26.2 and 26.3. All pass on 26.1.2 and 26.2. On 26.3 build 272 no leave line is logged, with this version or the released 0.11.2, so one `suite.js` check and three `presence-messages.js` checks fail there, and checks that expect no leave line prove nothing on that build.
+
+| Fail-closed promise | Covered by |
+| --- | --- |
+| Every circle has its own setting (owner, 2026-11-30): a circle with no entry adds and lifts nothing, so a new circle can't free a kid; only unlisted circles means the no-circle rule, or the lobby, or a disconnect; unlimited beats limited; listed circles add up. This replaces the 0.9.0 row that said a circle with no entry is never moved | unit `HomeWorldsCirclesTest` (9 of its 10 fail on the rules before this change), `HomeWorldsTest`, `PendingTest`; bot `home-worlds.js`, "One entry for each circle" |
+| Every invalid entry (both keys, `unlimited` not exactly true, neither key, empty or unreadable `worlds`, a bare name, a circle written twice) adds nothing and is named; a section with only such entries stays on; `no-circle` can't be unlimited | unit `HomeWorldsCirclesTest` (every form); bot checks four of the forms and the only-unusable section. The circle written twice and the unlimited `no-circle` have no bot check |
+| Startup and reload name each circle with no entry, and `/posse status` and `--json` show each circle's setting | unit `HomeWorldsCirclesTest`, `HomeWorldsStatusTest`; bot (reload warning, status line, `--json`). No bot check reads the warning at startup |
+| D368: outside their worlds, a player goes to the lobby or is disconnected. No other allowed world stands in, loaded or not; with several circles any of their lists may allow the lobby; the same for no circle with the no-circle list | unit `HomeWorldsTest`; bot `home-worlds.js`, rejoin, respawn, safety net and first join |
+| Lobby not set, not loaded or not in the group's worlds disconnects, each with its own reason; the main world only as that named, allowed lobby | unit `HomeWorldsTest`, `HomeWorldsListenerTest`; bot `home-worlds.js`, "Lobby" |
+| `lobby-world` and `no-circle.worlds`: default empty, wrong types and an empty or missing list are errors; no lobby, or a lobby missing from a list, warns; an old `fallback` loads with a warning, is never a destination and hides that entry's message | unit `SettingsLoaderTest` |
+| Join: pending at once, nothing told, no join line, kicked on the next tick | unit `HomeWorldsListenerTest`; bot "(rejoin)" and "already standing in the main world" |
+| World change: pending before the event is over, then moved or kicked; unreadable permissions kick | unit `HomeWorldsListenerTest`; bot "The check after a world change" with `/mt force` and `/mt window` (the move and what others see and hear; unreadable permissions are unit only) |
+| Teleport, portal and ride into a forbidden world are refused, including stacked riders; refused when it can't be decided or there's no destination world; checked at HIGHEST; paused lets only bypass teleport | unit with stand-in events; bot `home-worlds.js`, "Teleports into a world the player may not be in are refused", first-spawn placement, and a real nether portal with a boat, a minecart, a horse and a thrown pearl. No bot check for stacked riders or a check that can't be decided |
+| A pending or held player isn't seen, sees no player, and can't move or act; every way out restores it | unit `HomeWorldsListenerTest`, `EvictionTest`, `PresenceTest`; bot (body, nametag, Tab, commands, chat, private messages, teleport). Walking and damage have no bot check, because bots send no movement and the helper cancels damage |
+| A refusal another plugin takes back, or a destination it changes, is refused again | unit; bot "A refusal another plugin takes back" |
+| A removed LuckPerms group leaves the no-circle rule from the next teleport, reload or join; Posse doesn't watch for the change itself | bot "Removing a LuckPerms group" |
+| Only an account its circles allow gets into a children's world; `posse.bypass` alone opens none | bot "Who gets into a children's world" |
+| A reload or start applies to people online: pending and off the list before any move, allowed players left alone, first-join waits kept, one unreadable player doesn't stop the rest | unit `HomeWorldsListenerTest` (the re-check); the calls from `reload()` and `start()` have no unit test; bot "A reload that tightens the rules" and "(reload)" cover `reload`, nothing covers `start` with players online |
+| A move that reports success but lands somewhere forbidden disconnects | unit only |
+| Respawn: pending, kicked on the next tick; the respawn points back at an allowed death world, and is left alone when there is none | unit; bot "(respawn)" (disconnect only) |
+| A lobby that is really unloaded disconnects, and the player is not saved in another world | bot "A lobby that really is unloaded" |
+| An old `fallback` line on a running server warns, and the player goes to the lobby | unit `SettingsLoaderTest`; bot "Lobby" |
+| A teleport that returns false or ends in an error, or a world gone by teleport time, disconnects | unit; bot "Failed delayed move" (false only) |
+| The warning says why, names the lobby at most and no player; `posse status` warns beforehand | unit `HomeWorldsListenerTest`; bot |
+| A cancelled kick: tried again until the player has gone, warned once, no second round, an old retry does nothing after a rejoin; the held player's events are cancelled and no leave line goes out | unit `EvictionTest` (every handler's presence and priority; movement and teleport driven) and `HomeWorldsListenerTest`; bot `home-worlds.js`, "A disconnect another plugin cancels" (stays connected, chat and `/msg` reach nobody, teleport refused, gone once allowed) |
+| Paused at startup: refused without `posse.bypass` (operators and `posse.admin` too), a permission check that throws refuses, another plugin's refusal is kept, the log is once a minute and names nobody | unit `PausedLoginGateTest`; bot `home-worlds.js` "Paused at startup", `suite.js` "Config: broken at startup", `reach-leaks.js` paused part |
+| A login another plugin allowed again is caught at join: held at once, join line dropped, disconnected, retried if cancelled | unit `PausedLoginGateTest`; bot `home-worlds.js`, "Paused at startup" with `/mt allowlogin` |
+| The login check runs at HIGHEST, the hold at LOWEST and the silence at HIGHEST | unit `theChecksHaveTheLastWordAndTheHoldComesFirst` |
+| The guard goes in before anything that can fail; nothing escapes; a later failure leaves joins paused; a guard failure shuts the server down | unit `StartupTest` |
+| Bypass can join while paused; after a fix and reload everyone can | unit; bot |
+| `inSharedCircle`: same world doesn't count, shared circle and bypass do, no circles means true, a pending player is false while circles are in use | unit `ReachTest` |
+
+A kick that takes a moment to go through isn't reported as a cancelled one: unit `EvictionTest.aKickThatTakesAMomentIsNotReportedAsCancelled`, which failed before the fix. `reach-leaks.js` found it on a real server.
+
+The server runs showed that Paper calls the login checks on all three versions, that LuckPerms answers `posse.bypass` that early, and that a held player's chat, commands, private messages and teleports are stopped. They showed that these kicks send no join or leave line on 26.1.2 and 26.2. On 26.3 build 272 that is unproven, because the server logged no leave line at all. Still unchecked: walking and damage while held, and where Paper saves a player kicked while respawning. Bots on 26.3 can't use blocks, so block use by a held player rests on the unit test of the handler list.
+
+Gaps skipped: `PossePlugin`'s own wiring (registering the check, the paused flag, the service's null and error answers) has no unit test, because it needs a running server. The bot suite makes startup fail with a stand-in BlueMapMini and checks the closed door. Most of `Eviction`'s cancel handlers are covered by the handler list and priority test and not driven one by one; they share one method.
+
## 2026-11-27: names that reach past circles (0.11.2, K832)
| Promise | Covered by |
diff --git a/settings.gradle.kts b/settings.gradle.kts
index eb7805f..0fcb9c4 100644
--- a/settings.gradle.kts
+++ b/settings.gradle.kts
@@ -5,6 +5,7 @@ include("bluemapmini-stub")
project(":bluemapmini-stub").projectDir = file("test/stub")
// Test-only plugins for the live tests in test/live. Never shipped.
-include("live-test-helper", "live-test-fakeminimap")
+include("live-test-helper", "live-test-fakeminimap", "live-test-brokenminimap")
project(":live-test-helper").projectDir = file("test/live/helper")
project(":live-test-fakeminimap").projectDir = file("test/live/fakeminimap")
+project(":live-test-brokenminimap").projectDir = file("test/live/brokenminimap")
diff --git a/src/main/java/com/extantape/posse/PossePlugin.java b/src/main/java/com/extantape/posse/PossePlugin.java
index 6bfc4ad..14ed86f 100644
--- a/src/main/java/com/extantape/posse/PossePlugin.java
+++ b/src/main/java/com/extantape/posse/PossePlugin.java
@@ -32,13 +32,20 @@
/**
* Posse: who can hear whom, which commands are off, and a word filter. See README.md.
*
- * If the config is broken at startup there are no rules to follow, so chat and private messages are paused, and
- * admins are told why, until it's fixed and reloaded. A broken reload keeps the rules that were working.
+ * If the config is broken at startup there are no rules to follow, so chat and private messages are paused, joins are
+ * refused for anyone without {@code posse.bypass}, and the log says why, until it's fixed and reloaded. A startup that
+ * fails some other way pauses joining until a restart (see {@link Startup}). A broken reload keeps the rules that were
+ * working.
*/
public final class PossePlugin extends JavaPlugin implements ReachService {
private com.extantape.posse.listen.PresenceListener presence;
private com.extantape.posse.listen.BookListener books;
+ private com.extantape.posse.listen.HomeWorldsListener homeWorlds;
private PosseCommands commands;
+ /** Registered first thing at startup, and removed once Posse has started with working rules; null after that. */
+ private com.extantape.posse.listen.PausedLoginGate loginGate;
+ private com.extantape.posse.listen.Eviction eviction;
+ private final Startup startup = new Startup();
public static final String ADMIN = "posse.admin";
@@ -57,6 +64,53 @@ public record State(Settings settings, Messages messages, Quips quips) {
@Override
public void onEnable() {
+ startup.run(this::guardJoins, this::start, this::startFailed, () -> getServer().shutdown());
+ openJoinsIfSafe();
+ }
+
+ // Before anything that can fail: the join check, and the class that holds anyone who gets in regardless.
+ private void guardJoins() {
+ eviction = new com.extantape.posse.listen.Eviction(new com.extantape.posse.listen.Eviction.Host() {
+ @Override public Player player(UUID id) {
+ return Bukkit.getPlayer(id);
+ }
+
+ @Override public void nextTick(Runnable task) {
+ Bukkit.getScheduler().runTask(PossePlugin.this, task);
+ }
+
+ @Override public void later(Runnable task, long ticks) {
+ Bukkit.getScheduler().runTaskLater(PossePlugin.this, task, ticks);
+ }
+
+ @Override public void warn(String line) {
+ getLogger().warning(line);
+ }
+
+ @Override public void conceal(Player player) {
+ PossePlugin.this.conceal(player);
+ }
+ });
+ loginGate = new com.extantape.posse.listen.PausedLoginGate(this::paused, eviction, getLogger()::warning);
+ var plugins = getServer().getPluginManager();
+ plugins.registerEvents(eviction, this);
+ plugins.registerEvents(loginGate, this);
+ }
+
+ // Used even when startup failed and there's no presence listener to hide anyone.
+ public void conceal(Player player) {
+ if (presence != null) {
+ presence.conceal(player);
+ return;
+ }
+ for (Player other : Bukkit.getOnlinePlayers()) {
+ if (other == player) continue;
+ other.hideEntity(this, player);
+ player.hideEntity(this, other);
+ }
+ }
+
+ private void start() {
for (String file : List.of(SettingsLoader.CONFIG, SettingsLoader.FILTER, SettingsLoader.QUIPS)) {
if (!getDataFolder().toPath().resolve(file).toFile().exists()) saveResource(file, false);
}
@@ -74,7 +128,13 @@ public void onEnable() {
plugins.registerEvents(books, this);
Bukkit.getScheduler().runTaskTimer(this, books::sweep, 40L, 40L);
plugins.registerEvents(new PlayerListener(this), this);
- plugins.registerEvents(new com.extantape.posse.listen.HomeWorldsListener(this), this);
+ homeWorlds = new com.extantape.posse.listen.HomeWorldsListener(this, eviction);
+ plugins.registerEvents(homeWorlds, this);
+ // Registered again once every plugin is up, so its last look at a teleport runs after theirs.
+ Bukkit.getScheduler().runTask(this, () -> {
+ org.bukkit.event.HandlerList.unregisterAll(homeWorlds);
+ plugins.registerEvents(homeWorlds, this);
+ });
presence = new com.extantape.posse.listen.PresenceListener(this);
plugins.registerEvents(presence, this);
plugins.registerEvents(new com.extantape.posse.listen.AnnouncementListener(this), this);
@@ -92,12 +152,40 @@ public void onEnable() {
getServer().getServicesManager().register(ReachService.class, this, this, ServicePriority.Normal);
commands = new PosseCommands(this);
getLifecycleManager().registerEventHandler(LifecycleEvents.COMMANDS, event -> commands.register(event.registrar()));
+ // Anyone already online, as after a plugin manager loads Posse. The first read above came before the listeners.
+ recheckHomeWorlds();
+ }
+
+ /** Applies home worlds to everyone online. Does nothing until the listener exists. */
+ private void recheckHomeWorlds() {
+ if (homeWorlds != null) homeWorlds.recheck();
+ }
+
+ // Leaves Posse enabled and paused. Disabling it would take the join check away with it.
+ private void startFailed(Throwable cause) {
+ state = null;
+ getLogger().log(java.util.logging.Level.SEVERE, "Posse didn't start properly, so joining is paused until the "
+ + "server is restarted. Only players with posse.bypass can join. Chat rules may not be running. "
+ + "Fix the cause below, then restart.", cause);
+ getServer().getServicesManager().unregisterAll(this);
+ }
+
+ private void openJoinsIfSafe() {
+ if (loginGate != null && !paused()) {
+ org.bukkit.event.HandlerList.unregisterAll(loginGate);
+ loginGate = null;
+ }
}
@Override
public void onDisable() {
getServer().getServicesManager().unregisterAll(this);
if (presence != null) presence.showAll();
+ else {
+ for (Player viewer : Bukkit.getOnlinePlayers()) {
+ for (Player other : Bukkit.getOnlinePlayers()) if (viewer != other) viewer.showEntity(this, other);
+ }
+ }
partners.clear();
com.extantape.posse.rules.Pending.clear();
}
@@ -112,13 +200,18 @@ public PosseCommands commands() {
/** Reads the config files again. Returns true if the new rules were applied. */
public boolean reload(CommandSender sender) {
+ if (startup.failed()) {
+ getLogger().severe("Posse didn't start properly, so a reload can't fix it. Fix the cause and restart the server.");
+ return false;
+ }
SettingsLoader.Result result = new SettingsLoader(this::getResource).load(getDataFolder().toPath());
for (String warning : result.warnings()) getLogger().warning(warning);
if (!result.ok()) {
for (String error : result.errors()) getLogger().severe(error);
problems = result.errors();
if (state == null) {
- getLogger().severe("Posse couldn't read its config, so chat and private messages are paused until it's fixed. Then run /posse reload.");
+ getLogger().severe("Posse couldn't read its config, so chat, private messages and joining are paused until it's fixed. "
+ + "Players with posse.bypass can still join. Fix it, then run posse reload from the console.");
} else {
getLogger().severe("The config has problems, so Posse kept the rules it already had.");
}
@@ -127,6 +220,8 @@ public boolean reload(CommandSender sender) {
Settings settings = result.settings();
state = new State(settings, new Messages(settings.messages()),
new Quips(settings.quips(), settings.nobodyHeard().cooldownSeconds(), new Random()));
+ // During startup this does nothing: onEnable opens joins after the last step.
+ openJoinsIfSafe();
problems = result.warnings();
registerCirclePermissions(settings.reach());
if (presence != null) presence.refresh();
@@ -140,6 +235,7 @@ public boolean reload(CommandSender sender) {
getLogger().info(reach.active()
? "Chat rules are on, with " + reach.circles().size() + (reach.circles().size() == 1 ? " circle. " : " circles. ") + settings.filterSummary()
: "No circles are set up, so chat reaches everyone, as in vanilla. " + settings.filterSummary());
+ recheckHomeWorlds();
return true;
}
@@ -170,13 +266,14 @@ public void remember(Player player) {
if (known.remember(Subject.of(player), s.settings().reach().circles())) known.save();
}
- /** The current rules, or null while chat is paused because the config couldn't be read. */
+ /** The current rules, or null while Posse is paused. */
public State state() {
return state;
}
+ /** True until startup has finished with working rules. */
public boolean paused() {
- return state == null;
+ return !startup.complete() || state == null;
}
public Messages messages() {
@@ -201,17 +298,8 @@ public List problems() {
/** One line for each world named in home-worlds that doesn't exist. Empty when it's off or all are there. */
public List homeWorldProblems() {
State s = state;
- if (s == null || !s.settings().homeWorlds().enabled()) return List.of();
- var home = s.settings().homeWorlds();
- List out = new java.util.ArrayList<>();
- for (String world : home.namedWorlds()) {
- if (Bukkit.getWorld(world) != null) continue;
- boolean fallback = home.noCircle() != null && home.noCircle().fallback().equals(world)
- || home.byCircle().values().stream().anyMatch(e -> e.fallback().equals(world));
- out.add("home-worlds: the world \"" + world + "\" doesn't exist"
- + (fallback ? ", so players who need it land at the main world's spawn instead." : "."));
- }
- return out;
+ if (s == null) return List.of();
+ return s.settings().homeWorlds().problems(world -> Bukkit.getWorld(world) != null);
}
private void logHomeWorldProblems() {
@@ -280,6 +368,17 @@ public boolean sharesCircle(java.util.function.Predicate viewerHas, Play
}
}
+ @Override
+ public boolean inSharedCircle(Player viewer, Player to) {
+ State s = state;
+ if (s == null || viewer == null || to == null) return false;
+ try {
+ return s.settings().reach().inSharedCircle(Subject.of(viewer), Subject.of(to));
+ } catch (RuntimeException e) {
+ return false;
+ }
+ }
+
@Override
public boolean mayKnow(Player viewer, UUID owner, String world) {
State s = state;
diff --git a/src/main/java/com/extantape/posse/Startup.java b/src/main/java/com/extantape/posse/Startup.java
new file mode 100644
index 0000000..bd759b5
--- /dev/null
+++ b/src/main/java/com/extantape/posse/Startup.java
@@ -0,0 +1,51 @@
+package com.extantape.posse;
+
+import java.util.function.Consumer;
+
+/**
+ * Starts the plugin so that a failure leaves the door shut. Paper disables a plugin whose {@code onEnable} throws, and
+ * a disabled plugin's listeners stop working, so nothing may escape. The join guard goes in first. If anything after it
+ * fails, the plugin stays enabled with joins paused. If the guard itself can't go in, the server is shut down, because
+ * nothing would be left to keep players out.
+ */
+final class Startup {
+ private volatile boolean complete;
+ private volatile boolean failed;
+
+ /** True only once every step has finished. */
+ boolean complete() {
+ return complete;
+ }
+
+ boolean failed() {
+ return failed;
+ }
+
+ void run(Runnable guard, Runnable rest, Consumer onFailed, Runnable shutDown) {
+ try {
+ guard.run();
+ } catch (Throwable t) {
+ failed = true;
+ // The shutdown comes first, so a failure while reporting can't stop it.
+ shutDown.run();
+ report(onFailed, t);
+ return;
+ }
+ try {
+ rest.run();
+ complete = true;
+ } catch (Throwable t) {
+ failed = true;
+ report(onFailed, t);
+ }
+ }
+
+ private static void report(Consumer onFailed, Throwable cause) {
+ try {
+ onFailed.accept(cause);
+ } catch (Throwable again) {
+ // Nothing may escape. Joins stay paused because the startup never completed.
+ again.printStackTrace();
+ }
+ }
+}
diff --git a/src/main/java/com/extantape/posse/api/ReachService.java b/src/main/java/com/extantape/posse/api/ReachService.java
index 69fffae..5e6903d 100644
--- a/src/main/java/com/extantape/posse/api/ReachService.java
+++ b/src/main/java/com/extantape/posse/api/ReachService.java
@@ -5,7 +5,8 @@
/**
* Posse' answer to "may A reach B?", for other plugins. Get it from Bukkit's services manager:
* {@code Bukkit.getServicesManager().load(ReachService.class)}. Safe to call from any thread.
- * Every answer follows the same rules as chat, including circles, circle-only worlds and posse.bypass.
+ * Answers follow the same rules as chat, including circles, circle-only worlds and posse.bypass, unless a method says
+ * it is stricter.
*/
public interface ReachService {
/** Whether anything {@code from} says or sends can reach {@code to}. Always true for the same player. */
@@ -29,4 +30,13 @@ public interface ReachService {
* the main thread.
*/
boolean mayKnow(Player viewer, java.util.UUID owner, String world);
+
+ /**
+ * Whether {@code viewer} may see something about {@code to} that only circle-mates should, such as their place on a
+ * minimap: a shared circle, or either side's posse.bypass. Stricter than {@link #mayReach}: standing in the same
+ * world doesn't count. True for the same player, and with no circles set up. False while Posse is paused, for
+ * another player while either one is still being placed, and if Posse can't work it out. Call it from the main
+ * thread. Added in 0.11.3.
+ */
+ boolean inSharedCircle(Player viewer, Player to);
}
diff --git a/src/main/java/com/extantape/posse/command/PosseCommands.java b/src/main/java/com/extantape/posse/command/PosseCommands.java
index 1723f21..db0fda9 100644
--- a/src/main/java/com/extantape/posse/command/PosseCommands.java
+++ b/src/main/java/com/extantape/posse/command/PosseCommands.java
@@ -116,9 +116,9 @@ static Player online(String nameOrUuid) {
@Override public Console.Status status() {
PossePlugin.State state = plugin.state();
- if (state == null) return new Console.Status(true, List.of(), false, plugin.problems(), homeWorldsStatus(null));
+ if (state == null) return new Console.Status(true, List.of(), false, plugin.problems(), homeWorldsStatus(null, List.of()));
return new Console.Status(false, state.settings().reach().circles(), !state.settings().filter().isEmpty(), plugin.problems(),
- homeWorldsStatus(state.settings().homeWorlds()));
+ homeWorldsStatus(state.settings().homeWorlds(), state.settings().reach().circles()));
}
@Override public Console.Reloaded reload() {
@@ -140,24 +140,52 @@ static Player online(String nameOrUuid) {
};
/** The home-worlds part of status, for the --json answer. */
- static Map homeWorldsStatus(HomeWorlds home) {
+ static Map homeWorldsStatus(HomeWorlds home, List known) {
Map m = new java.util.LinkedHashMap<>();
boolean on = home != null && home.enabled();
m.put("enabled", on);
- m.put("circles", on ? List.copyOf(home.byCircle().keySet()) : List.of());
+ m.put("circles", on ? known.stream().filter(home.byCircle()::containsKey).toList() : List.of());
+ Map settings = new java.util.LinkedHashMap<>();
+ if (on) known.forEach(circle -> settings.put(circle, setting(home, circle)));
+ m.put("settings", settings);
m.put("noCircle", on && home.noCircle() != null);
+ m.put("lobby", on ? home.lobby() : "");
return m;
}
/** The home-worlds part of status, in a sentence. */
- static String homeWorldsSummary(HomeWorlds home) {
+ static String homeWorldsSummary(HomeWorlds home, List known) {
if (home == null || !home.enabled()) return "off";
List parts = new ArrayList<>();
- home.byCircle().forEach((circle, e) -> parts.add(circle + " stays in " + e.worlds().size() + (e.worlds().size() == 1 ? " world" : " worlds") + ", else " + e.fallback()));
- if (home.noCircle() != null) parts.add("no circle waits in " + home.noCircle().fallback());
+ for (String circle : known) {
+ parts.add(switch (setting(home, circle)) {
+ case "unlimited" -> circle + " has no limits";
+ case "limited" -> circle + " may be in " + worlds(home.byCircle().get(circle).worlds().size());
+ case "unusable" -> circle + " has an entry that can't be used and adds no worlds";
+ default -> circle + " has no entry and adds no worlds";
+ });
+ }
+ if (home.noCircle() != null) parts.add("no circle may be in " + worlds(home.noCircleWorlds().size()));
+ else parts.add(home.lobby().isEmpty()
+ ? "no no-circle entry, so players in no circle are disconnected"
+ : "no no-circle entry, so players in no circle may only be in the lobby");
+ parts.add(home.lobby().isEmpty()
+ ? "no lobby, so anyone outside those worlds is disconnected"
+ : "anyone outside those worlds goes to the lobby " + home.lobby() + " if their group may be there, and is disconnected if not");
return String.join("; ", parts);
}
+ /** One circle's home-worlds setting: limited, unlimited, unusable or none. */
+ private static String setting(HomeWorlds home, String circle) {
+ HomeWorlds.Entry e = home.byCircle().get(circle);
+ if (e != null) return e.unlimited() ? "unlimited" : "limited";
+ return home.broken().contains(circle) ? "unusable" : "none";
+ }
+
+ private static String worlds(int count) {
+ return count + (count == 1 ? " world" : " worlds");
+ }
+
/** Tells the player their circles and who online can hear them. Also the answer to /list while presence is limited. */
public int circles(Player player) {
PossePlugin.State state = plugin.state();
@@ -212,7 +240,7 @@ private int status(CommandSender sender) {
plugin.tell(sender, "admin-status", Map.of(
"circles", reach.circles().isEmpty() ? "none (vanilla chat)" : String.join(", ", reach.circles()),
"filter", state.settings().filter().isEmpty() ? "off" : "on"));
- plugin.tell(sender, "admin-home-worlds", Map.of("summary", homeWorldsSummary(state.settings().homeWorlds())));
+ plugin.tell(sender, "admin-home-worlds", Map.of("summary", homeWorldsSummary(state.settings().homeWorlds(), state.settings().reach().circles())));
}
for (String problem : plugin.problems()) plugin.tell(sender, "admin-problem", Map.of("problem", problem));
return Command.SINGLE_SUCCESS;
diff --git a/src/main/java/com/extantape/posse/config/SettingsLoader.java b/src/main/java/com/extantape/posse/config/SettingsLoader.java
index 7178814..486ecdc 100644
--- a/src/main/java/com/extantape/posse/config/SettingsLoader.java
+++ b/src/main/java/com/extantape/posse/config/SettingsLoader.java
@@ -33,7 +33,7 @@ public final class SettingsLoader {
private static final Pattern NAME = Pattern.compile("[a-z0-9_-]+");
private static final Set CONFIG_KEYS = Set.of("config-version", "circles", "circle-only-worlds",
"world-groups", "dimension-suffixes", "private-message-commands", "reply-commands", "broadcast-commands",
- "blocked-commands", "nobody-heard", "messages", "presence", "home-worlds", "book-authors");
+ "blocked-commands", "nobody-heard", "messages", "presence", "home-worlds", "lobby-world", "book-authors");
private static final Set FILTER_KEYS = Set.of("enabled", "check", "words", "allow", "mask-for-viewers");
/** The result: settings to apply, or errors explaining why there are none. Warnings either way. */
@@ -150,7 +150,46 @@ public Result load(String config, String filterText, String quips) {
if (!presence.equals("everyone") && !presence.equals("reach")) errors.add(CONFIG + ": presence must be everyone or reach.");
if (presence.equals("reach") && circles.isEmpty()) warnings.add(CONFIG + ": presence: reach has no effect until at least one circle is listed.");
- com.extantape.posse.rules.HomeWorlds homeWorlds = homeWorlds(base, circles);
+ String lobby = "";
+ if (base.get("lobby-world") != null) {
+ if (base.isString("lobby-world")) lobby = base.getString("lobby-world").trim();
+ else errors.add(CONFIG + ": lobby-world must be a world name, or \"\" for none.");
+ }
+ com.extantape.posse.rules.HomeWorlds homeWorlds = homeWorlds(base, writtenHomeWorlds(config), circles, lobby);
+ if (!lobby.isEmpty()) {
+ String named = lobby;
+ if (!homeWorlds.enabled()) {
+ warnings.add(CONFIG + ": lobby-world has no effect without home-worlds.");
+ } else {
+ homeWorlds.byCircle().keySet().stream().sorted()
+ .filter(circle -> !homeWorlds.byCircle().get(circle).unlimited())
+ .filter(circle -> !homeWorlds.byCircle().get(circle).worlds().contains(named))
+ .forEach(circle -> warnings.add(closedLobby(named, "home-worlds." + circle,
+ "players whose only circle is " + circle)));
+ if (homeWorlds.noCircle() != null && !homeWorlds.noCircleWorlds().contains(named)) {
+ warnings.add(closedLobby(named, "home-worlds.no-circle", "players in no circle"));
+ }
+ }
+ } else if (homeWorlds.enabled()) {
+ warnings.add(CONFIG + ": home-worlds is on and lobby-world isn't set, so anyone outside their home worlds is "
+ + "disconnected. To send them to a lobby, name it in lobby-world and add it to each group's worlds.");
+ }
+ if (homeWorlds.enabled()) {
+ for (String circle : circles) {
+ // An entry that can't be used has already been named, with what's wrong with it.
+ if (homeWorlds.byCircle().containsKey(circle) || homeWorlds.broken().contains(circle)) continue;
+ warnings.add(CONFIG + ": home-worlds." + circle + " is missing, so the circle " + circle + " adds no worlds. "
+ + "A player whose circles all lack a usable entry is treated like a player in no circle. Add home-worlds."
+ + circle + " with worlds: [...] to limit it, or unlimited: true for no limits.");
+ }
+ }
+ if (homeWorlds.enabled() && homeWorlds.noCircle() == null) {
+ warnings.add(CONFIG + ": home-worlds.no-circle is missing, " + (lobby.isEmpty()
+ ? "and no lobby-world is set, so players in no circle are disconnected. "
+ : "so players in no circle may only be in the lobby \"" + lobby + "\". ")
+ + "That includes anyone whose groups the permissions plugin doesn't report. To let them into other "
+ + "worlds, add home-worlds.no-circle with a worlds list.");
+ }
String shownAs = base.contains("book-authors.shown-as") ? String.valueOf(base.get("book-authors.shown-as")).trim() : "Unknown";
if (base.contains("book-authors.shown-as") && !base.isString("book-authors.shown-as")) errors.add(CONFIG + ": book-authors.shown-as must be text.");
@@ -166,8 +205,29 @@ public Result load(String config, String filterText, String quips) {
List.of(), List.copyOf(warnings));
}
- /** The optional home-worlds section (D290). Every slip is an error: a half-read rule could leave a kid in the wrong world. */
- private com.extantape.posse.rules.HomeWorlds homeWorlds(YamlConfiguration base, List circles) {
+ private static String closedLobby(String lobby, String entry, String who) {
+ return CONFIG + ": lobby-world \"" + lobby + "\" isn't in " + entry + ".worlds, so " + who
+ + " are disconnected when they're outside their worlds.";
+ }
+
+ /**
+ * The names written under home-worlds, in order. Bukkit drops a name with nothing after it, and an entry left like
+ * that must still count as written, or a section made only of them would switch home worlds off.
+ */
+ private static List writtenHomeWorlds(String config) {
+ if (config == null) return List.of();
+ Object root = new org.yaml.snakeyaml.Yaml(new org.yaml.snakeyaml.constructor.SafeConstructor(
+ new org.yaml.snakeyaml.LoaderOptions())).load(config);
+ if (!(root instanceof Map, ?> top) || !(top.get("home-worlds") instanceof Map, ?> written)) return List.of();
+ return written.keySet().stream().map(String::valueOf).toList();
+ }
+
+ /**
+ * The optional home-worlds section (D290). A circle's entry that can't be used adds no worlds and is named in a
+ * warning, and the section stays on. A slip anywhere else is an error: a half-read rule could leave a kid in the
+ * wrong world.
+ */
+ private com.extantape.posse.rules.HomeWorlds homeWorlds(YamlConfiguration base, List written, List circles, String lobby) {
if (!base.contains("home-worlds") || base.get("home-worlds") == null) return com.extantape.posse.rules.HomeWorlds.OFF;
ConfigurationSection section = base.getConfigurationSection("home-worlds");
if (section == null) {
@@ -176,48 +236,108 @@ private com.extantape.posse.rules.HomeWorlds homeWorlds(YamlConfiguration base,
}
Map byCircle = new LinkedHashMap<>();
com.extantape.posse.rules.HomeWorlds.Entry noCircle = null;
- for (String key : section.getKeys(false)) {
+ Set broken = new LinkedHashSet<>();
+ Set seen = new java.util.HashSet<>();
+ Set keys = new LinkedHashSet<>(written);
+ keys.addAll(section.getKeys(false));
+ for (String key : keys) {
String where = "home-worlds." + key;
+ boolean none = key.equals("no-circle");
+ String circle = key.toLowerCase(Locale.ROOT);
+ if (!none) {
+ if (!circles.contains(circle)) {
+ errors.add(CONFIG + ": " + where + " names a circle that isn't in circles.");
+ continue;
+ }
+ if (!seen.add(circle)) {
+ byCircle.remove(circle);
+ broken.add(circle);
+ warnings.add(CONFIG + ": home-worlds." + circle + " has more than one entry, so neither is used and it "
+ + "adds no worlds until only one is left.");
+ continue;
+ }
+ }
ConfigurationSection entry = section.getConfigurationSection(key);
if (entry == null) {
- errors.add(CONFIG + ": " + where + " must be a section" + (key.equals("no-circle") ? " with a fallback." : " with worlds and a fallback."));
+ if (none) errors.add(CONFIG + ": " + where + " must be a section with worlds.");
+ else unusable(broken, circle, "has neither worlds nor unlimited: true");
continue;
}
- boolean none = key.equals("no-circle");
for (String sub : entry.getKeys(false)) {
- if (!(sub.equals("fallback") || sub.equals("message") || (!none && sub.equals("worlds")))) {
+ if (sub.equals("unlimited")) {
+ if (none) {
+ warnings.add(CONFIG + ": home-worlds.no-circle can't be unlimited, so that line is ignored. It "
+ + "covers anyone whose groups aren't reported, so it always needs a worlds list.");
+ }
+ } else if (!(sub.equals("fallback") || sub.equals("message") || sub.equals("worlds"))) {
warnings.add(CONFIG + ": " + where + "." + sub + " isn't a setting Posse uses, so it's ignored.");
}
}
- String fallback = entry.isString("fallback") ? entry.getString("fallback").trim() : "";
- if (fallback.isEmpty()) errors.add(CONFIG + ": " + where + ".fallback must be a world name.");
+ // Before D368 each entry named a fallback world to send players to. It never chooses a destination now.
+ boolean old = entry.contains("fallback");
String message = null;
if (entry.contains("message")) {
if (entry.isString("message")) message = entry.getString("message");
else errors.add(CONFIG + ": " + where + ".message must be text.");
}
- if (none) {
- if (!fallback.isEmpty()) noCircle = new com.extantape.posse.rules.HomeWorlds.Entry(Set.of(), fallback, message);
- continue;
+ if (old) {
+ String lost = message == null ? "" : " Its message line was written for the old move, so it isn't shown "
+ + "while the fallback line is there. Check that it fits a move to the lobby before you remove fallback.";
+ warnings.add(CONFIG + ": " + where + ".fallback is no longer used and never chooses where a player goes. "
+ + "Anyone outside their worlds goes to lobby-world if their group may be there, and is "
+ + "disconnected if not. Remove the fallback line." + lost);
+ // Shown, an old line could tell a player they're somewhere they aren't.
+ message = null;
}
- String circle = key.toLowerCase(Locale.ROOT);
- if (!circles.contains(circle)) {
- errors.add(CONFIG + ": " + where + " names a circle that isn't in circles.");
+ if (none) {
+ List open = entry.contains("worlds") ? strings(CONFIG, entry, "worlds") : List.of();
+ String only = entry.isString("fallback") ? entry.getString("fallback").trim() : "";
+ if (!entry.contains("worlds") && !only.isEmpty()) {
+ // An old entry with no list let players in no circle be in its fallback and nowhere else. Staying
+ // there is still allowed, so an update opens nothing new. It is never somewhere they're sent.
+ open = List.of(only);
+ warnings.add(CONFIG + ": " + where + " has no worlds list, so players in no circle may still only be in \""
+ + only + "\". Write worlds: [" + only + "] in place of the fallback line.");
+ }
+ if (open.isEmpty()) {
+ errors.add(CONFIG + ": " + where + ".worlds must list at least one world.");
+ } else {
+ noCircle = new com.extantape.posse.rules.HomeWorlds.Entry(new LinkedHashSet<>(open), message);
+ }
continue;
}
- List worlds = strings(CONFIG, entry, "worlds");
- if (worlds.isEmpty()) errors.add(CONFIG + ": " + where + ".worlds must list at least one world.");
- if (!fallback.isEmpty() && !worlds.isEmpty() && !worlds.contains(fallback)) {
- errors.add(CONFIG + ": " + where + ".fallback must be one of its worlds.");
- }
- if (!fallback.isEmpty() && !worlds.isEmpty()) {
- byCircle.put(circle, new com.extantape.posse.rules.HomeWorlds.Entry(new LinkedHashSet<>(worlds), fallback, message));
+ boolean listed = entry.contains("worlds"), flagged = entry.contains("unlimited");
+ if (listed && flagged) {
+ unusable(broken, circle, "has both worlds and unlimited");
+ } else if (flagged) {
+ if (Boolean.TRUE.equals(entry.get("unlimited"))) {
+ byCircle.put(circle, com.extantape.posse.rules.HomeWorlds.Entry.noLimits());
+ } else {
+ unusable(broken, circle, "has an unlimited line that isn't exactly unlimited: true");
+ }
+ } else if (!listed) {
+ unusable(broken, circle, "has neither worlds nor unlimited: true");
+ } else {
+ List> raw = entry.getList("worlds");
+ if (raw == null || raw.isEmpty() || !raw.stream().allMatch(o -> o instanceof String || o instanceof Number || o instanceof Boolean)) {
+ unusable(broken, circle, "needs worlds to be a list of at least one world name");
+ } else {
+ byCircle.put(circle, new com.extantape.posse.rules.HomeWorlds.Entry(
+ new LinkedHashSet<>(strings(CONFIG, entry, "worlds")), message));
+ }
}
}
- if (circles.isEmpty() && !section.getKeys(false).isEmpty()) {
- errors.add(CONFIG + ": home-worlds needs at least one circle in circles. With none, nobody is in a circle and everyone would be sent to the no-circle world.");
+ if (circles.isEmpty() && !keys.isEmpty()) {
+ errors.add(CONFIG + ": home-worlds needs at least one circle in circles. With none, nobody is in a circle and everyone would be held to the no-circle worlds.");
}
- return new com.extantape.posse.rules.HomeWorlds(byCircle, noCircle);
+ return new com.extantape.posse.rules.HomeWorlds(byCircle, noCircle, lobby, broken);
+ }
+
+ /** Names a circle's entry that can't be used. It fails closed: the circle adds no worlds and lifts no limit. */
+ private void unusable(Set broken, String circle, String why) {
+ broken.add(circle);
+ warnings.add(CONFIG + ": home-worlds." + circle + " can't be used because it " + why + ", so the circle " + circle
+ + " adds no worlds until it's fixed. Write either worlds: [first_world, second_world] or unlimited: true.");
}
private String read(Path folder, String name) {
diff --git a/src/main/java/com/extantape/posse/listen/Eviction.java b/src/main/java/com/extantape/posse/listen/Eviction.java
new file mode 100644
index 0000000..dfba0d3
--- /dev/null
+++ b/src/main/java/com/extantape/posse/listen/Eviction.java
@@ -0,0 +1,329 @@
+package com.extantape.posse.listen;
+
+import com.extantape.posse.rules.Pending;
+import io.papermc.paper.event.player.AsyncChatEvent;
+import net.kyori.adventure.text.Component;
+import org.bukkit.entity.Entity;
+import org.bukkit.entity.Player;
+import org.bukkit.entity.Projectile;
+import org.bukkit.event.Cancellable;
+import org.bukkit.event.EventHandler;
+import org.bukkit.event.EventPriority;
+import org.bukkit.event.Listener;
+import org.bukkit.event.block.BlockBreakEvent;
+import org.bukkit.event.block.BlockDamageEvent;
+import org.bukkit.event.block.BlockPlaceEvent;
+import org.bukkit.event.block.SignChangeEvent;
+import org.bukkit.event.entity.EntityDamageByEntityEvent;
+import org.bukkit.event.entity.EntityDamageEvent;
+import org.bukkit.event.entity.EntityMountEvent;
+import org.bukkit.event.entity.EntityPickupItemEvent;
+import org.bukkit.event.entity.ProjectileLaunchEvent;
+import org.bukkit.event.inventory.InventoryClickEvent;
+import org.bukkit.event.inventory.InventoryDragEvent;
+import org.bukkit.event.inventory.InventoryOpenEvent;
+import org.bukkit.event.player.PlayerArmorStandManipulateEvent;
+import org.bukkit.event.player.PlayerBucketEmptyEvent;
+import org.bukkit.event.player.PlayerBucketFillEvent;
+import org.bukkit.event.player.PlayerCommandPreprocessEvent;
+import org.bukkit.event.player.PlayerDropItemEvent;
+import org.bukkit.event.player.PlayerEditBookEvent;
+import org.bukkit.event.player.PlayerInteractAtEntityEvent;
+import org.bukkit.event.player.PlayerInteractEntityEvent;
+import org.bukkit.event.player.PlayerInteractEvent;
+import org.bukkit.event.player.PlayerItemConsumeEvent;
+import org.bukkit.event.player.PlayerMoveEvent;
+import org.bukkit.event.player.PlayerPortalEvent;
+import org.bukkit.event.player.PlayerQuitEvent;
+import org.bukkit.event.player.PlayerSwapHandItemsEvent;
+import org.bukkit.event.player.PlayerTeleportEvent;
+
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * Disconnects players Posse can't let stay, and keeps at it. Another plugin can cancel a kick, so the kick is tried
+ * again for as long as the player is here. Until they have gone they are held: they can't move, use or break anything,
+ * chat, run commands, deal or take damage, or use an inventory, and being {@link Pending} they reach nobody.
+ *
+ * A player who is only {@link Pending}, with a move of Posse's still under way, is held back the same way until the
+ * move lands (2026-11-30). Teleports are the one difference: the move itself is a teleport, so a pending player may
+ * teleport, and the home-worlds check decides where to.
+ */
+@SuppressWarnings("deprecation")
+public final class Eviction implements Listener {
+ /** Ticks between tries while the player is still here. */
+ static final long RETRY_TICKS = 10;
+
+ /** What this needs from the server, so tests can stand in for it. */
+ public interface Host {
+ Player player(UUID id);
+
+ void nextTick(Runnable task);
+
+ void later(Runnable task, long ticks);
+
+ void warn(String line);
+
+ /** Takes the player out of everyone's game, and everyone out of theirs. */
+ void conceal(Player player);
+ }
+
+ /** One stay in the held state, so a retry left over from an earlier stay stops on its own. */
+ private static final class Hold {
+ boolean trying;
+ /** Whether at least one kick has been made. */
+ boolean tried;
+ boolean warned;
+ }
+
+ private final Host host;
+ /** Concurrent because chat is checked off the main thread. */
+ private final Map held = new ConcurrentHashMap<>();
+
+ public Eviction(Host host) {
+ this.host = host;
+ }
+
+ /** Holds the player at once. The hold ends only when they quit. */
+ public void hold(UUID id) {
+ Pending.begin(id);
+ held.computeIfAbsent(id, k -> new Hold());
+ conceal(id);
+ }
+
+ private void conceal(UUID id) {
+ quietly(() -> {
+ Player player = host.player(id);
+ if (player != null) host.conceal(player);
+ });
+ }
+
+ public boolean holds(UUID id) {
+ return held.containsKey(id);
+ }
+
+ /** Holds the player and disconnects them now, trying again for as long as they are here. */
+ public void now(UUID id, Component reason) {
+ hold(id);
+ Hold hold = held.get(id);
+ if (hold.trying) return;
+ hold.trying = true;
+ attempt(id, hold, reason);
+ }
+
+ /**
+ * Holds the player at once and disconnects them on the next tick. A kick from inside the join event would run the
+ * quit handlers before the join handlers had finished.
+ */
+ public void nextTick(UUID id, Component reason) {
+ hold(id);
+ host.nextTick(() -> {
+ if (holds(id)) now(id, reason);
+ });
+ }
+
+ private void attempt(UUID id, Hold hold, Component reason) {
+ if (held.get(id) != hold) return;
+ Player player = host.player(id);
+ if (player == null) return;
+ // The next try is booked first, so nothing that goes wrong below can end the tries.
+ host.later(() -> attempt(id, hold, reason), RETRY_TICKS);
+ // Still here a whole wait after being kicked. Sooner than that says nothing: a real server can list a player
+ // for a moment while a kick is going through.
+ if (hold.tried && !hold.warned) {
+ hold.warned = true;
+ host.warn("A disconnect didn't go through, perhaps because another plugin cancelled it. "
+ + "The player is held in place while Posse keeps trying.");
+ }
+ hold.tried = true;
+ // Again each time, for anyone who has joined since.
+ conceal(id);
+ quietly(player::leaveVehicle);
+ quietly(player::closeInventory);
+ quietly(() -> player.kick(reason));
+ }
+
+ private static void quietly(Runnable step) {
+ try {
+ step.run();
+ } catch (RuntimeException e) {
+ // The player stays held, and the next try is already booked.
+ }
+ }
+
+ /** Held, or waiting for a move to land. Safe to ask from the chat thread. */
+ private boolean frozen(UUID id) {
+ return holds(id) || Pending.has(id);
+ }
+
+ private void stop(Cancellable event, Entity who) {
+ if (who != null && frozen(who.getUniqueId())) event.setCancelled(true);
+ }
+
+ /** A held player was never meant to be here, so nobody is told they left. */
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onQuitLine(PlayerQuitEvent event) {
+ if (holds(event.getPlayer().getUniqueId())) event.quitMessage(null);
+ }
+
+ /** MONITOR, so the other quit handlers have already seen the player as pending. */
+ @EventHandler(priority = EventPriority.MONITOR)
+ public void onQuit(PlayerQuitEvent event) {
+ UUID id = event.getPlayer().getUniqueId();
+ if (held.remove(id) != null) Pending.end(id);
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onMove(PlayerMoveEvent event) {
+ stop(event, event.getPlayer());
+ }
+
+ /** Held players only, because Posse's own move of a pending player is a teleport. */
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onTeleport(PlayerTeleportEvent event) {
+ if (holds(event.getPlayer().getUniqueId())) event.setCancelled(true);
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onPortal(PlayerPortalEvent event) {
+ stop(event, event.getPlayer());
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onMount(EntityMountEvent event) {
+ stop(event, event.getEntity());
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onInteract(PlayerInteractEvent event) {
+ stop(event, event.getPlayer());
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onInteractEntity(PlayerInteractEntityEvent event) {
+ stop(event, event.getPlayer());
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onInteractAtEntity(PlayerInteractAtEntityEvent event) {
+ stop(event, event.getPlayer());
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onArmorStand(PlayerArmorStandManipulateEvent event) {
+ stop(event, event.getPlayer());
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onBreak(BlockBreakEvent event) {
+ stop(event, event.getPlayer());
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onBlockDamage(BlockDamageEvent event) {
+ stop(event, event.getPlayer());
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onPlace(BlockPlaceEvent event) {
+ stop(event, event.getPlayer());
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onBucketEmpty(PlayerBucketEmptyEvent event) {
+ stop(event, event.getPlayer());
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onBucketFill(PlayerBucketFillEvent event) {
+ stop(event, event.getPlayer());
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onConsume(PlayerItemConsumeEvent event) {
+ stop(event, event.getPlayer());
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onLaunch(ProjectileLaunchEvent event) {
+ Projectile projectile = event.getEntity();
+ if (projectile.getShooter() instanceof Player shooter) stop(event, shooter);
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onChat(AsyncChatEvent event) {
+ if (!frozen(event.getPlayer().getUniqueId())) return;
+ event.setCancelled(true);
+ quietly(() -> event.viewers().clear());
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onCommand(PlayerCommandPreprocessEvent event) {
+ stop(event, event.getPlayer());
+ }
+
+ /** Hitting a painting, an item frame or a vehicle isn't always damage, so the swing is stopped too. */
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onPreAttack(io.papermc.paper.event.player.PrePlayerAttackEntityEvent event) {
+ stop(event, event.getPlayer());
+ }
+
+ /** Arrows have their own pickup event. */
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onPickupArrow(org.bukkit.event.player.PlayerPickupArrowEvent event) {
+ stop(event, event.getPlayer());
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onSign(SignChangeEvent event) {
+ stop(event, event.getPlayer());
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onBook(PlayerEditBookEvent event) {
+ stop(event, event.getPlayer());
+ }
+
+ /** Both ways: a held player takes no damage and deals none, thrown and shot things included. */
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onDamage(EntityDamageEvent event) {
+ stop(event, event.getEntity());
+ if (event instanceof EntityDamageByEntityEvent hit) {
+ Entity by = hit.getDamager();
+ if (by instanceof Projectile projectile && projectile.getShooter() instanceof Player shooter) by = shooter;
+ stop(event, by);
+ }
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onDrop(PlayerDropItemEvent event) {
+ stop(event, event.getPlayer());
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onPickup(EntityPickupItemEvent event) {
+ stop(event, event.getEntity());
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onSwap(PlayerSwapHandItemsEvent event) {
+ stop(event, event.getPlayer());
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onInventoryOpen(InventoryOpenEvent event) {
+ stop(event, event.getPlayer());
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onInventoryClick(InventoryClickEvent event) {
+ stop(event, event.getWhoClicked());
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onInventoryDrag(InventoryDragEvent event) {
+ stop(event, event.getWhoClicked());
+ }
+}
diff --git a/src/main/java/com/extantape/posse/listen/HomeWorldsListener.java b/src/main/java/com/extantape/posse/listen/HomeWorldsListener.java
index f194a4b..6a34c18 100644
--- a/src/main/java/com/extantape/posse/listen/HomeWorldsListener.java
+++ b/src/main/java/com/extantape/posse/listen/HomeWorldsListener.java
@@ -3,59 +3,186 @@
import com.extantape.posse.PossePlugin;
import com.extantape.posse.rules.HomeWorlds;
import com.extantape.posse.rules.Pending;
+import com.extantape.posse.rules.Reach;
import com.extantape.posse.rules.Subject;
import com.extantape.posse.text.Messages;
+import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
+import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
+import org.bukkit.event.Cancellable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
+import org.bukkit.event.entity.EntityPortalEvent;
+import org.bukkit.event.entity.EntityTeleportEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerJoinEvent;
+import org.bukkit.event.player.PlayerPortalEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
+import org.bukkit.event.player.PlayerTeleportEvent;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.UUID;
+import java.util.WeakHashMap;
/**
- * Applies {@link HomeWorlds} (D290): on join, on respawn, and after any world change, as a safety net for a teleport
- * that got past the world plugin. Only the moved player is told anything.
+ * Applies {@link HomeWorlds} (D290): on join, on respawn, and to everyone online when the rules are read. A teleport,
+ * portal or ride is refused if it leads somewhere a player aboard may not be. After any world change there is a second
+ * look, as a safety net. Only the moved player is told anything. A player who must leave a world and has no world they
+ * may go to is disconnected through {@link Eviction}, which holds them until they have gone.
*/
public final class HomeWorldsListener implements Listener {
- private final PossePlugin plugin;
+ /** What a disconnected player reads. */
+ static final String SORRY = "Sorry, we couldn't get you to your world. Please join again.";
- public HomeWorldsListener(PossePlugin plugin) {
- this.plugin = plugin;
+ /** How long a move of Posse's own may take before the player is disconnected: ten seconds. */
+ static final long MOVE_TIMEOUT_TICKS = 200;
+
+ /** What this listener needs from the server and from Posse, so tests can stand in for both. */
+ interface Host extends Eviction.Host {
+ /** The home-worlds rules, or null while Posse is paused. */
+ HomeWorlds home();
+
+ Reach reach();
+
+ World world(String name);
+
+ void tell(Player player, String messageKey, Map vars);
+
+ /** Sends the player's held join line, if there is one. */
+ void announce(Player player);
+
+ Collection extends Player> online();
+
+ /** Brings the player list up to date, so someone just made pending drops off it. */
+ void refresh();
+ }
+
+ private final Host host;
+ /** Holds and disconnects players on their way out. Nothing may end their pending state or announce them. */
+ private final Eviction eviction;
+ /** Players whose delayed first-join check hasn't run. Only that check ends their pending state. */
+ private final Set waiting = new HashSet<>();
+ /**
+ * Players with a move of Posse's own under way, each with a token for that one move, so the end of a move from an
+ * earlier stay does nothing. The move's end, or its time limit, releases or disconnects them.
+ */
+ private final Map moving = new HashMap<>();
+ /** Teleports already refused, so a refusal that is taken back can be told from another plugin's. */
+ private final Set refused = Collections.newSetFromMap(new WeakHashMap<>());
+ private boolean warnedUnsure;
+ private boolean warnedTakenBack;
+
+ public HomeWorldsListener(PossePlugin plugin, Eviction eviction) {
+ this(hostOf(plugin), eviction);
+ }
+
+ HomeWorldsListener(Host host, Eviction eviction) {
+ this.host = host;
+ this.eviction = eviction;
}
- /** The move this player needs from {@code atWorld}, or null. Null too while the rules are paused or the feature is off. */
+ private static Host hostOf(PossePlugin plugin) {
+ return new Host() {
+ @Override public HomeWorlds home() {
+ PossePlugin.State state = plugin.state();
+ return state == null ? null : state.settings().homeWorlds();
+ }
+
+ @Override public Reach reach() {
+ PossePlugin.State state = plugin.state();
+ return state == null ? null : state.settings().reach();
+ }
+
+ @Override public World world(String name) {
+ return Bukkit.getWorld(name);
+ }
+
+ @Override public Player player(UUID id) {
+ return Bukkit.getPlayer(id);
+ }
+
+ @Override public void nextTick(Runnable task) {
+ Bukkit.getScheduler().runTask(plugin, task);
+ }
+
+ @Override public void later(Runnable task, long ticks) {
+ Bukkit.getScheduler().runTaskLater(plugin, task, ticks);
+ }
+
+ @Override public void tell(Player player, String messageKey, Map vars) {
+ plugin.tell(player, messageKey, vars);
+ }
+
+ @Override public void warn(String line) {
+ plugin.getLogger().warning(line);
+ }
+
+ @Override public void conceal(Player player) {
+ plugin.conceal(player);
+ }
+
+ @Override public void announce(Player player) {
+ if (plugin.presence() != null) plugin.presence().release(player);
+ }
+
+ @Override public Collection extends Player> online() {
+ return Bukkit.getOnlinePlayers();
+ }
+
+ @Override public void refresh() {
+ if (plugin.presence() != null) plugin.presence().refresh();
+ }
+ };
+ }
+
+ /** {@link #decide}, for a player who is already somewhere: if the question can't be answered, they can't stay. */
+ private HomeWorlds.Move judge(Player player, String atWorld) {
+ try {
+ return decide(player, atWorld);
+ } catch (RuntimeException e) {
+ return new HomeWorlds.Move(null, null, HomeWorlds.Kind.DISCONNECT, "Posse couldn't check which worlds they may be in");
+ }
+ }
+
+ /** What this player needs in {@code atWorld}, or null to leave them. Null too while paused or with the feature off. */
private HomeWorlds.Move decide(Player player, String atWorld) {
- PossePlugin.State state = plugin.state();
- if (state == null) return null;
- HomeWorlds home = state.settings().homeWorlds();
- if (!home.enabled()) return null;
+ HomeWorlds home = host.home();
+ if (home == null || !home.enabled()) return null;
Subject who = Subject.of(player.getUniqueId(), player.getName(), atWorld, player::hasPermission);
- return home.decide(state.settings().reach(), who, atWorld, w -> Bukkit.getWorld(w) != null, Bukkit.getWorlds().get(0).getName());
+ return home.decide(host.reach(), who, atWorld, w -> host.world(w) != null);
}
+ /** The spawn to send the player to, or null if there is none: a disconnect, or a lobby that has gone since. */
private Location spawnOf(HomeWorlds.Move move) {
- World world = Bukkit.getWorld(move.world());
- return world == null ? Bukkit.getWorlds().get(0).getSpawnLocation() : world.getSpawnLocation();
+ if (move.disconnect()) return null;
+ World world = host.world(move.world());
+ return world == null ? null : world.getSpawnLocation();
}
private void tell(Player player, HomeWorlds.Move move) {
- if (move.degraded()) {
- plugin.getLogger().warning("A player was moved to the main world's spawn because the home-worlds fallback \"" + move.wanted()
- + "\" doesn't exist. Create that world or fix home-worlds in config.yml.");
- }
- String key = move.kind() == HomeWorlds.Kind.NO_CIRCLE ? "home-waiting" : "home-moved";
+ String key = move.kind() == HomeWorlds.Kind.NO_CIRCLE ? "home-waiting" : "home-lobby";
Map vars = Map.of("world", move.world());
if (move.message() != null) {
if (!move.message().isBlank()) player.sendMessage(Messages.parse(move.message(), vars));
- } else plugin.tell(player, key, vars);
+ } else host.tell(player, key, vars);
+ }
+
+ /** The warning says what stopped the move, naming a world at most and never the player. */
+ private void warnNowhere(HomeWorlds.Move move) {
+ host.warn("A player outside their home worlds was disconnected because " + move.asDisconnect().why() + ".");
}
/**
@@ -74,81 +201,359 @@ public void onJoin(PlayerJoinEvent event) {
checkAfterJoin(player, false);
return;
}
- PossePlugin.State state = plugin.state();
UUID id = player.getUniqueId();
- boolean governed = state != null && state.settings().homeWorlds().governs(state.settings().reach(), Subject.of(player));
- if (governed) Pending.begin(id);
+ boolean governed = mayBeMoved(player);
+ if (governed && !Pending.has(id)) hide(player);
+ waiting.add(id);
// The task keeps the ID, not the Player, so a player who quit and came back is never mistaken for this one.
- Bukkit.getScheduler().runTaskLater(plugin, () -> {
- Player now = Bukkit.getPlayer(id);
+ host.later(() -> guarded(id, () -> {
+ waiting.remove(id);
+ Player now = host.player(id);
if (now == null) {
Pending.end(id);
return;
}
checkAfterJoin(now, governed);
- }, delay);
+ }), delay);
+ }
+
+ /** Makes a player pending: out of any seat or open inventory, and out of everyone's game (2026-11-30). */
+ private void hide(Player player) {
+ settle(player);
+ quietly(host::refresh);
+ }
+
+ /** Pending, and stopped where they are. The caller brings the player list up to date. */
+ private void settle(Player player) {
+ Pending.begin(player.getUniqueId());
+ quietly(player::leaveVehicle);
+ quietly(player::closeInventory);
+ }
+
+ private static void quietly(Runnable step) {
+ try {
+ step.run();
+ } catch (RuntimeException e) {
+ // The player is pending either way, and the list catches up on its timer.
+ }
+ }
+
+ /** Runs a check. If it breaks, the player is disconnected, never left waiting for something that won't come. */
+ private void guarded(UUID id, Runnable check) {
+ try {
+ check.run();
+ } catch (RuntimeException e) {
+ host.warn("A home-worlds check failed, so the player was disconnected.");
+ moving.remove(id);
+ eviction.nextTick(id, Component.text(SORRY));
+ }
+ }
+
+ /** Whether the rules could ever move this player. If that can't be worked out, they could. */
+ private boolean mayBeMoved(Player player) {
+ try {
+ HomeWorlds home = host.home();
+ return home != null && home.governs(host.reach(), Subject.of(player));
+ } catch (RuntimeException e) {
+ return true;
+ }
}
@EventHandler(priority = EventPriority.MONITOR)
public void onQuit(PlayerQuitEvent event) {
- Pending.end(event.getPlayer().getUniqueId());
+ // A held player stays pending until Eviction's own quit handler, which also runs at MONITOR.
+ UUID id = event.getPlayer().getUniqueId();
+ waiting.remove(id);
+ moving.remove(id);
+ if (!eviction.holds(id)) Pending.end(id);
}
/** Ends the pending state and sends the held join line, for where the player is now. Runs on the main thread. */
private void release(UUID id) {
+ if (eviction.holds(id)) return;
Pending.end(id);
- Player player = Bukkit.getPlayer(id);
- if (player != null && plugin.presence() != null) plugin.presence().release(player);
+ Player player = host.player(id);
+ if (player == null) return;
+ try {
+ host.announce(player);
+ } catch (RuntimeException e) {
+ host.warn("A join line held back during a home-worlds check couldn't be sent.");
+ }
}
private void checkAfterJoin(Player player, boolean alreadyPending) {
UUID id = player.getUniqueId();
- HomeWorlds.Move move = decide(player, player.getWorld().getName());
+ if (eviction.holds(id) || moving.containsKey(id)) return;
+ HomeWorlds.Move move = judge(player, player.getWorld().getName());
if (move == null) {
- if (alreadyPending) release(id);
+ if (alreadyPending || Pending.has(id)) release(id);
return;
}
- // A returning player who has to be moved is pending too, until the move is done (K832). Otherwise their join
- // line would go to whoever can reach the world they must not be in, and so would the leave line if the move
- // fails and they are disconnected. Nobody hears of them until they are where they may be.
- Pending.begin(id);
- player.teleportAsync(spawnOf(move)).thenAccept(ok -> Bukkit.getScheduler().runTask(plugin, () -> {
- Player now = Bukkit.getPlayer(id);
- if (ok) {
- if (now != null) tell(now, move);
- release(id);
- } else {
- // Fail closed: a player who must not stay here and couldn't be moved is sent off, never left in place.
- plugin.getLogger().warning("A home-worlds move on join didn't go through, so the player was disconnected instead of being left there.");
- if (now != null) now.kick(net.kyori.adventure.text.Component.text("Sorry, we couldn't get you to your world. Please join again."));
+ send(player, move, "on join", true);
+ }
+
+ /**
+ * Moves a player who can't stay where they are to the lobby, or disconnects them. A player who has to be moved is
+ * pending until the move is done (K832). Otherwise their join line, chat and place on the player list would reach
+ * whoever can reach the world they must not be in. Nobody hears of them until they are where they may be.
+ *
+ * @param when what led to this, for the log
+ * @param nextTick whether a disconnect waits a tick, because this runs inside a join or a reload
+ */
+ private void send(Player player, HomeWorlds.Move move, String when, boolean nextTick) {
+ UUID id = player.getUniqueId();
+ Location to = spawnOf(move);
+ if (to == null) {
+ warnNowhere(move);
+ if (nextTick) eviction.nextTick(id, Component.text(SORRY));
+ else eviction.now(id, Component.text(SORRY));
+ return;
+ }
+ if (!Pending.has(id)) hide(player);
+ Object thisMove = new Object();
+ moving.put(id, thisMove);
+ try {
+ host.later(() -> {
+ if (!moving.remove(id, thisMove) || host.player(id) == null || eviction.holds(id)) return;
+ host.warn("A home-worlds move " + when + " didn't finish in time, so the player was disconnected.");
+ eviction.now(id, Component.text(SORRY));
+ }, MOVE_TIMEOUT_TICKS);
+ // A teleport that ends in an error counts as one that didn't go through.
+ player.teleportAsync(to).whenComplete((ok, error) -> host.nextTick(() -> {
+ if (moving.remove(id, thisMove)) {
+ guarded(id, () -> arrive(id, move, when, error == null && Boolean.TRUE.equals(ok)));
+ }
+ }));
+ } catch (RuntimeException e) {
+ moving.remove(id);
+ host.warn(didNotGoThrough(when));
+ if (nextTick) eviction.nextTick(id, Component.text(SORRY));
+ else eviction.now(id, Component.text(SORRY));
+ }
+ }
+
+ private static String didNotGoThrough(String when) {
+ return "A home-worlds move " + when + " didn't go through, so the player was disconnected instead of being left there.";
+ }
+
+ private void arrive(UUID id, HomeWorlds.Move move, String when, boolean landed) {
+ Player now = host.player(id);
+ if (now == null || eviction.holds(id)) return;
+ // Looked at again where they really are, because another plugin may have changed where the move landed.
+ if (landed && judge(now, now.getWorld().getName()) == null) {
+ try {
+ tell(now, move);
+ } catch (RuntimeException e) {
+ host.warn("A moved player couldn't be told why they were moved.");
}
- }));
+ if (!waiting.contains(id)) release(id);
+ } else {
+ // Fail closed: a player who must not stay here and couldn't be moved is sent off, never left in place.
+ host.warn(didNotGoThrough(when));
+ eviction.now(id, Component.text(SORRY));
+ }
}
+ /**
+ * A respawn can't be cancelled, so a player with nowhere to go is held at once and disconnected on the next tick.
+ * The server saves where they are when they leave. If the world they died in is one they may be in, the respawn is
+ * pointed back there, so a forbidden world isn't saved. If neither world is allowed, the server's respawn point
+ * stands, because Posse has no allowed place to name. The join check looks at them again next time.
+ */
@EventHandler(priority = EventPriority.HIGH)
public void onRespawn(PlayerRespawnEvent event) {
Player player = event.getPlayer();
- HomeWorlds.Move move = decide(player, event.getRespawnLocation().getWorld().getName());
+ HomeWorlds.Move move = judge(player, event.getRespawnLocation().getWorld().getName());
if (move == null) return;
- event.setRespawnLocation(spawnOf(move));
+ Location to = spawnOf(move);
+ if (to == null) {
+ World diedIn = player.getWorld();
+ if (host.world(diedIn.getName()) != null && judge(player, diedIn.getName()) == null) {
+ event.setRespawnLocation(diedIn.getSpawnLocation());
+ }
+ warnNowhere(move);
+ eviction.nextTick(player.getUniqueId(), Component.text(SORRY));
+ return;
+ }
+ event.setRespawnLocation(to);
tell(player, move);
}
- @EventHandler(priority = EventPriority.MONITOR)
+ /**
+ * The safety net, for anyone who changed world in a way the teleport checks below didn't refuse. A player who
+ * arrived where they may not be is pending at once, and this runs before the player list catches up at MONITOR.
+ * The move itself waits a tick, so the teleport that brought them has finished. The later look also catches a
+ * permissions plugin that changes someone's circles as they change world.
+ */
+ @EventHandler(priority = EventPriority.LOW)
public void onWorldChange(PlayerChangedWorldEvent event) {
Player player = event.getPlayer();
- // Next tick, so the teleport that caused this has finished before this one starts.
- Bukkit.getScheduler().runTask(plugin, () -> {
- if (!player.isOnline()) return;
- HomeWorlds.Move move = decide(player, player.getWorld().getName());
- if (move == null) return;
- player.teleportAsync(spawnOf(move)).thenAccept(ok -> {
- if (ok) tell(player, move);
- else Bukkit.getScheduler().runTask(plugin, () -> {
- plugin.getLogger().warning("A home-worlds move after a world change didn't go through, so the player was disconnected instead of being left there.");
- if (player.isOnline()) player.kick(net.kyori.adventure.text.Component.text("Sorry, we couldn't get you to your world. Please join again."));
- });
- });
- });
+ UUID id = player.getUniqueId();
+ if (eviction.holds(id)) return;
+ if (judge(player, player.getWorld().getName()) != null && !Pending.has(id)) hide(player);
+ host.nextTick(() -> guarded(id, () -> checkAfterWorldChange(id)));
+ }
+
+ private void checkAfterWorldChange(UUID id) {
+ Player player = host.player(id);
+ if (player == null || eviction.holds(id) || moving.containsKey(id)) return;
+ HomeWorlds.Move move = judge(player, player.getWorld().getName());
+ if (move == null) {
+ // Pending from the moment they changed world, and allowed after all. A first-join wait runs its course.
+ if (Pending.has(id) && !waiting.contains(id)) release(id);
+ return;
+ }
+ send(player, move, "after a world change", false);
+ }
+
+ /**
+ * Looks at everyone online again, for when the rules have just been read, so a tighter config applies to people
+ * who are already here. Everyone who can't stay is pending, and off the player list, before anyone is moved.
+ * Someone still waiting for their first-join check is moved by that check. Runs on the main thread.
+ */
+ public void recheck() {
+ Map leaving = new LinkedHashMap<>();
+ boolean hid = false;
+ for (Player player : List.copyOf(host.online())) {
+ UUID id = player.getUniqueId();
+ if (eviction.holds(id) || moving.containsKey(id)) continue;
+ HomeWorlds.Move move = judge(player, player.getWorld().getName());
+ if (move == null) {
+ // Pending with nothing left to end it would leave them frozen.
+ if (Pending.has(id) && !waiting.contains(id)) release(id);
+ continue;
+ }
+ if (!Pending.has(id)) settle(player);
+ hid = true;
+ if (!waiting.contains(id)) leaving.put(player, move);
+ }
+ if (!hid) return;
+ host.refresh();
+ leaving.forEach((player, move) -> send(player, move, "after a reload", true));
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
+ public void onTeleport(PlayerTeleportEvent event) {
+ if (forbidden(event.getPlayer(), event.getTo())) {
+ refuse(event);
+ event.setTo(event.getFrom());
+ }
+ }
+
+ /** Portals have their own list of listeners, so the teleport check above never hears of them. */
+ @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
+ public void onPortal(PlayerPortalEvent event) {
+ if (forbidden(event.getPlayer(), event.getTo())) {
+ refuse(event);
+ event.setTo(event.getFrom());
+ }
+ }
+
+ /** A boat, minecart or mount that takes its riders with it. */
+ @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
+ public void onEntityTeleport(EntityTeleportEvent event) {
+ if (forbidden(event.getEntity(), event.getTo())) {
+ refuse(event);
+ event.setTo(event.getFrom());
+ }
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
+ public void onEntityPortal(EntityPortalEvent event) {
+ if (forbidden(event.getEntity(), event.getTo())) {
+ refuse(event);
+ event.setTo(event.getFrom());
+ }
+ }
+
+ /*
+ * The last look, after every other priority (2026-11-30). Another plugin can take a refusal back, or change where a
+ * teleport leads after the check above. These run even on cancelled events, and put the refusal back along with the
+ * starting point. The check after a world change covers a plugin that gets in later still.
+ */
+
+ @EventHandler(priority = EventPriority.MONITOR)
+ public void onTeleportLast(PlayerTeleportEvent event) {
+ if (mustPutBack(event, event.getPlayer(), event.getTo(), event.getFrom())) {
+ event.setCancelled(true);
+ event.setTo(event.getFrom());
+ }
+ }
+
+ @EventHandler(priority = EventPriority.MONITOR)
+ public void onPortalLast(PlayerPortalEvent event) {
+ if (mustPutBack(event, event.getPlayer(), event.getTo(), event.getFrom())) {
+ event.setCancelled(true);
+ event.setTo(event.getFrom());
+ }
+ }
+
+ @EventHandler(priority = EventPriority.MONITOR)
+ public void onEntityTeleportLast(EntityTeleportEvent event) {
+ if (mustPutBack(event, event.getEntity(), event.getTo(), event.getFrom())) {
+ event.setCancelled(true);
+ event.setTo(event.getFrom());
+ }
+ }
+
+ @EventHandler(priority = EventPriority.MONITOR)
+ public void onEntityPortalLast(EntityPortalEvent event) {
+ if (mustPutBack(event, event.getEntity(), event.getTo(), event.getFrom())) {
+ event.setCancelled(true);
+ event.setTo(event.getFrom());
+ }
+ }
+
+ private void refuse(Cancellable event) {
+ event.setCancelled(true);
+ refused.add(event);
+ }
+
+ /** Whether a refusal has to be put back, or a destination changed since the check has to be refused. */
+ private boolean mustPutBack(Cancellable event, Entity mover, Location to, Location from) {
+ boolean ours = refused.contains(event);
+ // Refused here and still exactly as left, or refused by someone else: nothing to do.
+ if (event.isCancelled() && (!ours || (to != null && to.equals(from)))) return false;
+ if (!ours && !forbidden(mover, to)) return false;
+ // Once, because a player standing in a portal asks again and again.
+ if (!warnedTakenBack) {
+ host.warn("Another plugin changed a teleport after Posse had checked it. Posse refused it again.");
+ warnedTakenBack = true;
+ }
+ return true;
+ }
+
+ /** Whether the teleport would take any player aboard somewhere they may not be. */
+ private boolean forbidden(Entity mover, Location to) {
+ for (Player player : aboard(mover, new ArrayList<>())) {
+ if (!mayArrive(player, to)) return true;
+ }
+ return false;
+ }
+
+ /** The mover if it is a player, and every player riding it, however high they are stacked. */
+ private static List aboard(Entity mover, List found) {
+ if (mover instanceof Player player) found.add(player);
+ for (Entity rider : mover.getPassengers()) aboard(rider, found);
+ return found;
+ }
+
+ /**
+ * Whether home worlds lets this player arrive there. Anything that stops the question being answered is a no:
+ * unreadable rules or permissions, or a destination with no loaded world. While Posse is paused it has no rules,
+ * so only a player with posse.bypass may teleport.
+ */
+ private boolean mayArrive(Player player, Location to) {
+ try {
+ HomeWorlds home = host.home();
+ if (home == null) return player.hasPermission("posse.bypass");
+ if (!home.enabled()) return true;
+ return decide(player, to.getWorld().getName()) == null;
+ } catch (RuntimeException e) {
+ // Said once, because a player standing in a portal asks again and again.
+ if (!warnedUnsure) host.warn("A teleport was refused because Posse couldn't check where it led.");
+ warnedUnsure = true;
+ return false;
+ }
}
}
diff --git a/src/main/java/com/extantape/posse/listen/PausedLoginGate.java b/src/main/java/com/extantape/posse/listen/PausedLoginGate.java
new file mode 100644
index 0000000..44104bb
--- /dev/null
+++ b/src/main/java/com/extantape/posse/listen/PausedLoginGate.java
@@ -0,0 +1,97 @@
+package com.extantape.posse.listen;
+
+import net.kyori.adventure.text.Component;
+import org.bukkit.entity.Player;
+import org.bukkit.event.EventHandler;
+import org.bukkit.event.EventPriority;
+import org.bukkit.event.Listener;
+import org.bukkit.event.player.PlayerJoinEvent;
+import org.bukkit.event.player.PlayerLoginEvent;
+
+import java.util.function.BooleanSupplier;
+import java.util.function.Consumer;
+import java.util.function.LongSupplier;
+
+/**
+ * Refuses joins while Posse is paused because it couldn't load its rules at startup: a config it can't read, or a
+ * startup that failed partway. With no rules, home worlds can't move anyone, so nobody may come in except players with
+ * {@code posse.bypass}. There is no setting for this, because a config that can't be read couldn't turn it off or on.
+ *
+ * The login check uses {@link PlayerLoginEvent}. Paper 26.1 to 26.3 mark it deprecated (since 1.21.6, not marked for
+ * removal) and warn that listening to it makes the server create the player early. It is still the join check that can
+ * ask the player for a permission: Paper's newer login check offers only the connection. Posse therefore registers this
+ * at startup and removes it once startup has finished with working rules. Another plugin could allow a login again, and
+ * a later Paper could stop calling the event, so the join is checked too: the player is held at once, their join line
+ * is dropped, and they are disconnected.
+ */
+@SuppressWarnings("deprecation")
+public final class PausedLoginGate implements Listener {
+ static final String REFUSAL = "The server's safety rules didn't load, so joining is paused. Please try again later.";
+ private static final String BYPASS = "posse.bypass";
+ private static final long LOG_EVERY_MILLIS = 60_000;
+
+ private final BooleanSupplier paused;
+ private final Eviction eviction;
+ private final Consumer log;
+ private final LongSupplier clock;
+ private long lastLogged;
+ private boolean logged;
+
+ public PausedLoginGate(BooleanSupplier paused, Eviction eviction, Consumer log) {
+ this(paused, eviction, log, System::currentTimeMillis);
+ }
+
+ PausedLoginGate(BooleanSupplier paused, Eviction eviction, Consumer log, LongSupplier clock) {
+ this.paused = paused;
+ this.eviction = eviction;
+ this.log = log;
+ this.clock = clock;
+ }
+
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onLogin(PlayerLoginEvent event) {
+ // A join that something else has already refused stays refused, with its own message.
+ if (event.getResult() != PlayerLoginEvent.Result.ALLOWED || !refused(event.getPlayer())) return;
+ event.disallow(PlayerLoginEvent.Result.KICK_OTHER, Component.text(REFUSAL));
+ logRefusal();
+ }
+
+ /** First, so that every other join handler already sees a player who reaches nobody. */
+ @EventHandler(priority = EventPriority.LOWEST)
+ public void onJoinFirst(PlayerJoinEvent event) {
+ Player player = event.getPlayer();
+ if (refused(player)) eviction.hold(player.getUniqueId());
+ }
+
+ /** Late, so a join line another plugin wrote is dropped too. */
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onJoinLast(PlayerJoinEvent event) {
+ Player player = event.getPlayer();
+ if (!eviction.holds(player.getUniqueId()) && !refused(player)) return;
+ event.joinMessage(null);
+ eviction.nextTick(player.getUniqueId(), Component.text(REFUSAL));
+ logRefusal();
+ }
+
+ private boolean refused(Player player) {
+ return paused.getAsBoolean() && !bypasses(player);
+ }
+
+ private static boolean bypasses(Player player) {
+ try {
+ return player.hasPermission(BYPASS);
+ } catch (RuntimeException e) {
+ return false;
+ }
+ }
+
+ private void logRefusal() {
+ long now = clock.getAsLong();
+ if (!logged || now - lastLogged >= LOG_EVERY_MILLIS) {
+ logged = true;
+ lastLogged = now;
+ log.accept("A join was refused because Posse's safety rules aren't loaded. See the earlier errors in the log. "
+ + "Fix a config problem and run posse reload from the console. If Posse didn't start, restart the server.");
+ }
+ }
+}
diff --git a/src/main/java/com/extantape/posse/listen/PresenceListener.java b/src/main/java/com/extantape/posse/listen/PresenceListener.java
index 0d83399..9d9b7f7 100644
--- a/src/main/java/com/extantape/posse/listen/PresenceListener.java
+++ b/src/main/java/com/extantape/posse/listen/PresenceListener.java
@@ -143,7 +143,8 @@ public void refresh() {
boolean see, know;
try {
see = maySee(viewer, other);
- know = Presence.mayKnowOf(see, viewer.getWorld().equals(other.getWorld()));
+ know = Presence.mayKnowOf(see, viewer.getWorld().equals(other.getWorld()),
+ Pending.has(viewer.getUniqueId()) || Pending.has(other.getUniqueId()));
} catch (RuntimeException e) {
see = false;
know = false;
@@ -165,6 +166,17 @@ public void refresh() {
}
}
+ /** Hides one player from everyone, and everyone from them, at once. A later {@link #refresh} shows them again. */
+ public void conceal(Player player) {
+ for (Player other : Bukkit.getOnlinePlayers()) {
+ if (other == player) continue;
+ other.hideEntity(plugin, player);
+ hidden.computeIfAbsent(other.getUniqueId(), id -> new HashSet<>()).add(player.getUniqueId());
+ player.hideEntity(plugin, other);
+ hidden.computeIfAbsent(player.getUniqueId(), id -> new HashSet<>()).add(other.getUniqueId());
+ }
+ }
+
/** Undoes Posse's own hiding, for when the plugin is turned off. */
public void showAll() {
for (Player viewer : Bukkit.getOnlinePlayers()) {
diff --git a/src/main/java/com/extantape/posse/rules/HomeWorlds.java b/src/main/java/com/extantape/posse/rules/HomeWorlds.java
index 9d893a8..4b3f470 100644
--- a/src/main/java/com/extantape/posse/rules/HomeWorlds.java
+++ b/src/main/java/com/extantape/posse/rules/HomeWorlds.java
@@ -9,33 +9,67 @@
* Keeps players in the worlds their circles belong in (D290, 2026-11-25). Players rejoin where they logged out, so
* this only steps in when that world isn't one their circle allows. Nothing moves unless {@code home-worlds} is set.
*
- * The rules, in order:
+ * Each circle's entry either lists worlds or says it has no limits (owner, 2026-11-30). The rules, in order:
*
- * - A player in no circle goes to the {@code no-circle} fallback, unless they're already there.
- * - A player in any circle that has no entry is never moved. That covers the visitor in both a kids' and an adults'
- * circle, and every adult group.
- * - Otherwise every circle they hold has an entry, and they may be in any of those worlds. Anywhere else, they go
- * to the fallback of the first of their circles that has one.
- * - Fails closed: if that fallback world doesn't exist, they go to the main world's spawn instead, and the caller
- * logs a warning. They are never left where they are.
+ * - A player in any circle with no limits is never moved, whatever their other circles say.
+ * - Otherwise they may be in any world listed by any of their circles. A circle with no usable entry adds none.
+ * - A player whose circles add nothing, or who is in no circle, may be in the worlds of the {@code no-circle}
+ * entry. With no such entry they may only be in the lobby.
+ * - Anywhere else, they go to the server's lobby (D368, 2026-11-30), but only if one is named, it is in the worlds
+ * they may be in, and it is loaded.
+ * - Fails closed: otherwise the answer is to disconnect them. No other world is ever chosen, the main world
+ * included unless it is that lobby, and they are never left where they are.
*
*/
public final class HomeWorlds {
- /** Where a circle's players may be, where they go otherwise, and an optional line to tell them. */
- public record Entry(Set worlds, String fallback, String message) {
+ /**
+ * Where a group's players may be, and an optional line to tell the ones who are moved to the lobby. An unlimited
+ * entry lists no worlds: its players are never moved.
+ */
+ public record Entry(Set worlds, String message, boolean unlimited) {
public Entry {
worlds = Set.copyOf(worlds);
}
+
+ public Entry(Set worlds, String message) {
+ this(worlds, message, false);
+ }
+
+ public static Entry noLimits() {
+ return new Entry(Set.of(), null, true);
+ }
}
- /** Why a player is moved, so the right message can be used. */
- public enum Kind { CIRCLE, NO_CIRCLE }
+ /**
+ * What happens to a player who can't stay, which picks the message: a circle's player or one in no circle goes to
+ * the lobby. {@code DISCONNECT} means there is nowhere to move them.
+ */
+ public enum Kind { LOBBY, NO_CIRCLE, DISCONNECT }
/**
- * A move to make. {@code world} is the world whose spawn to use; {@code degraded} means the wanted fallback
- * doesn't exist and the main world stands in; {@code message} is the entry's own line, or null for the default.
+ * What to do with a player who can't stay. {@code world} is the lobby whose spawn to use, or null when they must be
+ * disconnected; {@code message} is the entry's own line, or null for the default; {@code why} says what stopped a
+ * move, for the log, and is null for a move.
*/
- public record Move(String world, boolean degraded, String wanted, String message, Kind kind) {}
+ public record Move(String world, String message, Kind kind, String why) {
+ /** There is nowhere the player may be sent, so they are disconnected. */
+ public boolean disconnect() {
+ return kind == Kind.DISCONNECT;
+ }
+
+ /** A move turned into a disconnect, for a lobby that stopped being loaded after the decision. */
+ public Move asDisconnect() {
+ return disconnect() ? this : nowhere(notLoaded(world));
+ }
+
+ private static Move nowhere(String why) {
+ return new Move(null, null, Kind.DISCONNECT, why);
+ }
+
+ private static String notLoaded(String lobby) {
+ return "the lobby \"" + lobby + "\" isn't loaded";
+ }
+ }
/** How long a first-ever join waits before its world is checked, so first-spawn placement happens first (D297). One second. */
public static final long FIRST_JOIN_DELAY_TICKS = 20;
@@ -50,16 +84,39 @@ public static long joinDelayTicks(boolean playedBefore) {
private final Map byCircle;
private final List orderedKeys;
private final Entry noCircle;
+ private final String lobby;
+ private final Set broken;
- /** @param byCircle circle name to its entry, in config order; @param noCircle the entry for players with no circle, or null */
+ /** The same, on a server that names no lobby. */
public HomeWorlds(Map inOrder, Entry noCircle) {
+ this(inOrder, noCircle, "");
+ }
+
+ /**
+ * @param inOrder circle name to its entry, in config order
+ * @param noCircle the entry for players with no circle, or null
+ * @param lobby the server's lobby world, or empty for none
+ */
+ public HomeWorlds(Map inOrder, Entry noCircle, String lobby) {
+ this(inOrder, noCircle, lobby, Set.of());
+ }
+
+ /** @param broken circles whose entry was written and can't be used. They add nothing, and the rules stay on. */
+ public HomeWorlds(Map inOrder, Entry noCircle, String lobby, Set broken) {
+ this.broken = Set.copyOf(broken);
+ this.lobby = lobby == null ? "" : lobby;
this.byCircle = Map.copyOf(inOrder);
this.orderedKeys = List.copyOf(inOrder.keySet());
this.noCircle = noCircle;
}
public boolean enabled() {
- return !byCircle.isEmpty() || noCircle != null;
+ return !byCircle.isEmpty() || noCircle != null || !broken.isEmpty();
+ }
+
+ /** Circles whose entry can't be used. */
+ public Set broken() {
+ return broken;
}
public Map byCircle() {
@@ -70,64 +127,104 @@ public Entry noCircle() {
return noCircle;
}
- /** Every world named anywhere in the section, for checking they exist. */
+ /** The server's lobby world, or empty when none is named. */
+ public String lobby() {
+ return lobby;
+ }
+
+ /**
+ * The worlds players in no circle may be in. With no no-circle entry that is the lobby and nowhere else, or no world
+ * at all when no lobby is named. Empty when home worlds is off.
+ */
+ public Set noCircleWorlds() {
+ return enabled() ? noCircleEntry().worlds() : Set.of();
+ }
+
+ /**
+ * The rule for players in no circle, whether or not the config spells it out (2026-11-30). A player whose groups a
+ * permissions plugin doesn't report looks the same as one in no group, so leaving the entry out must not open
+ * every world to them.
+ */
+ private Entry noCircleEntry() {
+ return noCircle != null ? noCircle : new Entry(lobby.isEmpty() ? Set.of() : Set.of(lobby), null);
+ }
+
+ /** One line for each world named here that isn't loaded, saying what to do. Empty when it's off. */
+ public List problems(Predicate exists) {
+ List out = new java.util.ArrayList<>();
+ if (!enabled()) return out;
+ for (String world : namedWorlds()) {
+ if (exists.test(world)) continue;
+ out.add(world.equals(lobby)
+ ? "home-worlds: the lobby world \"" + world + "\" doesn't exist, so anyone outside their home worlds "
+ + "is disconnected until it does."
+ : "home-worlds: the world \"" + world + "\" doesn't exist. Check its spelling, or load it.");
+ }
+ return out;
+ }
+
+ /** Every world named in these rules, the lobby included, for checking they exist. */
public Set namedWorlds() {
Set all = new java.util.TreeSet<>();
- for (Entry e : byCircle.values()) {
- all.addAll(e.worlds());
- all.add(e.fallback());
- }
- if (noCircle != null) all.add(noCircle.fallback());
+ for (Entry e : byCircle.values()) all.addAll(e.worlds());
+ all.addAll(noCircleWorlds());
+ if (enabled() && !lobby.isEmpty()) all.add(lobby);
return all;
}
/**
- * Whether these rules can ever move this player: home worlds are on and either the player is in no circle and
- * there is a no-circle entry, or every circle they hold has an entry. A player in a circle with no entry, such as
- * an adult, is never moved, so there is nothing to wait for.
+ * Whether these rules can ever move this player: home worlds are on and none of their circles has no limits. A
+ * player with an unlimited circle is never moved, so there is nothing to wait for.
*/
public boolean governs(Reach reach, Subject who) {
if (!enabled() || reach == null || !reach.active()) return false;
- List circles = reach.circlesOf(who);
- if (circles.isEmpty()) return noCircle != null;
- for (String circle : circles) if (!byCircle.containsKey(circle)) return false;
- return true;
+ return !unlimited(reach.circlesOf(who));
+ }
+
+ private boolean unlimited(List circles) {
+ for (String circle : circles) {
+ Entry e = byCircle.get(circle);
+ if (e != null && e.unlimited()) return true;
+ }
+ return false;
}
/**
- * Whether and where to move a player.
+ * Whether a player has to leave a world, and what happens to them.
*
- * @param who the player, for their circles
- * @param atWorld the world they're in or about to be in (a respawn point, say)
- * @param exists whether a world is loaded
- * @param mainWorld the main world's name, the last resort
- * @return the move, or null to leave them
+ * @param who the player, for their circles
+ * @param atWorld the world they're in or about to be in (a respawn point, say)
+ * @param exists whether a world is loaded
+ * @return a move or a disconnect, or null to leave them
*/
- public Move decide(Reach reach, Subject who, String atWorld, Predicate exists, String mainWorld) {
+ public Move decide(Reach reach, Subject who, String atWorld, Predicate exists) {
if (!enabled() || reach == null || !reach.active()) return null;
List circles = reach.circlesOf(who);
- if (circles.isEmpty()) {
- if (noCircle == null || atWorld.equals(noCircle.fallback())) return null;
- return move(noCircle, atWorld, exists, mainWorld, Kind.NO_CIRCLE);
- }
+ if (unlimited(circles)) return null;
Entry first = null;
Set allowed = new java.util.HashSet<>();
for (String circle : orderedKeys) {
if (circles.contains(circle)) {
Entry e = byCircle.get(circle);
+ if (e == null) continue;
if (first == null) first = e;
allowed.addAll(e.worlds());
}
}
- for (String circle : circles) if (!byCircle.containsKey(circle)) return null;
- if (first == null || allowed.contains(atWorld)) return null;
- return move(first, atWorld, exists, mainWorld, Kind.CIRCLE);
+ if (first == null) {
+ Entry none = noCircleEntry();
+ if (none.worlds().contains(atWorld)) return null;
+ return move(none.message(), none.worlds(), exists, Kind.NO_CIRCLE);
+ }
+ if (allowed.contains(atWorld)) return null;
+ return move(first.message(), allowed, exists, Kind.LOBBY);
}
- private static Move move(Entry entry, String atWorld, Predicate exists, String mainWorld, Kind kind) {
- if (exists.test(entry.fallback())) return new Move(entry.fallback(), false, entry.fallback(), entry.message(), kind);
- // The fallback is missing. The main world is the last resort; standing in it already is as far as this can go.
- if (atWorld.equals(mainWorld)) return null;
- return new Move(mainWorld, true, entry.fallback(), entry.message(), kind);
+ /** The lobby, if one is named, the player may be there and it's loaded. Else nowhere. */
+ private Move move(String message, Set allowed, Predicate exists, Kind kind) {
+ if (lobby.isEmpty()) return Move.nowhere("no lobby-world is set");
+ if (!allowed.contains(lobby)) return Move.nowhere("the lobby \"" + lobby + "\" isn't open to their group");
+ if (!exists.test(lobby)) return Move.nowhere(Move.notLoaded(lobby));
+ return new Move(lobby, message, kind, null);
}
}
diff --git a/src/main/java/com/extantape/posse/rules/Pending.java b/src/main/java/com/extantape/posse/rules/Pending.java
index 7bc2451..47900ad 100644
--- a/src/main/java/com/extantape/posse/rules/Pending.java
+++ b/src/main/java/com/extantape/posse/rules/Pending.java
@@ -5,9 +5,10 @@
import java.util.concurrent.ConcurrentHashMap;
/**
- * Players whose delayed first-join world check hasn't run yet (D297). Until it does they reach nobody and nobody
- * reaches them: no chat, no private messages, no tab entry, no join line. Fails closed. Shared by every rule through
- * {@link Subject#pending()}, and safe to read from the async chat thread.
+ * Players who aren't settled yet: waiting for the delayed first-join check (D297), for a home-worlds move to land, or
+ * for a disconnect to happen. Until then they reach nobody and nobody reaches them: no chat, no private messages, no
+ * tab entry, no join line. They aren't seen and can't act (see the Eviction listener). Fails closed. Shared by every
+ * rule through {@link Subject#pending()}, and safe to read from the async chat thread.
*/
public final class Pending {
private static final Set WAITING = ConcurrentHashMap.newKeySet();
diff --git a/src/main/java/com/extantape/posse/rules/Presence.java b/src/main/java/com/extantape/posse/rules/Presence.java
index d62b1ff..ee9a47a 100644
--- a/src/main/java/com/extantape/posse/rules/Presence.java
+++ b/src/main/java/com/extantape/posse/rules/Presence.java
@@ -23,12 +23,15 @@ public static boolean maySee(Subject viewer, Subject other, boolean byReach, Rea
* Whether the viewer's game should know the other player exists at all (K832). A game that knows a player offers
* their name when Tab is pressed in chat or after a command, listed or not, so a player the viewer may not see is
* kept from it entirely. The one exception is a player standing in the same world: the viewer can see them walk
- * by, and hiding them would make them invisible, so they stay known and only leave the player list.
+ * by, and hiding them would make them invisible, so they stay known and only leave the player list. A player whose
+ * move is still pending gets no such exception (2026-11-30): body and nametag are hidden from everyone, and
+ * everyone's from them, until they are where they may be or have gone.
*
- * @param maySee the answer from {@link #maySee}
- * @param sameWorld whether both stand in the very same world right now
+ * @param maySee the answer from {@link #maySee}
+ * @param sameWorld whether both stand in the very same world right now
+ * @param eitherPending whether the viewer or the other player is {@link Pending}
*/
- public static boolean mayKnowOf(boolean maySee, boolean sameWorld) {
- return maySee || sameWorld;
+ public static boolean mayKnowOf(boolean maySee, boolean sameWorld, boolean eitherPending) {
+ return !eitherPending && (maySee || sameWorld);
}
}
diff --git a/src/main/java/com/extantape/posse/rules/Reach.java b/src/main/java/com/extantape/posse/rules/Reach.java
index a4a1e97..8e4f8c2 100644
--- a/src/main/java/com/extantape/posse/rules/Reach.java
+++ b/src/main/java/com/extantape/posse/rules/Reach.java
@@ -98,6 +98,19 @@ public Why why(Subject from, Subject to) {
return sameWorld ? Why.CIRCLE_ONLY_WORLD : Why.NOT_SHARED;
}
+ /**
+ * Whether {@code viewer} may see something about {@code to} that only circle-mates should, such as their place on a
+ * map. Only a shared circle or either side's posse.bypass counts. Standing in the same world doesn't, so players in
+ * different circles stay apart in every world. With no circles set up the rules are off. A pending player is seen
+ * by nobody and sees nobody else.
+ */
+ public boolean inSharedCircle(Subject viewer, Subject to) {
+ if (!active() || viewer.id().equals(to.id())) return true;
+ if (viewer.pending() || to.pending()) return false;
+ if (viewer.has(BYPASS) || to.has(BYPASS)) return true;
+ return sharedCircle(viewer, to) != null;
+ }
+
/** The first circle both players are in, or null. */
public String sharedCircle(Subject from, Subject to) {
for (String circle : circles) {
diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml
index dcd0ae1..81c673b 100644
--- a/src/main/resources/config.yml
+++ b/src/main/resources/config.yml
@@ -24,25 +24,49 @@ circle-only-worlds: []
presence: everyone
# Keeps players in the worlds their circles belong in, for a server where a kids' group must never end up in an
-# adults' world. Off unless this section is here. Players rejoin where they logged out, so this only steps in when
-# that world isn't allowed: on join, on respawn, and after any world change (in case a teleport got past your
-# world plugin). Needs at least one circle.
-# - An entry per circle: the worlds its players may be in, and the world they're sent to otherwise (one of those
-# worlds). A player in any circle with no entry is never moved, so a visitor in both a kids' and an adults'
-# circle is left alone.
-# - no-circle: where players in no circle at all wait. Pair it with circle-only-worlds for a circle-only station.
-# - message (optional): the line the moved player gets, in MiniMessage. is the world they're sent to.
-# If a fallback world doesn't exist, the player goes to the main world's spawn, /posse status says so, and the log
-# warns. A player is never left where they were. Nothing goes to other players.
+# adults' world. Off unless this section is here. A teleport, portal or ride into a world a player may not be in
+# is refused. Anyone found in such a world is moved: on join, on respawn, after a world change that got past the
+# refusal, and after a reload. Needs at least one circle.
+# - One entry for each circle, with one of these two lines:
+# worlds: [first_world, second_world] the circle's players may be in these worlds
+# unlimited: true no limits: its players are never moved
+# - A player in any unlimited circle has no limits, even if they're in a limited circle too. Anyone else may be
+# in every world listed by any of their circles.
+# - A circle with no entry adds no worlds and lifts no limits. So does an entry with both lines, neither line,
+# or unlimited set to anything but true. Posse names it in the log and in /posse status. A player whose
+# circles all add nothing is treated like a player in no circle.
+# - no-circle: the worlds players in no circle may be in. It always needs worlds and can't be unlimited. Pair it
+# with circle-only-worlds for a circle-only station. Without this entry those players may be only in
+# lobby-world, and are disconnected if there is none. That includes anyone whose groups your permissions
+# plugin doesn't report.
+# - Upgrading from an earlier version: a circle with no entry, such as your adults, used to be left alone.
+# It is now limited until you give it unlimited: true.
+# - message (optional): the line a player gets when they're moved to the lobby, in MiniMessage. is
+# the lobby's name.
+# A player found anywhere else goes to lobby-world, below, or is disconnected. Put the lobby in each list.
+# /posse status and the log name any world that's missing.
+# If Posse's config can't be read or Posse can't start, only players with posse.bypass can join. There's no switch
+# to turn that off.
+# The older fallback line no longer does anything. Posse warns about it until you remove it.
# home-worlds:
# kids:
-# worlds: [kids_world, kids_world_nether, kids_world_the_end]
-# fallback: kids_world
-# message: "Welcome back! You're in the kids' world."
+# worlds: [kids_world, kids_world_nether, kids_world_the_end, lobby_world]
+# message: "Welcome! You're in the lobby."
+# adults:
+# unlimited: true
# no-circle:
-# fallback: station
+# worlds: [station, lobby_world]
home-worlds: {}
+# This server's lobby, used with home-worlds. It's the only place Posse ever sends a player. It sends them there
+# only if it's loaded and in the worlds their group may be in (for players in no circle, the no-circle list).
+# Otherwise they're disconnected with a short, kind message. They're never left where they are, and no other world
+# stands in. The main world is used only if you name it here and list it for their group.
+# This also covers a respawn: someone with no bed who dies in their own world usually respawns in the main world,
+# and Posse then sends them to the lobby.
+# Leave "" for no lobby: anyone outside their home worlds is then disconnected.
+lobby-world: ""
+
# Who sees the author of a written book (D291). With hide on, a player sees a book's author only if they share a
# circle with that person, or are that person. Everyone else sees shown-as in its place, and a title that holds the
# author's name shows **** for it. The true author is kept on the book and comes back for anyone who may see it, so
@@ -119,19 +143,19 @@ messages:
filtered-sign: "That sign has a word we don't use here, so it wasn't saved. Try different words!"
filtered-book: "That book has a word we don't use here, so your changes weren't saved. Try different words!"
filtered-item-name: "That name has a word we don't use here. Try a different one!"
- home-moved: "Welcome back! You're in ."
home-waiting: "Welcome! You can wait here until an admin adds you to a group."
+ home-lobby: "You're in now, because the world you were in isn't open to you."
circles-off: "Everyone on the server can hear you."
circles-none: "You're not in any circles, so only people in the same world can hear you."
circles-yours: "Your circles: "
circles-nobody: "Nobody else online can hear you right now."
circles-hearers: "People online who can hear you (): "
circles-hearers-count: "People online who can hear you: "
- admin-paused: "[Posse] Chat and private messages are paused because the config couldn't be read. Fix it, then run /posse reload. The console says what's wrong."
+ admin-paused: "[Posse] Chat, private messages and joining are paused because the config couldn't be read. Fix it, then run /posse reload. The console says what's wrong."
admin-warnings: "[Posse] The config has warning(s). Run /posse status to see them."
admin-reloaded: "[Posse] Reloaded."
admin-reload-failed: "[Posse] The config has problems, so nothing changed. The old rules are still in place."
- admin-reload-failed-paused: "[Posse] The config still has problems, so chat stays paused."
+ admin-reload-failed-paused: "[Posse] The config still has problems, so chat and joining stay paused."
admin-problem: " - "
admin-status: "[Posse] Circles: . Word filter: ."
admin-home-worlds: "[Posse] Home worlds: ."
diff --git a/src/test/java/com/extantape/posse/StartupTest.java b/src/test/java/com/extantape/posse/StartupTest.java
new file mode 100644
index 0000000..105ee6b
--- /dev/null
+++ b/src/test/java/com/extantape/posse/StartupTest.java
@@ -0,0 +1,86 @@
+package com.extantape.posse;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+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;
+
+/** A start that goes wrong must never leave joins open. */
+class StartupTest {
+ private final Startup startup = new Startup();
+ private final List steps = new ArrayList<>();
+ private final List reported = new ArrayList<>();
+
+ private void run(Runnable guard, Runnable rest) {
+ startup.run(guard, rest, cause -> {
+ steps.add("report");
+ reported.add(cause);
+ }, () -> steps.add("shutdown"));
+ }
+
+ private static Runnable fails(Error error) {
+ return () -> {
+ throw error;
+ };
+ }
+
+ private static Runnable fails(RuntimeException error) {
+ return () -> {
+ throw error;
+ };
+ }
+
+ @Test
+ void aGoodStartIsComplete() {
+ assertFalse(startup.complete(), "not before it has run");
+ run(() -> steps.add("guard"), () -> {
+ assertFalse(startup.complete(), "still paused while the rest starts");
+ steps.add("rest");
+ });
+ assertTrue(startup.complete());
+ assertFalse(startup.failed());
+ assertEquals(List.of("guard", "rest"), steps);
+ }
+
+ @Test
+ void ifJoinsCannotBeGuardedTheServerShutsDownFirstAndNothingElseStarts() {
+ RuntimeException broken = new IllegalStateException("made up");
+ run(fails(broken), () -> steps.add("rest"));
+ assertFalse(startup.complete());
+ assertTrue(startup.failed());
+ assertEquals(List.of("shutdown", "report"), steps);
+ assertEquals(List.of(broken), reported);
+ }
+
+ @Test
+ void anExceptionLaterLeavesTheStartIncompleteAndTheServerRunning() {
+ RuntimeException broken = new IllegalStateException("made up");
+ run(() -> steps.add("guard"), fails(broken));
+ assertFalse(startup.complete());
+ assertTrue(startup.failed());
+ assertEquals(List.of("guard", "report"), steps);
+ assertEquals(List.of(broken), reported);
+ }
+
+ @Test
+ void anErrorSuchAsAMissingClassIsCaughtToo() {
+ Error missing = new NoClassDefFoundError("made up");
+ run(() -> steps.add("guard"), fails(missing));
+ assertTrue(startup.failed());
+ assertEquals(List.of(missing), reported);
+ }
+
+ @Test
+ void aReportThatFailsDoesNotEscape() {
+ startup.run(() -> { }, fails(new IllegalStateException("made up")), cause -> {
+ throw new IllegalStateException("the report broke too");
+ }, () -> steps.add("shutdown"));
+ assertTrue(startup.failed());
+ assertFalse(startup.complete());
+ assertTrue(steps.isEmpty());
+ }
+}
diff --git a/src/test/java/com/extantape/posse/command/HomeWorldsStatusTest.java b/src/test/java/com/extantape/posse/command/HomeWorldsStatusTest.java
new file mode 100644
index 0000000..b005804
--- /dev/null
+++ b/src/test/java/com/extantape/posse/command/HomeWorldsStatusTest.java
@@ -0,0 +1,36 @@
+package com.extantape.posse.command;
+
+import com.extantape.posse.rules.HomeWorlds;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class HomeWorldsStatusTest {
+ private static final List CIRCLES = List.of("kids", "adults", "teens", "guests");
+
+ private static HomeWorlds home() {
+ return new HomeWorlds(Map.of("kids", new HomeWorlds.Entry(Set.of("kidland", "hub"), null), "adults", HomeWorlds.Entry.noLimits()),
+ null, "hub", Set.of("teens"));
+ }
+
+ @Test
+ void theSummaryShowsEveryCirclesSettingInOrder() {
+ String line = PosseCommands.homeWorldsSummary(home(), CIRCLES);
+ assertTrue(line.startsWith("kids may be in 2 worlds; adults has no limits; teens has an entry that can't be used and adds no worlds; "
+ + "guests has no entry and adds no worlds; "), line);
+ assertEquals("off", PosseCommands.homeWorldsSummary(HomeWorlds.OFF, CIRCLES));
+ }
+
+ @Test
+ void theJsonStatusSaysWhichSettingEachCircleHas() {
+ Map status = PosseCommands.homeWorldsStatus(home(), CIRCLES);
+ assertEquals(Map.of("kids", "limited", "adults", "unlimited", "teens", "unusable", "guests", "none"), status.get("settings"));
+ assertEquals(List.of("kids", "adults"), status.get("circles"));
+ assertEquals(Map.of(), PosseCommands.homeWorldsStatus(null, List.of()).get("settings"));
+ }
+}
diff --git a/src/test/java/com/extantape/posse/config/HomeWorldsCirclesTest.java b/src/test/java/com/extantape/posse/config/HomeWorldsCirclesTest.java
new file mode 100644
index 0000000..e3afcb4
--- /dev/null
+++ b/src/test/java/com/extantape/posse/config/HomeWorldsCirclesTest.java
@@ -0,0 +1,174 @@
+package com.extantape.posse.config;
+
+import com.extantape.posse.rules.HomeWorlds;
+import com.extantape.posse.rules.Subject;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** What each circle's home-worlds setting means: a worlds list, no limits, or nothing. */
+class HomeWorldsCirclesTest {
+ private static final String NO_LIMITS = "adults: { unlimited: true }";
+
+ /** Circles kids, adults and teens. Kids have a list; {@code %s} adds more entries. */
+ private static final String CONFIG = """
+ circles: [kids, adults, teens]
+ lobby-world: hub
+ home-worlds:
+ kids: { worlds: [kidland, hub] }
+ no-circle: { worlds: [station, hub] }
+ %s
+ """;
+
+ private static SettingsLoader.Result load(String config) {
+ SettingsLoader.Result r = new SettingsLoader(n -> SettingsLoader.class.getResourceAsStream("/" + n)).load(config, null, null);
+ assertTrue(r.ok(), r.errors().toString());
+ return r;
+ }
+
+ private static SettingsLoader.Result with(String more) {
+ return load(CONFIG.formatted(more));
+ }
+
+ private static Subject in(String world, String... circles) {
+ Set held = new java.util.HashSet<>();
+ for (String circle : circles) held.add("posse.circle." + circle);
+ return Subject.of(UUID.randomUUID(), "Made-up", world, held::contains);
+ }
+
+ private static HomeWorlds.Move move(SettingsLoader.Result r, String at, String... circles) {
+ return r.settings().homeWorlds().decide(r.settings().reach(), in(at, circles), at, w -> true);
+ }
+
+ private static boolean governs(SettingsLoader.Result r, String... circles) {
+ return r.settings().homeWorlds().governs(r.settings().reach(), in("hub", circles));
+ }
+
+ private static String sentTo(HomeWorlds.Move m) {
+ return m == null ? "stays" : m.disconnect() ? "disconnected" : m.world();
+ }
+
+ @Test
+ void aKidAlsoInANewCircleWithNoEntryKeepsTheirLimits() {
+ SettingsLoader.Result r = with("");
+ assertEquals("hub", sentTo(move(r, "grownups", "kids", "teens")));
+ assertEquals("stays", sentTo(move(r, "kidland", "kids", "teens")));
+ assertEquals("hub", sentTo(move(r, "station", "kids", "teens")), "the unlisted circle adds no worlds, the no-circle list included");
+ assertTrue(governs(r, "kids", "teens"));
+ }
+
+ @Test
+ void aPlayerWhoseCirclesAllLackEntriesIsHandledLikeNoCircle() {
+ SettingsLoader.Result r = with("");
+ for (String[] circles : new String[][]{{"teens"}, {"adults"}, {"adults", "teens"}}) {
+ assertEquals("hub", sentTo(move(r, "grownups", circles)), String.join(",", circles));
+ assertEquals("stays", sentTo(move(r, "station", circles)));
+ assertTrue(governs(r, circles));
+ }
+ assertEquals(HomeWorlds.Kind.NO_CIRCLE, move(r, "grownups", "teens").kind());
+ }
+
+ @Test
+ void withOnlyUnlistedCirclesAndNoNoCircleEntryItIsTheLobbyOrADisconnect() {
+ String config = "circles: [kids, adults]\n%s\nhome-worlds:\n kids: { worlds: [kidland] }\n";
+ SettingsLoader.Result lobby = load(config.formatted("lobby-world: hub"));
+ assertEquals("hub", sentTo(move(lobby, "grownups", "adults")));
+ assertEquals("hub", sentTo(move(lobby, "kidland", "adults")));
+ assertEquals("stays", sentTo(move(lobby, "hub", "adults")));
+ SettingsLoader.Result none = load(config.formatted(""));
+ for (String w : List.of("hub", "grownups", "kidland")) assertEquals("disconnected", sentTo(move(none, w, "adults")), w);
+ HomeWorlds.Move gone = lobby.settings().homeWorlds().decide(lobby.settings().reach(), in("grownups", "adults"), "grownups", w -> false);
+ assertEquals("disconnected", sentTo(gone), "the lobby isn't loaded");
+ }
+
+ @Test
+ void aPlayerInAnyUnlimitedCircleHasNoLimitsEvenWithALimitedOne() {
+ SettingsLoader.Result r = with(NO_LIMITS);
+ for (String[] circles : new String[][]{{"adults"}, {"adults", "kids"}, {"adults", "teens"}, {"kids", "teens", "adults"}}) {
+ assertNull(move(r, "anywhere", circles), String.join(",", circles));
+ assertFalse(governs(r, circles), String.join(",", circles));
+ }
+ assertEquals("hub", sentTo(move(r, "anywhere", "kids")));
+ assertEquals("hub", sentTo(move(r, "anywhere", "teens")));
+ }
+
+ @Test
+ void listedCirclesAddUp() {
+ SettingsLoader.Result r = with("teens: { worlds: [teenland, hub] }");
+ for (String w : List.of("kidland", "teenland", "hub")) assertEquals("stays", sentTo(move(r, w, "kids", "teens")), w);
+ assertEquals("hub", sentTo(move(r, "grownups", "kids", "teens")));
+ }
+
+ @Test
+ void unlimitedFalseBesideNothingElseAndEveryOtherInvalidFormAddsNothingAndIsNamed() {
+ for (String bad : List.of(
+ "adults: { worlds: [grownups], unlimited: true }",
+ "adults: { worlds: [grownups], unlimited: false }",
+ "adults: { unlimited: \"true\" }",
+ "adults: { unlimited: 1 }",
+ "adults: { unlimited: }",
+ "adults: { unlimited: false }",
+ "adults: {}",
+ "adults: { message: Hi }",
+ "adults: { fallback: grownups }",
+ "adults: { unlimted: true }",
+ "adults: { worlds: [] }",
+ "adults: { worlds: grownups }",
+ "adults: unlimited",
+ "adults: true")) {
+ SettingsLoader.Result r = with(bad);
+ assertEquals("hub", sentTo(move(r, "grownups", "adults")), bad);
+ assertTrue(governs(r, "adults"), bad);
+ assertEquals("hub", sentTo(move(r, "grownups", "adults", "kids")), bad);
+ assertEquals("stays", sentTo(move(r, "kidland", "adults", "kids")), bad);
+ List named = r.warnings().stream().filter(w -> w.contains("home-worlds.adults")).toList();
+ assertTrue(named.stream().anyMatch(w -> w.contains("adds no worlds")), bad + " " + r.warnings());
+ }
+ }
+
+ @Test
+ void aSectionWithOnlyInvalidEntriesStaysOn() {
+ for (String bad : List.of("kids: {}", "kids: { unlimited: yes please }", "kids: true", "kids:")) {
+ SettingsLoader.Result r = load("circles: [kids]\nlobby-world: hub\nhome-worlds:\n " + bad + "\n");
+ assertTrue(r.settings().homeWorlds().enabled(), bad);
+ assertEquals("hub", sentTo(move(r, "grownups", "kids")), bad);
+ assertEquals("hub", sentTo(move(r, "grownups")), bad);
+ }
+ }
+
+ @Test
+ void oneCircleWrittenTwiceAddsNothing() {
+ SettingsLoader.Result r = with("adults: { worlds: [grownups, hub] }\n Adults: { unlimited: true }");
+ assertEquals("hub", sentTo(move(r, "elsewhere", "adults")));
+ assertEquals("hub", sentTo(move(r, "grownups", "adults")), "neither of the two is trusted");
+ assertTrue(r.warnings().toString().contains("more than one entry"), r.warnings().toString());
+ }
+
+ @Test
+ void everyCircleWithNoEntryIsNamedInAWarning() {
+ List warnings = with("").warnings();
+ for (String circle : List.of("adults", "teens")) {
+ assertEquals(1, warnings.stream().filter(w -> w.contains("home-worlds." + circle + " is missing")).count(), warnings.toString());
+ }
+ assertFalse(warnings.toString().contains("home-worlds.kids is missing"), warnings.toString());
+ List all = with(NO_LIMITS + "\n teens: { worlds: [teenland, hub] }").warnings();
+ assertTrue(all.isEmpty(), "an unlimited circle needs no lobby in a list: " + all);
+ List invalid = with("adults: {}\n teens: { unlimited: true }").warnings();
+ assertEquals(1, invalid.size(), "one warning for a broken entry: " + invalid);
+ assertTrue(load("circles: [kids, adults]\n").warnings().isEmpty(), "nothing to say with home worlds off");
+ }
+
+ @Test
+ void theNoCircleEntryCanNeverBeUnlimited() {
+ SettingsLoader.Result r = load("circles: [kids]\nlobby-world: hub\nhome-worlds:\n kids: { worlds: [hub] }\n no-circle: { worlds: [hub], unlimited: true }\n");
+ assertEquals("hub", sentTo(move(r, "grownups")));
+ assertTrue(r.warnings().toString().contains("home-worlds.no-circle can't be unlimited"), r.warnings().toString());
+ }
+}
diff --git a/src/test/java/com/extantape/posse/config/SettingsLoaderTest.java b/src/test/java/com/extantape/posse/config/SettingsLoaderTest.java
index 456c9f3..ee4c9a5 100644
--- a/src/test/java/com/extantape/posse/config/SettingsLoaderTest.java
+++ b/src/test/java/com/extantape/posse/config/SettingsLoaderTest.java
@@ -111,44 +111,175 @@ void presenceReachWithoutCirclesWarns() {
}
private static final String HOME = """
- circles: [kids, adults]
+ circles: [kids]
+ lobby-world: " hub "
home-worlds:
- kids: { worlds: [kidland, kidland_nether], fallback: kidland, message: "Hi" }
- no-circle: { fallback: station }
+ kids: { worlds: [kidland, kidland_nether, hub], message: "Hi" }
+ no-circle: { worlds: [station, hub] }
""";
@Test
void homeWorldsAreOffByDefault() {
SettingsLoader.Result r = load(null, null, null);
assertFalse(r.settings().homeWorlds().enabled());
+ assertEquals("", r.settings().homeWorlds().lobby());
assertTrue(r.warnings().isEmpty(), r.warnings().toString());
}
@Test
- void homeWorldsAreRead() {
+ void homeWorldsTheLobbyAndTheNoCircleListAreRead() {
SettingsLoader.Result r = load(HOME, null, null);
assertTrue(r.ok(), r.errors().toString());
+ assertTrue(r.warnings().isEmpty(), r.warnings().toString());
var home = r.settings().homeWorlds();
assertTrue(home.enabled());
- assertEquals("kidland", home.byCircle().get("kids").fallback());
+ assertEquals("hub", home.lobby());
+ assertEquals(java.util.Set.of("kidland", "kidland_nether", "hub"), home.byCircle().get("kids").worlds());
assertEquals("Hi", home.byCircle().get("kids").message());
- assertEquals("station", home.noCircle().fallback());
+ assertEquals(java.util.Set.of("station", "hub"), home.noCircleWorlds());
}
@Test
void homeWorldsMistakesAreErrorsSoNothingHalfAppliesToKids() {
for (String bad : java.util.List.of(
- "circles: [kids]\nhome-worlds:\n kids: { worlds: [a], fallback: b }\n",
- "circles: [kids]\nhome-worlds:\n kids: { worlds: [a] }\n",
- "circles: [kids]\nhome-worlds:\n kids: { fallback: a }\n",
- "circles: [kids]\nhome-worlds:\n grown: { worlds: [a], fallback: a }\n",
+ "circles: [kids]\nhome-worlds:\n grown: { worlds: [a] }\n",
"circles: [kids]\nhome-worlds:\n no-circle: {}\n",
+ "circles: [kids]\nhome-worlds:\n no-circle: { worlds: [], fallback: station }\n",
+ "circles: [kids]\nhome-worlds:\n no-circle: { fallback: \"\" }\n",
"circles: [kids]\nhome-worlds: [a]\n",
- "home-worlds:\n no-circle: { fallback: station }\n")) {
+ "home-worlds:\n no-circle: { worlds: [station] }\n",
+ "circles: [kids]\nlobby-world: [hub]\n",
+ "circles: [kids]\nlobby-world: 3\n")) {
assertFalse(load(bad, null, null).ok(), bad);
}
}
+ @Test
+ void theShippedConfigNamesNoLobby() throws java.io.IOException {
+ try (java.io.InputStream in = SettingsLoader.class.getClassLoader().getResourceAsStream("config.yml")) {
+ String shipped = new String(in.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8);
+ assertTrue(shipped.contains("\nlobby-world: \"\"\n"), "the default names no world");
+ }
+ }
+
+ @Test
+ void aMissingNoCircleEntryIsNamedWithWhatHappensMeanwhile() {
+ SettingsLoader.Result r = load("circles: [kids]\nlobby-world: hub\nhome-worlds:\n kids: { worlds: [kidland, hub] }\n", null, null);
+ assertTrue(r.ok(), r.errors().toString());
+ assertEquals(1, r.warnings().size(), r.warnings().toString());
+ String line = r.warnings().getFirst();
+ assertTrue(line.contains("home-worlds.no-circle is missing"), line);
+ assertTrue(line.contains("may only be in the lobby \"hub\""), line);
+
+ SettingsLoader.Result none = load("circles: [kids]\nhome-worlds:\n kids: { worlds: [kidland] }\n", null, null);
+ String all = none.warnings().toString();
+ assertTrue(all.contains("home-worlds.no-circle is missing"), all);
+ assertTrue(all.contains("players in no circle are disconnected"), all);
+ }
+
+ @Test
+ void homeWorldsWithNoLobbyWarnThatPlayersWillBeDisconnected() {
+ SettingsLoader.Result r = load("circles: [kids]\nhome-worlds:\n kids: { worlds: [kidland] }\n no-circle: { worlds: [station] }\n", null, null);
+ assertTrue(r.ok(), r.errors().toString());
+ assertEquals(1, r.warnings().size(), r.warnings().toString());
+ assertTrue(r.warnings().getFirst().contains("lobby-world isn't set"), r.warnings().toString());
+ assertTrue(r.warnings().getFirst().contains("is disconnected"), r.warnings().toString());
+ }
+
+ @Test
+ void aLobbyThatCanNeverBeUsedIsAWarningForEachGroupItIsClosedTo() {
+ SettingsLoader.Result off = load("lobby-world: hub\n", null, null);
+ assertTrue(off.ok(), off.errors().toString());
+ assertTrue(off.warnings().toString().contains("lobby-world has no effect without home-worlds"),
+ off.warnings().toString());
+ SettingsLoader.Result closed = load("""
+ circles: [kids, adults]
+ lobby-world: hub
+ home-worlds:
+ kids: { worlds: [kidland] }
+ adults: { worlds: [grownups, hub] }
+ no-circle: { worlds: [station] }
+ """, null, null);
+ assertTrue(closed.ok(), closed.errors().toString());
+ String all = closed.warnings().toString();
+ assertEquals(2, closed.warnings().size(), all);
+ assertTrue(all.contains("isn't in home-worlds.kids.worlds"), all);
+ assertTrue(all.contains("isn't in home-worlds.no-circle.worlds"), all);
+ assertFalse(all.contains("home-worlds.adults"), all);
+ }
+
+ /** An install from before D368, with a fallback in each entry. {@code %s} is the lobby line, or nothing. */
+ private static final String OLD = """
+ circles: [kids]
+ %s
+ home-worlds:
+ kids: { worlds: [kidland, hub], fallback: kidland, message: "Back in your own world" }
+ no-circle: { worlds: [station, hub], fallback: station }
+ """;
+
+ private static com.extantape.posse.rules.HomeWorlds.Move moveFrom(SettingsLoader.Result r, String at,
+ String... permissions) {
+ java.util.Set held = java.util.Set.of(permissions);
+ var who = com.extantape.posse.rules.Subject.of(java.util.UUID.randomUUID(), "Kit", at, held::contains);
+ return r.settings().homeWorlds().decide(r.settings().reach(), who, at, w -> true);
+ }
+
+ @Test
+ void anOldFallbackLoadsWithAClearWarningAndIsNeverADestination() {
+ SettingsLoader.Result r = load(OLD.formatted(""), null, null);
+ assertTrue(r.ok(), r.errors().toString());
+ String all = r.warnings().toString();
+ assertTrue(all.contains("home-worlds.kids.fallback is no longer used and never chooses where a player goes"), all);
+ assertTrue(all.contains("home-worlds.no-circle.fallback is no longer used"), all);
+ assertTrue(all.contains("lobby-world isn't set"), all);
+ String kid = "posse.circle.kids";
+ assertTrue(moveFrom(r, "grownups", kid).disconnect(), "the fallback is loaded, and still isn't used");
+ assertTrue(moveFrom(r, "grownups").disconnect());
+
+ SettingsLoader.Result named = load(OLD.formatted("lobby-world: hub"), null, null);
+ assertEquals("hub", moveFrom(named, "grownups", kid).world());
+ assertEquals("hub", moveFrom(named, "grownups").world());
+ org.junit.jupiter.api.Assertions.assertNull(moveFrom(named, "kidland", kid), "the lists mean what they did");
+ }
+
+ @Test
+ void anOldEntrysLineIsNotShownWhileItsFallbackIsThere() {
+ SettingsLoader.Result r = load(OLD.formatted("lobby-world: hub"), null, null);
+ org.junit.jupiter.api.Assertions.assertNull(r.settings().homeWorlds().byCircle().get("kids").message());
+ assertTrue(r.warnings().toString().contains("message line was written for the old move"), r.warnings().toString());
+ }
+
+ @Test
+ void anOldFallbackOutsideTheListAddsNoPermission() {
+ SettingsLoader.Result r = load("""
+ circles: [kids]
+ lobby-world: hub
+ home-worlds:
+ kids: { worlds: [kidland, hub], fallback: grownups }
+ no-circle: { worlds: [hub], fallback: station }
+ """, null, null);
+ assertTrue(r.ok(), r.errors().toString());
+ String kid = "posse.circle.kids";
+ assertEquals("hub", moveFrom(r, "grownups", kid).world());
+ assertEquals("hub", moveFrom(r, "station").world());
+ }
+
+ @Test
+ void anOldNoCircleEntryWithOnlyAFallbackStillAllowsThatWorldAndSendsNobodyThere() {
+ SettingsLoader.Result r = load("""
+ circles: [kids]
+ lobby-world: hub
+ home-worlds:
+ no-circle: { fallback: station }
+ """, null, null);
+ assertTrue(r.ok(), r.errors().toString());
+ assertEquals(java.util.Set.of("station"), r.settings().homeWorlds().noCircleWorlds());
+ assertTrue(r.warnings().toString().contains("Write worlds: [station]"), r.warnings().toString());
+ org.junit.jupiter.api.Assertions.assertNull(moveFrom(r, "station"));
+ var move = moveFrom(r, "grownups");
+ assertTrue(move.disconnect(), "the lobby isn't on their list, and station is never somewhere they're sent");
+ }
+
@Test
void bookAuthorsAreHiddenByDefault() {
SettingsLoader.Result r = load(null, null, null);
diff --git a/src/test/java/com/extantape/posse/listen/EvictionTest.java b/src/test/java/com/extantape/posse/listen/EvictionTest.java
new file mode 100644
index 0000000..6b5b1c7
--- /dev/null
+++ b/src/test/java/com/extantape/posse/listen/EvictionTest.java
@@ -0,0 +1,214 @@
+package com.extantape.posse.listen;
+
+import com.extantape.posse.rules.Pending;
+import net.kyori.adventure.text.Component;
+import org.bukkit.Location;
+import org.bukkit.World;
+import org.bukkit.event.Cancellable;
+import org.bukkit.event.EventHandler;
+import org.bukkit.event.EventPriority;
+import org.bukkit.event.player.PlayerMoveEvent;
+import org.bukkit.event.player.PlayerQuitEvent;
+import org.bukkit.event.player.PlayerTeleportEvent;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import java.lang.reflect.Method;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** A player Posse can't let stay is held until they have gone, however long the disconnect takes. */
+class EvictionTest {
+ private final World main = Fakes.world("main");
+ private final Fakes.Scheduler server = new Fakes.Scheduler();
+ private final Eviction eviction = new Eviction(server);
+ private final Fakes.Someone kit = server.add(new Fakes.Someone("Kit", main));
+ private final Fakes.Someone sam = server.add(new Fakes.Someone("Sam", main));
+ private static final Component WHY = Component.text("Off you go.");
+
+ @AfterEach
+ void forget() {
+ Pending.clear();
+ }
+
+ private PlayerQuitEvent quit(Fakes.Someone s) {
+ s.online = false;
+ PlayerQuitEvent event = new PlayerQuitEvent(s.player, Component.text("left"), PlayerQuitEvent.QuitReason.DISCONNECTED);
+ eviction.onQuitLine(event);
+ eviction.onQuit(event);
+ return event;
+ }
+
+ @Test
+ void nowKicksAtOnceAfterGettingThemOutOfSeatsAndInventories() {
+ eviction.now(kit.id, WHY);
+ assertEquals(List.of("Off you go."), kit.kicks);
+ assertEquals(1, kit.vehiclesLeft);
+ assertEquals(1, kit.inventoriesClosed);
+ assertTrue(eviction.holds(kit.id));
+ assertTrue(Pending.has(kit.id));
+ assertTrue(server.warnings.isEmpty(), "the kick went through");
+ }
+
+ @Test
+ void nextTickHoldsAtOnceAndKicksLater() {
+ eviction.nextTick(kit.id, WHY);
+ assertTrue(eviction.holds(kit.id));
+ assertTrue(kit.kicks.isEmpty());
+ server.run();
+ assertEquals(1, kit.kicks.size());
+ }
+
+ @Test
+ void aCancelledKickIsTriedUntilTheyHaveGoneAndWarnsOnce() {
+ kit.kickCancelled = true;
+ eviction.now(kit.id, WHY);
+ for (int i = 0; i < 5; i++) server.retry();
+ assertEquals(6, kit.kicks.size());
+ assertEquals(1, server.warnings.size());
+ assertFalse(server.warnings.getFirst().contains("Kit"));
+ quit(kit);
+ server.retry();
+ assertEquals(6, kit.kicks.size());
+ assertTrue(server.retries.isEmpty());
+ }
+
+ /** Found on a real server: the player is still listed for a moment after a kick that is going through. */
+ @Test
+ void aKickThatTakesAMomentIsNotReportedAsCancelled() {
+ kit.kickLandsLater = true;
+ eviction.now(kit.id, WHY);
+ assertTrue(server.warnings.isEmpty(), "too soon to say it didn't go through");
+ quit(kit);
+ server.retry();
+ assertTrue(server.warnings.isEmpty());
+ assertEquals(1, kit.kicks.size());
+ }
+
+ @Test
+ void askingTwiceStartsOnlyOneRoundOfTries() {
+ kit.kickCancelled = true;
+ eviction.now(kit.id, WHY);
+ eviction.now(kit.id, WHY);
+ eviction.nextTick(kit.id, WHY);
+ server.run();
+ assertEquals(1, kit.kicks.size());
+ assertEquals(1, server.retries.size());
+ }
+
+ @Test
+ void aTryLeftOverFromAnEarlierStayDoesNothingAfterTheyRejoin() {
+ kit.kickCancelled = true;
+ eviction.now(kit.id, WHY);
+ quit(kit);
+ kit.online = true;
+ server.retry();
+ assertEquals(1, kit.kicks.size());
+ assertFalse(eviction.holds(kit.id));
+ }
+
+ @Test
+ void quittingEndsTheHoldAndSaysNothingToAnyone() {
+ eviction.hold(kit.id);
+ assertNull(quit(kit).quitMessage());
+ assertFalse(eviction.holds(kit.id));
+ assertFalse(Pending.has(kit.id));
+ assertNotNull(quit(sam).quitMessage(), "someone who wasn't held keeps their line");
+ }
+
+ private static boolean cancelledBy(java.util.function.Consumer handler, PlayerMoveEvent event) {
+ handler.accept(event);
+ return event.isCancelled();
+ }
+
+ @Test
+ void aHeldPlayerCannotMoveAndOthersCan() {
+ eviction.hold(kit.id);
+ Location a = new Location(main, 0, 64, 0);
+ Location b = new Location(main, 1, 64, 0);
+ assertTrue(cancelledBy(eviction::onMove, new PlayerMoveEvent(kit.player, a, b)));
+ assertFalse(cancelledBy(eviction::onMove, new PlayerMoveEvent(sam.player, a, b)));
+ PlayerTeleportEvent teleport = new PlayerTeleportEvent(kit.player, a, b);
+ eviction.onTeleport(teleport);
+ assertTrue(teleport.isCancelled());
+ }
+
+ private static boolean cancels(java.util.function.Consumer handler, E event) {
+ handler.accept(event);
+ return event.isCancelled();
+ }
+
+ @Test
+ void aPlayerWhoseMoveIsPendingCannotMoveOrActEvenThoughTheyArentBeingDisconnected() {
+ Pending.begin(kit.id);
+ Location a = new Location(main, 0, 64, 0);
+ Location b = new Location(main, 1, 64, 0);
+ org.bukkit.entity.Entity boat = Fakes.vehicle();
+ assertTrue(cancels(eviction::onMove, new PlayerMoveEvent(kit.player, a, b)));
+ assertTrue(cancels(eviction::onPortal, new org.bukkit.event.player.PlayerPortalEvent(kit.player, a, b)));
+ assertTrue(cancels(eviction::onMount, new org.bukkit.event.entity.EntityMountEvent(kit.player, boat)));
+ assertTrue(cancels(eviction::onCommand, new org.bukkit.event.player.PlayerCommandPreprocessEvent(kit.player, "/home",
+ new java.util.HashSet<>())));
+ assertTrue(cancels(eviction::onPreAttack, new io.papermc.paper.event.player.PrePlayerAttackEntityEvent(kit.player, boat, true)));
+ assertTrue(cancels(eviction::onChat, new io.papermc.paper.event.player.AsyncChatEvent(false, kit.player,
+ new java.util.HashSet<>(), io.papermc.paper.chat.ChatRenderer.defaultRenderer(), Component.text("hi"),
+ Component.text("hi"), null)));
+
+ assertFalse(cancels(eviction::onMove, new PlayerMoveEvent(sam.player, a, b)), "others carry on");
+ assertFalse(cancels(eviction::onTeleport, new PlayerTeleportEvent(kit.player, a, b)),
+ "Posse's own move has to go through; where it may lead is the home-worlds check's business");
+
+ Pending.end(kit.id);
+ assertFalse(cancels(eviction::onMove, new PlayerMoveEvent(kit.player, a, b)), "free again once it's over");
+ assertFalse(cancels(eviction::onMount, new org.bukkit.event.entity.EntityMountEvent(kit.player, boat)));
+ }
+
+ @Test
+ void aPendingPlayerWhoQuitsKeepsTheQuitLineForPresenceToDecide() {
+ Pending.begin(kit.id);
+ assertNotNull(quit(kit).quitMessage());
+ }
+
+ @Test
+ void holdingSomeoneHidesThemAndEveryFurtherTryHidesThemAgain() {
+ kit.kickCancelled = true;
+ eviction.hold(kit.id);
+ assertEquals(List.of("Kit"), server.concealed);
+ server.concealed.clear();
+ eviction.now(kit.id, WHY);
+ server.concealed.clear();
+ server.retry();
+ assertEquals(List.of("Kit"), server.concealed);
+ }
+
+ /** The server calls these for us, so this pins which events are covered and that each has the last word. */
+ @Test
+ void everyWayToActIsCoveredAtTheHighestPriority() {
+ List handlers = Stream.of(Eviction.class.getDeclaredMethods())
+ .filter(m -> m.isAnnotationPresent(EventHandler.class)).toList();
+ assertEquals(Set.of("PlayerMoveEvent", "PlayerTeleportEvent", "PlayerPortalEvent", "EntityMountEvent",
+ "PlayerInteractEvent", "PlayerInteractEntityEvent", "PlayerInteractAtEntityEvent",
+ "PlayerArmorStandManipulateEvent", "BlockBreakEvent", "BlockDamageEvent", "BlockPlaceEvent",
+ "PlayerBucketEmptyEvent", "PlayerBucketFillEvent", "PlayerItemConsumeEvent",
+ "ProjectileLaunchEvent", "AsyncChatEvent", "PlayerCommandPreprocessEvent", "SignChangeEvent",
+ "PlayerEditBookEvent", "EntityDamageEvent", "PlayerDropItemEvent", "EntityPickupItemEvent",
+ "PlayerSwapHandItemsEvent", "InventoryOpenEvent", "InventoryClickEvent", "InventoryDragEvent",
+ "PlayerQuitEvent", "PrePlayerAttackEntityEvent", "PlayerPickupArrowEvent"),
+ handlers.stream().map(m -> m.getParameterTypes()[0].getSimpleName()).collect(Collectors.toSet()));
+ for (Method m : handlers) {
+ EventHandler how = m.getAnnotation(EventHandler.class);
+ assertFalse(how.ignoreCancelled(), m.getName());
+ if (Cancellable.class.isAssignableFrom(m.getParameterTypes()[0])) {
+ assertEquals(EventPriority.HIGHEST, how.priority(), m.getName());
+ }
+ }
+ }
+}
diff --git a/src/test/java/com/extantape/posse/listen/Fakes.java b/src/test/java/com/extantape/posse/listen/Fakes.java
new file mode 100644
index 0000000..58dcb62
--- /dev/null
+++ b/src/test/java/com/extantape/posse/listen/Fakes.java
@@ -0,0 +1,202 @@
+package com.extantape.posse.listen;
+
+import net.kyori.adventure.text.Component;
+import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
+import org.bukkit.Location;
+import org.bukkit.World;
+import org.bukkit.entity.Entity;
+import org.bukkit.entity.Player;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Proxy;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+
+/** Made-up worlds and players that answer only what the listeners ask. Anything else fails the test. */
+final class Fakes {
+ private Fakes() {
+ }
+
+ static String text(Component component) {
+ return PlainTextComponentSerializer.plainText().serialize(component);
+ }
+
+ @SuppressWarnings("unchecked")
+ static T proxy(Class type, String label, InvocationHandler handler) {
+ return (T) Proxy.newProxyInstance(Fakes.class.getClassLoader(), new Class>[]{type}, (self, method, args) -> {
+ switch (method.getName()) {
+ case "equals" -> {
+ return self == args[0];
+ }
+ case "hashCode" -> {
+ return System.identityHashCode(self);
+ }
+ case "toString" -> {
+ return label;
+ }
+ default -> {
+ return handler.invoke(self, method, args);
+ }
+ }
+ });
+ }
+
+ static World world(String name) {
+ Location[] spawn = new Location[1];
+ World world = proxy(World.class, name, (self, method, args) -> switch (method.getName()) {
+ case "getName" -> name;
+ case "getSpawnLocation" -> spawn[0].clone();
+ default -> throw new UnsupportedOperationException(method.getName());
+ });
+ spawn[0] = new Location(world, 0, 64, 0);
+ return world;
+ }
+
+ /** A made-up vehicle: all it answers is who is aboard. */
+ static Entity vehicle(Entity... riders) {
+ return proxy(Entity.class, "vehicle", (self, method, args) -> switch (method.getName()) {
+ case "getPassengers" -> List.of(riders);
+ default -> throw new UnsupportedOperationException(method.getName());
+ });
+ }
+
+ /** A server with a made-up scheduler: nothing queued runs until the test says so. */
+ static class Scheduler implements Eviction.Host {
+ final Map online = new HashMap<>();
+ final ArrayDeque queued = new ArrayDeque<>();
+ /** Further tries at a disconnect, kept apart so that running the queue can't loop for ever. */
+ final ArrayDeque retries = new ArrayDeque<>();
+ final List warnings = new ArrayList<>();
+ /** Checks on a move that may never finish, kept apart so they only run when a test lets that long pass. */
+ final ArrayDeque timeouts = new ArrayDeque<>();
+ /** Everyone who was hidden from the game, once for each time. */
+ final List concealed = new ArrayList<>();
+
+ Someone add(Someone someone) {
+ online.put(someone.id, someone);
+ return someone;
+ }
+
+ void run() {
+ while (!queued.isEmpty()) queued.poll().run();
+ }
+
+ /** Lets the wait between tries pass once. */
+ void retry() {
+ List due = new ArrayList<>(retries);
+ retries.clear();
+ due.forEach(Runnable::run);
+ }
+
+ /** Lets a move's time limit pass. */
+ void timeOut() {
+ List due = new ArrayList<>(timeouts);
+ timeouts.clear();
+ due.forEach(Runnable::run);
+ }
+
+ @Override public void conceal(Player player) {
+ concealed.add(player.getName());
+ }
+
+ @Override public Player player(UUID id) {
+ Someone someone = online.get(id);
+ return someone == null || !someone.online ? null : someone.player;
+ }
+
+ @Override public void nextTick(Runnable task) {
+ queued.add(task);
+ }
+
+ @Override public void later(Runnable task, long ticks) {
+ if (ticks == HomeWorldsListener.MOVE_TIMEOUT_TICKS) timeouts.add(task);
+ else (ticks == Eviction.RETRY_TICKS ? retries : queued).add(task);
+ }
+
+ @Override public void warn(String line) {
+ warnings.add(line);
+ }
+ }
+
+ /** A made-up player and a record of what was done to them. */
+ static final class Someone {
+ final UUID id;
+ final String name;
+ final Player player;
+ World at;
+ boolean online = true;
+ boolean playedBefore = true;
+ boolean permissionsBroken;
+ /** Another plugin cancels every kick, so the player stays. */
+ boolean kickCancelled;
+ /** As on a real server, the kick goes through only after the call has returned. */
+ boolean kickLandsLater;
+ int vehiclesLeft;
+ int inventoriesClosed;
+ final List kicks = new ArrayList<>();
+ final List heard = new ArrayList<>();
+ final List teleports = new ArrayList<>();
+ CompletableFuture teleport = CompletableFuture.completedFuture(true);
+ /** Where a teleport really lands, if another plugin changes it; null means where it was sent. */
+ World teleportLandsIn;
+ final List passengers = new ArrayList<>();
+ /** The server throws instead of starting a teleport. */
+ boolean teleportThrows;
+
+ Someone(String name, World at, String... permissions) {
+ this.name = name;
+ this.at = at;
+ this.id = UUID.nameUUIDFromBytes(name.getBytes(StandardCharsets.UTF_8));
+ Set perms = Set.of(permissions);
+ this.player = proxy(Player.class, name, (self, method, args) -> switch (method.getName()) {
+ case "getUniqueId" -> id;
+ case "getName" -> name;
+ case "getWorld" -> this.at;
+ case "isOnline" -> online;
+ case "hasPlayedBefore" -> playedBefore;
+ case "hasPermission" -> {
+ if (permissionsBroken) throw new IllegalStateException("permissions aren't ready");
+ yield perms.contains((String) args[0]);
+ }
+ case "kick" -> {
+ kicks.add(text((Component) args[0]));
+ if (!kickCancelled && !kickLandsLater) online = false;
+ yield null;
+ }
+ case "leaveVehicle" -> {
+ vehiclesLeft++;
+ yield false;
+ }
+ case "closeInventory" -> {
+ inventoriesClosed++;
+ yield null;
+ }
+ case "sendMessage" -> {
+ heard.add(text((Component) args[0]));
+ yield null;
+ }
+ case "teleportAsync" -> {
+ if (teleportThrows) throw new IllegalStateException("made up");
+ Location to = (Location) args[0];
+ teleports.add(to);
+ // As on a server, one that goes through has moved them by the time the caller hears of it.
+ yield teleport.thenApply(ok -> {
+ if (ok) this.at = teleportLandsIn != null ? teleportLandsIn : to.getWorld();
+ return ok;
+ });
+ }
+ case "getPassengers" -> {
+ yield List.copyOf(passengers);
+ }
+ default -> throw new UnsupportedOperationException(method.getName());
+ });
+ }
+ }
+}
diff --git a/src/test/java/com/extantape/posse/listen/HomeWorldsListenerTest.java b/src/test/java/com/extantape/posse/listen/HomeWorldsListenerTest.java
new file mode 100644
index 0000000..05fa7fc
--- /dev/null
+++ b/src/test/java/com/extantape/posse/listen/HomeWorldsListenerTest.java
@@ -0,0 +1,950 @@
+package com.extantape.posse.listen;
+
+import com.extantape.posse.rules.HomeWorlds;
+import com.extantape.posse.rules.Pending;
+import com.extantape.posse.rules.Reach;
+import net.kyori.adventure.text.Component;
+import org.bukkit.Location;
+import org.bukkit.World;
+import org.bukkit.entity.Entity;
+import org.bukkit.entity.Player;
+import org.bukkit.event.Cancellable;
+import org.bukkit.event.EventHandler;
+import org.bukkit.event.EventPriority;
+import org.bukkit.event.entity.EntityPortalEvent;
+import org.bukkit.event.entity.EntityTeleportEvent;
+import org.bukkit.event.player.PlayerChangedWorldEvent;
+import org.bukkit.event.player.PlayerJoinEvent;
+import org.bukkit.event.player.PlayerPortalEvent;
+import org.bukkit.event.player.PlayerQuitEvent;
+import org.bukkit.event.player.PlayerRespawnEvent;
+import org.bukkit.event.player.PlayerTeleportEvent;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** What home worlds does to a player, above all when there is nowhere to send them. */
+class HomeWorldsListenerTest {
+ private final World main = Fakes.world("main");
+ private final World kidland = Fakes.world("kidland");
+ private final World nether = Fakes.world("kidland_nether");
+ private final World grownups = Fakes.world("grownups");
+ private final World station = Fakes.world("station");
+
+ private final class Server extends Fakes.Scheduler implements HomeWorldsListener.Host {
+ final Map worlds = new HashMap<>();
+ final List told = new ArrayList<>();
+ final List announced = new ArrayList<>();
+ boolean paused;
+ /** Home worlds isn't set in the config. */
+ boolean off;
+ /** The rules can't be read when asked. */
+ boolean broken;
+ /** How often the player list was asked to catch up. */
+ int refreshes;
+ /** Who was already pending each time it was. */
+ final List hiddenAtRefresh = new ArrayList<>();
+ String lobby = "station";
+ /** The worlds kids may be in. */
+ Set kidWorlds = Set.of("kidland", "kidland_nether", "station");
+ /** The lobby unloads straight after it's next looked up. */
+ boolean lobbyGoesAfterOneLook;
+
+ Server() {
+ for (World w : List.of(main, kidland, nether, grownups, station)) worlds.put(w.getName(), w);
+ }
+
+ Fakes.Someone join(String name, World at, String... permissions) {
+ return add(new Fakes.Someone(name, at, permissions));
+ }
+
+ @Override public HomeWorlds home() {
+ if (broken) throw new IllegalStateException("made up");
+ if (paused) return null;
+ if (off) return HomeWorlds.OFF;
+ Map by = new LinkedHashMap<>();
+ by.put("kids", new HomeWorlds.Entry(kidWorlds, null));
+ by.put("adults", HomeWorlds.Entry.noLimits());
+ return new HomeWorlds(by, null, lobby);
+ }
+
+ /** Adults are unlimited, so the rules never move them. */
+ @Override public Reach reach() {
+ return paused ? null : new Reach(List.of("kids", "adults"), Set.of(), Map.of(), List.of());
+ }
+
+ /** Messages can't be sent. */
+ boolean tellBroken;
+ /** The join line can't be sent. */
+ boolean announceBroken;
+
+ @Override public World world(String name) {
+ World found = worlds.get(name);
+ if (lobbyGoesAfterOneLook && name.equals(lobby)) worlds.remove(lobby);
+ return found;
+ }
+
+ @Override public void tell(Player player, String key, Map vars) {
+ if (tellBroken) throw new IllegalStateException("made up");
+ told.add(key);
+ }
+
+ @Override public void announce(Player player) {
+ if (announceBroken) throw new IllegalStateException("made up");
+ announced.add(player.getName());
+ }
+
+ @Override public Collection extends Player> online() {
+ return super.online.values().stream().filter(s -> s.online).map(s -> s.player).toList();
+ }
+
+ @Override public void refresh() {
+ refreshes++;
+ for (Fakes.Someone s : super.online.values()) if (Pending.has(s.id)) hiddenAtRefresh.add(s.name);
+ }
+ }
+
+ private final Server server = new Server();
+ private final Eviction eviction = new Eviction(server);
+ private final HomeWorldsListener listener = new HomeWorldsListener(server, eviction);
+ private static final String KID = "posse.circle.kids";
+ private static final String ADULT = "posse.circle.adults";
+ private static final String DISCONNECTED = "A player outside their home worlds was disconnected because ";
+ /** The warning when the named, allowed lobby isn't loaded. */
+ private static final String NOWHERE = DISCONNECTED + "the lobby \"station\" isn't loaded.";
+
+ @AfterEach
+ void forget() {
+ Pending.clear();
+ }
+
+ private void join(Fakes.Someone s) {
+ listener.onJoin(new PlayerJoinEvent(s.player, Component.text("joined")));
+ }
+
+ /** Both MONITOR quit handlers. */
+ private void quit(Fakes.Someone s) {
+ s.online = false;
+ PlayerQuitEvent event = new PlayerQuitEvent(s.player, Component.text("left"), PlayerQuitEvent.QuitReason.DISCONNECTED);
+ listener.onQuit(event);
+ eviction.onQuit(event);
+ }
+
+ private PlayerRespawnEvent respawn(Fakes.Someone s, World at) {
+ PlayerRespawnEvent event = new PlayerRespawnEvent(s.player, new Location(at, 1, 70, 1), false, false, false,
+ PlayerRespawnEvent.RespawnReason.DEATH);
+ listener.onRespawn(event);
+ return event;
+ }
+
+ /** Pending, nothing told, nothing announced, never moved anywhere, and the warning names the lobby only. */
+ private void assertOnTheWayOut(Fakes.Someone s) {
+ assertOnTheWayOut(s, NOWHERE);
+ }
+
+ private void assertOnTheWayOut(Fakes.Someone s, String warning) {
+ assertTrue(Pending.has(s.id), "pending before the kick, so no join or leave line goes out");
+ assertTrue(s.teleports.isEmpty(), "never moved to a stand-in world");
+ assertTrue(s.heard.isEmpty());
+ assertTrue(server.told.isEmpty());
+ assertTrue(server.announced.isEmpty());
+ assertEquals(List.of(warning), server.warnings);
+ }
+
+ private void assertKickedThenCleared(Fakes.Someone s) {
+ server.run();
+ assertEquals(List.of(HomeWorldsListener.SORRY), s.kicks);
+ assertTrue(Pending.has(s.id), "still pending until they have gone");
+ quit(s);
+ assertFalse(Pending.has(s.id));
+ assertTrue(server.announced.isEmpty());
+ }
+
+ @Test
+ void joinWithNoLobbyIsPendingAtOnceAndKickedOnTheNextTick() {
+ server.worlds.remove("station");
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ join(kit);
+ assertOnTheWayOut(kit);
+ assertTrue(kit.kicks.isEmpty(), "not from inside the join event");
+ assertKickedThenCleared(kit);
+ }
+
+ @Test
+ void joinInTheMainWorldWithNoLobbyIsNotLeftThere() {
+ server.worlds.remove("station");
+ Fakes.Someone kit = server.join("Kit", main, KID);
+ join(kit);
+ assertOnTheWayOut(kit);
+ assertKickedThenCleared(kit);
+ }
+
+ @Test
+ void aFirstJoinWithNoLobbyIsDisconnectedAfterTheWait() {
+ server.worlds.remove("station");
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ kit.playedBefore = false;
+ join(kit);
+ assertTrue(Pending.has(kit.id));
+ server.run();
+ assertEquals(List.of(HomeWorldsListener.SORRY), kit.kicks);
+ assertTrue(server.announced.isEmpty());
+ assertTrue(kit.teleports.isEmpty());
+ }
+
+ @Test
+ void aWorldChangeWithNoLobbyIsPendingThenKickedWithNothingTold() {
+ server.worlds.remove("station");
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ listener.onWorldChange(new PlayerChangedWorldEvent(kit.player, kidland));
+ server.run();
+ assertOnTheWayOut(kit);
+ assertKickedThenCleared(kit);
+ }
+
+ @Test
+ void aRespawnWithNoLobbyKeepsItsPlaceAndKicksOnTheNextTick() {
+ server.worlds.remove("station");
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ PlayerRespawnEvent event = respawn(kit, grownups);
+ assertEquals("grownups", event.getRespawnLocation().getWorld().getName(),
+ "they died somewhere they may not be either, so there is no allowed place to name");
+ assertOnTheWayOut(kit);
+ assertTrue(kit.kicks.isEmpty());
+ assertKickedThenCleared(kit);
+ }
+
+ @Test
+ void aRespawnWithNowhereToGoIsPointedBackAtAnAllowedDeathWorld() {
+ server.worlds.remove("station");
+ Fakes.Someone kit = server.join("Kit", nether, KID);
+ PlayerRespawnEvent event = respawn(kit, grownups);
+ assertEquals("kidland_nether", event.getRespawnLocation().getWorld().getName());
+ assertTrue(Pending.has(kit.id), "held for the tick all the same");
+ server.run();
+ assertEquals(List.of(HomeWorldsListener.SORRY), kit.kicks);
+ }
+
+ @Test
+ void aRespawnKickSkipsSomeoneWhoHasAlreadyLeft() {
+ server.worlds.remove("station");
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ respawn(kit, grownups);
+ quit(kit);
+ server.run();
+ assertTrue(kit.kicks.isEmpty());
+ assertFalse(Pending.has(kit.id));
+ }
+
+ @Test
+ void aMoveThatFinishesLateNeverAnnouncesSomeoneOnTheirWayOut() {
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ kit.teleport = new CompletableFuture<>();
+ kit.kickCancelled = true;
+ join(kit);
+ server.worlds.remove("station");
+ respawn(kit, grownups);
+ server.run();
+ kit.teleport.complete(true);
+ server.run();
+ assertTrue(Pending.has(kit.id));
+ assertTrue(server.announced.isEmpty());
+ assertTrue(server.told.isEmpty());
+ assertTrue(kit.kicks.contains(HomeWorldsListener.SORRY));
+ }
+
+ @Test
+ void whenTheLobbyIsOpenTheyAreMovedThereToldAndAnnounced() {
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ join(kit);
+ assertTrue(Pending.has(kit.id));
+ server.run();
+ assertEquals("station", kit.teleports.getFirst().getWorld().getName(),
+ "the lobby, although their own worlds are loaded");
+ assertEquals(List.of("home-lobby"), server.told);
+ assertEquals(List.of("Kit"), server.announced);
+ assertFalse(Pending.has(kit.id));
+ assertTrue(kit.kicks.isEmpty());
+ assertTrue(server.warnings.isEmpty());
+ }
+
+ @Test
+ void aRespawnAndAWorldChangeGoToTheLobbyToo() {
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ assertEquals("station", respawn(kit, grownups).getRespawnLocation().getWorld().getName());
+ listener.onWorldChange(new PlayerChangedWorldEvent(kit.player, kidland));
+ server.run();
+ assertEquals("station", kit.teleports.getFirst().getWorld().getName());
+ assertTrue(kit.kicks.isEmpty());
+ }
+
+ @Test
+ void aJoinMoveThatDoesNotGoThroughDisconnects() {
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ kit.teleport = CompletableFuture.completedFuture(false);
+ join(kit);
+ server.run();
+ assertEquals(List.of(HomeWorldsListener.SORRY), kit.kicks);
+ assertTrue(Pending.has(kit.id));
+ assertTrue(server.announced.isEmpty());
+ }
+
+ @Test
+ void aJoinMoveThatEndsInAnErrorDisconnects() {
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ kit.teleport = CompletableFuture.failedFuture(new IllegalStateException("made up"));
+ join(kit);
+ server.run();
+ assertEquals(List.of(HomeWorldsListener.SORRY), kit.kicks);
+ assertTrue(server.announced.isEmpty());
+ }
+
+ @Test
+ void aWorldChangeMoveThatEndsInAnErrorDisconnects() {
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ kit.teleport = CompletableFuture.failedFuture(new IllegalStateException("made up"));
+ listener.onWorldChange(new PlayerChangedWorldEvent(kit.player, kidland));
+ server.run();
+ assertEquals(List.of(HomeWorldsListener.SORRY), kit.kicks);
+ }
+
+ @Test
+ void someoneTheRulesDoNotCoverIsLeftAloneEvenWithNoLobby() {
+ server.worlds.remove("station");
+ Fakes.Someone ada = server.join("Ada", grownups, ADULT);
+ join(ada);
+ respawn(ada, grownups);
+ listener.onWorldChange(new PlayerChangedWorldEvent(ada.player, main));
+ server.run();
+ assertTrue(ada.kicks.isEmpty());
+ assertFalse(Pending.has(ada.id));
+ }
+
+ /** Their own worlds are loaded and allowed throughout, and are never somewhere they're sent. */
+ private void assertDisconnectedOnJoinBecause(String why) {
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ join(kit);
+ assertOnTheWayOut(kit, DISCONNECTED + why + ".");
+ assertKickedThenCleared(kit);
+ }
+
+ @Test
+ void withNoLobbySetTheyAreDisconnected() {
+ server.lobby = "";
+ assertDisconnectedOnJoinBecause("no lobby-world is set");
+ }
+
+ @Test
+ void aLobbyTheirGroupMayNotBeInDisconnects() {
+ server.kidWorlds = Set.of("kidland", "kidland_nether");
+ assertDisconnectedOnJoinBecause("the lobby \"station\" isn't open to their group");
+ }
+
+ @Test
+ void aLobbyThatIsNotLoadedDisconnects() {
+ server.worlds.remove("station");
+ assertDisconnectedOnJoinBecause("the lobby \"station\" isn't loaded");
+ }
+
+ @Test
+ void aLobbyThatGoesAfterTheDecisionDisconnects() {
+ server.lobbyGoesAfterOneLook = true;
+ assertDisconnectedOnJoinBecause("the lobby \"station\" isn't loaded");
+ }
+
+ @Test
+ void aMoveToTheLobbyThatDoesNotGoThroughTellsThemNothing() {
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ kit.teleport = CompletableFuture.completedFuture(false);
+ join(kit);
+ server.run();
+ assertEquals(List.of(HomeWorldsListener.SORRY), kit.kicks);
+ assertTrue(server.told.isEmpty());
+ assertTrue(server.announced.isEmpty());
+ }
+
+ @Test
+ void aCancelledKickKeepsThemHeldAndIsTriedAgainUntilTheyHaveGone() {
+ server.worlds.remove("station");
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ kit.kickCancelled = true;
+ join(kit);
+ server.run();
+ server.retry();
+ server.retry();
+ assertEquals(3, kit.kicks.size());
+ assertTrue(eviction.holds(kit.id));
+ assertTrue(Pending.has(kit.id));
+ assertTrue(server.announced.isEmpty());
+ assertEquals(2, server.warnings.size(), "why, then once that the kick didn't go through");
+ kit.kickCancelled = false;
+ server.retry();
+ assertEquals(4, kit.kicks.size());
+ quit(kit);
+ server.retry();
+ assertEquals(4, kit.kicks.size());
+ assertTrue(server.retries.isEmpty());
+ assertFalse(Pending.has(kit.id));
+ }
+
+ @Test
+ void aHeldPlayerIsNotCheckedOrReleasedAgain() {
+ server.worlds.remove("station");
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ kit.kickCancelled = true;
+ join(kit);
+ server.run();
+ server.worlds.put("station", station);
+ listener.onWorldChange(new PlayerChangedWorldEvent(kit.player, kidland));
+ join(kit);
+ server.run();
+ assertTrue(kit.teleports.isEmpty());
+ assertTrue(Pending.has(kit.id));
+ assertTrue(server.announced.isEmpty());
+ }
+
+ @Test
+ void whilePausedThisListenerDoesNothingBecauseTheLoginGateKeepsPlayersOut() {
+ server.paused = true;
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ join(kit);
+ server.run();
+ assertTrue(kit.teleports.isEmpty());
+ assertTrue(kit.kicks.isEmpty());
+ }
+
+ private void changeWorld(Fakes.Someone s, World from) {
+ listener.onWorldChange(new PlayerChangedWorldEvent(s.player, from));
+ }
+
+ @Test
+ void aWorldChangeIntoAForbiddenWorldIsPendingBeforeTheEventIsOver() {
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ changeWorld(kit, kidland);
+ assertTrue(Pending.has(kit.id), "unlisted and unreachable from the moment they arrive, not a tick later");
+ assertTrue(kit.teleports.isEmpty(), "the move itself waits for the teleport that brought them to finish");
+ }
+
+ @Test
+ void aWorldChangeMoveIsPendingUntilItIsDone() {
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ kit.teleport = new CompletableFuture<>();
+ changeWorld(kit, kidland);
+ server.run();
+ assertEquals(1, kit.teleports.size());
+ assertTrue(Pending.has(kit.id), "still pending while the move is under way");
+ kit.teleport.complete(true);
+ server.run();
+ assertFalse(Pending.has(kit.id));
+ assertEquals(List.of("home-lobby"), server.told);
+ assertEquals(List.of("Kit"), server.announced);
+ assertTrue(kit.kicks.isEmpty());
+ }
+
+ @Test
+ void aMoveThatReportsSuccessButLandsSomewhereForbiddenDisconnects() {
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ kit.teleportLandsIn = main;
+ join(kit);
+ server.run();
+ assertEquals(List.of(HomeWorldsListener.SORRY), kit.kicks);
+ assertTrue(Pending.has(kit.id));
+ assertTrue(server.announced.isEmpty());
+ }
+
+ @Test
+ void movingBetweenAllowedWorldsDuringAFirstJoinWaitDoesNotEndTheWaitEarly() {
+ Fakes.Someone kit = server.join("Kit", kidland, KID);
+ kit.playedBefore = false;
+ join(kit);
+ assertTrue(Pending.has(kit.id));
+ kit.at = nether;
+ changeWorld(kit, kidland);
+ Runnable delayedCheck = server.queued.pollFirst();
+ server.run();
+ assertTrue(Pending.has(kit.id), "only the delayed check ends it");
+ assertTrue(server.announced.isEmpty());
+ delayedCheck.run();
+ assertFalse(Pending.has(kit.id));
+ assertEquals(List.of("Kit"), server.announced);
+ }
+
+ @Test
+ void aMoveDuringAFirstJoinWaitLeavesThemPendingForTheDelayedCheck() {
+ Fakes.Someone kit = server.join("Kit", kidland, KID);
+ kit.playedBefore = false;
+ join(kit);
+ Runnable delayedCheck = server.queued.pollFirst();
+ kit.at = grownups;
+ changeWorld(kit, kidland);
+ server.run();
+ assertEquals("station", kit.teleports.getFirst().getWorld().getName());
+ assertTrue(Pending.has(kit.id));
+ delayedCheck.run();
+ assertFalse(Pending.has(kit.id));
+ }
+
+ @Test
+ void permissionsThatCannotBeReadOnAWorldChangeDisconnect() {
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ kit.permissionsBroken = true;
+ changeWorld(kit, kidland);
+ server.run();
+ assertEquals(List.of(HomeWorldsListener.SORRY), kit.kicks);
+ assertTrue(kit.teleports.isEmpty());
+ assertTrue(Pending.has(kit.id));
+ }
+
+ private PlayerTeleportEvent teleportEvent(Fakes.Someone s, World to) {
+ return new PlayerTeleportEvent(s.player, new Location(s.at, 0, 64, 0), new Location(to, 5, 64, 5),
+ PlayerTeleportEvent.TeleportCause.PLUGIN);
+ }
+
+ private boolean teleportRefused(Fakes.Someone s, World to) {
+ PlayerTeleportEvent event = teleportEvent(s, to);
+ listener.onTeleport(event);
+ return event.isCancelled();
+ }
+
+ private boolean portalRefused(Fakes.Someone s, World to) {
+ PlayerPortalEvent event = new PlayerPortalEvent(s.player, new Location(s.at, 0, 64, 0), new Location(to, 5, 64, 5));
+ listener.onPortal(event);
+ return event.isCancelled();
+ }
+
+ private boolean vehicleTeleportRefused(Entity vehicle, World to) {
+ EntityTeleportEvent event = new EntityTeleportEvent(vehicle, new Location(kidland, 0, 64, 0), new Location(to, 5, 64, 5));
+ listener.onEntityTeleport(event);
+ return event.isCancelled();
+ }
+
+ private boolean vehiclePortalRefused(Entity vehicle, World to) {
+ EntityPortalEvent event = new EntityPortalEvent(vehicle, new Location(kidland, 0, 64, 0), new Location(to, 5, 64, 5));
+ listener.onEntityPortal(event);
+ return event.isCancelled();
+ }
+
+ @Test
+ void aTeleportIntoAForbiddenWorldIsRefused() {
+ Fakes.Someone kit = server.join("Kit", kidland, KID);
+ assertTrue(teleportRefused(kit, grownups));
+ assertTrue(teleportRefused(kit, main));
+ assertFalse(Pending.has(kit.id), "they never left, so nothing about them changes");
+ assertTrue(kit.kicks.isEmpty());
+ }
+
+ @Test
+ void aPortalIntoAForbiddenWorldIsRefused() {
+ assertTrue(portalRefused(server.join("Kit", kidland, KID), grownups));
+ }
+
+ @Test
+ void allowedWorldsAndPossesOwnLobbyMoveAreNotRefused() {
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ assertFalse(teleportRefused(kit, station), "Posse's own move is to the lobby");
+ assertFalse(teleportRefused(kit, kidland));
+ assertFalse(portalRefused(kit, nether));
+ }
+
+ @Test
+ void someoneTheRulesDoNotCoverMayTeleportAnywhere() {
+ Fakes.Someone ada = server.join("Ada", kidland, ADULT);
+ assertFalse(teleportRefused(ada, grownups));
+ assertFalse(portalRefused(ada, main));
+ }
+
+ @Test
+ void withHomeWorldsOffNoTeleportIsRefused() {
+ server.off = true;
+ assertFalse(teleportRefused(server.join("Kit", kidland, KID), grownups));
+ }
+
+ @Test
+ void aTeleportThatCannotBeDecidedIsRefused() {
+ Fakes.Someone kit = server.join("Kit", kidland, KID);
+ kit.permissionsBroken = true;
+ assertTrue(teleportRefused(kit, kidland), "permissions can't be read");
+ kit.permissionsBroken = false;
+ server.broken = true;
+ assertTrue(teleportRefused(kit, kidland), "the rules can't be read");
+ assertTrue(portalRefused(kit, kidland));
+ assertEquals(1, server.warnings.size(), "said once, since a portal asks over and over");
+ assertFalse(server.warnings.getFirst().contains("Kit"));
+ }
+
+ @Test
+ void aTeleportWithNoWorldToCheckIsRefused() {
+ Fakes.Someone kit = server.join("Kit", kidland, KID);
+ PlayerTeleportEvent event = new PlayerTeleportEvent(kit.player, new Location(kidland, 0, 64, 0),
+ new Location(null, 5, 64, 5), PlayerTeleportEvent.TeleportCause.PLUGIN);
+ listener.onTeleport(event);
+ assertTrue(event.isCancelled());
+ }
+
+ @Test
+ void whilePausedOnlyBypassMayTeleport() {
+ server.paused = true;
+ assertTrue(teleportRefused(server.join("Kit", kidland, KID), kidland));
+ assertFalse(teleportRefused(server.join("Ada", kidland, "posse.bypass"), grownups));
+ }
+
+ @Test
+ void aVehicleCarryingSomeoneIntoAForbiddenWorldIsRefused() {
+ Fakes.Someone kit = server.join("Kit", kidland, KID);
+ assertTrue(vehicleTeleportRefused(Fakes.vehicle(kit.player), grownups));
+ assertTrue(vehiclePortalRefused(Fakes.vehicle(kit.player), grownups));
+ assertTrue(vehiclePortalRefused(Fakes.vehicle(Fakes.vehicle(kit.player)), grownups), "a rider of a rider");
+ }
+
+ @Test
+ void anAdultCarryingAKidIsRefusedTooWhicheverTeleportItIs() {
+ Fakes.Someone ada = server.join("Ada", kidland, ADULT);
+ ada.passengers.add(server.join("Kit", kidland, KID).player);
+ assertTrue(teleportRefused(ada, grownups));
+ assertTrue(portalRefused(ada, grownups));
+ }
+
+ @Test
+ void emptyVehiclesAndAllowedRidesAreLeftAlone() {
+ Fakes.Someone kit = server.join("Kit", kidland, KID);
+ assertFalse(vehicleTeleportRefused(Fakes.vehicle(), grownups));
+ assertFalse(vehiclePortalRefused(Fakes.vehicle(kit.player), nether));
+ server.broken = true;
+ assertFalse(vehiclePortalRefused(Fakes.vehicle(), grownups), "nobody aboard, nothing to decide");
+ }
+
+ @Test
+ void theTeleportChecksRunLastSoNothingEarlierCanSlipPast() {
+ for (String name : List.of("onTeleport", "onPortal", "onEntityTeleport", "onEntityPortal")) {
+ Method method = Stream.of(HomeWorldsListener.class.getDeclaredMethods())
+ .filter(m -> m.getName().equals(name)).findFirst().orElseThrow();
+ EventHandler handler = method.getAnnotation(EventHandler.class);
+ assertEquals(EventPriority.HIGHEST, handler.priority(), name);
+ assertTrue(Cancellable.class.isAssignableFrom(method.getParameterTypes()[0]), name);
+ }
+ }
+
+ @Test
+ void aRecheckMovesSomeoneTheRulesNoLongerAllowAndHidesThemFirst() {
+ Fakes.Someone kit = server.join("Kit", nether, KID);
+ kit.teleport = new CompletableFuture<>();
+ server.kidWorlds = Set.of("kidland", "station");
+ listener.recheck();
+ assertTrue(Pending.has(kit.id));
+ assertEquals(List.of("Kit"), server.hiddenAtRefresh, "the player list catches up while they are pending");
+ assertEquals("station", kit.teleports.getFirst().getWorld().getName());
+ kit.teleport.complete(true);
+ server.run();
+ assertFalse(Pending.has(kit.id));
+ assertEquals(List.of("home-lobby"), server.told);
+ assertTrue(kit.kicks.isEmpty());
+ }
+
+ @Test
+ void aRecheckDisconnectsSomeoneWithNowhereToGo() {
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ server.lobby = "";
+ listener.recheck();
+ assertOnTheWayOut(kit, DISCONNECTED + "no lobby-world is set.");
+ assertKickedThenCleared(kit);
+ }
+
+ @Test
+ void aRecheckLeavesAllowedAndUncoveredPlayersAloneAndLooksAtEveryone() {
+ Fakes.Someone kit = server.join("Kit", kidland, KID);
+ Fakes.Someone ada = server.join("Ada", grownups, ADULT);
+ Fakes.Someone jo = server.join("Jo", grownups, KID);
+ Fakes.Someone lee = server.join("Lee", main, KID);
+ listener.recheck();
+ server.run();
+ assertTrue(kit.teleports.isEmpty() && ada.teleports.isEmpty());
+ assertFalse(Pending.has(kit.id));
+ assertFalse(Pending.has(ada.id));
+ assertEquals(1, jo.teleports.size());
+ assertEquals(1, lee.teleports.size());
+ }
+
+ @Test
+ void oneUnreadablePlayerDoesNotStopTheRecheck() {
+ Fakes.Someone jo = server.join("Jo", grownups, KID);
+ jo.permissionsBroken = true;
+ Fakes.Someone lee = server.join("Lee", main, KID);
+ listener.recheck();
+ server.run();
+ assertEquals(List.of(HomeWorldsListener.SORRY), jo.kicks);
+ assertEquals(1, lee.teleports.size());
+ }
+
+ @Test
+ void aRecheckDoesNotStartASecondMove() {
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ kit.teleport = new CompletableFuture<>();
+ join(kit);
+ listener.recheck();
+ assertEquals(1, kit.teleports.size());
+ }
+
+ // A: a server whose config says nothing about players in no circle.
+
+ @Test
+ void aPlayerInNoCircleWithNoNoCircleEntryIsSentToTheLobby() {
+ Fakes.Someone nia = server.join("Nia", grownups);
+ join(nia);
+ server.run();
+ assertEquals("station", nia.teleports.getFirst().getWorld().getName());
+ assertEquals(List.of("home-waiting"), server.told);
+ assertEquals(List.of("Nia"), server.announced);
+ assertTrue(teleportRefused(nia, grownups));
+ assertTrue(teleportRefused(nia, kidland), "a kids' world is not open to someone whose group is unknown");
+ }
+
+ @Test
+ void aPlayerInNoCircleWithNoNoCircleEntryAndNoLobbyIsDisconnected() {
+ server.lobby = "";
+ Fakes.Someone nia = server.join("Nia", kidland);
+ join(nia);
+ assertOnTheWayOut(nia, DISCONNECTED + "no lobby-world is set.");
+ assertKickedThenCleared(nia);
+ }
+
+ @Test
+ void groupsThatCannotBeReadOnJoinDisconnect() {
+ Fakes.Someone nia = server.join("Nia", station);
+ nia.permissionsBroken = true;
+ join(nia);
+ server.run();
+ assertEquals(List.of(HomeWorldsListener.SORRY), nia.kicks);
+ assertTrue(Pending.has(nia.id));
+ assertTrue(server.announced.isEmpty());
+ }
+
+ // B: nobody sees a player whose move is pending, and every way out ends that.
+
+ @Test
+ void aPlayerIsHiddenAndOutOfSeatsAndInventoriesBeforeTheMoveStarts() {
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ kit.teleport = new CompletableFuture<>();
+ join(kit);
+ assertEquals(List.of("Kit"), server.hiddenAtRefresh);
+ assertEquals(1, kit.vehiclesLeft);
+ assertEquals(1, kit.inventoriesClosed);
+ }
+
+ @Test
+ void aFirstJoinWaitAndAWorldChangeHideThemAtOnceToo() {
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ kit.playedBefore = false;
+ join(kit);
+ assertEquals(List.of("Kit"), server.hiddenAtRefresh);
+ quit(kit);
+ server.hiddenAtRefresh.clear();
+ Fakes.Someone jo = server.join("Jo", grownups, KID);
+ changeWorld(jo, kidland);
+ assertEquals(List.of("Jo"), server.hiddenAtRefresh);
+ }
+
+ @Test
+ void aTeleportTheServerWillNotStartDisconnects() {
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ kit.teleportThrows = true;
+ join(kit);
+ server.run();
+ assertEquals(List.of(HomeWorldsListener.SORRY), kit.kicks);
+ assertTrue(Pending.has(kit.id));
+ assertTrue(server.announced.isEmpty());
+ }
+
+ @Test
+ void aMoveThatNeverFinishesDisconnectsAfterTheTimeLimit() {
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ kit.teleport = new CompletableFuture<>();
+ join(kit);
+ server.run();
+ assertTrue(kit.kicks.isEmpty());
+ server.timeOut();
+ assertEquals(List.of(HomeWorldsListener.SORRY), kit.kicks);
+ kit.teleport.complete(true);
+ server.run();
+ assertTrue(Pending.has(kit.id));
+ assertTrue(server.announced.isEmpty());
+ assertTrue(server.told.isEmpty());
+ }
+
+ @Test
+ void theTimeLimitDoesNothingToAMoveThatFinished() {
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ join(kit);
+ server.run();
+ server.timeOut();
+ server.run();
+ assertTrue(kit.kicks.isEmpty());
+ assertFalse(Pending.has(kit.id));
+ }
+
+ @Test
+ void aMoveLeftOverFromAnEarlierStayDoesNothingToTheNewOne() {
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ CompletableFuture first = new CompletableFuture<>();
+ kit.teleport = first;
+ join(kit);
+ quit(kit);
+ kit.online = true;
+ kit.teleport = new CompletableFuture<>();
+ join(kit);
+ first.complete(false);
+ server.run();
+ assertTrue(kit.kicks.isEmpty(), "the old move's end says nothing about this stay");
+ assertTrue(Pending.has(kit.id));
+ }
+
+ @Test
+ void aMessageThatCannotBeSentStillReleasesThem() {
+ server.tellBroken = true;
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ join(kit);
+ server.run();
+ assertFalse(Pending.has(kit.id), "they are where they may be, so they aren't left frozen");
+ assertEquals(List.of("Kit"), server.announced);
+ assertTrue(kit.kicks.isEmpty());
+ }
+
+ @Test
+ void aJoinLineThatCannotBeSentIsWarnedAboutAndBreaksNothing() {
+ server.announceBroken = true;
+ Fakes.Someone kit = server.join("Kit", grownups, KID);
+ join(kit);
+ server.run();
+ assertFalse(Pending.has(kit.id));
+ assertEquals(1, server.warnings.size());
+ assertFalse(server.warnings.getFirst().contains("Kit"));
+ }
+
+ @Test
+ void aRecheckReleasesSomeoneLeftPendingWithNothingComingForThem() {
+ Fakes.Someone kit = server.join("Kit", kidland, KID);
+ Pending.begin(kit.id);
+ listener.recheck();
+ assertFalse(Pending.has(kit.id));
+ }
+
+ // C: another plugin that takes a refusal back.
+
+ @Test
+ void aRefusedTeleportPointsBackAtWhereItStarted() {
+ Fakes.Someone kit = server.join("Kit", kidland, KID);
+ PlayerTeleportEvent event = teleportEvent(kit, grownups);
+ listener.onTeleport(event);
+ assertEquals("kidland", event.getTo().getWorld().getName(),
+ "so taking the cancel back goes nowhere");
+ Entity boat = Fakes.vehicle(kit.player);
+ EntityTeleportEvent ride = new EntityTeleportEvent(boat, new Location(kidland, 0, 64, 0), new Location(grownups, 5, 64, 5));
+ listener.onEntityTeleport(ride);
+ assertEquals("kidland", ride.getTo().getWorld().getName());
+ EntityPortalEvent portal = new EntityPortalEvent(boat, new Location(kidland, 0, 64, 0), new Location(grownups, 5, 64, 5));
+ listener.onEntityPortal(portal);
+ assertEquals("kidland", portal.getTo().getWorld().getName());
+ }
+
+ @Test
+ void aRefusalAnotherPluginTakesBackIsPutBack() {
+ Fakes.Someone kit = server.join("Kit", kidland, KID);
+ PlayerTeleportEvent event = teleportEvent(kit, grownups);
+ listener.onTeleport(event);
+ event.setCancelled(false);
+ event.setTo(new Location(grownups, 5, 64, 5));
+ listener.onTeleportLast(event);
+ assertTrue(event.isCancelled());
+ assertEquals("kidland", event.getTo().getWorld().getName());
+ assertEquals(1, server.warnings.size());
+ assertFalse(server.warnings.getFirst().contains("Kit"));
+ }
+
+ @Test
+ void aRefusedPortalOrRideAnotherPluginTakesBackIsPutBack() {
+ Fakes.Someone kit = server.join("Kit", kidland, KID);
+ PlayerPortalEvent portal = new PlayerPortalEvent(kit.player, new Location(kidland, 0, 64, 0), new Location(grownups, 5, 64, 5));
+ listener.onPortal(portal);
+ portal.setCancelled(false);
+ portal.setTo(new Location(grownups, 5, 64, 5));
+ listener.onPortalLast(portal);
+ assertTrue(portal.isCancelled());
+ Entity boat = Fakes.vehicle(kit.player);
+ EntityTeleportEvent ride = new EntityTeleportEvent(boat, new Location(kidland, 0, 64, 0), new Location(grownups, 5, 64, 5));
+ listener.onEntityTeleport(ride);
+ ride.setCancelled(false);
+ listener.onEntityTeleportLast(ride);
+ assertTrue(ride.isCancelled());
+ EntityPortalEvent through = new EntityPortalEvent(boat, new Location(kidland, 0, 64, 0), new Location(grownups, 5, 64, 5));
+ listener.onEntityPortal(through);
+ through.setCancelled(false);
+ listener.onEntityPortalLast(through);
+ assertTrue(through.isCancelled());
+ }
+
+ @Test
+ void aDestinationChangedAfterTheCheckIsRefusedAtTheEnd() {
+ Fakes.Someone kit = server.join("Kit", kidland, KID);
+ PlayerTeleportEvent event = teleportEvent(kit, nether);
+ listener.onTeleport(event);
+ assertFalse(event.isCancelled());
+ event.setTo(new Location(grownups, 5, 64, 5));
+ listener.onTeleportLast(event);
+ assertTrue(event.isCancelled());
+ assertEquals("kidland", event.getTo().getWorld().getName());
+ }
+
+ @Test
+ void theLastLookLeavesAllowedTeleportsAndOtherPluginsRefusalsAlone() {
+ Fakes.Someone kit = server.join("Kit", kidland, KID);
+ PlayerTeleportEvent allowed = teleportEvent(kit, nether);
+ listener.onTeleport(allowed);
+ listener.onTeleportLast(allowed);
+ assertFalse(allowed.isCancelled());
+ PlayerTeleportEvent theirs = teleportEvent(kit, nether);
+ theirs.setCancelled(true);
+ listener.onTeleportLast(theirs);
+ assertTrue(theirs.isCancelled());
+ assertEquals("kidland_nether", theirs.getTo().getWorld().getName());
+ assertTrue(server.warnings.isEmpty());
+ }
+
+ @Test
+ void theLastLookRunsAfterEveryOtherPriorityEvenOnCancelledEvents() {
+ for (String name : List.of("onTeleportLast", "onPortalLast", "onEntityTeleportLast", "onEntityPortalLast")) {
+ Method method = Stream.of(HomeWorldsListener.class.getDeclaredMethods())
+ .filter(m -> m.getName().equals(name)).findFirst().orElseThrow();
+ EventHandler handler = method.getAnnotation(EventHandler.class);
+ assertEquals(EventPriority.MONITOR, handler.priority(), name);
+ assertFalse(handler.ignoreCancelled(), name);
+ }
+ }
+
+ @Test
+ void aRecheckDuringAFirstJoinWaitHidesThemAndLeavesTheMoveToTheDelayedCheck() {
+ Fakes.Someone jo = server.join("Jo", grownups, KID);
+ jo.playedBefore = false;
+ join(jo);
+ // As if the rules didn't cover them when they joined, and the reload now does.
+ Pending.end(jo.id);
+ listener.recheck();
+ assertTrue(Pending.has(jo.id));
+ assertTrue(jo.teleports.isEmpty());
+ server.run();
+ assertEquals(1, jo.teleports.size());
+ assertFalse(Pending.has(jo.id));
+ }
+}
diff --git a/src/test/java/com/extantape/posse/listen/PausedLoginGateTest.java b/src/test/java/com/extantape/posse/listen/PausedLoginGateTest.java
new file mode 100644
index 0000000..2119901
--- /dev/null
+++ b/src/test/java/com/extantape/posse/listen/PausedLoginGateTest.java
@@ -0,0 +1,179 @@
+package com.extantape.posse.listen;
+
+import com.extantape.posse.rules.Pending;
+import net.kyori.adventure.text.Component;
+import org.bukkit.event.EventHandler;
+import org.bukkit.event.EventPriority;
+import org.bukkit.event.player.PlayerJoinEvent;
+import org.bukkit.event.player.PlayerLoginEvent;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import java.net.InetAddress;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** While Posse's rules aren't loaded, only posse.bypass gets in. */
+@SuppressWarnings("deprecation")
+class PausedLoginGateTest {
+ private final AtomicBoolean paused = new AtomicBoolean(true);
+ private final AtomicLong clock = new AtomicLong(1_000);
+ private final List log = new ArrayList<>();
+ private final Fakes.Scheduler server = new Fakes.Scheduler();
+ private final Eviction eviction = new Eviction(server);
+ private final PausedLoginGate gate = new PausedLoginGate(paused::get, eviction, log::add, clock::get);
+
+ @AfterEach
+ void forget() {
+ Pending.clear();
+ }
+
+ private PlayerLoginEvent login(Fakes.Someone s) {
+ PlayerLoginEvent event = new PlayerLoginEvent(s.player, "localhost", InetAddress.getLoopbackAddress());
+ gate.onLogin(event);
+ return event;
+ }
+
+ private static Fakes.Someone someone(String name, String... permissions) {
+ return new Fakes.Someone(name, Fakes.world("main"), permissions);
+ }
+
+ private static void assertRefused(PlayerLoginEvent event) {
+ assertEquals(PlayerLoginEvent.Result.KICK_OTHER, event.getResult());
+ assertEquals("The server's safety rules didn't load, so joining is paused. Please try again later.",
+ Fakes.text(event.kickMessage()));
+ }
+
+ @Test
+ void aPlayerWithoutTheBypassIsRefusedKindly() {
+ assertRefused(login(someone("Kit", "posse.circle.kids")));
+ }
+
+ @Test
+ void adminPermissionAloneDoesNotGetSomeoneIn() {
+ assertRefused(login(someone("Ada", "posse.admin")));
+ }
+
+ @Test
+ void theBypassGetsIn() {
+ assertEquals(PlayerLoginEvent.Result.ALLOWED, login(someone("Ada", "posse.bypass")).getResult());
+ assertTrue(log.isEmpty());
+ }
+
+ @Test
+ void permissionsThatCannotBeReadMeanRefused() {
+ Fakes.Someone ada = someone("Ada", "posse.bypass");
+ ada.permissionsBroken = true;
+ assertRefused(login(ada));
+ }
+
+ @Test
+ void onceTheRulesLoadEveryoneGetsIn() {
+ paused.set(false);
+ assertEquals(PlayerLoginEvent.Result.ALLOWED, login(someone("Kit")).getResult());
+ }
+
+ @Test
+ void anotherRefusalIsLeftAsItIs() {
+ Fakes.Someone ada = someone("Ada", "posse.bypass");
+ PlayerLoginEvent event = new PlayerLoginEvent(ada.player, "localhost", InetAddress.getLoopbackAddress());
+ event.disallow(PlayerLoginEvent.Result.KICK_BANNED, Component.text("Not today."));
+ gate.onLogin(event);
+ assertEquals(PlayerLoginEvent.Result.KICK_BANNED, event.getResult());
+ assertEquals("Not today.", Fakes.text(event.kickMessage()));
+ }
+
+ @Test
+ void theLogSaysSoOnceAMinuteAndNamesNobody() {
+ login(someone("Kit"));
+ clock.addAndGet(59_999);
+ login(someone("Sam"));
+ assertEquals(1, log.size());
+ clock.addAndGet(1);
+ login(someone("Kit"));
+ assertEquals(2, log.size());
+ assertTrue(log.stream().noneMatch(line -> line.contains("Kit") || line.contains("Sam")));
+ }
+
+ private static String refusalText() {
+ return "The server's safety rules didn't load, so joining is paused. Please try again later.";
+ }
+
+ private PlayerJoinEvent joinAnyway(Fakes.Someone s) {
+ server.add(s);
+ PlayerJoinEvent event = new PlayerJoinEvent(s.player, Component.text("joined"));
+ gate.onJoinFirst(event);
+ gate.onJoinLast(event);
+ return event;
+ }
+
+ @Test
+ void aJoinThatGotPastTheLoginCheckIsHeldSilencedAndDisconnected() {
+ Fakes.Someone kit = someone("Kit", "posse.circle.kids");
+ PlayerJoinEvent event = joinAnyway(kit);
+ assertNull(event.joinMessage());
+ assertTrue(eviction.holds(kit.id));
+ assertTrue(Pending.has(kit.id));
+ assertTrue(kit.kicks.isEmpty(), "not from inside the join event");
+ server.run();
+ assertEquals(List.of(refusalText()), kit.kicks);
+ assertEquals(1, log.size());
+ }
+
+ @Test
+ void aJoinKickThatIsCancelledIsTriedAgainWhileTheyStayHeld() {
+ Fakes.Someone kit = someone("Kit");
+ kit.kickCancelled = true;
+ joinAnyway(kit);
+ server.run();
+ server.retry();
+ assertEquals(2, kit.kicks.size());
+ assertTrue(eviction.holds(kit.id));
+ assertEquals(1, server.warnings.size());
+ }
+
+ @Test
+ void theBypassJoinsAsUsual() {
+ Fakes.Someone ada = someone("Ada", "posse.bypass");
+ PlayerJoinEvent event = joinAnyway(ada);
+ assertNotNull(event.joinMessage());
+ assertFalse(eviction.holds(ada.id));
+ server.run();
+ assertTrue(ada.kicks.isEmpty());
+ }
+
+ @Test
+ void aJoinWithUnreadablePermissionsIsRefused() {
+ Fakes.Someone ada = someone("Ada", "posse.bypass");
+ ada.permissionsBroken = true;
+ joinAnyway(ada);
+ assertTrue(eviction.holds(ada.id));
+ }
+
+ @Test
+ void onceTheRulesLoadAJoinIsLeftAlone() {
+ paused.set(false);
+ Fakes.Someone kit = someone("Kit");
+ assertNotNull(joinAnyway(kit).joinMessage());
+ assertFalse(eviction.holds(kit.id));
+ }
+
+ @Test
+ void theChecksHaveTheLastWordAndTheHoldComesFirst() throws Exception {
+ assertEquals(EventPriority.HIGHEST, priority("onLogin", PlayerLoginEvent.class));
+ assertEquals(EventPriority.LOWEST, priority("onJoinFirst", PlayerJoinEvent.class));
+ assertEquals(EventPriority.HIGHEST, priority("onJoinLast", PlayerJoinEvent.class));
+ }
+
+ private static EventPriority priority(String method, Class> event) throws NoSuchMethodException {
+ return PausedLoginGate.class.getMethod(method, event).getAnnotation(EventHandler.class).priority();
+ }
+}
diff --git a/src/test/java/com/extantape/posse/rules/HomeWorldsTest.java b/src/test/java/com/extantape/posse/rules/HomeWorldsTest.java
index 83a6045..16f5238 100644
--- a/src/test/java/com/extantape/posse/rules/HomeWorldsTest.java
+++ b/src/test/java/com/extantape/posse/rules/HomeWorldsTest.java
@@ -13,6 +13,7 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
class HomeWorldsTest {
@@ -20,31 +21,61 @@ class HomeWorldsTest {
private static final Predicate EXISTS = WORLDS::contains;
private static final Reach REACH = new Reach(List.of("kids", "adults"), Set.of(), Map.of(), List.of("_nether", "_the_end"));
+ /** Kids may be in their own worlds or the station, people with no circle only the station. The station is the lobby. */
private static HomeWorlds configured() {
+ return withLobby("station");
+ }
+
+ private static HomeWorlds withLobby(String lobby) {
Map by = new LinkedHashMap<>();
- by.put("kids", new HomeWorlds.Entry(Set.of("kidland", "kidland_nether", "kidland_the_end"), "kidland", "Hello kid"));
- return new HomeWorlds(by, new HomeWorlds.Entry(Set.of(), "station", null));
+ by.put("kids", new HomeWorlds.Entry(Set.of("kidland", "kidland_nether", "kidland_the_end", "station"), "Hello kid"));
+ by.put("adults", HomeWorlds.Entry.noLimits());
+ return new HomeWorlds(by, new HomeWorlds.Entry(Set.of("station"), "Wait here"), lobby);
}
private static HomeWorlds.Move decide(HomeWorlds h, Subject s) {
- return h.decide(REACH, s, s.world(), EXISTS, "main");
+ return h.decide(REACH, s, s.world(), EXISTS);
+ }
+
+ private static HomeWorlds.Move without(HomeWorlds h, Subject s, String... missing) {
+ Set gone = Set.of(missing);
+ return h.decide(REACH, s, s.world(), w -> EXISTS.test(w) && !gone.contains(w));
+ }
+
+ private static void assertDisconnect(HomeWorlds.Move m, String why) {
+ assertEquals(HomeWorlds.Kind.DISCONNECT, m.kind());
+ assertTrue(m.disconnect());
+ assertNull(m.world(), "a disconnect names no world to send them to");
+ assertNull(m.message());
+ assertEquals(why, m.why());
+ }
+
+ private static final String UNSET = "no lobby-world is set";
+
+ private static String closed(String lobby) {
+ return "the lobby \"" + lobby + "\" isn't open to their group";
+ }
+
+ private static String unloaded(String lobby) {
+ return "the lobby \"" + lobby + "\" isn't loaded";
}
@Test
void aKidInAKidsWorldStays() {
- for (String w : List.of("kidland", "kidland_nether", "kidland_the_end")) {
+ for (String w : List.of("kidland", "kidland_nether", "kidland_the_end", "station")) {
assertNull(decide(configured(), player("Kit", w, circle("kids"))), w);
}
}
@Test
- void aKidInTheAdultsWorldTheStationOrACaveIsMovedToTheirFallback() {
- for (String w : List.of("grownups", "station", "cave", "main")) {
+ void aKidOutsideTheirWorldsGoesToTheLobbyAlthoughTheirOtherWorldsAreLoaded() {
+ for (String w : List.of("grownups", "cave", "main")) {
HomeWorlds.Move m = decide(configured(), player("Kit", w, circle("kids")));
- assertEquals("kidland", m.world(), w);
- assertFalse(m.degraded());
- assertEquals(HomeWorlds.Kind.CIRCLE, m.kind());
+ assertEquals("station", m.world(), w);
+ assertFalse(m.disconnect());
+ assertEquals(HomeWorlds.Kind.LOBBY, m.kind());
assertEquals("Hello kid", m.message());
+ assertNull(m.why());
}
}
@@ -61,42 +92,86 @@ void anAdultIsNeverMoved() {
}
@Test
- void someoneWithNoCircleGoesToTheStationUnlessAlreadyThere() {
+ void someoneWithNoCircleGoesToTheLobbyUnlessAlreadyInAWorldOnTheirList() {
HomeWorlds.Move m = decide(configured(), player("New", "grownups"));
assertEquals("station", m.world());
assertEquals(HomeWorlds.Kind.NO_CIRCLE, m.kind());
- assertNull(m.message());
+ assertEquals("Wait here", m.message());
assertNull(decide(configured(), player("New", "station")));
}
@Test
- void aMissingFallbackFailsClosedToTheMainWorld() {
- Predicate noKidland = w -> !w.equals("kidland") && EXISTS.test(w);
- HomeWorlds.Move m = configured().decide(REACH, player("Kit", "grownups", circle("kids")), "grownups", noKidland, "main");
- assertEquals("main", m.world());
- assertTrue(m.degraded());
- assertEquals("kidland", m.wanted());
- // Already in the main world, there is nowhere further to go.
- assertNull(configured().decide(REACH, player("Kit", "main", circle("kids")), "main", noKidland, "main"));
- // A missing station does the same for someone with no circle.
- Predicate noStation = w -> !w.equals("station") && EXISTS.test(w);
- assertTrue(configured().decide(REACH, player("New", "grownups"), "grownups", noStation, "main").degraded());
+ void withNoLobbySetEveryoneOutsideTheirWorldsIsDisconnected() {
+ for (String none : new String[]{"", null}) {
+ assertDisconnect(decide(withLobby(none), player("Kit", "grownups", circle("kids"))), UNSET);
+ assertDisconnect(decide(withLobby(none), player("New", "kidland")), UNSET);
+ }
+ }
+
+ @Test
+ void aLobbyTheirGroupMayNotBeInDisconnects() {
+ assertDisconnect(decide(withLobby("grownups"), player("Kit", "main", circle("kids"))), closed("grownups"));
+ // Open to kids, and not on the no-circle list.
+ assertDisconnect(decide(withLobby("kidland"), player("New", "main")), closed("kidland"));
+ }
+
+ @Test
+ void aLobbyThatIsNotLoadedDisconnectsAndNoOtherAllowedWorldStandsIn() {
+ assertDisconnect(without(configured(), player("Kit", "grownups", circle("kids")), "station"), unloaded("station"));
+ assertDisconnect(without(configured(), player("New", "grownups"), "station"), unloaded("station"));
+ assertDisconnect(configured().decide(REACH, player("Kit", "main", circle("kids")), "main", w -> false),
+ unloaded("station"));
+ }
+
+ @Test
+ void someoneAlreadyInAnAllowedWorldStaysWhateverTheLobbyIsDoing() {
+ assertNull(without(configured(), player("Kit", "kidland_nether", circle("kids")), "station"));
+ assertNull(decide(withLobby(""), player("Kit", "kidland", circle("kids"))));
+ assertNull(decide(withLobby(""), player("New", "station")));
+ }
+
+ @Test
+ void theNoCircleListMayHoldSeveralWorlds() {
+ HomeWorlds two = new HomeWorlds(Map.of(), new HomeWorlds.Entry(Set.of("cave", "station"), null), "station");
+ assertNull(decide(two, player("New", "cave")));
+ assertEquals("station", decide(two, player("New", "main")).world());
}
@Test
- void aKidWhoHoldsOnlyKidsCirclesAcrossTwoEntriesMayBeInEitherSet() {
+ void theMainWorldIsUsedOnlyWhenItIsTheNamedAllowedLobby() {
+ assertDisconnect(decide(withLobby(""), player("Kit", "grownups", circle("kids"))), UNSET);
+ assertDisconnect(decide(withLobby("main"), player("Kit", "grownups", circle("kids"))), closed("main"));
Map by = new LinkedHashMap<>();
- by.put("kids", new HomeWorlds.Entry(Set.of("kidland"), "kidland", null));
- by.put("adults", new HomeWorlds.Entry(Set.of("grownups"), "grownups", null));
- HomeWorlds both = new HomeWorlds(by, null);
+ by.put("kids", new HomeWorlds.Entry(Set.of("kidland", "main"), null));
+ HomeWorlds mainIsLobby = new HomeWorlds(by, null, "main");
+ assertEquals("main", decide(mainIsLobby, player("Kit", "grownups", circle("kids"))).world());
+ }
+
+ @Test
+ void aKidWhoHoldsOnlyKidsCirclesAcrossTwoEntriesMayBeInEitherSetAndInTheLobbyEitherOpens() {
+ Map by = new LinkedHashMap<>();
+ by.put("kids", new HomeWorlds.Entry(Set.of("kidland"), "First line"));
+ by.put("adults", new HomeWorlds.Entry(Set.of("grownups", "station"), "Second line"));
+ HomeWorlds both = new HomeWorlds(by, null, "station");
assertNull(decide(both, player("Vee", "grownups", circle("kids"), circle("adults"))));
- assertEquals("kidland", decide(both, player("Vee", "cave", circle("kids"), circle("adults"))).world());
+ HomeWorlds.Move m = decide(both, player("Vee", "cave", circle("adults"), circle("kids")));
+ assertEquals("station", m.world());
+ assertEquals("First line", m.message(), "the entry listed first in the config");
+ assertDisconnect(decide(both, player("Kit", "cave", circle("kids"))), closed("station"));
+ }
+
+ @Test
+ void aMoveTurnedIntoADisconnectSaysTheLobbyIsNotLoaded() {
+ HomeWorlds.Move move = decide(configured(), player("Kit", "grownups", circle("kids")));
+ assertDisconnect(move.asDisconnect(), unloaded("station"));
+ HomeWorlds.Move none = decide(withLobby(""), player("Kit", "grownups", circle("kids")));
+ assertSame(none, none.asDisconnect());
}
@Test
void theRespawnPointIsCheckedNotTheCurrentWorld() {
Subject kid = player("Kit", "kidland", circle("kids"));
- assertEquals("kidland", configured().decide(REACH, kid, "grownups", EXISTS, "main").world());
+ assertEquals("station", configured().decide(REACH, kid, "grownups", EXISTS).world());
}
@Test
@@ -109,7 +184,7 @@ void offMovesNobody() {
@Test
void withNoCirclesInUseNobodyIsMoved() {
Reach none = new Reach(List.of(), Set.of(), Map.of(), List.of());
- assertNull(configured().decide(none, player("New", "grownups"), "grownups", EXISTS, "main"));
+ assertNull(configured().decide(none, player("New", "grownups"), "grownups", EXISTS));
}
@Test
@@ -124,11 +199,61 @@ void aFirstJoinWaitsForPlacementAndAReturningPlayerDoesNot() {
}
@Test
- void aKidPlacedInAnAllowedLobbyStaysAndOneInADisallowedWorldIsMoved() {
- Map by = new LinkedHashMap<>();
- by.put("kids", new HomeWorlds.Entry(Set.of("kidland", "cave"), "kidland", null));
- HomeWorlds lobbyAllowed = new HomeWorlds(by, null);
- assertNull(decide(lobbyAllowed, player("Kit", "cave", circle("kids"))));
- assertEquals("kidland", decide(lobbyAllowed, player("Kit", "grownups", circle("kids"))).world());
+ void theLobbyCountsAsANamedWorldOnlyWhileTheRulesAreOn() {
+ HomeWorlds elsewhere = new HomeWorlds(Map.of(), new HomeWorlds.Entry(Set.of("cave"), null), "station");
+ assertEquals(Set.of("cave", "station"), elsewhere.namedWorlds());
+ assertTrue(new HomeWorlds(Map.of(), null, "station").namedWorlds().isEmpty());
+ assertTrue(new HomeWorlds(Map.of(), null, "station").problems(w -> false).isEmpty());
+ }
+
+ /** Kids have an entry; the config says nothing about players in no circle. */
+ private static HomeWorlds noEntry(String lobby) {
+ return new HomeWorlds(Map.of("kids", new HomeWorlds.Entry(Set.of("kidland", "station"), "Hello kid")), null, lobby);
+ }
+
+ @Test
+ void withNoNoCircleEntryAPlayerInNoCircleMayOnlyBeInTheLobby() {
+ for (String w : List.of("grownups", "kidland", "main", "cave")) {
+ HomeWorlds.Move m = decide(noEntry("station"), player("New", w));
+ assertEquals(HomeWorlds.Kind.NO_CIRCLE, m == null ? null : m.kind(), w);
+ assertEquals("station", m.world(), w);
+ assertNull(m.message(), "the default waiting line");
+ }
+ assertNull(decide(noEntry("station"), player("New", "station")));
+ assertEquals(Set.of("station"), noEntry("station").noCircleWorlds());
+ }
+
+ @Test
+ void withNoNoCircleEntryAndNoUsableLobbyAPlayerInNoCircleIsDisconnectedEverywhere() {
+ for (String w : List.of("station", "kidland", "main")) {
+ HomeWorlds.Move m = decide(noEntry(""), player("New", w));
+ assertEquals(HomeWorlds.Kind.DISCONNECT, m == null ? null : m.kind(), w);
+ assertEquals(UNSET, m.why(), w);
+ }
+ HomeWorlds.Move gone = without(noEntry("station"), player("New", "main"), "station");
+ assertEquals(unloaded("station"), gone == null ? null : gone.why());
+ assertEquals(Set.of(), noEntry("").noCircleWorlds());
+ }
+
+ @Test
+ void withNoNoCircleEntryTheRulesStillCoverAPlayerInNoCircle() {
+ for (String lobby : List.of("station", "")) {
+ assertTrue(noEntry(lobby).governs(REACH, player("New", "main")), lobby);
+ }
+ // A circle with no entry is covered the same way (owner, 2026-11-30).
+ assertTrue(noEntry("station").governs(REACH, player("Ada", "main", circle("adults"))));
+ assertEquals(HomeWorlds.Kind.NO_CIRCLE, decide(noEntry("station"), player("Ada", "main", circle("adults"))).kind());
+ assertEquals(Set.of(), HomeWorlds.OFF.noCircleWorlds());
+ assertEquals(Set.of(), new HomeWorlds(Map.of(), null, "station").noCircleWorlds(), "off stays off");
+ }
+
+ @Test
+ void aMissingWorldSaysWhatHappensMeanwhile() {
+ assertTrue(configured().problems(EXISTS).isEmpty());
+ assertEquals(List.of("home-worlds: the world \"kidland\" doesn't exist. Check its spelling, or load it."),
+ configured().problems(w -> !w.equals("kidland")));
+ assertEquals(List.of("home-worlds: the lobby world \"station\" doesn't exist, so anyone outside their home worlds "
+ + "is disconnected until it does."),
+ configured().problems(w -> !w.equals("station")));
}
}
diff --git a/src/test/java/com/extantape/posse/rules/OldNodesTest.java b/src/test/java/com/extantape/posse/rules/OldNodesTest.java
index 9c14eec..a2b3177 100644
--- a/src/test/java/com/extantape/posse/rules/OldNodesTest.java
+++ b/src/test/java/com/extantape/posse/rules/OldNodesTest.java
@@ -39,10 +39,10 @@ void anOldBypassNodeBypassesNothing() {
@Test
void anOldCircleNodeLeavesAKidInNoCircleForHomeWorlds() {
Map by = new java.util.LinkedHashMap<>();
- by.put("kids", new HomeWorlds.Entry(Set.of("kidland"), "kidland", null));
- HomeWorlds home = new HomeWorlds(by, new HomeWorlds.Entry(Set.of(), "station", null));
+ by.put("kids", new HomeWorlds.Entry(Set.of("kidland"), null));
+ HomeWorlds home = new HomeWorlds(by, new HomeWorlds.Entry(Set.of("station"), null), "station");
Subject old = player("Kit", "grownups", "mayor.circle.kids");
- assertEquals("station", home.decide(reach, old, "grownups", w -> true, "main").world());
- assertNull(home.decide(reach, player("Kit", "kidland", circle("kids")), "kidland", w -> true, "main"));
+ assertEquals("station", home.decide(reach, old, "grownups", w -> true).world());
+ assertNull(home.decide(reach, player("Kit", "kidland", circle("kids")), "kidland", w -> true));
}
}
diff --git a/src/test/java/com/extantape/posse/rules/PendingTest.java b/src/test/java/com/extantape/posse/rules/PendingTest.java
index 086771f..b494d0e 100644
--- a/src/test/java/com/extantape/posse/rules/PendingTest.java
+++ b/src/test/java/com/extantape/posse/rules/PendingTest.java
@@ -61,13 +61,15 @@ void noJoinLineGoesToAnyoneWhileThePlayerIsPendingAndItGoesOnceTheyAreNot() {
@Test
void homeWorldsOnlyWaitsForPlayersItCanMove() {
Map by = new LinkedHashMap<>();
- by.put("kids", new HomeWorlds.Entry(Set.of("kidland"), "kidland", null));
+ by.put("kids", new HomeWorlds.Entry(Set.of("kidland"), null));
+ assertTrue(new HomeWorlds(by, null).governs(reach, player("Ada", "main", circle("adults"))), "a circle with no entry");
+ by.put("adults", HomeWorlds.Entry.noLimits());
HomeWorlds home = new HomeWorlds(by, null);
assertTrue(home.governs(reach, player("Kit", "main", circle("kids"))));
assertFalse(home.governs(reach, player("Ada", "main", circle("adults"))));
assertFalse(home.governs(reach, player("Vee", "main", circle("kids"), circle("adults"))));
- assertFalse(home.governs(reach, player("New", "main")));
- HomeWorlds withStation = new HomeWorlds(by, new HomeWorlds.Entry(Set.of(), "station", null));
+ assertTrue(home.governs(reach, player("New", "main")), "no no-circle entry still means lobby only");
+ HomeWorlds withStation = new HomeWorlds(by, new HomeWorlds.Entry(Set.of("station"), null));
assertTrue(withStation.governs(reach, player("New", "main")));
assertFalse(HomeWorlds.OFF.governs(reach, player("Kit", "main", circle("kids"))));
}
diff --git a/src/test/java/com/extantape/posse/rules/PresenceTest.java b/src/test/java/com/extantape/posse/rules/PresenceTest.java
index 59ce44c..82f140f 100644
--- a/src/test/java/com/extantape/posse/rules/PresenceTest.java
+++ b/src/test/java/com/extantape/posse/rules/PresenceTest.java
@@ -68,9 +68,17 @@ void pausedRulesShowNobodyButYourself() {
@Test
void aPlayerOutOfSightIsKeptFromTheGameUnlessTheyStandInTheSameWorld() {
// K832: a game offers every player it knows on Tab, so only someone the viewer may see, or can see walk by, is known.
- assertTrue(Presence.mayKnowOf(true, false));
- assertTrue(Presence.mayKnowOf(true, true));
- assertTrue(Presence.mayKnowOf(false, true));
- assertFalse(Presence.mayKnowOf(false, false));
+ assertTrue(Presence.mayKnowOf(true, false, false));
+ assertTrue(Presence.mayKnowOf(true, true, false));
+ assertTrue(Presence.mayKnowOf(false, true, false));
+ assertFalse(Presence.mayKnowOf(false, false, false));
+ }
+
+ @Test
+ void aPendingPlayerIsNotSeenEvenStandingInTheSameWorld() {
+ // Body and nametag too, whichever side is waiting for their move.
+ assertFalse(Presence.mayKnowOf(false, true, true));
+ assertFalse(Presence.mayKnowOf(false, false, true));
+ assertFalse(Presence.mayKnowOf(true, true, true));
}
}
diff --git a/src/test/java/com/extantape/posse/rules/ReachTest.java b/src/test/java/com/extantape/posse/rules/ReachTest.java
index fc5bb99..af14726 100644
--- a/src/test/java/com/extantape/posse/rules/ReachTest.java
+++ b/src/test/java/com/extantape/posse/rules/ReachTest.java
@@ -16,6 +16,48 @@ class ReachTest {
private final Reach reach = new Reach(List.of("red", "blue"), Set.of("hall"),
Map.of("meadow", "home", "meadow_flat", "home"), List.of("_nether", "_the_end"));
+ @Test
+ void circlesOnlyNeedsASharedCircleInEveryWorld() {
+ Subject red = player("a", "forest", circle("red"));
+ Subject red2 = player("b", "meadow", circle("red"));
+ Subject blue = player("c", "forest", circle("blue"));
+ Subject none = player("d", "forest");
+ assertTrue(reach.inSharedCircle(red, red2));
+ assertTrue(reach.inSharedCircle(red2, red));
+ assertTrue(reach.mayReach(red, blue), "chat still counts the same world");
+ assertFalse(reach.inSharedCircle(red, blue));
+ assertFalse(reach.inSharedCircle(blue, red));
+ assertTrue(reach.mayReach(red, none));
+ assertFalse(reach.inSharedCircle(red, none));
+ assertFalse(reach.inSharedCircle(none, player("e", "forest")));
+ assertFalse(reach.inSharedCircle(player("f", "hall"), player("g", "hall")));
+ }
+
+ @Test
+ void circlesOnlyCountsEitherSidesBypassAndYourself() {
+ Subject mod = player("mod", "meadow", Reach.BYPASS);
+ Subject blue = player("c", "forest", circle("blue"));
+ assertTrue(reach.inSharedCircle(mod, blue));
+ assertTrue(reach.inSharedCircle(blue, mod));
+ assertTrue(reach.inSharedCircle(blue, blue));
+ }
+
+ @Test
+ void circlesOnlyAllowsEveryoneWithNoCirclesConfigured() {
+ Reach off = new Reach(List.of(), Set.of("hall"), Map.of(), List.of("_nether"));
+ assertTrue(off.inSharedCircle(player("a", "one"), player("b", "two")));
+ }
+
+ @Test
+ void circlesOnlyShowsNothingToOrAboutSomeoneStillBeingPlaced() {
+ Subject waiting = Players.pending("w", "forest", circle("red"), Reach.BYPASS);
+ Subject red = player("a", "forest", circle("red"));
+ assertFalse(reach.inSharedCircle(waiting, red));
+ assertFalse(reach.inSharedCircle(red, waiting));
+ assertFalse(reach.inSharedCircle(player("mod", "forest", Reach.BYPASS), waiting));
+ assertTrue(reach.inSharedCircle(waiting, waiting));
+ }
+
@Test
void noCirclesMeansVanilla() {
Reach off = new Reach(List.of(), Set.of("hall"), Map.of(), List.of("_nether"));
diff --git a/test/live/README.md b/test/live/README.md
index c964444..f4b85a3 100644
--- a/test/live/README.md
+++ b/test/live/README.md
@@ -41,8 +41,8 @@ It takes about 4 minutes. The summary lists failures and skipped checks. The ful
| Reach matrix | Eight players in two circles, with no circle, and with bypass, across two world groups (one by suffix, one listed), their Nether and End, and a circle-only world. Public chat from each, and 336 private messages over six commands, match an independent model of the rule. |
| Join and leave lines | `presence-messages.js`, run with `POSSE_SUITE=presence-messages.js test/live/run.sh ` (about 1 minute): six made-up players join and leave in turn, first with `presence: everyone` as a control, then `reach`. Each line is read from mineflayer's text events and from the raw chat packets, and both must match. The main suite's presence part also covers it. |
| Book authors | `book-authors.js`, run with `POSSE_SUITE=book-authors.js POSSE_PORT=25733 test/live/run.sh `: a kid's signed book is dropped and picked up by an adult (sees Unknown), a same-circle kid, the visitor in both circles and a player in no circle; a quest-journal-style book with the name in its title; a chest opened by an adult and by a kid; the true author coming back when a circle is granted; the settings. A bot can't read a tooltip, so each check reads the server's own copy of the book, which is what the client is sent. Item frames and lecterns aren't driven. |
-| Home worlds | `home-worlds.js`, run with `POSSE_SUITE=home-worlds.js test/live/run.sh ` (about 2 minutes): five made-up players leave in different worlds, then rejoin, die and respawn, and are teleported around. Kids end up only in kids' worlds, the visitor and an adult are left alone, a player with no circle waits in the station, a missing fallback lands in the main world, and with the section removed nothing moves. Run it with a port in your own range, such as `POSSE_PORT=25733`. |
-| Reach leaks (K832) | `reach-leaks.js`, run with `POSSE_SUITE=reach-leaks.js test/live/run.sh ` (about 3 minutes): seven made-up players in a kids' circle, an adults' circle, both, bypass, and no circle. With no circles first as a control, then with circles and `presence: reach`: who is sent a death line and an advancement line, which names Tab offers after seven commands (vanilla, namespaced and a test plugin's own completer), which players each bot's game was told about, `/list` in three forms, the server list sample, a returning kid moved on join, a kid disconnected while joining, and the dead player's own death screen. Each part checks a refused pair, an allowed pair and bypass, and then all of it again with a config Posse can't read, so the rules are paused. `POSSE_JAR=` runs it against an older release; on 0.11.1 the refused checks fail. A bot has no Tab menu of its own, so the names a real game would offer by itself are read from the players the bot's game was told about. |
+| Home worlds | `home-worlds.js`, run with `POSSE_SUITE=home-worlds.js test/live/run.sh ` (about 2 minutes): made-up players leave in different worlds, then rejoin, die and respawn, and are teleported around. A teleport into a world they may not be in is refused, and a reload that tightens the rules moves or disconnects people already there, with several online at once. It checks each circle's setting: a circle with no entry or an unusable one (both keys, neither, `unlimited` not `true`, a bare name) adds nothing and is named in the log and in `/posse status`, a new circle doesn't free a kid, an unlimited circle lifts every limit even beside a limited one, and a section with only an unusable entry stays on. It also checks that a pending or held player has no body, name tag or Tab entry and can't run commands; that a missing `no-circle` entry means lobby only; that only an account allowed by its circles gets into a children's world; that a refusal another plugin takes back or redirects is refused again (`/mt uncancel`, `/mt redirect`); the check after a world change that got past the refusal (`/mt force`, with `/mt window` holding the server so the pending moment can be looked at); and what removing a LuckPerms group does. For portals, a made-up kid rides a boat, a minecart and a horse into a real nether portal and throws a pearl through one, using `/summon` and `/ride`. An adult goes first each time, and the kid's check is skipped if the adult doesn't arrive. The bots send no movement and the helper cancels player damage, so walking and damage while pending are covered by unit tests only. Kids end up only in kids' worlds, the visitor and an adult are left alone, a player with no circle waits in the station or goes to the lobby, the lobby is the only place anyone is sent and only when it's named, loaded and open to the player's group, an old `fallback` line loads with a warning and sends nobody anywhere, a disconnect that `/mt blockkick` cancels holds the player until it goes through, and with the section removed nothing moves. A lobby that's missing, or really unloaded with `/mt unload`, disconnects on reload, rejoin and respawn, with no join or leave line, and the player is never saved in another world. Last, it restarts with a broken config: players without `posse.bypass` are refused (operators too), a player with it gets in, a login that `/mt allowlogin` lets through is disconnected at join with no join or leave line, and after the fix and a reload others can join. A held login whose kick is cancelled stays held. Last of all it swaps in the broken BlueMapMini stand-in (`brokenminimap/`), which makes Posse's startup fail, and checks that joining stays paused until a restart with the good jar back. Run it with a port in your own range, such as `POSSE_PORT=25733`. |
+| Reach leaks (K832) | `reach-leaks.js`, run with `POSSE_SUITE=reach-leaks.js test/live/run.sh ` (about 3 minutes): seven made-up players in a kids' circle, an adults' circle, both, bypass, and no circle. With no circles first as a control, then with circles and `presence: reach`: who is sent a death line and an advancement line, which names Tab offers after seven commands (vanilla, namespaced and a test plugin's own completer), which players each bot's game was told about, `/list` in three forms, the server list sample, a returning kid moved on join, a kid disconnected while joining, and the dead player's own death screen. Each part checks a refused pair, an allowed pair and bypass, and then all of it again with a config Posse can't read, so the rules are paused. Only `posse.bypass` can join a paused server, so the suite first checks that a bot without it is refused, then lends the bypass to the other bots while they join and takes it away before checking them. `POSSE_JAR=` runs it against an older release; on 0.11.1 the refused checks fail. A bot has no Tab menu of its own, so the names a real game would offer by itself are read from the players the bot's game was told about. |
| `/circles` | Lists your circles and exactly who can hear you, a count without `posse.circles.names`, and an explanation in a circle-only world. |
| 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. |
@@ -54,9 +54,9 @@ It takes about 4 minutes. The summary lists failures and skipped checks. The ful
| Share (mocked) | Recipients filtered exactly as chat, and cancelled for a no-circle sender in a circle-only world. |
| Graves (D231) | With a LanternGraves jar (`POSSE_LG_JAR`), real graves from planned deaths: each bot sees the owner's name or "Grave" exactly as an independent model of `mayKnow` says, with the owner in the same group, moved away, sharing a circle, offline, and in a circle-only world. Skipped without the jar. |
| LuckPerms | A circle granted or removed takes effect with no relog. |
-| Config | A broken reload keeps the old rules; a broken config at startup pauses chat and private messages until it's fixed and reloaded. |
+| Config | A broken reload keeps the old rules; a broken config at startup refuses joins without `posse.bypass` and pauses chat and private messages, even for players with it, until it's fixed and reloaded. |
| Load | 20 more bots, 300 lines in about 15 seconds: all delivered within their circle, TPS, chat latency, no kicks. |
## The test-only plugins
-`helper/` makes worlds, moves players, gives items and reports TPS, with one console command, `/mt`, and has one player command, `/mtwho`, whose Tab offers every online player, as a plugin that knows nothing of Posse would. It also stops test players taking damage, since a bot that spawns inside a block in a made-up Nether would otherwise die and respawn in the wrong world. `fakeminimap/` is the BlueMapMini stand-in. Both are built by `./gradlew build` and never shipped. Never install either on a real server.
+`helper/` makes worlds, moves players, gives items and reports TPS, with one console command, `/mt`, and has one player command, `/mtwho`, whose Tab offers every online player, as a plugin that knows nothing of Posse would. `/mt blockkick` cancels a player's kicks while it's on, and `/mt allowlogin` allows one refused login again, standing in for another plugin doing either. It also stops test players taking damage, since a bot that spawns inside a block in a made-up Nether would otherwise die and respawn in the wrong world. `fakeminimap/` is the BlueMapMini stand-in. Both are built by `./gradlew build` and never shipped. Never install either on a real server.
diff --git a/test/live/brokenminimap/build.gradle.kts b/test/live/brokenminimap/build.gradle.kts
new file mode 100644
index 0000000..2c62912
--- /dev/null
+++ b/test/live/brokenminimap/build.gradle.kts
@@ -0,0 +1,21 @@
+// Test only, for the live tests. Never shipped.
+plugins {
+ java
+}
+
+java {
+ toolchain.languageVersion.set(JavaLanguageVersion.of(25))
+}
+
+repositories {
+ mavenCentral()
+ maven("https://repo.papermc.io/repository/maven-public/")
+}
+
+dependencies {
+ compileOnly(rootProject.extra["paperApi"] as String)
+}
+
+tasks.jar {
+ archiveBaseName.set("LiveTestBrokenMinimap")
+}
diff --git a/test/live/brokenminimap/src/main/java/com/extantape/bluemapmini/api/CoordinateShareEvent.java b/test/live/brokenminimap/src/main/java/com/extantape/bluemapmini/api/CoordinateShareEvent.java
new file mode 100644
index 0000000..ef74b18
--- /dev/null
+++ b/test/live/brokenminimap/src/main/java/com/extantape/bluemapmini/api/CoordinateShareEvent.java
@@ -0,0 +1,17 @@
+package com.extantape.bluemapmini.api;
+
+import org.bukkit.event.Event;
+import org.bukkit.event.HandlerList;
+
+/**
+ * Test only, and broken on purpose: it has no static getHandlerList(), so the server refuses to register a listener
+ * for it with an error that isn't a LinkageError. That is how home-worlds.js makes Posse's startup fail from outside.
+ */
+public final class CoordinateShareEvent extends Event {
+ private static final HandlerList HANDLERS = new HandlerList();
+
+ @Override
+ public HandlerList getHandlers() {
+ return HANDLERS;
+ }
+}
diff --git a/test/live/brokenminimap/src/main/java/com/extantape/posse/livetest/brokenminimap/BrokenMinimap.java b/test/live/brokenminimap/src/main/java/com/extantape/posse/livetest/brokenminimap/BrokenMinimap.java
new file mode 100644
index 0000000..9f7d480
--- /dev/null
+++ b/test/live/brokenminimap/src/main/java/com/extantape/posse/livetest/brokenminimap/BrokenMinimap.java
@@ -0,0 +1,7 @@
+package com.extantape.posse.livetest.brokenminimap;
+
+import org.bukkit.plugin.java.JavaPlugin;
+
+/** Test only. A BlueMapMini stand-in whose share event can't be listened to. It does nothing else. */
+public final class BrokenMinimap extends JavaPlugin {
+}
diff --git a/test/live/brokenminimap/src/main/resources/paper-plugin.yml b/test/live/brokenminimap/src/main/resources/paper-plugin.yml
new file mode 100644
index 0000000..69cef7d
--- /dev/null
+++ b/test/live/brokenminimap/src/main/resources/paper-plugin.yml
@@ -0,0 +1,5 @@
+# Test only. A broken stand-in for BlueMapMini, used to make Posse's startup fail. Never install on a real server.
+name: BlueMapMini
+version: '0.0.0-broken'
+main: com.extantape.posse.livetest.brokenminimap.BrokenMinimap
+api-version: '26.1'
diff --git a/test/live/helper/src/main/java/com/extantape/posse/livetest/LiveTestHelper.java b/test/live/helper/src/main/java/com/extantape/posse/livetest/LiveTestHelper.java
index 34d80f9..32ce755 100644
--- a/test/live/helper/src/main/java/com/extantape/posse/livetest/LiveTestHelper.java
+++ b/test/live/helper/src/main/java/com/extantape/posse/livetest/LiveTestHelper.java
@@ -25,9 +25,21 @@
* mt stall after that player next joins, makes each of the next 30 ticks take longer, so a
* 20-tick delay lasts about 20 x in real time and a test can look inside it (D297)
* mt blocktp cancels every later teleport of that player, so a move Posse tries fails (D297)
+ * mt blockkick while on is true, cancels every kick of that player, as another plugin might
+ * mt allowlogin allows that player's next login again after other plugins refused it
+ * mt uncancel from now on takes back any refusal of that player's teleports, at MONITOR
+ * mt redirect from now on points that player's teleports at the world's spawn, at MONITOR
+ * mt force the player's next teleport goes where it was first asked to go, whatever anyone refused:
+ * a listener registered at that moment, so it runs after every plugin's own last look
+ * mt reset ends uncancel and redirect for that player
+ * mt window at that player's next world change, prints who can see whom ("HRT window start ..."),
+ * then keeps the server thread busy for and prints "HRT window end". Chat events that
+ * arrive meanwhile print "HRT chat cancelled="
+ * mt sees prints "HRT sees "
* mt where prints "HRT where "
* mt tps prints "HRT tps <1m> mspt "
* mt worlds prints "HRT worlds "
+ * mt unload unloads an empty world, as a failed or removed world would be; prints "HRT unload "
* mt give - puts one item in the player's main hand
* mt book puts a signed book in the player's first slot (D291)
* mt drop drops the player's first-slot item 20 blocks east, where nobody stands, and remembers the spot
@@ -78,6 +90,23 @@ public void onTeleport(org.bukkit.event.player.PlayerTeleportEvent event) {
if (blocked.contains(event.getPlayer().getName())) event.setCancelled(true);
}
+ /** Players whose kicks are cancelled (mt blockkick). */
+ private final java.util.Set unkickable = java.util.concurrent.ConcurrentHashMap.newKeySet();
+
+ @EventHandler(priority = org.bukkit.event.EventPriority.HIGHEST)
+ public void onKick(org.bukkit.event.player.PlayerKickEvent event) {
+ if (unkickable.contains(event.getPlayer().getName())) event.setCancelled(true);
+ }
+
+ /** Players whose next refused login is allowed again (mt allowlogin). */
+ private final java.util.Set allowedLogins = java.util.concurrent.ConcurrentHashMap.newKeySet();
+
+ @SuppressWarnings("deprecation")
+ @EventHandler(priority = org.bukkit.event.EventPriority.MONITOR)
+ public void onLogin(org.bukkit.event.player.PlayerLoginEvent event) {
+ if (allowedLogins.remove(event.getPlayer().getName())) event.allow();
+ }
+
/** Players whose next join is followed by a main-thread stall: name to milliseconds (mt stall). */
private final java.util.Map stalls = new java.util.concurrent.ConcurrentHashMap<>();
@@ -93,6 +122,68 @@ public void onStallJoin(org.bukkit.event.player.PlayerJoinEvent event) {
}, 1L, 1L);
}
+ // Stand-ins for another plugin that changes a teleport after Posse has checked it.
+ private final java.util.Set uncancel = java.util.concurrent.ConcurrentHashMap.newKeySet();
+ private final java.util.Map redirect = new java.util.concurrent.ConcurrentHashMap<>();
+
+ @EventHandler(priority = org.bukkit.event.EventPriority.MONITOR)
+ public void onTeleportChanged(org.bukkit.event.player.PlayerTeleportEvent event) {
+ String name = event.getPlayer().getName();
+ if (uncancel.contains(name)) event.setCancelled(false);
+ String world = redirect.get(name);
+ World w = world == null ? null : Bukkit.getWorld(world);
+ if (w != null) event.setTo(w.getSpawnLocation());
+ }
+
+ /** One forced teleport. Its listeners are registered now, so the second runs after Posse's own at MONITOR. */
+ private void force(String name) {
+ Listener once = new Listener() {};
+ org.bukkit.Location[] asked = new org.bukkit.Location[1];
+ Bukkit.getPluginManager().registerEvent(org.bukkit.event.player.PlayerTeleportEvent.class, once, org.bukkit.event.EventPriority.LOWEST, (l, e) -> {
+ org.bukkit.event.player.PlayerTeleportEvent t = (org.bukkit.event.player.PlayerTeleportEvent) e;
+ if (asked[0] == null && t.getPlayer().getName().equals(name)) asked[0] = t.getTo().clone();
+ }, this, false);
+ Bukkit.getPluginManager().registerEvent(org.bukkit.event.player.PlayerTeleportEvent.class, once, org.bukkit.event.EventPriority.MONITOR, (l, e) -> {
+ org.bukkit.event.player.PlayerTeleportEvent t = (org.bukkit.event.player.PlayerTeleportEvent) e;
+ if (asked[0] == null || !t.getPlayer().getName().equals(name)) return;
+ t.setCancelled(false);
+ t.setTo(asked[0]);
+ org.bukkit.event.HandlerList.unregisterAll(once);
+ getLogger().info("HRT forced " + name + " " + asked[0].getWorld().getName());
+ }, this, false);
+ }
+
+ private final java.util.Map windows = new java.util.concurrent.ConcurrentHashMap<>();
+ private volatile boolean windowOpen;
+
+ @EventHandler(priority = org.bukkit.event.EventPriority.MONITOR)
+ public void onChangedWorld(org.bukkit.event.player.PlayerChangedWorldEvent event) {
+ Player p = event.getPlayer();
+ getLogger().info("HRT changed " + p.getName() + " " + event.getFrom().getName() + " " + p.getWorld().getName());
+ Long ms = windows.remove(p.getName());
+ if (ms == null) return;
+ java.util.List seenBy = new java.util.ArrayList<>(), sees = new java.util.ArrayList<>();
+ for (Player other : Bukkit.getOnlinePlayers()) {
+ if (other.equals(p)) continue;
+ if (other.canSee(p)) seenBy.add(other.getName());
+ if (p.canSee(other)) sees.add(other.getName());
+ }
+ windowOpen = true;
+ getLogger().info("HRT window start " + p.getName() + " " + p.getWorld().getName() + " seenBy=" + String.join(",", seenBy) + " sees=" + String.join(",", sees) + " .");
+ try {
+ Thread.sleep(ms);
+ } catch (InterruptedException ignored) {
+ Thread.currentThread().interrupt();
+ }
+ windowOpen = false;
+ getLogger().info("HRT window end " + p.getName());
+ }
+
+ @EventHandler(priority = org.bukkit.event.EventPriority.MONITOR)
+ public void onChatSeen(io.papermc.paper.event.player.AsyncChatEvent event) {
+ if (windowOpen) getLogger().info("HRT chat " + event.getPlayer().getName() + " cancelled=" + event.isCancelled());
+ }
+
@Override
public void onEnable() {
getServer().getPluginManager().registerEvents(this, this);
@@ -162,12 +253,68 @@ public void onEnable() {
getLogger().info("HRT blocktp set");
return 1;
})))
+ .then(Commands.literal("blockkick").then(Commands.argument("player", StringArgumentType.word())
+ .then(Commands.argument("on", com.mojang.brigadier.arguments.BoolArgumentType.bool()).executes(ctx -> {
+ String name = StringArgumentType.getString(ctx, "player");
+ if (com.mojang.brigadier.arguments.BoolArgumentType.getBool(ctx, "on")) unkickable.add(name);
+ else unkickable.remove(name);
+ getLogger().info("HRT blockkick set");
+ return 1;
+ }))))
+ .then(Commands.literal("allowlogin").then(Commands.argument("player", StringArgumentType.word()).executes(ctx -> {
+ allowedLogins.add(StringArgumentType.getString(ctx, "player"));
+ getLogger().info("HRT allowlogin set");
+ return 1;
+ })))
+ .then(Commands.literal("uncancel").then(Commands.argument("player", StringArgumentType.word()).executes(ctx -> {
+ uncancel.add(StringArgumentType.getString(ctx, "player"));
+ getLogger().info("HRT uncancel set");
+ return 1;
+ })))
+ .then(Commands.literal("redirect").then(Commands.argument("player", StringArgumentType.word())
+ .then(Commands.argument("world", StringArgumentType.word()).executes(ctx -> {
+ redirect.put(StringArgumentType.getString(ctx, "player"), StringArgumentType.getString(ctx, "world"));
+ getLogger().info("HRT redirect set");
+ return 1;
+ }))))
+ .then(Commands.literal("force").then(Commands.argument("player", StringArgumentType.word()).executes(ctx -> {
+ force(StringArgumentType.getString(ctx, "player"));
+ getLogger().info("HRT force set");
+ return 1;
+ })))
+ .then(Commands.literal("reset").then(Commands.argument("player", StringArgumentType.word()).executes(ctx -> {
+ String name = StringArgumentType.getString(ctx, "player");
+ uncancel.remove(name);
+ redirect.remove(name);
+ getLogger().info("HRT reset set");
+ return 1;
+ })))
+ .then(Commands.literal("window").then(Commands.argument("player", StringArgumentType.word())
+ .then(Commands.argument("ms", com.mojang.brigadier.arguments.IntegerArgumentType.integer(0, 10000)).executes(ctx -> {
+ windows.put(StringArgumentType.getString(ctx, "player"), (long) com.mojang.brigadier.arguments.IntegerArgumentType.getInteger(ctx, "ms"));
+ getLogger().info("HRT window set");
+ return 1;
+ }))))
+ .then(Commands.literal("sees").then(Commands.argument("a", StringArgumentType.word())
+ .then(Commands.argument("b", StringArgumentType.word()).executes(ctx -> {
+ Player a = Bukkit.getPlayerExact(StringArgumentType.getString(ctx, "a"));
+ Player b = Bukkit.getPlayerExact(StringArgumentType.getString(ctx, "b"));
+ getLogger().info(a == null || b == null ? "HRT sees FAILED"
+ : "HRT sees " + a.getName() + " " + b.getName() + " " + a.canSee(b) + " " + b.canSee(a));
+ return 1;
+ }))))
.then(Commands.literal("where").then(Commands.argument("player", StringArgumentType.word()).executes(ctx -> {
String name = StringArgumentType.getString(ctx, "player");
Player p = Bukkit.getPlayerExact(name);
getLogger().info("HRT where " + name + " " + (p == null ? "OFFLINE" : p.getWorld().getName()));
return 1;
})))
+ .then(Commands.literal("unload").then(Commands.argument("name", StringArgumentType.word()).executes(ctx -> {
+ String name = StringArgumentType.getString(ctx, "name");
+ World world = Bukkit.getWorld(name);
+ getLogger().info("HRT unload " + name + " " + (world != null && Bukkit.unloadWorld(world, true)));
+ return 1;
+ })))
.then(Commands.literal("worlds").executes(ctx -> {
getLogger().info("HRT worlds " + String.join(",", Bukkit.getWorlds().stream().map(World::getName).toList()));
return 1;
diff --git a/test/live/home-worlds.js b/test/live/home-worlds.js
index 71d545e..9332e51 100644
--- a/test/live/home-worlds.js
+++ b/test/live/home-worlds.js
@@ -1,18 +1,28 @@
-// Home worlds (D290) on one throwaway server: a rejoin and a respawn, plus the world-change safety net and a missing
-// fallback. See README.md in this folder. Usage: node home-worlds.js , relative to the work folder.
-// All names are made up. Run it with POSSE_SUITE=home-worlds.js test/live/run.sh .
+// Home worlds (D290, D368) on one throwaway server: a rejoin and a respawn, refused teleports, a reload that applies to
+// people already online, one entry for each circle (limited, unlimited, missing or unusable), the lobby missing, unset,
+// closed or unloaded, an old fallback line, a cancelled disconnect,
+// what a pending player can see and do, a refusal another plugin takes back, the check after a world change, a LuckPerms
+// group being removed, riders and thrown pearls at a nether portal, joining while paused, and a startup that fails.
+// See README.md in this folder. Usage: node home-worlds.js , relative to the work folder. All names
+// are made up. Run it with POSSE_SUITE=home-worlds.js test/live/run.sh .
+// Bots here send no movement and the helper cancels all player damage, so walking and damage while pending are covered
+// by the unit tests only. Each portal check first sends an adult through; if the adult doesn't arrive, it is skipped.
const crypto = require('crypto');
-const { sleep, check, section, summary, Server, Bot } = require('./lib.js');
+const fs = require('fs'), path = require('path');
+const { sleep, check, skip, section, summary, Server, Bot } = require('./lib.js');
const [dir, jar, port] = process.argv.slice(2);
+const BROKEN_MAP = path.join(__dirname, 'brokenminimap/build/libs/LiveTestBrokenMinimap.jar');
const CONFIG = `circles: [kids, adults]
+lobby-world: lobby
home-worlds:
kids:
- worlds: [kidland, kidland_nether]
- fallback: kidland
- message: "HOMEKID Welcome back! You're in the kids' world."
+ worlds: [kidland, kidland_nether, lobby]
+ message: "HOMEKID You're in the lobby."
+ adults:
+ unlimited: true
no-circle:
- fallback: station
+ worlds: [station, lobby]
`;
// Where each made-up player last was, before the rules were on. K = kids' circle, A = adults', V = both, X = none.
const PEOPLE = {
@@ -39,6 +49,96 @@ async function reload() { return s.run('posse reload', /\[Posse\] (Reloaded|The
// The protocol sends listed as 1 or 0; an entry with no listed update yet counts as listed.
const listedTo = (viewer, other) => { const p = bots[viewer].bot.players[other]; return !!p && (p.listed === undefined || Boolean(p.listed)); };
const text = (n, re, from = 0) => bots[n].heard(re, from);
+// Only lines /circles itself sends. Quips that answer unheard chat also say "can hear you", so that phrase alone is too loose.
+const CIRCLES_REPLY = /Your circles:|You're not in any circles|Everyone on the server can hear you|Nobody else online can hear you right now|People online who can hear you/;
+/** Whether the viewer's client holds a body (and so a nametag) for the other player. */
+const bodyOf = (viewer, other) => !!(bots[viewer].bot.players[other] && bots[viewer].bot.players[other].entity);
+/** What the server says: " ". */
+const sees = async (a, b) => { const m = await s.run(`mt sees ${a} ${b}`, new RegExp(`HRT sees ${a} ${b} (true|false) (true|false)`), 5000); return m ? `${m[1]} ${m[2]}` : null; };
+const uuid = (n) => { const h = crypto.createHash('md5').update('OfflinePlayer:' + n).digest(); h[6] = (h[6] & 0x0f) | 0x30; h[8] = (h[8] & 0x3f) | 0x80; const x = h.toString('hex'); return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`; };
+
+/** Boats, minecarts, horses and thrown pearls at a nether portal, the adult first as the control. */
+async function portals() {
+ section('Nether portals: riders and thrown pearls (an adult goes first, to show the path works)');
+ const RULES = `circles: [kids, adults]
+lobby-world: lobby
+home-worlds:
+ kids:
+ worlds: [world, lobby]
+ adults:
+ unlimited: true
+presence: reach
+`;
+ const OFFRULES = 'circles: [kids, adults]\npresence: reach\n';
+ const set = async (config) => { s.writeConfig('config.yml', config); await reload(); };
+ const tpWait = async (n, w) => { await s.run(`mt tp ${n} ${w}`, new RegExp(`HRT tp ${n} ${w} (true|false)`), 10000); await sleep(1500); };
+ await set(OFFRULES);
+ for (const n of ['A1', 'K1']) if (!bots[n] || bots[n].ended) await join(n);
+ await tpWait('A1', 'world');
+ const at = await s.run('data get entity A1 Pos', /A1 has the following entity data: \[(-?[\d.]+)d, (-?[\d.]+)d, (-?[\d.]+)d\]/, 8000);
+ if (!at) return skip('nether portal checks', 'couldn\'t read a position to build at');
+ const [ox, oy, oz] = [Math.floor(+at[1]), Math.floor(+at[2]), Math.floor(+at[3])];
+ const here = 'execute in minecraft:overworld run';
+
+ /** Sends one player at a portal. Returns whether their world changed within the wait. */
+ const attempt = async (n, kind, x) => {
+ const z = oz + 6;
+ await s.run('kill @e[tag=pt]', null);
+ await s.run(`${here} fill ${x - 3} ${oy} ${z - 3} ${x + 3} ${oy + 4} ${z + 3} air`, null);
+ await tpWait(n, 'world');
+ await s.run(`${here} tp ${n} ${x}.5 ${oy} ${z - 2}.5`, null);
+ await sleep(1500);
+ const portal = `${here} fill ${x - 1} ${oy} ${z} ${x + 1} ${oy + 2} ${z} nether_portal[axis=x] strict`;
+ let ready = true;
+ const from = s.mark();
+ if (kind === 'ender_pearl') {
+ const ints = uuid(n).replace(/-/g, '').match(/.{8}/g).map((h) => parseInt(h, 16) | 0).join(',');
+ await s.run(portal, null);
+ await s.run(`${here} summon ender_pearl ${x}.5 ${oy + 1} ${z - 1}.5 {Owner:[I;${ints}],Motion:[0.0,0.05,0.4]}`, null);
+ } else {
+ const extra = kind === 'horse' ? ',Tame:1b' : '';
+ await s.run(`${here} summon ${kind} ${x}.5 ${oy} ${z}.5 {Tags:["pt"]${extra}}`, null);
+ await sleep(500);
+ ready = !!(await s.run(`ride ${n} mount @e[tag=pt,limit=1]`, /started riding/, 5000));
+ await sleep(500);
+ await s.run(portal, null);
+ }
+ const crossed = !!(await s.waitLog(new RegExp(`HRT changed ${n} world world_nether`), 12000, from));
+ return { ready, crossed };
+ };
+ const clear = async (x) => {
+ await s.run('kill @e[tag=pt]', null);
+ await s.run(`${here} fill ${x - 3} ${oy} ${oz + 3} ${x + 3} ${oy + 4} ${oz + 9} air`, null);
+ };
+
+ let x = ox + 8;
+ for (const kind of ['oak_boat', 'minecart', 'horse', 'ender_pearl']) {
+ const what = kind === 'ender_pearl' ? 'a thrown pearl through a portal' : `riding a ${kind.replace('oak_', '')} into a portal`;
+ await set(RULES);
+ // A summoned pearl sometimes misses the portal, so the adult gets three tries before the check is skipped.
+ let control;
+ for (let tries = 0; tries < 3; tries++) {
+ control = await attempt('A1', kind, x);
+ await clear(x);
+ await sleep(1000);
+ if (control.ready && control.crossed) break;
+ await tpWait('A1', 'station');
+ }
+ if (!control.ready || !control.crossed) {
+ skip(`child account: ${what}`, control.ready ? 'the adult control did not arrive in the nether, so a refusal would prove nothing' : 'the adult control could not mount');
+ } else {
+ await set(RULES);
+ const kid = await attempt('K1', kind, x);
+ const now = await where('K1');
+ if (!kid.ready) skip(`child account: ${what}`, 'the child bot could not mount');
+ else check(`child account: ${what} is refused (the adult control got through)`, !kid.crossed && now === 'world' && !bots.K1.ended, `${kid.crossed} ${now}`);
+ await clear(x);
+ }
+ await tpWait('A1', 'station');
+ x += 8;
+ }
+ await set(OFFRULES);
+}
(async () => {
s = new Server(dir, jar);
@@ -56,25 +156,25 @@ const text = (n, re, from = 0) => bots[n].heard(re, from);
s.writeConfig('config.yml', CONFIG);
check('reload applies home-worlds', /Reloaded/.test((await reload() || [''])[0]));
const status = await s.run('posse status', /Home worlds: ([^\n]*)/, 5000);
- check('posse status reports home-worlds', status && /kids stays in 2 worlds, else kidland/.test(status[1]) && /no circle waits in station/.test(status[1]), status && status[1]);
+ check('posse status reports home-worlds', status && /kids may be in 3 worlds/.test(status[1]) && /adults has no limits/.test(status[1]) && /no circle may be in 2 worlds/.test(status[1]) && /goes to the lobby lobby/.test(status[1]), status && status[1]);
const m0 = s.mark();
section('Rejoin: everyone comes back where they left, kids kept to kids\' worlds');
for (const n of NAMES) await join(n);
- const rejoin = { K1: 'kidland', K2: 'kidland_nether', A1: 'grownups', V1: 'grownups', X1: 'station' };
+ const rejoin = { K1: 'lobby', K2: 'kidland_nether', A1: 'grownups', V1: 'grownups', X1: 'lobby' };
for (const [n, want] of Object.entries(rejoin)) {
const got = await waitWhere(n, want);
check(`${n} rejoins in ${want}`, got === want, got);
}
- check('K1 is told, in the config\'s words', text('K1', /HOMEKID Welcome back/));
- check('K2, already in a kids\' world, is told nothing', !text('K2', /HOMEKID|Welcome back|wait here/));
- check('A1 and V1 are told nothing', !text('A1', /HOMEKID|Welcome back|wait here/) && !text('V1', /HOMEKID|Welcome back|wait here/));
+ check('K1 is told, in the config\'s words', text('K1', /HOMEKID You're in the lobby/));
+ check('K2, already in a kids\' world, is told nothing', !text('K2', /HOMEKID|wait here/));
+ check('A1 and V1 are told nothing', !text('A1', /HOMEKID|wait here/) && !text('V1', /HOMEKID|wait here/));
check('X1 is told to wait here', text('X1', /wait here until an admin adds you to a group/));
check('nobody else hears those lines', ['K2', 'A1', 'V1'].every((n) => !text(n, /wait here until|HOMEKID/)));
- section('Respawn: a kid who dies and would respawn in the main world lands in kidland');
+ section('Respawn: a kid who dies and would respawn in the main world lands in the lobby');
// With no bed, vanilla respawns in the main world, which is outside the kids' list.
- const afterDeath = { K1: 'kidland', K2: 'kidland', A1: 'world', X1: 'station' };
+ const afterDeath = { K1: 'lobby', K2: 'lobby', A1: 'world', X1: 'lobby' };
for (const [n, want] of Object.entries(afterDeath)) {
const here = await where(n);
await s.run(`mt grave ${n} 0`, new RegExp(`HRT planned death ${n}`), 8000);
@@ -82,11 +182,15 @@ const text = (n, re, from = 0) => bots[n].heard(re, from);
const got = await waitWhere(n, want);
check(`${n} (died in ${here}) respawns in ${want}`, got === want, got);
}
- check('K1 is told again after the respawn', text('K1', /HOMEKID Welcome back/));
+ check('K1 is told again after the respawn', text('K1', /HOMEKID You're in the lobby/));
- section('Safety net: a teleport that slips past the world plugin is undone');
- await s.run('mt tp K2 grownups', /HRT tp K2 grownups true/, 8000);
- check('K2 sent to the adults\' world is back in a kids\' world', (await waitWhere('K2', 'kidland')) === 'kidland', await where('K2'));
+ section('Teleports into a world the player may not be in are refused');
+ /** Teleports a player and returns what the server said: 'true' if it happened, 'false' if it was refused. */
+ const teleport = async (n, w) => ((await s.run(`mt tp ${n} ${w}`, new RegExp(`HRT tp ${n} ${w} (true|false)`), 8000)) || [])[1];
+ const refused = await teleport('K2', 'grownups');
+ await sleep(2500);
+ check('a kid\'s teleport to the adults\' world is refused', refused === 'false', refused);
+ check('and K2 never left the lobby', (await where('K2')) === 'lobby' && !bots.K2.ended, await where('K2'));
await s.run('mt tp K2 kidland_nether', /HRT tp K2 kidland_nether true/, 8000);
await sleep(2500);
check('K2 moving between kids\' worlds is left alone', (await where('K2')) === 'kidland_nether', await where('K2'));
@@ -96,40 +200,51 @@ const text = (n, re, from = 0) => bots[n].heard(re, from);
await s.run('mt tp A1 kidland', /HRT tp A1 kidland true/, 8000);
await sleep(2500);
check('an adult is left where they went', (await where('A1')) === 'kidland', await where('A1'));
- await s.run('mt tp X1 grownups', /HRT tp X1 grownups true/, 8000);
- check('a player with no circle is sent back to the station', (await waitWhere('X1', 'station')) === 'station', await where('X1'));
+ const noCircle = await teleport('X1', 'grownups');
+ check('a player with no circle is refused the adults\' world and stays put', noCircle === 'false' && (await where('X1')) === 'lobby', `${noCircle} ${await where('X1')}`);
- section('First join (D297): placement after the join event is respected, a disallowed placement is still undone');
- // The lobby is a kids' world here. F1 is placed there on first join, F2 in the adults' world, F3 has no circle.
- // O1 holds only the old mayor.* nodes, which grant nothing.
- s.writeConfig('config.yml', CONFIG.replace('[kidland, kidland_nether]', '[kidland, kidland_nether, lobby]'));
+ section('A reload that tightens the rules applies to people already online');
+ s.writeConfig('config.yml', 'circles: [kids, adults]\n');
+ await reload();
+ await s.run('mt tp K2 grownups', /HRT tp K2 grownups true/, 8000);
+ await sleep(1000);
+ check('with home-worlds off, K2 can stand in the adults\' world', (await where('K2')) === 'grownups', await where('K2'));
+ s.writeConfig('config.yml', CONFIG);
await reload();
- const uuid = (n) => { const h = crypto.createHash('md5').update('OfflinePlayer:' + n).digest(); h[6] = (h[6] & 0x0f) | 0x30; h[8] = (h[8] & 0x3f) | 0x80; const x = h.toString('hex'); return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`; };
+ check('turning the rules on moves K2 to the lobby', (await waitWhere('K2', 'lobby')) === 'lobby' && !bots.K2.ended, await where('K2'));
+ check('and leaves the adult and the visitor where they are', (await where('A1')) === 'kidland' && (await where('V1')) === 'kidland', `${await where('A1')} ${await where('V1')}`);
+
+ section('First join (D297): placement after the join event is respected, a disallowed placement is refused');
+ // F1 is placed in kidland on first join, F2 in the adults' world, F3 has no circle. O1 holds only the old mayor.*
+ // nodes, which grant nothing.
const fresh = { F1: ['posse.circle.kids'], F2: ['posse.circle.kids'], F3: [], O1: ['mayor.circle.kids', 'mayor.bypass', 'mayor.filter.bypass'] };
for (const [n, perms] of Object.entries(fresh)) for (const p of perms) await s.run(`lp user ${uuid(n)} permission set ${p} true`, null);
- for (const [n, w] of Object.entries({ F1: 'lobby', F2: 'grownups', F3: 'grownups', O1: 'grownups' })) await s.run(`mt firstspawn ${n} ${w}`, /HRT firstspawn set/, 5000);
+ for (const [n, w] of Object.entries({ F1: 'kidland', F2: 'grownups', F3: 'grownups', O1: 'grownups' })) await s.run(`mt firstspawn ${n} ${w}`, /HRT firstspawn set/, 5000);
for (const n of Object.keys(fresh)) { bots[n] = new Bot(n, +port); await bots[n].spawned; }
await sleep(6000);
- check('F1, a new kid placed in the allowed lobby, stays there', (await where('F1')) === 'lobby', await where('F1'));
+ check('F1, a new kid placed in an allowed world, stays there', (await where('F1')) === 'kidland', await where('F1'));
check('F1 is told nothing', !text('F1', /HOMEKID|wait here/));
- check('F2, a new kid placed in the adults\' world, ends in kidland', (await waitWhere('F2', 'kidland')) === 'kidland', await where('F2'));
- check('F3, a new player with no circle placed in the adults\' world, ends in the station', (await waitWhere('F3', 'station')) === 'station', await where('F3'));
- check('O1, with only old mayor.circle.kids, is in no circle, so is moved to the station', (await waitWhere('O1', 'station')) === 'station', await where('O1'));
+ check('F2, a new kid whose placement is the adults\' world, ends in the lobby', (await waitWhere('F2', 'lobby')) === 'lobby', await where('F2'));
+ check('and the placement itself was refused', /HRT firstspawn F2 grownups false/.test(s.log));
+ check('F3, a new player with no circle placed in the adults\' world, ends in the lobby', (await waitWhere('F3', 'lobby')) === 'lobby', await where('F3'));
+ check('O1, with only old mayor.circle.kids, is in no circle, so is moved to the lobby', (await waitWhere('O1', 'lobby')) === 'lobby', await where('O1'));
check('nobody was disconnected', Object.keys(fresh).every((n) => !bots[n].kicked && !bots[n].ended));
+ // Both were sent to the lobby, where everyone reaches everyone, so F2 steps into another world first.
+ await s.run('mt tp F2 kidland', /HRT tp F2 kidland true/, 8000);
+ await sleep(1500);
const chk = await s.run('posse check O1 F2', /O1 can('t)? reach F2[^\n]*/, 5000);
check('an old mayor.bypass grants no bypass: O1 cannot reach F2', chk && chk[1] === "'t" && !/bypass/.test(chk[0]), chk && chk[0]);
const chk2 = await s.run('posse check F2 O1', /F2 can('t)? reach O1[^\n]*/, 5000);
check('and F2 cannot reach O1 either', chk2 && chk2[1] === "'t", chk2 && chk2[0]);
- s.writeConfig('config.yml', CONFIG);
- await reload();
section('Pending first join (D297): a new kid reaches nobody until the delayed check has run');
- // presence: reach is on. A1 (adult) stands in the main world; K1 (kid) stands in kidland. G1 is a new kid with no
- // first-spawn placement, so they are left in the main world and the check must move them to kidland. The helper
+ // presence: reach is on. A1 (adult) stands in the main world; K1 (kid) stands in the lobby. G1 is a new kid with no
+ // first-spawn placement, so they are left in the main world and the check must move them to the lobby. The helper
// slows the server's next 30 ticks to a quarter second each after G1 joins, so the pending state lasts long enough to look at.
- s.writeConfig('config.yml', CONFIG.replace('[kidland, kidland_nether]', '[kidland, kidland_nether, lobby]') + 'presence: reach\n');
+ s.writeConfig('config.yml', CONFIG + 'presence: reach\n');
await reload();
await s.run('mt tp A1 world', /HRT tp A1 world true/, 8000);
+ await s.run('mt tp K1 lobby', /HRT tp K1 lobby true/, 8000);
await sleep(1500);
for (const n of ['G1', 'H1']) await s.run(`lp user ${uuid(n)} permission set posse.circle.kids true`, null);
const a0 = bots.A1.mark(), k0 = bots.K1.mark(), ra0 = bots.A1.rawMark(), rk0 = bots.K1.rawMark();
@@ -140,6 +255,7 @@ const text = (n, re, from = 0) => bots[n].heard(re, from);
bots.G1.say('/msg A1 pendingpm one');
bots.G1.say('/msg K1 pendingpm two');
bots.A1.say('/msg G1 pendingpm three');
+ bots.G1.say('/circles');
await sleep(2500);
// Looked at while the server is still stalled, so G1's delayed check cannot have run.
check('A1, in the same world, hears no chat from G1', !text('A1', /pendingchat/, a0) && !bots.A1.rawHeard(/pendingchat/, ra0));
@@ -149,14 +265,21 @@ const text = (n, re, from = 0) => bots[n].heard(re, from);
check('A1 has no tab entry for G1', !listedTo('A1', 'G1'));
check('G1 sees nobody in the tab either while pending', !listedTo('G1', 'A1') && !listedTo('G1', 'K1'));
check('K1 has no tab entry and no join line for G1 yet', !listedTo('K1', 'G1') && !text('K1', /G1 joined the game/, k0));
+ check('A1, in the same world, is sent no body or nametag for G1, and G1 none for A1', !bodyOf('A1', 'G1') && !bodyOf('G1', 'A1'), `${bodyOf('A1', 'G1')} ${bodyOf('G1', 'A1')}`);
+ check('the server hides G1 and A1 from each other', (await sees('A1', 'G1')) === 'false false');
+ check('pending: a command G1 runs gets no answer', !text('G1', CIRCLES_REPLY, g0), bots.G1.lines(g0).slice(-3).join(' | '));
check('G1 is still in the main world while pending', (await where('G1')) === 'world', await where('G1'));
- check('after the check, G1 is moved to kidland', (await waitWhere('G1', 'kidland', 10000)) === 'kidland', await where('G1'));
+ check('after the check, G1 is moved to the lobby', (await waitWhere('G1', 'lobby', 10000)) === 'lobby', await where('G1'));
await sleep(1500);
check('K1, now in the same world as G1, gets the join line', text('K1', /G1 joined the game/, k0), bots.K1.lines(k0).slice(-4).join(' | '));
check('K1 has a tab entry for G1', !!listedTo('K1', 'G1'));
+ check('after the move K1 and G1 see each other again', (await sees('K1', 'G1')) === 'true true' && !!bodyOf('K1', 'G1'), `${await sees('K1', 'G1')} ${bodyOf('K1', 'G1')}`);
+ const g1m = bots.G1.mark();
+ bots.G1.say('/circles');
+ check('and G1\'s commands work again', await bots.G1.waitFor(CIRCLES_REPLY, 4000, g1m), bots.G1.lines(g1m).slice(-3).join(' | '));
check('A1, who can no longer reach G1, never gets a join line', !text('A1', /G1 joined the game/, a0));
check('A1 has no tab entry for G1 after the move', !listedTo('A1', 'G1'));
- check('G1 is told the config\'s welcome line', text('G1', /HOMEKID Welcome back/));
+ check('G1 is told the config\'s lobby line', text('G1', /HOMEKID You're in the lobby/));
const gm = bots.G1.mark();
bots.G1.say('afterchat hello');
await sleep(1500);
@@ -177,19 +300,222 @@ const text = (n, re, from = 0) => bots[n].heard(re, from);
s.writeConfig('config.yml', CONFIG);
await reload();
- section('Fails closed: a missing fallback world');
- s.writeConfig('config.yml', CONFIG.replace('kidland_nether]\n fallback: kidland', 'kidland_nether, ghostland]\n fallback: ghostland'));
+ section('Fails closed: a missing lobby disconnects (reload)');
+ // The lobby named here, ghostland, was never made. kidland stays an allowed world. OFF has no home-worlds at all.
+ const OFF = 'circles: [kids, adults]\npresence: reach\n';
+ const GHOST = CONFIG.replace('lobby-world: lobby', 'lobby-world: ghostland').replace(/lobby\]/g, 'ghostland]') + 'presence: reach\n';
+ const SORRY = /join again/;
+ const WARN = /outside their home worlds was disconnected because the lobby "ghostland" isn't loaded/;
+ /** A tp that may disconnect the player at once, so it only waits for the helper to say it ran. */
+ const tp = async (n, w) => s.run(`mt tp ${n} ${w}`, new RegExp(`HRT tp ${n} ${w} (true|false)`), 8000);
+ const gone = async (n, ms = 10000) => {
+ const until = Date.now() + ms;
+ while (Date.now() < until && !bots[n].ended) await sleep(100);
+ return !!bots[n].ended;
+ };
+ /** Joins a player who is expected to be sent off again, so a failure to spawn isn't an error. */
+ const tryJoin = async (n) => { bots[n] = new Bot(n, +port); bots[n].spawned.catch(() => {}); await gone(n); await sleep(1000); };
+ const watch = () => ({ chat: { A1: bots.A1.mark(), K2: bots.K2.mark() }, raw: { A1: bots.A1.rawMark(), K2: bots.K2.rawMark() } });
+ // A death line is left out: K2 shares a circle with a kid who dies here, so it rightly reaches them.
+ const mentions = (n, m) => ['A1', 'K2'].flatMap((v) => bots[v].raw.slice(m.raw[v])
+ .filter((c) => c.m.includes(n) && !/"death\./.test(c.m)).map((c) => `${v} ${c.n} ${c.m.slice(0, 200)}`));
+ const unheard = (n, m) => ['A1', 'K2'].every((v) => !text(v, new RegExp(`${n} (joined|left) the game`), m.chat[v])) && mentions(n, m).length === 0;
+ /** With the rules off, rejoins and says which world the player was saved in. */
+ const savedWorld = async (n) => { s.writeConfig('config.yml', OFF); await reload(); await join(n); return where(n); };
+
+ // Earlier new players may be standing in a world a later section unloads.
+ for (const n of ['F1', 'F2', 'F3', 'O1', 'G1']) bots[n].quit();
+ await sleep(2000);
+ s.writeConfig('config.yml', OFF);
await reload();
+ // X1 waits in the station, which the no-circle list keeps open, so these reloads leave them alone.
+ await tp('A1', 'grownups'); await tp('K2', 'kidland'); await tp('K1', 'grownups'); await tp('X1', 'station');
+ await sleep(1500);
+ let w = watch();
const sm = s.mark();
- const st = await s.run('posse status', /the world "ghostland" doesn't exist[^\n]*/, 5000);
- check('posse status says which world is missing', !!st, st && st[0]);
+ s.writeConfig('config.yml', GHOST);
+ check('a reload naming a missing lobby is accepted', /Reloaded/.test((await reload() || [''])[0]));
+ check('a kid already in a world they may not be in is disconnected by the reload, with kidland loaded', await gone('K1'), bots.K1.ended);
+ check('and told to join again', SORRY.test(bots.K1.kicked || ''), bots.K1.kicked);
+ await sleep(1500);
+ check('nobody is told the kid left', unheard('K1', w), mentions('K1', w).join(' | '));
+ check('the log names the missing lobby', WARN.test(s.since(sm)));
+ check('and the warning names no player', s.since(sm).split('\n').filter((l) => WARN.test(l)).every((l) => !/K1/.test(l)));
+ const kept = await teleport('K2', 'grownups');
+ check('a kid in an allowed world is kept there: the teleport out is refused', kept === 'false' && !bots.K2.ended && (await where('K2')) === 'kidland', `${kept} ${await where('K2')}`);
+ const st = await s.run('posse status', /the lobby world "ghostland" doesn't exist[^\n]*/, 5000);
+ check('posse status warns about the missing world before anyone needs it', st && /is disconnected until it does/.test(st[0]), st && st[0]);
const json = await s.run('posse status --json hw1', /ea-result[^\n]*hw1[^\n]*/, 5000);
- check('the --json status reports home-worlds on and the problem', json && /"homeWorlds":\{/.test(json[0]) && /"enabled":true/.test(json[0]) && /"circles":\["kids"\]/.test(json[0]) && /"noCircle":true/.test(json[0]) && /ghostland/.test(json[0]), json && json[0].slice(0, 300));
- await s.run('mt tp K1 grownups', /HRT tp K1 grownups true/, 8000);
- check('a kid sent out lands in the main world, never left where they were', (await waitWhere('K1', 'world')) === 'world', await where('K1'));
- check('the log warns about the missing fallback', /home-worlds fallback "ghostland" doesn't exist/.test(s.since(sm)));
+ check('the --json status reports home-worlds on and the problem', json && /"homeWorlds":\{/.test(json[0]) && /"enabled":true/.test(json[0]) && /"circles":\["kids","adults"\]/.test(json[0]) && /"settings":\{[^}]*"adults":"unlimited"/.test(json[0]) && /"noCircle":true/.test(json[0]) && /ghostland/.test(json[0]), json && json[0].slice(0, 300));
+
+ section('Fails closed: a missing lobby disconnects (rejoin)');
+ w = watch();
+ await tryJoin('K1');
+ check('a kid who rejoins in a world they may not be in is disconnected', !!bots.K1.ended && SORRY.test(bots.K1.kicked || ''), bots.K1.kicked);
+ check('nobody is told the kid joined or left', unheard('K1', w), mentions('K1', w).join(' | '));
+ let saved = await savedWorld('K1');
+ check('the kid was never moved to another world: still saved where they were', saved === 'grownups', saved);
+
+ section('Fails closed: already standing in the main world');
+ await tp('K1', 'world');
+ await sleep(1000);
+ bots.K1.quit(); await sleep(2000);
+ s.writeConfig('config.yml', GHOST);
+ await reload();
+ w = watch();
+ await tryJoin('K1');
+ check('a kid rejoining in the main world is disconnected, never left there', !!bots.K1.ended && SORRY.test(bots.K1.kicked || ''), bots.K1.kicked);
+ check('nobody is told the kid joined or left', unheard('K1', w), mentions('K1', w).join(' | '));
+
+ section('Fails closed: a missing lobby disconnects (respawn)');
+ await savedWorld('K1');
+ await tp('K1', 'kidland');
+ await sleep(1000);
+ s.writeConfig('config.yml', GHOST);
+ await reload();
+ await sleep(1000);
+ check('a kid in an allowed world is left alone while the lobby is missing', !bots.K1.ended && (await where('K1')) === 'kidland', await where('K1'));
+ w = watch();
+ // With no bed, vanilla respawns in the main world, which the kid may not be in.
+ await s.run('mt grave K1 0', /HRT planned death K1/, 8000);
+ check('the respawning kid is disconnected', await gone('K1'), bots.K1.ended);
+ check('and told to join again', SORRY.test(bots.K1.kicked || ''), bots.K1.kicked);
+ await sleep(1500);
+ check('nobody is told the kid left', unheard('K1', w), mentions('K1', w).join(' | '));
+
+ section('Fails closed: a lobby that really is unloaded');
+ // X1, in no circle, waits in the station while the lobby is taken away. Nobody else is standing in the lobby.
+ s.writeConfig('config.yml', OFF);
+ await reload();
+ await tp('X1', 'station');
+ await sleep(1500);
+ const um = await s.run('mt unload lobby', /HRT unload lobby (true|false)/, 30000);
+ check('the lobby is unloaded', um && um[1] === 'true', um && um[0]);
+ s.writeConfig('config.yml', CONFIG + 'presence: reach\n');
+ await reload();
+ const stay = await teleport('X1', 'world');
+ check('with the lobby unloaded, a teleport to the main world is refused', stay === 'false' && !bots.X1.ended && (await where('X1')) === 'station', `${stay} ${await where('X1')}`);
+ // Put there with the rules off, then the rules are read again.
+ s.writeConfig('config.yml', OFF);
+ await reload();
+ await tp('X1', 'world');
+ await sleep(1000);
+ const xm = s.mark();
+ s.writeConfig('config.yml', CONFIG + 'presence: reach\n');
+ await reload();
+ check('a player standing in the main world is disconnected by the reload', await gone('X1'), bots.X1.ended);
+ check('and told to join again', SORRY.test(bots.X1.kicked || ''), bots.X1.kicked);
+ check('the log names the unloaded lobby', /disconnected because the lobby "lobby" isn't loaded/.test(s.since(xm)));
+ await tryJoin('X1');
+ check('and is disconnected again on rejoin', !!bots.X1.ended && SORRY.test(bots.X1.kicked || ''), bots.X1.kicked);
+ saved = await savedWorld('X1');
+ check('nobody moved them anywhere: still saved in the main world', saved === 'world', saved);
+ bots.X1.quit();
+ await s.run('mt world lobby', /HRT world (lobby|FAILED)/, 60000);
+ // savedWorld left home-worlds off, so K1 can be put anywhere.
+ bots.K1 = null;
+ await join('K1');
+ await tp('K1', 'grownups');
+ await sleep(1000);
+ bots.K1.quit();
+ await sleep(2000);
+ s.writeConfig('config.yml', CONFIG);
+ await reload();
+ await join('K1');
+ check('with the lobby back, the kid can join and is placed in it', (await waitWhere('K1', 'lobby')) === 'lobby', await where('K1'));
+
+ section('Lobby: used only when it is set, loaded and open to the player\'s group');
+ // Their own worlds are loaded throughout, and are never somewhere they're sent.
+ const lobbyConfig = (kids, extra = '') => `circles: [kids, adults]
+lobby-world: lobby
+home-worlds:
+ kids:
+ worlds: [${kids}]
+ adults:
+ unlimited: true
+ no-circle:
+ worlds: [station${extra}]
+presence: reach
+`;
+ const OPEN = lobbyConfig('kidland, lobby', ', lobby');
+ const SHUT = lobbyConfig('kidland');
+ const UNSET = OPEN.replace('lobby-world: lobby\n', '');
+ const LEGACY = OPEN.replace('worlds: [kidland, lobby]', 'worlds: [kidland, lobby]\n fallback: kidland');
+ /** Puts a player in a world with the rules off, then turns the given config on, which applies to them at once. */
+ const standIn = async (n, world, config) => {
+ s.writeConfig('config.yml', OFF);
+ await reload();
+ if (!bots[n] || bots[n].ended) await join(n);
+ await tp(n, world);
+ await sleep(1000);
+ s.writeConfig('config.yml', config);
+ await reload();
+ };
+ // K1 is still connected from the section above.
+ const lm = bots.K1.mark();
+ await standIn('K1', 'grownups', OPEN);
+ check('lobby open to kids: a kid outside their worlds is sent to the lobby, with kidland loaded', (await waitWhere('K1', 'lobby')) === 'lobby', await where('K1'));
+ check('and is not disconnected', !bots.K1.ended, bots.K1.kicked);
+ check('and is told they are in the lobby', await bots.K1.waitFor(/in lobby now, because/, 4000, lm), bots.K1.lines(lm).slice(-3).join(' | '));
+ await standIn('K1', 'grownups', SHUT);
+ check('lobby not open to kids: disconnected', (await gone('K1')) && SORRY.test(bots.K1.kicked || ''), bots.K1.kicked);
+ await sleep(1500);
+ saved = await savedWorld('K1');
+ check('and never placed in the lobby or another world', saved === 'grownups', saved);
+ // A player in no circle follows the same rule, with the no-circle list.
+ await standIn('X1', 'grownups', OPEN);
+ check('lobby on the no-circle list: a player with no circle is sent there, with the station loaded', (await waitWhere('X1', 'lobby')) === 'lobby' && !bots.X1.ended, await where('X1'));
+ s.writeConfig('config.yml', SHUT);
+ await reload();
+ check('a reload that closes the lobby to no circle disconnects someone standing in it', (await gone('X1')) && SORRY.test(bots.X1.kicked || ''), bots.X1.kicked);
+ const um2 = s.mark();
+ await standIn('K1', 'grownups', UNSET);
+ check('no lobby set: disconnected', (await gone('K1')) && SORRY.test(bots.K1.kicked || ''), bots.K1.kicked);
+ check('and the log says no lobby is set', /disconnected because no lobby-world is set/.test(s.since(um2)));
+ const om = s.mark();
+ await standIn('K1', 'grownups', LEGACY);
+ check('an old fallback line loads with a warning', /home-worlds\.kids\.fallback is no longer used/.test(s.since(om)));
+ check('and the kid goes to the lobby, never to the old fallback', (await waitWhere('K1', 'lobby')) === 'lobby' && !bots.K1.ended, await where('K1'));
+ // A named lobby that isn't loaded counts as no lobby. K1 is moved out of it first, so nobody is standing in it.
+ await standIn('K1', 'kidland', OFF);
+ const gl = await s.run('mt unload lobby', /HRT unload lobby (true|false)/, 30000);
+ check('the lobby is unloaded', gl && gl[1] === 'true', gl && gl[0]);
+ await tp('K1', 'grownups');
+ await sleep(1000);
+ s.writeConfig('config.yml', OPEN);
+ await reload();
+ check('lobby named but not loaded: disconnected', (await gone('K1')) && SORRY.test(bots.K1.kicked || ''), bots.K1.kicked);
+ await s.run('mt world lobby', /HRT world (lobby|FAILED)/, 60000);
+
+ section('A disconnect another plugin cancels: the player is held until it goes through');
+ // K2, in an allowed world, is the one who must not hear K1.
+ await standIn('K2', 'kidland', OFF);
+ await standIn('K1', 'grownups', OFF);
+ // A1, an adult, is never moved, and stands beside K1.
+ await tp('A1', 'grownups');
+ await sleep(2500);
+ check('before the hold, A1 beside K1 has their body and tab entry', bodyOf('A1', 'K1') && listedTo('A1', 'K1') && (await sees('A1', 'K1')) === 'true true', `${bodyOf('A1', 'K1')} ${listedTo('A1', 'K1')} ${await sees('A1', 'K1')}`);
+ await s.run('mt blockkick K1 true', /HRT blockkick set/, 5000);
+ const hold = s.mark(), heard = bots.K2.mark();
+ s.writeConfig('config.yml', GHOST.replace('presence: reach', 'presence: everyone'));
+ await reload();
+ await sleep(2500);
+ check('the kick was cancelled, so the bot is still connected', !bots.K1.ended, bots.K1.ended);
+ check('held: A1 beside them loses their body and tab entry, even with presence: everyone', !bodyOf('A1', 'K1') && !listedTo('A1', 'K1'), `${bodyOf('A1', 'K1')} ${listedTo('A1', 'K1')}`);
+ check('held: the server hides them both ways', (await sees('A1', 'K1')) === 'false false');
+ check('the log says they are held', /A disconnect didn't go through/.test(s.since(hold)));
+ bots.K1.say('heldchat hello');
+ bots.K1.say('/msg K2 heldpm hello');
+ await sleep(2000);
+ check('held: their chat and private message reach nobody', !text('K2', /heldchat|heldpm/, heard), bots.K2.lines(heard).slice(-3).join(' | '));
+ const moved = await s.run('mt tp K1 kidland', /HRT tp K1 kidland (true|false)/, 8000);
+ check('held: a teleport is refused', moved && moved[1] === 'false', moved && moved[0]);
+ await s.run('mt blockkick K1 false', /HRT blockkick set/, 5000);
+ check('once the kick can go through, they are disconnected', await gone('K1'), bots.K1.ended);
section('Off by default: with the section removed nothing moves');
+ await standIn('K1', 'kidland', OFF);
+ await standIn('X1', 'grownups', OFF);
s.writeConfig('config.yml', 'circles: [kids, adults]\n');
await reload();
await s.run('mt tp K1 grownups', /HRT tp K1 grownups true/, 8000);
@@ -201,9 +527,292 @@ const text = (n, re, from = 0) => bots[n].heard(re, from);
const off = await s.run('posse status', /Home worlds: ([^\n]*)/, 5000);
check('status says off', off && off[1] === 'off.', off && off[1]);
- const errors = s.errors(m0).filter((l) => !/ghostland|home-worlds fallback|didn't go through/.test(l));
+ section('No no-circle entry: the no-circle list is the lobby and nothing else');
+ const NOCIRCLE = `circles: [kids, adults]
+lobby-world: lobby
+home-worlds:
+ kids:
+ worlds: [kidland, lobby]
+ adults:
+ unlimited: true
+presence: reach
+`;
+ await standIn('X1', 'station', OFF);
+ const nm = s.mark();
+ s.writeConfig('config.yml', NOCIRCLE);
+ await reload();
+ check('a player with no circle is moved to the lobby', (await waitWhere('X1', 'lobby')) === 'lobby' && !bots.X1.ended, await where('X1'));
+ check('the startup warning names the missing entry', /home-worlds\.no-circle is missing/.test(s.since(nm)));
+ for (const w2 of ['station', 'grownups', 'kidland', 'world']) {
+ const r = await teleport('X1', w2);
+ check(`and is refused ${w2}`, r === 'false' && (await where('X1')) === 'lobby', `${r} ${await where('X1')}`);
+ }
+ await standIn('X1', 'station', NOCIRCLE.replace('lobby-world: lobby\n', ''));
+ check('with no lobby set either, they are disconnected', (await gone('X1')) && SORRY.test(bots.X1.kicked || ''), bots.X1.kicked);
+
+ section('One entry for each circle: no entry and an unusable entry add nothing, unlimited lifts every limit');
+ // K2 is in kids and newclub, A1 in adults only, V1 in kids and adults. newclub has no entry anywhere here.
+ await s.run(`lp user ${uuid('K2')} permission set posse.circle.newclub true`, null);
+ const entries = (adults) => `circles: [kids, adults, newclub]
+lobby-world: lobby
+home-worlds:
+ kids:
+ worlds: [kidland, lobby]
+${adults}presence: reach
+`;
+ const statusLine = async () => ((await s.run('posse status', /Home worlds: ([^\n]*)/, 5000)) || [])[1] || '';
+ const park = async () => {
+ s.writeConfig('config.yml', OFF);
+ await reload();
+ for (const n of ['K2', 'A1', 'V1']) if (!bots[n] || bots[n].ended) await join(n);
+ await tp('K2', 'kidland'); await tp('A1', 'grownups'); await tp('V1', 'grownups');
+ await sleep(1500);
+ };
+ await park();
+ const em = s.mark();
+ s.writeConfig('config.yml', entries(''));
+ await reload();
+ check('an adult whose circle has no entry is moved to the lobby, like a player in no circle', (await waitWhere('A1', 'lobby')) === 'lobby' && !bots.A1.ended, await where('A1'));
+ const unlisted = await teleport('A1', 'grownups');
+ check('and is refused the adults\' world', unlisted === 'false' && (await where('A1')) === 'lobby', `${unlisted} ${await where('A1')}`);
+ const club = await teleport('K2', 'grownups');
+ check('a kid also in a new circle with no entry keeps the kids\' limits', club === 'false' && (await where('K2')) === 'kidland', `${club} ${await where('K2')}`);
+ check('the log names each circle with no entry', /home-worlds\.adults is missing/.test(s.since(em)) && /home-worlds\.newclub is missing/.test(s.since(em)), s.since(em).slice(-600));
+ let line = await statusLine();
+ check('/posse status shows each circle\'s setting', /kids may be in 2 worlds/.test(line) && /adults has no entry and adds no worlds/.test(line) && /newclub has no entry and adds no worlds/.test(line), line);
+
+ await park();
+ s.writeConfig('config.yml', entries(' adults:\n unlimited: true\n'));
+ await reload();
+ await sleep(2000);
+ check('with unlimited: true, the adult is left where they are', (await where('A1')) === 'grownups' && !bots.A1.ended, await where('A1'));
+ check('an account in an unlimited circle and a limited one has no limits', (await where('V1')) === 'grownups' && (await teleport('V1', 'station')) === 'true', await where('V1'));
+ check('while the kid in the new circle is still refused', (await teleport('K2', 'grownups')) === 'false');
+
+ const bad = {
+ 'both worlds and unlimited': ' adults:\n worlds: [grownups, lobby]\n unlimited: true\n',
+ 'unlimited that is not true': ' adults:\n unlimited: "true"\n',
+ 'neither worlds nor unlimited': ' adults:\n message: "hello"\n',
+ 'a bare name': ' adults:\n',
+ };
+ for (const [what, text2] of Object.entries(bad)) {
+ await park();
+ const bm = s.mark();
+ s.writeConfig('config.yml', entries(text2));
+ await reload();
+ check(`an entry with ${what} adds nothing: the adult is moved to the lobby`, (await waitWhere('A1', 'lobby')) === 'lobby' && !bots.A1.ended, await where('A1'));
+ check(`and is refused the adults' world (${what})`, (await teleport('A1', 'grownups')) === 'false');
+ check(`the log names the entry and says it adds nothing (${what})`, /home-worlds\.adults[^\n]*adds no worlds/.test(s.since(bm)), s.since(bm).slice(-500));
+ line = await statusLine();
+ check(`/posse status shows it as unusable (${what})`, /adults has an entry that can't be used and adds no worlds/.test(line), line);
+ }
+ // Nothing but an unusable entry: home worlds must stay on.
+ await park();
+ s.writeConfig('config.yml', 'circles: [kids, adults]\nlobby-world: lobby\nhome-worlds:\n kids:\npresence: reach\n');
+ await reload();
+ await sleep(2500);
+ line = await statusLine();
+ check('a section with only an unusable entry is still on', line !== 'off.' && /kids has an entry that can't be used/.test(line), line);
+ check('so a kid is moved to the lobby and refused other worlds', (await waitWhere('K2', 'lobby')) === 'lobby' && (await teleport('K2', 'grownups')) === 'false', await where('K2'));
+ await s.run(`lp user ${uuid('K2')} permission unset posse.circle.newclub`, null);
+
+ section('A reload that tightens the rules, with several people online at once');
+ s.writeConfig('config.yml', OFF);
+ await reload();
+ for (const n of ['K1', 'K2', 'A1', 'X1']) if (!bots[n] || bots[n].ended) await join(n);
+ await tp('K1', 'grownups'); await tp('K2', 'kidland'); await tp('A1', 'grownups'); await tp('X1', 'grownups');
+ await sleep(1500);
+ s.writeConfig('config.yml', CONFIG + 'presence: reach\n');
+ await reload();
+ const first = [await waitWhere('K1', 'lobby'), await where('K2'), await where('A1'), await waitWhere('X1', 'lobby')];
+ check('kid and no-circle player moved, allowed kid and adult left alone', first.join() === 'lobby,kidland,grownups,lobby', first.join());
+ s.writeConfig('config.yml', CONFIG.replace(' adults:\n unlimited: true', ' adults:\n worlds: [kidland]') + 'presence: reach\n');
+ await reload();
+ check('tightened again: the adult, whose list leaves out the lobby, is disconnected', (await gone('A1')) && SORRY.test(bots.A1.kicked || ''), bots.A1.kicked);
+ await sleep(1500);
+ check('and the others are untouched', ['K1', 'K2', 'X1'].every((n) => !bots[n].ended) && [await where('K1'), await where('K2'), await where('X1')].join() === 'lobby,kidland,lobby', ['K1', 'K2', 'X1'].map((n) => bots[n].ended).join());
+
+ section('Who gets into a children\'s world');
+ s.writeConfig('config.yml', OFF);
+ await reload();
+ await join('A1');
+ await tp('A1', 'station'); await tp('X1', 'station'); await tp('K2', 'kidland');
+ await sleep(1500);
+ s.writeConfig('config.yml', CONFIG + 'presence: reach\n');
+ await reload();
+ const outsider = await teleport('X1', 'kidland');
+ check('an account in no circle is refused the children\'s world', outsider === 'false' && (await where('X1')) === 'station', `${outsider} ${await where('X1')}`);
+ // Home worlds never read posse.bypass (outside a paused start). An admin gets in through an unlimited circle.
+ await s.run(`lp user ${uuid('X1')} permission set posse.bypass true`, null);
+ await sleep(1500);
+ const bypassOnly = await teleport('X1', 'kidland');
+ check('posse.bypass on its own opens no world', bypassOnly === 'false' && (await where('X1')) === 'station', `${bypassOnly} ${await where('X1')}`);
+ await s.run(`lp user ${uuid('X1')} permission unset posse.bypass`, null);
+ const admin = await teleport('A1', 'kidland');
+ check('an allowed adult account gets in', admin === 'true' && (await waitWhere('A1', 'kidland')) === 'kidland', `${admin} ${await where('A1')}`);
+
+ section('Removing a LuckPerms group leaves the player with the no-circle rule');
+ await s.run('lp creategroup crew', null);
+ await sleep(1000);
+ await s.run('lp group crew permission set posse.circle.kids true', null);
+ await s.run(`lp user ${uuid('M1')} parent add crew`, null);
+ await sleep(1000);
+ s.writeConfig('config.yml', OFF);
+ await reload();
+ await join('M1');
+ await tp('M1', 'kidland');
+ await sleep(1500);
+ s.writeConfig('config.yml', CONFIG + 'presence: reach\n');
+ await reload();
+ const asKid = await teleport('M1', 'station');
+ check('in the group, M1 follows the kids\' list', (await where('M1')) === 'kidland' && asKid === 'false', `${asKid} ${await where('M1')}`);
+ await s.run(`lp user ${uuid('M1')} parent remove crew`, null);
+ await sleep(3000);
+ console.log(`INFO three seconds after the group was removed, with no teleport or reload, M1 is in ${await where('M1')}`);
+ const without = await teleport('M1', 'kidland_nether');
+ check('out of the group, the next teleport follows the no-circle list: a kids\' world is refused', without === 'false', without);
+ s.writeConfig('config.yml', CONFIG + 'presence: reach\n');
+ await reload();
+ check('and the next reload moves them to the lobby', (await waitWhere('M1', 'lobby')) === 'lobby' && !bots.M1.ended, await where('M1'));
+ bots.M1.quit();
+
+ section('A refusal another plugin takes back, or redirects, is refused again');
+ await standIn('K1', 'lobby', CONFIG + 'presence: reach\n');
+ const cm = s.mark();
+ await s.run('mt uncancel K1', /HRT uncancel set/, 5000);
+ const undone = await teleport('K1', 'grownups');
+ await sleep(1500);
+ check('another plugin un-cancels a refused teleport: it stays refused', undone === 'false' && (await where('K1')) === 'lobby' && !/HRT changed K1 \S+ grownups/.test(s.since(cm)), `${undone} ${await where('K1')}`);
+ check('the log says Posse refused it again', /changed a teleport after Posse had checked it/.test(s.since(cm)));
+ await s.run('mt reset K1', /HRT reset set/, 5000);
+ await s.run('mt redirect K1 grownups', /HRT redirect set/, 5000);
+ const turned = await teleport('K1', 'kidland');
+ await sleep(1500);
+ check('another plugin redirects an allowed teleport somewhere forbidden: refused', turned === 'false' && (await where('K1')) === 'lobby' && !/HRT changed K1 \S+ grownups/.test(s.since(cm)), `${turned} ${await where('K1')}`);
+ await s.run('mt reset K1', /HRT reset set/, 5000);
+ check('with the other plugin gone, an allowed teleport works', (await teleport('K1', 'kidland')) === 'true');
+
+ section('The check after a world change: nobody sees or hears the player until they are moved');
+ // presence: everyone, so only the pending state can hide anyone.
+ await standIn('K1', 'lobby', CONFIG + 'presence: everyone\n');
+ await tp('A1', 'grownups');
+ await sleep(2500);
+ check('before it, A1 and K1 can see each other', (await sees('A1', 'K1')) === 'true true', await sees('A1', 'K1'));
+ await s.run('mt force K1', /HRT force set/, 5000);
+ await s.run('mt window K1 3000', /HRT window set/, 5000);
+ const wm = s.mark(), wa = bots.A1.mark(), wk = bots.K1.mark();
+ s.cmd('mt tp K1 grownups');
+ const opened = await s.waitLog(/HRT window start K1 (\S+) seenBy=(\S*) sees=(\S*) \./, 10000, wm);
+ if (opened) {
+ bots.K1.say('windowchat kid');
+ bots.A1.say('windowchat adult');
+ }
+ await s.waitLog(/HRT window end K1/, 10000, wm);
+ check('a forced teleport past every refusal reaches the world-change check', !!opened && opened[1] === 'grownups' && /HRT forced K1 grownups/.test(s.since(wm)), opened && opened[0]);
+ check('in the window, nobody can see K1', !!opened && opened[2] === '', opened && opened[2]);
+ check('and K1 can see nobody', !!opened && opened[3] === '', opened && opened[3]);
+ const inside = (s.since(wm).split('HRT window start K1')[1] || '').split('HRT window end K1')[0];
+ if (/HRT chat K1 /.test(inside) && /HRT chat A1 /.test(inside)) {
+ check('in the window, K1\'s chat is cancelled', /HRT chat K1 cancelled=true/.test(inside) && !/HRT chat K1 cancelled=false/.test(inside));
+ check('while an adult\'s chat goes on as usual', /HRT chat A1 cancelled=false/.test(inside));
+ } else {
+ skip('chat during the world-change window', 'the server handled no chat while its main thread was held');
+ }
+ check('K1 is then moved to the lobby', (await waitWhere('K1', 'lobby', 10000)) === 'lobby' && !bots.K1.ended, await where('K1'));
+ await sleep(1500);
+ check('A1 never heard K1\'s line, and K1 never heard A1\'s from the window', !text('A1', /windowchat kid/, wa) && !text('K1', /windowchat adult/, wk));
+ check('and once K1 has landed, they can see each other again', (await sees('A1', 'K1')) === 'true true', await sees('A1', 'K1'));
+
+ await portals();
+
+ const errors = s.errors(m0).filter((l) => !/ghostland|home-worlds|didn't go through|outside their home worlds|changed a teleport after Posse/.test(l));
check('no errors or exceptions in the log', errors.length === 0, errors.slice(0, 4).join(' || '));
- Object.values(bots).forEach((b) => b.quit());
+
+ section('Paused at startup: only posse.bypass can join');
+ Object.values(bots).forEach((b) => b && b.quit());
+ await sleep(2000);
+ await s.stop();
+ s.writeConfig('config.yml', 'circles: [kids\nnope: : :');
+ await s.start();
+ // The made-up worlds are loaded by the helper, so load them again before anyone rejoins where they left.
+ for (const w of ['kidland', 'kidland_nether', 'grownups', 'station', 'lobby']) await s.run(`mt world ${w}`, new RegExp(`HRT world (${w}|FAILED)`), 60000);
+ check('the console says joining is paused', /chat, private messages and joining are paused until it's fixed/.test(s.log));
+ const refusal = /safety rules didn't load, so joining is paused/;
+ for (const n of ['K1', 'P1']) {
+ await tryJoin(n);
+ check(`${n}, without posse.bypass, is refused with a kind message`, !!bots[n].ended && refusal.test(bots[n].kicked || ''), bots[n].kicked);
+ }
+ await s.run('op P2', null);
+ await tryJoin('P2');
+ check('an operator without posse.bypass is refused too', refusal.test(bots.P2.kicked || ''), bots.P2.kicked);
+ const logged = (s.log.match(/A join was refused because Posse's safety rules aren't loaded/g) || []).length;
+ check('refusals are logged, no more than once a minute', logged >= 1 && logged <= 2, logged);
+ await s.run(`lp user ${uuid('B1')} permission set posse.bypass true`, null);
+ await sleep(1500);
+ await join('B1');
+ await sleep(2000);
+ check('a player with posse.bypass can join while paused', !bots.B1.ended && !bots.B1.kicked, bots.B1.kicked);
+ // Another plugin allowing the login again doesn't get a player in: the join is checked too.
+ const seen = bots.B1.mark();
+ await s.run('mt allowlogin P1', /HRT allowlogin set/, 5000);
+ await tryJoin('P1');
+ check('a login another plugin allowed again is disconnected at the join', !!bots.P1.ended && refusal.test(bots.P1.kicked || ''), bots.P1.kicked);
+ check('and nobody is shown a join or leave line for them', !text('B1', /P1 (joined|left) the game/, seen), bots.B1.lines(seen).slice(-3).join(' | '));
+
+ section('Paused at startup: a refused player whose kick is cancelled is held');
+ await s.run('mt blockkick P3 true', /HRT blockkick set/, 5000);
+ await s.run('mt allowlogin P3', /HRT allowlogin set/, 5000);
+ const pm = s.mark(), pb = bots.B1.mark(), pr = bots.B1.rawMark();
+ bots.P3 = new Bot('P3', +port); bots.P3.spawned.catch(() => {});
+ await sleep(4000);
+ check('the kick was cancelled, so P3 is still connected', !bots.P3.ended, bots.P3.kicked);
+ check('the log says they are held', /A disconnect didn't go through/.test(s.since(pm)));
+ check('held while paused: hidden from the bypass player both ways', (await sees('B1', 'P3')) === 'false false', await sees('B1', 'P3'));
+ check('with no join line, body or tab entry', !text('B1', /P3 joined the game/, pb) && !bots.B1.rawHeard(/P3/, pr) && !bodyOf('B1', 'P3') && !listedTo('B1', 'P3'), bots.B1.rawSample(pr));
+ const pmoved = await s.run('mt tp P3 world', /HRT tp P3 world (true|false)/, 8000);
+ check('held while paused: a teleport is refused', pmoved && pmoved[1] === 'false', pmoved && pmoved[0]);
+ await s.run('mt blockkick P3 false', /HRT blockkick set/, 5000);
+ check('once the kick can go through, P3 is disconnected', await gone('P3'), bots.P3.ended);
+ await sleep(1000);
+ check('with no leave line', !text('B1', /P3 left the game/, pb), bots.B1.lines(pb).slice(-3).join(' | '));
+
+ s.writeConfig('config.yml', CONFIG);
+ check('the fixed config reloads', /Reloaded/.test((await reload() || [''])[0]));
+ await join('K1');
+ check('after the reload a player without bypass can join, and the rules apply', !bots.K1.kicked && ['kidland', 'kidland_nether', 'lobby'].includes(await where('K1')), await where('K1'));
+
+ section('A startup that fails another way pauses joining until a restart');
+ // A stand-in BlueMapMini whose share event can't be listened to, so Posse's startup throws part way through.
+ Object.values(bots).forEach((b) => b && b.quit());
+ await sleep(2000);
+ await s.stop();
+ const mapJar = s.path('plugins/LiveTestFakeMinimap.jar');
+ const goodMap = fs.readFileSync(mapJar);
+ fs.copyFileSync(BROKEN_MAP, mapJar);
+ await s.start();
+ check('the console says Posse didn\'t start properly', /Posse didn't start properly, so joining is paused/.test(s.log), (s.log.match(/[^\n]*Posse didn't start[^\n]*/) || [''])[0]);
+ check('and the server stays up', s.proc.exitCode === null);
+ for (const w2 of ['kidland', 'kidland_nether', 'grownups', 'station', 'lobby']) await s.run(`mt world ${w2}`, new RegExp(`HRT world (${w2}|FAILED)`), 60000);
+ await tryJoin('K1');
+ check('a player without posse.bypass is refused', !!bots.K1.ended && refusal.test(bots.K1.kicked || ''), bots.K1.kicked);
+ await join('B1');
+ await sleep(1500);
+ check('a player with posse.bypass can join', !bots.B1.ended && !bots.B1.kicked, bots.B1.kicked);
+ await s.run('mt allowlogin P1', /HRT allowlogin set/, 5000);
+ const fm = bots.B1.mark();
+ await tryJoin('P1');
+ check('a login another plugin allowed again is still disconnected', !!bots.P1.ended && refusal.test(bots.P1.kicked || ''), bots.P1.kicked);
+ check('with no join or leave line', !text('B1', /P1 (joined|left) the game/, fm), bots.B1.lines(fm).slice(-3).join(' | '));
+ bots.B1.quit();
+ await sleep(1500);
+ await s.stop();
+ fs.writeFileSync(mapJar, goodMap);
+ await s.start();
+ for (const w2 of ['kidland', 'kidland_nether', 'grownups', 'station', 'lobby']) await s.run(`mt world ${w2}`, new RegExp(`HRT world (${w2}|FAILED)`), 60000);
+ await join('K1');
+ await sleep(1500);
+ check('after a healthy restart, joins are open again', !bots.K1.ended && !bots.K1.kicked && !/Posse didn't start properly/.test(s.log), bots.K1.kicked);
+ Object.values(bots).forEach((b) => b && b.quit());
await s.stop();
process.exit(summary() ? 1 : 0);
})().catch(async (e) => {
diff --git a/test/live/reach-leaks.js b/test/live/reach-leaks.js
index 1a96f00..6030db6 100644
--- a/test/live/reach-leaks.js
+++ b/test/live/reach-leaks.js
@@ -4,7 +4,7 @@
// Run it with POSSE_SUITE=reach-leaks.js test/live/run.sh . All names are made up.
//
// Each part checks a pair that must be refused, a pair that is allowed, a player with posse.bypass, and Posse unable
-// to decide (the rules paused by a config it can't read). A control with no circles shows the test can see a line
+// to decide (the rules paused by a config it can't read, where only posse.bypass can join). A control with no circles shows the test can see a line
// when one is sent. On Posse 0.11.1 the refused checks fail: that is the bug this test was written for.
const mc = require('minecraft-protocol');
const { sleep, check, section, summary, Server, Bot } = require('./lib.js');
@@ -13,12 +13,14 @@ const [dir, jar, port] = process.argv.slice(2);
const CONFIG = `circles: [kids, adults]
circle-only-worlds: [station]
presence: reach
+lobby-world: kidland
home-worlds:
kids:
worlds: [kidland]
- fallback: kidland
+ adults:
+ unlimited: true
no-circle:
- fallback: station
+ worlds: [station]
`;
// K = kids' circle, A = adults', V = both, M = an adult moderator with posse.bypass, X = no circle, waiting in the station.
const PEOPLE = {
@@ -253,10 +255,21 @@ const TAB = ['/msg ', '/tell ', '/w ', '/minecraft:msg ', '/minecraft:tell ', '/
await s.stop();
s.writeConfig('config.yml', 'circles: [kids\nnope: : :');
await s.start();
- check('the console explains the pause', /chat and private messages are paused until it's fixed/.test(s.log));
+ check('the console explains the pause', /chat, private messages and joining are paused until it's fixed/.test(s.log));
// The made-up worlds are loaded by the helper, so load them again before anyone rejoins where they left.
for (const w of ['kidland', 'grownups', 'station']) await s.run(`mt world ${w}`, new RegExp(`HRT world (${w}|FAILED)`), 60000);
+ // Only posse.bypass can join while paused.
+ const kid = new Bot('K1', +port); kid.spawned.catch(() => {});
+ const until = Date.now() + 10000;
+ while (Date.now() < until && !kid.ended) await sleep(200);
+ check('paused: a player without posse.bypass is refused', !!kid.ended && /safety rules didn't load, so joining is paused/.test(kid.kicked || ''), kid.kicked || kid.ended);
+ // The checks below need players without the bypass online while paused. They join holding it, then it's taken away.
+ const lent = NAMES.filter((n) => !PEOPLE[n].bypass);
+ for (const n of lent) await s.run(`lp user ${n} permission set posse.bypass true`, null);
+ await sleep(1500);
for (const n of NAMES) await join(n);
+ for (const n of lent) await s.run(`lp user ${n} permission unset posse.bypass`, null);
+ await sleep(4000);
check('everyone is back in their own world', (await where('K2')) === 'kidland' && (await where('A2')) === 'grownups', `${await where('K2')} ${await where('A2')}`);
await sleep(3000);
const forAdult = [], forMod = [];
diff --git a/test/live/suite.js b/test/live/suite.js
index d726632..844b6da 100644
--- a/test/live/suite.js
+++ b/test/live/suite.js
@@ -327,9 +327,12 @@ async function presence() {
let bad = presenceBad(reaches);
check(`each of ${NAMES.length} players lists exactly the players they can reach`, bad.length === 0, bad.slice(0, 12).join('; '));
const marks = Object.fromEntries(all().map((b) => [b.name, b.mark()]));
- bots.N2.quit(); await sleep(1500);
- const sawLeave = all().filter((b) => b.name !== 'N2' && b.heard('N2 left the game', marks[b.name])).map((b) => b.name).sort();
const wantSee = NAMES.filter((b) => b !== 'N2' && reaches(b, 'N2')).sort();
+ bots.N2.quit();
+ // A loaded machine can be slow, so wait for those who should be told, then a little longer for anyone who shouldn't.
+ for (const n of wantSee) await bots[n].waitFor('N2 left the game', 8000, marks[n]);
+ await sleep(1500);
+ const sawLeave = all().filter((b) => b.name !== 'N2' && b.heard('N2 left the game', marks[b.name])).map((b) => b.name).sort();
check('only players who can reach N2 see that N2 left', JSON.stringify(sawLeave) === JSON.stringify(wantSee), `saw ${sawLeave}, want ${wantSee}`);
const m2 = Object.fromEntries(all().filter((b) => b.name !== 'N2').map((b) => [b.name, b.mark()]));
bots.N2 = new Bot('N2', +port); await bots.N2.spawned; await sleep(500);
@@ -428,7 +431,14 @@ async function pausedOnBrokenStart() {
const good = fs.readFileSync(s.path('plugins/Posse/config.yml'), 'utf8');
s.writeConfig('config.yml', 'circles: [red\nnope: : :');
await s.start();
- check('the console explains the pause', /chat and private messages are paused until it's fixed/.test(s.log));
+ check('the console explains the pause', /chat, private messages and joining are paused until it's fixed/.test(s.log));
+ const refused = new Bot('N1', +port); refused.spawned.catch(() => {});
+ const until = Date.now() + 10000;
+ while (Date.now() < until && !refused.ended) await sleep(100);
+ check('while paused, a player without posse.bypass is refused with a kind message', !!refused.ended && /safety rules didn't load, so joining is paused/.test(refused.kicked || ''), refused.kicked);
+ check('and the log says why the join was refused, without naming them', /A join was refused because Posse's safety rules aren't loaded/.test(s.log) && !/Posse\][^\n]*\bN1\b/.test(s.log));
+ // Only posse.bypass gets in. Chat, private messages and the player list stay paused for them too.
+ for (const n of ['R1', 'R2']) await lp(`user ${n} permission set posse.bypass true`);
s.cmd('op R2'); await sleep(300);
await join(['R1', 'R2']);
await sleep(800);
@@ -442,6 +452,9 @@ async function pausedOnBrokenStart() {
check('D283: while paused, nobody is listed to anyone else (fail closed)', !listedTo('R1', 'R2') && !listedTo('R2', 'R1'));
s.writeConfig('config.yml', good);
await reload();
+ for (const n of ['R1', 'R2']) await lp(`user ${n} permission unset posse.bypass`);
+ await join(['N1']);
+ check('after the fix and reload, a player without posse.bypass can join', !bots.N1.kicked && !bots.N1.ended, bots.N1.kicked);
const k = bots.R2.mark(); bots.R1.say('back again'); await sleep(1200);
check('fixing the config and reloading brings chat back', bots.R2.heard('back again', k));
s.cmd('deop R2');
@@ -555,7 +568,7 @@ async function graves() {
// README: "Blocked text is never logged or stored." The words the filter test used must not be in the server log.
const leaked = ['sh1t', 'b1tch'].filter((w) => s.log.toLowerCase().includes(w));
check('filtered words never reach the server log', leaked.length === 0, leaked.join(', '));
- const errors = s.errors().filter((l) => !/config.yml: isn't valid YAML|couldn't read its config|The config has problems|SEVERE.*Posse.*(YAML|paused|kept)/.test(l));
+ const errors = s.errors().filter((l) => !/config.yml: isn't valid YAML|couldn't read its config|config couldn't be read|The config has problems|A join was refused because Posse's safety rules aren't loaded|SEVERE.*Posse.*(YAML|paused|kept)/.test(l));
check('no errors or exceptions in the log', errors.length === 0, errors.slice(0, 8).join(' || '));
check('no test player died and respawned elsewhere', !/HRT death /.test(s.log), (s.log.match(/.*HRT death .*/) || [''])[0]);
const kicked = all().filter((b) => b.kicked);