Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d0000810c1 | ||
|
|
1addc93062 |
@@ -1,53 +1,9 @@
|
||||
# Repository Agent Guidance
|
||||
# spigot-invisibilty agent entrypoint
|
||||
|
||||
## User-story-driven development
|
||||
The canonical stories, engineering guidance, and **all process documents** are in the private [SoMC OKF wiki](https://git.garvis.dev/dmg/somc-okf/src/branch/main/index.md).
|
||||
|
||||
The `design/` directory is the OKF v0.1 product record for this repository. Use user stories to plan, implement, verify, and track all behavior.
|
||||
Before work, read the sibling `../somc-okf/index.md`, `../somc-okf/processes/index.md`, `../somc-okf/projects/spigot-invisibilty/index.md`, `engineering.md` in that project section, and relevant `../somc-okf/user-stories/spigot-invisibilty/` stories. Also follow the parent workspace `AGENTS.md` when present.
|
||||
|
||||
Before changing behavior:
|
||||
For standalone checkouts, start at the [project page](https://git.garvis.dev/dmg/somc-okf/src/branch/main/projects/spigot-invisibilty/index.md) and [shared process](https://git.garvis.dev/dmg/somc-okf/src/branch/main/processes/development.md). Obtain wiki access before feature work; do not recreate a local knowledge bundle. Source builds do not require private wiki access.
|
||||
|
||||
1. Read `design/index.md` and every story related to the requested behavior.
|
||||
2. Draft updates to an existing story or create a new `design/user-stories/us-NNN-short-name.md` story before implementation.
|
||||
3. Define observable acceptance criteria using user or operator language.
|
||||
4. Present the relevant new or updated stories and acceptance criteria to the user for review, and wait for explicit confirmation before changing implementation code.
|
||||
5. Incorporate requested story changes before proceeding.
|
||||
6. Set story status to `in-progress` while approved implementation is incomplete.
|
||||
|
||||
While implementing:
|
||||
|
||||
1. Work in vertical slices against the documented acceptance criteria.
|
||||
2. Add tests for important behavior before implementation when practical.
|
||||
3. Keep implementation references and related-story links current.
|
||||
4. Do not mark an acceptance criterion complete until the behavior exists and has been validated.
|
||||
|
||||
Before completing or committing:
|
||||
|
||||
1. Set a completed story status to `done` only when all acceptance criteria are complete and verified.
|
||||
2. Check completed acceptance criteria and record validation evidence where appropriate.
|
||||
3. Update `design/index.md` and `design/user-stories/index.md` whenever stories are added, renamed, moved, or materially reclassified.
|
||||
4. Add a high-level entry to `design/log.md` under the verified current date.
|
||||
5. Run OKF validation along with relevant Gradle tests, lint checks, and builds.
|
||||
|
||||
## OKF conventions
|
||||
|
||||
- Every non-reserved Markdown file in `design/` must have YAML frontmatter with a non-empty `type`.
|
||||
- User stories use `type: User Story` and include `status`, `title`, and `description`.
|
||||
- Allowed story statuses are `backlog`, `in-progress`, and `done`.
|
||||
- Every user story includes an acceptance-criteria section using Markdown task-list items.
|
||||
- `design/index.md` and `design/log.md` are reserved OKF files and follow the OKF index/log structures.
|
||||
- Store user stories in `design/user-stories/` and keep their catalog current.
|
||||
- Use standard Markdown links and keep repository-local links valid when files move.
|
||||
- Preserve unknown frontmatter extensions.
|
||||
|
||||
## Java and Spigot development
|
||||
|
||||
- Use the Java version and Spigot API version declared by the Gradle build.
|
||||
- Treat compiler warnings as errors.
|
||||
- Prefer test-first development for domain rules and state transitions when practical.
|
||||
- Run `./gradlew clean check jar` before completing implementation work.
|
||||
- Keep Bukkit event handlers thin and move testable game rules into focused domain services.
|
||||
- Do not perform blocking file or network operations on the server tick thread.
|
||||
|
||||
## Timestamps
|
||||
|
||||
Always run `date +%Y-%m-%d` before adding or updating dates in stories or the design log. Use RFC 3339 UTC timestamps (`YYYY-MM-DDTHH:MM:SSZ`) when a date-time is required. Never guess dates.
|
||||
Development follows [Development cycle](https://git.garvis.dev/dmg/somc-okf/src/branch/main/runbooks/development-cycle.md): approved stories, failing tests, passing implementation, verification, then source/wiki commit and push. GitOps updates are committed locally **without pushing**; only [Do release](https://git.garvis.dev/dmg/somc-okf/src/branch/main/runbooks/do-release.md) authorizes a reviewed GitOps push.
|
||||
|
||||
@@ -46,11 +46,3 @@ tasks.processResources {
|
||||
expand("version" to pluginVersion)
|
||||
}
|
||||
}
|
||||
|
||||
tasks.register<Exec>("validateOkf") {
|
||||
commandLine("./scripts/validate-okf.sh")
|
||||
}
|
||||
|
||||
tasks.check {
|
||||
dependsOn("validateOkf")
|
||||
}
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
---
|
||||
okf_version: "0.1"
|
||||
---
|
||||
|
||||
# Spigot Stealth Design
|
||||
|
||||
Spigot Stealth rewards players who spend time under invisibility effects from potions they drink, then lets unlocked players conceal their identity for a later session.
|
||||
|
||||
## Explore
|
||||
|
||||
- [User stories](user-stories/) - Approved requirements for progression, stealth sessions, commands, persistence, and delivery.
|
||||
- [Design log](log.md) - Material product decisions and bundle changes.
|
||||
@@ -1,33 +0,0 @@
|
||||
# Spigot Stealth Design Log
|
||||
|
||||
## 2026-09-05
|
||||
|
||||
- **Fix**: Reworked US-002 server-list filtering for Purpur's native `NameAndId` samples by filtering names through Bukkit, limiting ProtocolLib to guarded count adjustment, and rate-limiting compatibility warnings; verified the complete Gradle build and OKF bundle.
|
||||
- **Completion**: Extended US-002, US-004, and US-005 with a persistent, permission-gated sleep-count policy that excludes concealed players by default, applies immediately, restores prior player state, and supports contextual administration; verified the complete Gradle build and OKF bundle.
|
||||
- **Completion**: Extended US-002 with ProtocolLib filtering of concealed sessions from multiplayer server-list counts and player samples while preserving actual online state and advertised capacity; verified the complete Gradle build and OKF bundle.
|
||||
|
||||
## 2026-09-04
|
||||
|
||||
- **Completion**: Extended US-002 so concealed players disconnect without a public quit announcement while ordinary quit messages remain unchanged; verified listener tests, the complete Gradle build, and the OKF bundle.
|
||||
- **Completion**: Extended US-003 and US-004 with contextual, prefix-filtered command completion that suppresses generic player suggestions, plus an administrative list of all known online and offline unlocked players; verified the complete Gradle build and OKF bundle.
|
||||
|
||||
## 2026-08-14
|
||||
|
||||
- **Completion**: Completed US-004 with exact known online and offline targeting, complete status, idempotent grants, confirmed resets, active concealment discovery, operator-default permissions, asynchronous persisted replies, and console audits; verified the full Gradle build.
|
||||
- **Implementation**: Began US-004 with test-first exact offline targeting, grant/reset transitions, concealed-player listing, permissions, confirmation, and audit logging.
|
||||
- **Completion**: Completed US-002 with single-use durable prepared logins, join-announcement suppression, ProtocolLib tab-only removal, scoreboard overhead-name suppression, visible physical entities, periodic observer refresh, respawn restoration, and disconnect or disable cleanup; verified the full Gradle build.
|
||||
- **Implementation**: Began US-002 with test-first prepared-login consumption, session-scoped concealment, join suppression, tab removal, and overhead-name presentation.
|
||||
- **Completion**: Completed US-003 with `/stealth progress`, live unsaved interval inclusion, configured target and remaining output, concise duration formatting, and unlocked usage guidance; verified the full Gradle build.
|
||||
- **Implementation**: Began US-003 with player-facing progress command and human-readable duration tests.
|
||||
- **Completion**: Completed US-001 with direct potion-drink effect attribution, monotonic elapsed-time accumulation, safe refresh and stop transitions, durable UUID progress, exact-once unlocking, and title plus chat presentation; verified the full Gradle build.
|
||||
- **Implementation**: Began US-001 with monotonic-clock progression tests and potion-cause event attribution.
|
||||
- **Completion**: Completed US-005 with validated eight-hour defaults and configurable messages, UUID-keyed immutable state, RFC 3339 timing metadata, safe invalid-record defaults, unknown-field preservation, atomic YAML replacement, periodic saves, and serialized off-thread persistence; verified the full Gradle build.
|
||||
- **Implementation**: Began US-005 with test-first validated settings, UUID-keyed state, and defensive asynchronous persistence.
|
||||
- **Completion**: Completed US-006 with a Java 17 Gradle build, strict compiler linting, Spigot API, JUnit 5, Mockito, plugin metadata, OKF validation, Gitea CI, conventional-commit checks, semantic releases, and versioned release assets; verified the full build and a `1.2.3` release JAR.
|
||||
- **Implementation**: Began US-006 with a test-driven Java 17, Gradle, Spigot, OKF validation, and Gitea delivery foundation modeled on Spigot Tyrant.
|
||||
- **Creation**: Established the OKF v0.1 product record for Spigot Stealth.
|
||||
- **Decision**: Only invisibility from a potion the player directly drinks contributes to the default eight-hour unlock requirement.
|
||||
- **Decision**: An unlocked player who disconnects while their qualifying potion effect remains active conceals their identity for the entirety of their next online session.
|
||||
- **Decision**: Each concealed session requires a new qualifying potion and disconnect; concealment never carries automatically into another session.
|
||||
- **Decision**: Concealed players remain physically visible but have no join announcement, tab-list entry, or overhead name tag for any player, including administrators.
|
||||
- **Decision**: Administrators can inspect and manage online or offline progression and list currently concealed players.
|
||||
@@ -1,8 +0,0 @@
|
||||
# Spigot Stealth User Stories
|
||||
|
||||
1. [US-001: Accumulate invisibility time and unlock stealth](us-001-accumulate-invisibility-and-unlock.md) - Earn stealth by spending eight hours under invisibility effects from directly consumed potions.
|
||||
2. [US-002: Rejoin without a visible identity](us-002-rejoin-without-visible-identity.md) - Turn a qualifying invisible disconnect into one concealed online session.
|
||||
3. [US-003: Check personal stealth progress](us-003-check-personal-progress.md) - View accumulated time, remaining time, and unlock status.
|
||||
4. [US-004: Inspect and manage player stealth](us-004-administer-player-stealth.md) - Inspect and modify online or offline progression and find concealed players.
|
||||
5. [US-005: Configure and persist stealth progression](us-005-configure-and-persist-progression.md) - Keep progression durable and operator-configurable.
|
||||
6. [US-006: Build, test, and release the plugin](us-006-build-test-and-release.md) - Provide repeatable Gradle builds and Gitea delivery.
|
||||
@@ -1,32 +0,0 @@
|
||||
---
|
||||
type: User Story
|
||||
title: "US-001: Accumulate invisibility time and unlock stealth"
|
||||
description: Reward sustained use of directly consumed invisibility potions with the stealth ability.
|
||||
status: done
|
||||
---
|
||||
|
||||
# US-001: Accumulate invisibility time and unlock stealth
|
||||
|
||||
As a **player**, I want my qualifying invisibility time to accumulate so that sustained potion use eventually unlocks stealth.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [x] Only time spent online under an invisibility effect produced by a potion the player directly drank contributes to progression.
|
||||
- [x] Invisibility received from splash potions, lingering potions, tipped arrows, commands, plugins, or other sources does not contribute.
|
||||
- [x] Qualifying time stops when the effect ends, is removed, is replaced by a non-qualifying source, the player disconnects, or the plugin disables.
|
||||
- [x] Refreshed or overlapping qualifying effects never count elapsed time more than once.
|
||||
- [x] Qualifying time accumulates across effects, sessions, and server restarts.
|
||||
- [x] The ability unlocks when accumulated qualifying time reaches eight hours by default.
|
||||
- [x] Reaching the threshold grants the unlock exactly once without discarding excess elapsed time.
|
||||
- [x] When an online player unlocks stealth, they receive both a full-screen title and a chat message explaining the ability.
|
||||
- [x] Progress and unlock ownership are associated with the player's UUID rather than their current name.
|
||||
|
||||
## Validation
|
||||
|
||||
Automated tests verify monotonic accumulation across intervals, refresh without duplicate time, exact-once threshold crossing with excess-time preservation, direct potion-drink cause filtering, non-qualifying replacement, UUID state, and online title and chat presentation. The complete `./gradlew clean check jar` lifecycle passes.
|
||||
|
||||
## Related
|
||||
|
||||
- [Rejoin without a visible identity](us-002-rejoin-without-visible-identity.md)
|
||||
- [Check personal stealth progress](us-003-check-personal-progress.md)
|
||||
- [Configure and persist stealth progression](us-005-configure-and-persist-progression.md)
|
||||
@@ -1,48 +0,0 @@
|
||||
---
|
||||
type: User Story
|
||||
title: "US-002: Rejoin without a visible identity"
|
||||
description: Let an unlocked player turn a qualifying invisible disconnect into one identity-concealed session.
|
||||
status: done
|
||||
---
|
||||
|
||||
# US-002: Rejoin without a visible identity
|
||||
|
||||
As an **unlocked player**, I want to disconnect while invisibility from a potion I drank is active so that my identity is concealed throughout my next session.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [x] An unlocked player becomes eligible for a concealed login only by disconnecting while an invisibility effect from a potion they directly drank remains active.
|
||||
- [x] A player who has not unlocked stealth cannot prepare a concealed login.
|
||||
- [x] An ordinary disconnect without an active qualifying effect clears any preparation for the next login.
|
||||
- [x] On a prepared login, no public join announcement is shown.
|
||||
- [x] When a concealed player disconnects, no public quit or disconnect announcement is shown.
|
||||
- [x] Ordinary players' quit messages remain unchanged.
|
||||
- [x] Concealment is checked before disconnect cleanup so announcement suppression is reliable.
|
||||
- [x] Throughout the concealed session, the player is absent from every other player's tab list, including administrators' tab lists.
|
||||
- [x] The multiplayer server list's online-player count excludes currently concealed players.
|
||||
- [x] Concealed players are excluded from any player-name sample shown for the server-list count, while ordinary players remain represented.
|
||||
- [x] The public count never becomes negative, and the configured maximum-player count remains unchanged.
|
||||
- [x] Server-list concealment changes only the public ping response and does not alter actual online-player state or gameplay.
|
||||
- [x] Server-list filtering remains error-free when Purpur represents player samples with native `NameAndId` values rather than Mojang `GameProfile` values.
|
||||
- [x] A server-ping compatibility failure leaves the original response usable and does not produce repeated unhandled listener exceptions.
|
||||
- [x] By default, concealed players are excluded from sleep-percentage calculations.
|
||||
- [x] When the sleep-count policy is `include`, concealed players count normally; ordinary players are never modified by either policy.
|
||||
- [x] A player's previous sleeping-ignore state is restored when concealment ends, the player disconnects or is reset, the policy changes to `include`, or the plugin disables.
|
||||
- [x] Policy changes apply immediately to currently concealed players.
|
||||
- [x] Throughout the concealed session, no overhead name tag identifies the player to any other player, including administrators.
|
||||
- [x] The concealed player's physical character remains visible in the world and retains ordinary movement, interaction, combat, and permission behavior.
|
||||
- [x] The concealed player receives a private message explaining that stealth is active for the session.
|
||||
- [x] Concealment lasts until the player disconnects and is handled predictably across death and plugin reload or disable events.
|
||||
- [x] Disconnecting consumes the current concealed session; another concealed login requires another qualifying potion and qualifying disconnect.
|
||||
- [x] Merely owning the unlock never conceals an ordinary login or carries concealment automatically into a later session.
|
||||
- [x] Prepared-login state survives a server restart between the qualifying disconnect and the next login.
|
||||
|
||||
## Validation
|
||||
|
||||
Automated tests verify unlocked and locked disconnect transitions, ordinary-disconnect clearing, one-login consumption, concealed join and quit announcement suppression, preservation of ordinary announcements, private activation messaging, ordinary-login presentation, tab removal for existing and new observers, overhead-name suppression, active concealed-session tracking, ProtocolLib-independent native player-sample filtering, guarded public server-list count adjustment, nonnegative counts, unchanged maximum capacity, default sleep-count exclusion, immediate policy changes, restoration of prior sleeping-ignore state, and the absence of entity-hiding calls. ProtocolLib is declared as a required dependency, prepared state round trips through YAML, and `./gradlew clean check jar` passes.
|
||||
|
||||
## Related
|
||||
|
||||
- [Accumulate invisibility time and unlock stealth](us-001-accumulate-invisibility-and-unlock.md)
|
||||
- [Inspect and manage player stealth](us-004-administer-player-stealth.md)
|
||||
- [Configure and persist stealth progression](us-005-configure-and-persist-progression.md)
|
||||
@@ -1,31 +0,0 @@
|
||||
---
|
||||
type: User Story
|
||||
title: "US-003: Check personal stealth progress"
|
||||
description: Show a player their accumulated qualifying invisibility time and stealth unlock status.
|
||||
status: done
|
||||
---
|
||||
|
||||
# US-003: Check personal stealth progress
|
||||
|
||||
As a **player**, I want to check my stealth progress so that I know how close I am to unlocking the ability and how to use it afterward.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [x] `/stealth progress` reports the player's accumulated qualifying invisibility time.
|
||||
- [x] Before unlock, the command reports the configured target and remaining duration.
|
||||
- [x] While a qualifying effect is active, the report includes elapsed time not yet written during the current tracking interval.
|
||||
- [x] After unlock, the command clearly reports that stealth is unlocked and explains how to prepare a concealed login.
|
||||
- [x] Durations are presented in a concise, human-readable form.
|
||||
- [x] Repeated command use does not change progression or concealment state.
|
||||
- [x] The command has clear usage metadata and an appropriate player permission.
|
||||
- [x] `/stealth` tab-completes `progress`, filtered by the entered prefix.
|
||||
- [x] Unsupported argument positions return no suggestions instead of Bukkit's generic player list.
|
||||
|
||||
## Validation
|
||||
|
||||
Automated tests verify concise duration formatting, live in-flight progress, configured target and remaining output, command non-mutation, unlocked usage guidance, prefix-filtered completion, and suppression of irrelevant suggestions. Command metadata and the complete `./gradlew clean check jar` lifecycle pass.
|
||||
|
||||
## Related
|
||||
|
||||
- [Accumulate invisibility time and unlock stealth](us-001-accumulate-invisibility-and-unlock.md)
|
||||
- [Configure and persist stealth progression](us-005-configure-and-persist-progression.md)
|
||||
@@ -1,44 +0,0 @@
|
||||
---
|
||||
type: User Story
|
||||
title: "US-004: Inspect and manage player stealth"
|
||||
description: Give administrators durable controls for online and offline progression, unlocks, and active concealment.
|
||||
status: done
|
||||
---
|
||||
|
||||
# US-004: Inspect and manage player stealth
|
||||
|
||||
As a **server administrator**, I want to inspect and correct player stealth state so that I can support players whether they are online or offline.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [x] `/stealthadmin status <player|uuid>` reports accumulated time, unlock status, prepared-login state, and current concealment state.
|
||||
- [x] Status inspection works for online players and known offline players selected by exact current or previously recorded name or UUID.
|
||||
- [x] `/stealthadmin grant <player|uuid>` grants the unlock to an online or known offline player without altering accumulated time unnecessarily.
|
||||
- [x] Granting an already-owned unlock is safe and clearly reports that no change was needed.
|
||||
- [x] Granting the unlock sends the normal full-screen title and chat notification when the target is online.
|
||||
- [x] `/stealthadmin reset <player|uuid> confirm` clears accumulated time, unlock ownership, prepared-login state, and current concealment for an online or known offline player.
|
||||
- [x] Reset requires explicit confirmation and safely restores an online concealed player to ordinary identity presentation.
|
||||
- [x] `/stealthadmin list` lists every currently online concealed player and clearly reports when there are none.
|
||||
- [x] Concealed players remain absent from administrators' ordinary tab lists and retain hidden overhead name tags; the admin command is the supported discovery mechanism.
|
||||
- [x] Commands clearly reject unknown, ambiguous, malformed, or otherwise invalid targets without creating unintended player records.
|
||||
- [x] Administrative inspection and modification require an operator-default administrative permission.
|
||||
- [x] State-changing operations persist before success is reported and are safe under retries.
|
||||
- [x] Grant and reset actions record the administrator, target UUID, and action in the server log without blocking the server tick thread.
|
||||
- [x] `/stealthadmin` tab-completes `status`, `grant`, `reset`, and `list`, filtered by the entered prefix.
|
||||
- [x] Target positions for `status`, `grant`, and `reset` suggest known player names, and reset's final argument suggests `confirm`.
|
||||
- [x] Administrative completions require the administrative permission, and irrelevant positions return no suggestions instead of Bukkit's generic player list.
|
||||
- [x] `/stealthadmin list unlocked` lists every known online or offline player with stealth unlocked.
|
||||
- [x] The unlocked list is sorted case-insensitively, identifies nameless records by UUID, and clearly reports when it is empty.
|
||||
- [x] Existing `/stealthadmin list` behavior continues to list currently concealed online players.
|
||||
- [x] `/stealthadmin sleepcount status` reports whether concealed players are included in or excluded from sleep-percentage calculations.
|
||||
- [x] `/stealthadmin sleepcount <include|exclude>` persists the policy before reporting success, applies it immediately, and records the administrator and policy in the server log.
|
||||
- [x] The `sleepcount`, `status`, `include`, and `exclude` arguments are permission-gated and contextually tab-completed.
|
||||
|
||||
## Validation
|
||||
|
||||
Automated tests verify exact offline name and UUID resolution, ambiguous and unknown rejection without record creation, complete status output, idempotent grants and notification, complete resets with presentation cleanup, online concealed-player filtering, online and offline unlocked-player listing, contextual permission-gated completion, durable sleep-count status and policy changes, immediate policy refresh, confirmation and permission gates, persisted-before-success replies, and audit records. The complete `./gradlew clean check jar` lifecycle passes.
|
||||
|
||||
## Related
|
||||
|
||||
- [Rejoin without a visible identity](us-002-rejoin-without-visible-identity.md)
|
||||
- [Configure and persist stealth progression](us-005-configure-and-persist-progression.md)
|
||||
@@ -1,36 +0,0 @@
|
||||
---
|
||||
type: User Story
|
||||
title: "US-005: Configure and persist stealth progression"
|
||||
description: Give operators validated settings and durable, defensive storage for stealth behavior.
|
||||
status: done
|
||||
---
|
||||
|
||||
# US-005: Configure and persist stealth progression
|
||||
|
||||
As a **server operator**, I want stealth progression to be configurable and durable so that the plugin remains predictable across restarts and balance changes.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [x] The qualifying-time threshold is configurable and defaults to eight hours.
|
||||
- [x] Player-facing progress, unlock, prepared-login, and concealed-session messages are configurable.
|
||||
- [x] Startup validates required settings before registering partially functional listeners, commands, or tasks.
|
||||
- [x] Invalid required configuration prevents initialization and produces a clear server log message.
|
||||
- [x] UUID-keyed state stores accumulated qualifying duration, unlock ownership, active qualifying timing data, prepared-login state, and any current concealment metadata needed for safe recovery.
|
||||
- [x] Qualifying runtime intervals use a monotonic elapsed-time source so wall-clock adjustments cannot grant or remove progress.
|
||||
- [x] Durable timestamps, when required, use RFC 3339 UTC notation.
|
||||
- [x] State is saved periodically, after material state changes, and during orderly plugin disable.
|
||||
- [x] State uses atomic replacement where supported so an interrupted write does not replace valid data with a partial file.
|
||||
- [x] Corrupt, unknown, or invalid records cannot silently grant time, an unlock, a prepared login, or concealment.
|
||||
- [x] Unknown forward-compatible fields are preserved where practical.
|
||||
- [x] Persistence work does not perform blocking file operations on the server tick thread.
|
||||
- [x] The sleep-count policy persists in `state.yml` and defaults safely to `exclude` when missing or invalid.
|
||||
|
||||
## Validation
|
||||
|
||||
Verified settings defaults and rejection, packaged configuration, safe UUID-state defaults, sleep-count policy defaults and round trips, RFC 3339 round trips, unknown-field preservation, invalid-record rejection, atomic repository writes, and dedicated-thread loading and saving with automated tests and `./gradlew clean check jar`.
|
||||
|
||||
## Related
|
||||
|
||||
- [Accumulate invisibility time and unlock stealth](us-001-accumulate-invisibility-and-unlock.md)
|
||||
- [Rejoin without a visible identity](us-002-rejoin-without-visible-identity.md)
|
||||
- [Inspect and manage player stealth](us-004-administer-player-stealth.md)
|
||||
@@ -1,31 +0,0 @@
|
||||
---
|
||||
type: User Story
|
||||
title: "US-006: Build, test, and release the plugin"
|
||||
description: Give maintainers repeatable builds, automated verification, and versioned Gitea releases.
|
||||
status: done
|
||||
---
|
||||
|
||||
# US-006: Build, test, and release the plugin
|
||||
|
||||
As a **plugin maintainer**, I want automated builds and releases modeled on Spigot Tyrant so that tested, correctly versioned artifacts can be distributed consistently.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [x] The Gradle Kotlin DSL project compiles against Spigot API `26.2-R0.1-SNAPSHOT` using a Java 17 toolchain.
|
||||
- [x] Compiler lint warnings fail the build.
|
||||
- [x] Automated JUnit 5 and Mockito tests run as part of the Gradle check lifecycle.
|
||||
- [x] Pushes and pull requests build and test the plugin in Gitea Actions.
|
||||
- [x] Pull requests validate conventional commit messages.
|
||||
- [x] CI stores a `spigot-stealth` development JAR as a workflow artifact.
|
||||
- [x] Main-branch conventional commits drive semantic versioning.
|
||||
- [x] A successful release builds a versioned JAR and attaches it to the corresponding Gitea release.
|
||||
- [x] Build files, Gradle wrapper, workflows, and release behavior follow `../spigot-tyrant/` where applicable while using Spigot Stealth names and identifiers.
|
||||
- [x] OKF validation using `okf-base.yaml` runs locally through the repository validation script and in CI.
|
||||
|
||||
## Validation
|
||||
|
||||
Verified with `./gradlew clean check jar`, a release-version `1.2.3` JAR with matching embedded plugin metadata, and `./scripts/validate-okf.sh`.
|
||||
|
||||
## Related
|
||||
|
||||
- [Configure and persist stealth progression](us-005-configure-and-persist-progression.md)
|
||||
@@ -1,23 +0,0 @@
|
||||
okf_version: "0.1"
|
||||
|
||||
base:
|
||||
name: Spigot Stealth Design
|
||||
roots:
|
||||
- path: design
|
||||
reserved_files:
|
||||
index: index.md
|
||||
log: log.md
|
||||
|
||||
profile:
|
||||
types:
|
||||
User Story:
|
||||
required: [type, title, description, status]
|
||||
optional: []
|
||||
status_values: [backlog, in-progress, done]
|
||||
date_fields: []
|
||||
|
||||
hygiene:
|
||||
broken_links: error
|
||||
reserved_files: error
|
||||
unknown_fields: error
|
||||
split_candidates: off
|
||||
@@ -1,111 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# OKF Bundle Validator v0.1
|
||||
# Usage: validate.sh <bundle-path>
|
||||
# Checks conformance with OKF v0.1 spec:
|
||||
# E1: All non-reserved .md files have YAML frontmatter
|
||||
# E2: All frontmatter has non-empty 'type' field
|
||||
# E3: Reserved files follow structure rules
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
REPOSITORY_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
BUNDLE="${1:-${REPOSITORY_ROOT}/design}"
|
||||
MANIFEST="${REPOSITORY_ROOT}/okf-base.yaml"
|
||||
|
||||
if command -v okflint >/dev/null 2>&1; then
|
||||
exec okflint validate --manifest "$MANIFEST" "$BUNDLE"
|
||||
fi
|
||||
|
||||
echo "Warning: okflint is unavailable; running core OKF v0.1 validation only." >&2
|
||||
|
||||
ERRORS=0
|
||||
WARNINGS=0
|
||||
TOTAL=0
|
||||
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[0;33m'
|
||||
NC='\033[0m'
|
||||
|
||||
if [ ! -d "$BUNDLE" ]; then
|
||||
echo -e "${RED}Error: '$BUNDLE' is not a directory${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Validating OKF bundle: $BUNDLE"
|
||||
echo "---"
|
||||
|
||||
# Find all .md files
|
||||
while IFS= read -r -d '' file; do
|
||||
TOTAL=$((TOTAL + 1))
|
||||
relative="${file#$BUNDLE/}"
|
||||
basename=$(basename "$file")
|
||||
|
||||
# Skip reserved files (validate separately)
|
||||
if [[ "$basename" == "index.md" || "$basename" == "log.md" ]]; then
|
||||
# E3: Check reserved file structure
|
||||
if [[ "$basename" == "index.md" ]]; then
|
||||
# index.md should NOT have frontmatter (except bundle root may have okf_version)
|
||||
if head -1 "$file" | grep -q "^---$"; then
|
||||
# Allow only if it's bundle root and contains okf_version
|
||||
if [[ "$relative" != "index.md" ]]; then
|
||||
echo -e "${RED}E3: $relative — index.md should not have frontmatter${NC}"
|
||||
ERRORS=$((ERRORS + 1))
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
if [[ "$basename" == "log.md" ]]; then
|
||||
# log.md should have date headings in YYYY-MM-DD format
|
||||
if ! grep -qE "^## [0-9]{4}-[0-9]{2}-[0-9]{2}" "$file" 2>/dev/null; then
|
||||
if [ -s "$file" ]; then
|
||||
echo -e "${YELLOW}W: $relative — log.md has no ISO 8601 date headings${NC}"
|
||||
WARNINGS=$((WARNINGS + 1))
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
continue
|
||||
fi
|
||||
|
||||
# E1: Check for YAML frontmatter
|
||||
if ! head -1 "$file" | grep -q "^---$"; then
|
||||
echo -e "${RED}E1: $relative — no YAML frontmatter${NC}"
|
||||
ERRORS=$((ERRORS + 1))
|
||||
continue
|
||||
fi
|
||||
|
||||
# Extract frontmatter (between first --- and second ---)
|
||||
frontmatter=$(sed -n '2,/^---$/p' "$file" | sed '$d')
|
||||
|
||||
# E2: Check for non-empty type field
|
||||
type_value=$(echo "$frontmatter" | grep -E "^type:" | sed 's/^type:\s*//' | tr -d '"' | tr -d "'" | xargs)
|
||||
if [ -z "$type_value" ]; then
|
||||
echo -e "${RED}E2: $relative — missing or empty 'type' field${NC}"
|
||||
ERRORS=$((ERRORS + 1))
|
||||
continue
|
||||
fi
|
||||
|
||||
# Warnings for recommended fields
|
||||
if ! echo "$frontmatter" | grep -qE "^title:"; then
|
||||
echo -e "${YELLOW}W1: $relative — missing recommended 'title' field${NC}"
|
||||
WARNINGS=$((WARNINGS + 1))
|
||||
fi
|
||||
if ! echo "$frontmatter" | grep -qE "^description:"; then
|
||||
echo -e "${YELLOW}W1: $relative — missing recommended 'description' field${NC}"
|
||||
WARNINGS=$((WARNINGS + 1))
|
||||
fi
|
||||
|
||||
done < <(find "$BUNDLE" -name "*.md" -type f -print0 | sort -z)
|
||||
|
||||
# Summary
|
||||
echo "---"
|
||||
echo "Files scanned: $TOTAL"
|
||||
if [ $ERRORS -eq 0 ]; then
|
||||
echo -e "${GREEN}✅ Bundle is OKF v0.1 conformant${NC}"
|
||||
else
|
||||
echo -e "${RED}❌ $ERRORS error(s) — bundle is NOT conformant${NC}"
|
||||
fi
|
||||
if [ $WARNINGS -gt 0 ]; then
|
||||
echo -e "${YELLOW}⚠ $WARNINGS warning(s)${NC}"
|
||||
fi
|
||||
|
||||
exit $ERRORS
|
||||
@@ -18,6 +18,18 @@ public final class BukkitIdentityPresentation implements IdentityPresentation {
|
||||
private final Supplier<SleepCountPolicy> sleepCountPolicy;
|
||||
private final Map<UUID, Player> concealedPlayers = new LinkedHashMap<>();
|
||||
private final Map<UUID, Boolean> previousSleepingIgnored = new LinkedHashMap<>();
|
||||
private final Map<UUID, String> previousDisplayNames = new LinkedHashMap<>();
|
||||
private volatile java.util.Set<String> concealedNames = java.util.Set.of();
|
||||
|
||||
/** Immutable snapshot safe to read from outgoing packet threads. */
|
||||
public java.util.Set<String> concealedNames() {
|
||||
return concealedNames;
|
||||
}
|
||||
|
||||
private void publishNames() {
|
||||
concealedNames = concealedPlayers.values().stream().map(Player::getName)
|
||||
.collect(java.util.stream.Collectors.toUnmodifiableSet());
|
||||
}
|
||||
|
||||
public BukkitIdentityPresentation(
|
||||
Supplier<? extends Collection<? extends Player>> onlinePlayers,
|
||||
@@ -40,12 +52,17 @@ public final class BukkitIdentityPresentation implements IdentityPresentation {
|
||||
@Override
|
||||
public void conceal(Player player) {
|
||||
concealedPlayers.put(player.getUniqueId(), player);
|
||||
publishNames();
|
||||
previousDisplayNames.putIfAbsent(player.getUniqueId(), player.getDisplayName());
|
||||
player.setDisplayName("§kAnonymous§r");
|
||||
applySleepCountPolicy(player);
|
||||
Team team = scoreboard.getTeam(teamName(player.getUniqueId()));
|
||||
if (team == null) {
|
||||
team = scoreboard.registerNewTeam(teamName(player.getUniqueId()));
|
||||
}
|
||||
team.setOption(Team.Option.NAME_TAG_VISIBILITY, Team.OptionStatus.NEVER);
|
||||
team.setOption(Team.Option.NAME_TAG_VISIBILITY, Team.OptionStatus.ALWAYS);
|
||||
team.setPrefix("§k");
|
||||
team.setSuffix("§r");
|
||||
team.addEntry(player.getName());
|
||||
for (Player observer : onlinePlayers.get()) {
|
||||
if (!observer.getUniqueId().equals(player.getUniqueId())) {
|
||||
@@ -57,6 +74,10 @@ public final class BukkitIdentityPresentation implements IdentityPresentation {
|
||||
@Override
|
||||
public void reveal(Player player) {
|
||||
boolean wasConcealed = concealedPlayers.remove(player.getUniqueId()) != null;
|
||||
publishNames();
|
||||
if (previousDisplayNames.containsKey(player.getUniqueId())) {
|
||||
player.setDisplayName(previousDisplayNames.remove(player.getUniqueId()));
|
||||
}
|
||||
restoreSleepingIgnored(player);
|
||||
Team team = scoreboard.getTeam(teamName(player.getUniqueId()));
|
||||
if (team != null) {
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package games.dmg.spigotstealth;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.RecordComponent;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.function.UnaryOperator;
|
||||
|
||||
/** Small reflective bridge: avoids a compile/runtime dependency on a specific NMS or Brigadier version. */
|
||||
final class IdentityPacketFields {
|
||||
private IdentityPacketFields() { }
|
||||
|
||||
static List<?> filterEntries(List<?> entries, StealthChatMasker masker) throws ReflectiveOperationException {
|
||||
List<Object> filtered = new ArrayList<>();
|
||||
for (Object entry : entries) {
|
||||
Method text;
|
||||
try {
|
||||
text = entry.getClass().getMethod("text");
|
||||
} catch (NoSuchMethodException exception) {
|
||||
text = entry.getClass().getMethod("getText");
|
||||
}
|
||||
if (!masker.isConcealedName((String) text.invoke(entry))) {
|
||||
filtered.add(entry);
|
||||
}
|
||||
}
|
||||
return List.copyOf(filtered);
|
||||
}
|
||||
|
||||
static Object mapRecord(Object record, UnaryOperator<Object> mapper) throws ReflectiveOperationException {
|
||||
RecordComponent[] components = record.getClass().getRecordComponents();
|
||||
if (components == null) {
|
||||
throw new IllegalArgumentException("Unsupported non-record chat binding");
|
||||
}
|
||||
Class<?>[] types = new Class<?>[components.length];
|
||||
Object[] values = new Object[components.length];
|
||||
for (int i = 0; i < components.length; i++) {
|
||||
types[i] = components[i].getType();
|
||||
Object value = components[i].getAccessor().invoke(record);
|
||||
values[i] = value instanceof Optional<?> optional ? optional.map(mapper) : mapper.apply(value);
|
||||
}
|
||||
Constructor<?> constructor = record.getClass().getDeclaredConstructor(types);
|
||||
return constructor.newInstance(values);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package games.dmg.spigotstealth;
|
||||
|
||||
import com.comphenix.protocol.PacketType;
|
||||
import com.comphenix.protocol.events.ListenerPriority;
|
||||
import com.comphenix.protocol.events.PacketAdapter;
|
||||
import com.comphenix.protocol.events.PacketContainer;
|
||||
import com.comphenix.protocol.events.PacketEvent;
|
||||
import com.comphenix.protocol.reflect.StructureModifier;
|
||||
import com.comphenix.protocol.utility.MinecraftReflection;
|
||||
import com.comphenix.protocol.wrappers.WrappedChatComponent;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
/**
|
||||
* Outgoing identity-only masking. Registration is deliberately left to the plugin.
|
||||
* The supplier must return an immutable, safely published snapshot (for example AtomicReference::get).
|
||||
* It must not inspect Bukkit players or mutable session collections on the packet thread.
|
||||
*/
|
||||
public final class ProtocolLibIdentityMaskingListener extends PacketAdapter {
|
||||
private final Supplier<Set<String>> concealedNames;
|
||||
private final Consumer<String> warningLog;
|
||||
private final Set<PacketType> warned = ConcurrentHashMap.newKeySet();
|
||||
|
||||
public ProtocolLibIdentityMaskingListener(
|
||||
Plugin plugin, Supplier<Set<String>> concealedNames, Consumer<String> warningLog) {
|
||||
// ProtocolLib calls the vanilla PLAYER_CHAT packet CHAT.
|
||||
super(plugin, ListenerPriority.HIGHEST, PacketType.Play.Server.TAB_COMPLETE,
|
||||
PacketType.Play.Server.SYSTEM_CHAT, PacketType.Play.Server.CHAT,
|
||||
PacketType.Play.Server.DISGUISED_CHAT);
|
||||
this.concealedNames = Objects.requireNonNull(concealedNames, "concealedNames");
|
||||
this.warningLog = Objects.requireNonNull(warningLog, "warningLog");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPacketSending(PacketEvent event) {
|
||||
if (event.isCancelled()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Set<String> snapshot = concealedNames.get();
|
||||
if (snapshot.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
StealthChatMasker masker = new StealthChatMasker(snapshot);
|
||||
PacketContainer packet = event.getPacket().shallowClone();
|
||||
if (event.getPacketType().equals(PacketType.Play.Server.TAB_COMPLETE)) {
|
||||
filterSuggestions(packet, masker);
|
||||
} else if (event.getPacketType().equals(PacketType.Play.Server.SYSTEM_CHAT)) {
|
||||
maskSystemChat(packet, masker);
|
||||
} else {
|
||||
maskBoundNames(packet, masker);
|
||||
}
|
||||
event.setPacket(packet);
|
||||
} catch (ReflectiveOperationException | RuntimeException exception) {
|
||||
// Keep delivery usable; do not cancel signed chat and break the acknowledgement chain.
|
||||
if (warned.add(event.getPacketType())) {
|
||||
warningLog.accept("Stealth identity masking unavailable for " + event.getPacketType()
|
||||
+ "; original packet retained. Failure: " + exception.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void filterSuggestions(PacketContainer packet, StealthChatMasker masker)
|
||||
throws ReflectiveOperationException {
|
||||
StructureModifier<Object> fields = packet.getModifier();
|
||||
for (int i = 0; i < fields.size(); i++) {
|
||||
Object value = fields.read(i);
|
||||
if (value instanceof List<?> entries) {
|
||||
// Modern ClientboundCommandSuggestionsPacket stores its Entry list directly.
|
||||
fields.write(i, IdentityPacketFields.filterEntries(entries, masker));
|
||||
return;
|
||||
}
|
||||
if (value != null && value.getClass().getName().equals("com.mojang.brigadier.suggestion.Suggestions")) {
|
||||
Object range = value.getClass().getMethod("getRange").invoke(value);
|
||||
List<?> entries = (List<?>) value.getClass().getMethod("getList").invoke(value);
|
||||
List<?> filtered = IdentityPacketFields.filterEntries(entries, masker);
|
||||
fields.write(i, value.getClass().getConstructor(range.getClass(), List.class).newInstance(range, filtered));
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Pre-Brigadier protocol compatibility.
|
||||
StructureModifier<String[]> arrays = packet.getStringArrays();
|
||||
if (arrays.size() > 0) {
|
||||
arrays.write(0, java.util.Arrays.stream(arrays.read(0))
|
||||
.filter(name -> !masker.isConcealedName(name)).toArray(String[]::new));
|
||||
return;
|
||||
}
|
||||
throw new IllegalStateException("Unsupported command suggestions layout");
|
||||
}
|
||||
|
||||
private static void maskSystemChat(PacketContainer packet, StealthChatMasker masker) {
|
||||
StructureModifier<WrappedChatComponent> components = packet.getChatComponents();
|
||||
if (components.size() > 0) {
|
||||
WrappedChatComponent original = components.read(0);
|
||||
String json = original.getJson();
|
||||
String masked = masker.maskAnnouncement(json);
|
||||
if (!json.equals(masked)) {
|
||||
components.write(0, WrappedChatComponent.fromJson(masked));
|
||||
}
|
||||
} else if (packet.getStrings().size() > 0) {
|
||||
// Older SYSTEM_CHAT represents its component as JSON text.
|
||||
String json = packet.getStrings().read(0);
|
||||
packet.getStrings().write(0, masker.maskAnnouncement(json));
|
||||
} else {
|
||||
throw new IllegalStateException("Unsupported system chat layout");
|
||||
}
|
||||
}
|
||||
|
||||
private static void maskBoundNames(PacketContainer packet, StealthChatMasker masker)
|
||||
throws ReflectiveOperationException {
|
||||
StructureModifier<Object> fields = packet.getModifier();
|
||||
for (int i = 0; i < fields.size(); i++) {
|
||||
Object value = fields.read(i);
|
||||
if (value != null && (value.getClass().getName().endsWith("ChatType$BoundNetwork")
|
||||
|| value.getClass().getName().endsWith("ChatType$Bound"))) {
|
||||
Object masked = IdentityPacketFields.mapRecord(value, field -> {
|
||||
if (field != null && MinecraftReflection.getIChatBaseComponentClass().isInstance(field)) {
|
||||
String json = WrappedChatComponent.fromHandle(field).getJson();
|
||||
String replacement = masker.maskDisplayName(json);
|
||||
return json.equals(replacement) ? field : WrappedChatComponent.fromJson(replacement).getHandle();
|
||||
}
|
||||
return field;
|
||||
});
|
||||
fields.write(i, masked);
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Intentionally never touch signed body, unsigned body, UUID, signature, or filter mask.
|
||||
throw new IllegalStateException("Unsupported player chat display-name layout");
|
||||
}
|
||||
}
|
||||
@@ -77,11 +77,14 @@ public final class SpigotStealthPlugin extends JavaPlugin {
|
||||
manager, settings.unlockThreshold(), System::nanoTime, notifier);
|
||||
sessions = new StealthSessionService(manager, progression);
|
||||
protocolManager = ProtocolLibrary.getProtocolManager();
|
||||
identityPresentation = new BukkitIdentityPresentation(
|
||||
BukkitIdentityPresentation bukkitPresentation = new BukkitIdentityPresentation(
|
||||
getServer()::getOnlinePlayers,
|
||||
Objects.requireNonNull(getServer().getScoreboardManager(), "scoreboard manager").getMainScoreboard(),
|
||||
new ProtocolLibTabListController(protocolManager),
|
||||
() -> manager.snapshot().sleepCountPolicy());
|
||||
identityPresentation = bukkitPresentation;
|
||||
protocolManager.addPacketListener(new ProtocolLibIdentityMaskingListener(
|
||||
this, bukkitPresentation::concealedNames, getLogger()::warning));
|
||||
protocolManager.addPacketListener(new ProtocolLibServerListPingListener(
|
||||
this, sessions::concealedPlayerIds, getLogger()::warning));
|
||||
getServer().getPluginManager().registerEvents(
|
||||
@@ -90,6 +93,8 @@ public final class SpigotStealthPlugin extends JavaPlugin {
|
||||
new InvisibilityEffectListener(progression, Clock.systemUTC()), this);
|
||||
getServer().getPluginManager().registerEvents(
|
||||
new StealthSessionListener(sessions, identityPresentation, settings.concealedMessage()), this);
|
||||
getServer().getPluginManager().registerEvents(
|
||||
new StealthAdminJoinListener(sessions, getServer()::getOnlinePlayers), this);
|
||||
org.bukkit.command.PluginCommand stealthPluginCommand =
|
||||
Objects.requireNonNull(getCommand("stealth"), "stealth command");
|
||||
StealthCommand stealthCommand = new StealthCommand(manager, progression, settings);
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package games.dmg.spigotstealth;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Supplier;
|
||||
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;
|
||||
|
||||
/** Private administrative notices after the HIGHEST-priority session transition. */
|
||||
public final class StealthAdminJoinListener implements Listener {
|
||||
private static final String PERMISSION = "spigotstealth.admin";
|
||||
private static final String HINT = " Use /stealthadmin list to see who.";
|
||||
private final StealthSessionService sessions;
|
||||
private final Supplier<? extends Collection<? extends Player>> onlinePlayers;
|
||||
|
||||
public StealthAdminJoinListener(
|
||||
StealthSessionService sessions,
|
||||
Supplier<? extends Collection<? extends Player>> onlinePlayers) {
|
||||
this.sessions = Objects.requireNonNull(sessions, "sessions");
|
||||
this.onlinePlayers = Objects.requireNonNull(onlinePlayers, "onlinePlayers");
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onJoin(PlayerJoinEvent event) {
|
||||
Player joining = event.getPlayer();
|
||||
Set<UUID> concealed = sessions.concealedPlayerIds();
|
||||
int count = concealed.size();
|
||||
if (count == 0) {
|
||||
return;
|
||||
}
|
||||
String quantity = count + (count == 1 ? " player is" : " players are");
|
||||
if (joining.hasPermission(PERMISSION)) {
|
||||
joining.sendMessage("[Stealth] " + quantity + " invisible." + HINT);
|
||||
}
|
||||
if (concealed.contains(joining.getUniqueId())) {
|
||||
String notice = "[Stealth] An invisible player joined. " + quantity + " now invisible." + HINT;
|
||||
for (Player observer : onlinePlayers.get()) {
|
||||
if (!observer.getUniqueId().equals(joining.getUniqueId()) && observer.hasPermission(PERMISSION)) {
|
||||
observer.sendMessage(notice);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package games.dmg.spigotstealth;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParseException;
|
||||
import com.google.gson.JsonParser;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/** Masks semantic name slots, never searching/replacing user-authored message text. */
|
||||
public final class StealthChatMasker {
|
||||
private static final Set<String> NAME_FIRST_TRANSLATIONS = Set.of(
|
||||
"chat.type.text", "chat.type.announcement", "chat.type.emote",
|
||||
"commands.message.display.incoming", "commands.message.display.outgoing",
|
||||
"chat.type.advancement.task", "chat.type.advancement.goal", "chat.type.advancement.challenge");
|
||||
private final Set<String> names;
|
||||
|
||||
public StealthChatMasker(Set<String> concealedNames) {
|
||||
names = concealedNames.stream().map(name -> name.toLowerCase(Locale.ROOT)).collect(Collectors.toUnmodifiableSet());
|
||||
}
|
||||
|
||||
public boolean isConcealedName(String text) {
|
||||
return names.contains(text.toLowerCase(Locale.ROOT));
|
||||
}
|
||||
|
||||
public String maskAnnouncement(String json) {
|
||||
try {
|
||||
JsonElement component = JsonParser.parseString(json);
|
||||
return maskAnnouncement(component) ? component.toString() : json;
|
||||
} catch (JsonParseException | IllegalStateException exception) {
|
||||
return json;
|
||||
}
|
||||
}
|
||||
|
||||
public String maskDisplayName(String json) {
|
||||
try {
|
||||
return isConcealedName(plainName(JsonParser.parseString(json))) ? anonymous().toString() : json;
|
||||
} catch (JsonParseException | IllegalStateException exception) {
|
||||
return json;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean maskAnnouncement(JsonElement component) {
|
||||
boolean changed = false;
|
||||
if (component.isJsonArray()) {
|
||||
for (JsonElement child : component.getAsJsonArray()) {
|
||||
changed |= maskAnnouncement(child);
|
||||
}
|
||||
if (changed && !component.getAsJsonArray().isEmpty()) {
|
||||
clearInheritedActions(component.getAsJsonArray().get(0));
|
||||
}
|
||||
} else if (component.isJsonObject()) {
|
||||
JsonObject object = component.getAsJsonObject();
|
||||
// Translation arguments other than the explicitly known name slot are message content.
|
||||
if (object.has("translate") && object.get("translate").isJsonPrimitive()
|
||||
&& NAME_FIRST_TRANSLATIONS.contains(object.get("translate").getAsString())
|
||||
&& object.has("with") && object.get("with").isJsonArray()) {
|
||||
JsonArray arguments = object.getAsJsonArray("with");
|
||||
if (!arguments.isEmpty() && isConcealedName(plainName(arguments.get(0)))) {
|
||||
arguments.set(0, anonymous());
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (object.has("extra")) {
|
||||
changed |= maskAnnouncement(object.get("extra"));
|
||||
}
|
||||
// Prevent masked descendants from inheriting an identifying action from their parent.
|
||||
if (changed) {
|
||||
clearInheritedActions(object);
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
private static void clearInheritedActions(JsonElement component) {
|
||||
if (component.isJsonObject()) {
|
||||
for (String key : Set.of("hoverEvent", "clickEvent", "hover_event", "click_event", "insertion")) {
|
||||
component.getAsJsonObject().remove(key);
|
||||
}
|
||||
} else if (component.isJsonArray() && !component.getAsJsonArray().isEmpty()) {
|
||||
clearInheritedActions(component.getAsJsonArray().get(0));
|
||||
}
|
||||
}
|
||||
|
||||
private static String plainName(JsonElement component) {
|
||||
if (component.isJsonPrimitive()) {
|
||||
return component.getAsString();
|
||||
}
|
||||
StringBuilder text = new StringBuilder();
|
||||
if (component.isJsonArray()) {
|
||||
for (JsonElement child : component.getAsJsonArray()) {
|
||||
text.append(plainName(child));
|
||||
}
|
||||
} else if (component.isJsonObject()) {
|
||||
JsonObject object = component.getAsJsonObject();
|
||||
if (object.has("text") && object.get("text").isJsonPrimitive()) {
|
||||
text.append(object.get("text").getAsString());
|
||||
}
|
||||
if (object.has("extra")) {
|
||||
text.append(plainName(object.get("extra")));
|
||||
}
|
||||
}
|
||||
return text.toString();
|
||||
}
|
||||
|
||||
private static JsonObject anonymous() {
|
||||
JsonObject alias = new JsonObject();
|
||||
alias.addProperty("text", "Anonymous");
|
||||
alias.addProperty("obfuscated", true);
|
||||
alias.add("hoverEvent", com.google.gson.JsonNull.INSTANCE);
|
||||
alias.add("clickEvent", com.google.gson.JsonNull.INSTANCE);
|
||||
alias.addProperty("insertion", "");
|
||||
return alias;
|
||||
}
|
||||
}
|
||||
@@ -25,10 +25,14 @@ class BukkitIdentityPresentationTest {
|
||||
BukkitIdentityPresentation presentation = new BukkitIdentityPresentation(
|
||||
() -> List.of(target), scoreboard, mock(TabListController.class));
|
||||
|
||||
when(target.getDisplayName()).thenReturn("Original Alex");
|
||||
presentation.conceal(target);
|
||||
presentation.conceal(target);
|
||||
presentation.reveal(target);
|
||||
|
||||
verify(target).setSleepingIgnored(true);
|
||||
verify(target).setDisplayName("Original Alex");
|
||||
org.junit.jupiter.api.Assertions.assertTrue(presentation.concealedNames().isEmpty());
|
||||
verify(target, org.mockito.Mockito.times(2)).setSleepingIgnored(true);
|
||||
verify(target).setSleepingIgnored(false);
|
||||
}
|
||||
|
||||
@@ -73,7 +77,7 @@ class BukkitIdentityPresentationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void concealRemovesTabEntryAndHidesNameTagWithoutHidingEntity() {
|
||||
void concealRemovesTabEntryAndScramblesNameTagWithoutHidingEntity() {
|
||||
UUID targetId = UUID.randomUUID();
|
||||
Player target = player(targetId, "Alex");
|
||||
Player observer = player(UUID.randomUUID(), "Morgan");
|
||||
@@ -87,7 +91,11 @@ class BukkitIdentityPresentationTest {
|
||||
|
||||
presentation.conceal(target);
|
||||
|
||||
verify(team).setOption(Team.Option.NAME_TAG_VISIBILITY, Team.OptionStatus.NEVER);
|
||||
verify(team).setOption(Team.Option.NAME_TAG_VISIBILITY, Team.OptionStatus.ALWAYS);
|
||||
verify(team).setPrefix("§k");
|
||||
verify(team).setSuffix("§r");
|
||||
verify(target).setDisplayName("§kAnonymous§r");
|
||||
org.junit.jupiter.api.Assertions.assertEquals(java.util.Set.of("Alex"), presentation.concealedNames());
|
||||
verify(team).addEntry("Alex");
|
||||
verify(tabLists).remove(observer, targetId);
|
||||
verify(observer, never()).hidePlayer(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any());
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package games.dmg.spigotstealth;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class IdentityPacketFieldsTest {
|
||||
private final StealthChatMasker masker = new StealthChatMasker(Set.of("Secret"));
|
||||
|
||||
record Entry(String text, Optional<String> tooltip) { }
|
||||
record Bound(int chatType, String name, Optional<String> targetName) { }
|
||||
|
||||
@Test
|
||||
void filtersModernSuggestionEntriesWithoutChangingOrdinaryEntries() throws ReflectiveOperationException {
|
||||
Entry ordinary = new Entry("Someone", Optional.of("help"));
|
||||
List<Entry> entries = List.of(new Entry("sEcReT", Optional.empty()), ordinary);
|
||||
assertEquals(List.of(ordinary), IdentityPacketFields.filterEntries(entries, masker));
|
||||
assertEquals(2, entries.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rebuildsDisplayNameRecordWithoutMutatingOriginal() throws ReflectiveOperationException {
|
||||
Bound original = new Bound(42, "Secret", Optional.of("Secret"));
|
||||
Object copy = IdentityPacketFields.mapRecord(original,
|
||||
value -> value.equals("Secret") ? "Anonymous" : value);
|
||||
assertEquals(new Bound(42, "Anonymous", Optional.of("Anonymous")), copy);
|
||||
assertEquals("Secret", original.name());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package games.dmg.spigotstealth;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import com.comphenix.protocol.PacketType;
|
||||
import com.comphenix.protocol.events.PacketEvent;
|
||||
import com.comphenix.protocol.utility.MinecraftReflection;
|
||||
import com.comphenix.protocol.utility.MinecraftVersion;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.MockedStatic;
|
||||
|
||||
class ProtocolLibIdentityMaskingListenerTest {
|
||||
private static MockedStatic<MinecraftReflection> reflection;
|
||||
|
||||
@BeforeAll
|
||||
static void initializeProtocolTypesWithoutServer() {
|
||||
MinecraftVersion.setCurrentVersion(new MinecraftVersion(1, 21, 8));
|
||||
reflection = mockStatic(MinecraftReflection.class);
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void resetProtocolEnvironment() {
|
||||
reflection.close();
|
||||
MinecraftVersion.setCurrentVersion(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void skipsPacketWorkWhenNobodyIsConcealed() {
|
||||
AtomicReference<Set<String>> names = new AtomicReference<>(Set.of());
|
||||
var listener = new ProtocolLibIdentityMaskingListener(mock(Plugin.class), names::get, ignored -> { });
|
||||
PacketEvent event = mock(PacketEvent.class);
|
||||
listener.onPacketSending(event);
|
||||
verify(event, never()).getPacket();
|
||||
assertTrue(listener.getSendingWhitelist().getTypes().contains(PacketType.Play.Server.CHAT));
|
||||
assertTrue(listener.getSendingWhitelist().getTypes().contains(PacketType.Play.Server.SYSTEM_CHAT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsFreshSnapshotAndWarnsOnceWithoutCancellingOrReplacingFailedPacket() {
|
||||
List<String> warnings = new ArrayList<>();
|
||||
AtomicReference<Set<String>> names = new AtomicReference<>(Set.of());
|
||||
var listener = new ProtocolLibIdentityMaskingListener(mock(Plugin.class), names::get, warnings::add);
|
||||
PacketEvent event = mock(PacketEvent.class);
|
||||
when(event.getPacketType()).thenReturn(PacketType.Play.Server.CHAT);
|
||||
listener.onPacketSending(event);
|
||||
assertTrue(warnings.isEmpty());
|
||||
names.set(Set.of("Secret"));
|
||||
// No real NMS packet: the clone attempt fails and must leave event delivery untouched.
|
||||
listener.onPacketSending(event);
|
||||
listener.onPacketSending(event);
|
||||
assertEquals(1, warnings.size());
|
||||
verify(event, never()).setPacket(any());
|
||||
verify(event, never()).setCancelled(anyBoolean());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package games.dmg.spigotstealth;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class StealthAdminJoinListenerTest {
|
||||
@Test
|
||||
void joiningAdminReceivesCountButExistingAdminsDoNotReceiveOrdinaryJoinNotice() {
|
||||
Player joining = player(true);
|
||||
Player existing = player(true);
|
||||
StealthSessionService sessions = sessions(Set.of(UUID.randomUUID(), UUID.randomUUID()));
|
||||
new StealthAdminJoinListener(sessions, () -> List.of(joining, existing)).onJoin(event(joining));
|
||||
verify(joining).sendMessage("[Stealth] 2 players are invisible. Use /stealthadmin list to see who.");
|
||||
verify(existing, never()).sendMessage(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void concealedJoinNotifiesOnlyAdminsWithUpdatedCount() {
|
||||
Player joining = player(false);
|
||||
Player admin = player(true);
|
||||
Player ordinary = player(false);
|
||||
StealthSessionService sessions = sessions(Set.of(joining.getUniqueId()));
|
||||
new StealthAdminJoinListener(sessions, () -> List.of(joining, admin, ordinary)).onJoin(event(joining));
|
||||
verify(admin).sendMessage("[Stealth] An invisible player joined. 1 player is now invisible. Use /stealthadmin list to see who.");
|
||||
verify(joining, never()).sendMessage(anyString());
|
||||
verify(ordinary, never()).sendMessage(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void concealedAdminGetsExactlyOneNoticeEvenWhenIncludedInOnlinePlayers() {
|
||||
Player joining = player(true);
|
||||
Player admin = player(true);
|
||||
StealthSessionService sessions = sessions(Set.of(joining.getUniqueId(), UUID.randomUUID()));
|
||||
new StealthAdminJoinListener(sessions, () -> List.of(joining, admin)).onJoin(event(joining));
|
||||
verify(joining, times(1)).sendMessage("[Stealth] 2 players are invisible. Use /stealthadmin list to see who.");
|
||||
verify(admin).sendMessage("[Stealth] An invisible player joined. 2 players are now invisible. Use /stealthadmin list to see who.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void zeroCountIsSilent() {
|
||||
Player joining = player(true);
|
||||
new StealthAdminJoinListener(sessions(Set.of()), () -> List.of(joining)).onJoin(event(joining));
|
||||
verify(joining, never()).sendMessage(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void ordinaryJoinIsSilentAndSinglePlayerCountUsesSingular() {
|
||||
Player ordinary = player(false);
|
||||
Player admin = player(true);
|
||||
StealthAdminJoinListener listener = new StealthAdminJoinListener(
|
||||
sessions(Set.of(UUID.randomUUID())), () -> List.of(ordinary, admin));
|
||||
listener.onJoin(event(ordinary));
|
||||
verify(ordinary, never()).sendMessage(anyString());
|
||||
verify(admin, never()).sendMessage(anyString());
|
||||
listener.onJoin(event(admin));
|
||||
verify(admin).sendMessage("[Stealth] 1 player is invisible. Use /stealthadmin list to see who.");
|
||||
}
|
||||
|
||||
private static StealthSessionService sessions(Set<UUID> ids) {
|
||||
StealthSessionService sessions = mock(StealthSessionService.class);
|
||||
when(sessions.concealedPlayerIds()).thenReturn(ids);
|
||||
return sessions;
|
||||
}
|
||||
|
||||
private static Player player(boolean admin) {
|
||||
Player player = mock(Player.class);
|
||||
when(player.getUniqueId()).thenReturn(UUID.randomUUID());
|
||||
when(player.hasPermission("spigotstealth.admin")).thenReturn(admin);
|
||||
return player;
|
||||
}
|
||||
|
||||
private static PlayerJoinEvent event(Player player) {
|
||||
PlayerJoinEvent event = mock(PlayerJoinEvent.class);
|
||||
when(event.getPlayer()).thenReturn(player);
|
||||
return event;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package games.dmg.spigotstealth;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import com.google.gson.JsonParser;
|
||||
import java.util.Set;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class StealthChatMaskerTest {
|
||||
private final StealthChatMasker masker = new StealthChatMasker(Set.of("Secret"));
|
||||
|
||||
@Test
|
||||
void masksSenderAndRemovesIdentityMetadataWithoutChangingMessage() {
|
||||
String input = """
|
||||
{"translate":"chat.type.text","with":[
|
||||
{"text":"Secret","hoverEvent":{"action":"show_entity","contents":{"name":"Secret"}},
|
||||
"clickEvent":{"action":"suggest_command","value":"/msg Secret "}},
|
||||
{"text":"Secret says hello","clickEvent":{"action":"copy_to_clipboard","value":"Secret"}}]}
|
||||
""";
|
||||
var result = JsonParser.parseString(masker.maskAnnouncement(input)).getAsJsonObject();
|
||||
var args = result.getAsJsonArray("with");
|
||||
assertEquals(JsonParser.parseString("{\"text\":\"Anonymous\",\"obfuscated\":true,\"hoverEvent\":null,\"clickEvent\":null,\"insertion\":\"\"}"), args.get(0));
|
||||
assertEquals(JsonParser.parseString(input).getAsJsonObject().getAsJsonArray("with").get(1), args.get(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void handlesPrivateMessagesAndAdvancementNamesOnly() {
|
||||
for (String key : Set.of("commands.message.display.incoming", "commands.message.display.outgoing",
|
||||
"chat.type.advancement.task", "chat.type.advancement.goal", "chat.type.advancement.challenge")) {
|
||||
String input = "{\"translate\":\"" + key + "\",\"with\":[\"secret\",{\"text\":\"Secret\"}]}";
|
||||
var args = JsonParser.parseString(masker.maskAnnouncement(input)).getAsJsonObject().getAsJsonArray("with");
|
||||
assertEquals("Anonymous", args.get(0).getAsJsonObject().get("text").getAsString());
|
||||
assertEquals("Secret", args.get(1).getAsJsonObject().get("text").getAsString());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotTraverseMessageBodyEvenWhenItContainsChatTranslations() {
|
||||
String input = """
|
||||
{"translate":"chat.type.text","with":["Ordinary",
|
||||
{"translate":"chat.type.text","with":["Secret","body"]}]}
|
||||
""";
|
||||
assertEquals(input, masker.maskAnnouncement(input));
|
||||
}
|
||||
|
||||
@Test
|
||||
void handlesNestedAnnouncementsButNotPlainTextOrUnknownTranslations() {
|
||||
assertTrue(masker.maskAnnouncement("{\"text\":\"\",\"extra\":[{\"translate\":\"chat.type.text\",\"with\":[\"Secret\",\"hello\"]}]}").contains("Anonymous"));
|
||||
for (String input : Set.of("{\"text\":\"Secret: hello\"}", "{\"translate\":\"custom\",\"with\":[\"Secret\"]}", "not json")) {
|
||||
assertEquals(input, masker.maskAnnouncement(input));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void removesInheritedActionsFromArrayParent() {
|
||||
String json = """
|
||||
[{"text":"","hover_event":{"action":"show_text","value":"Secret"}},
|
||||
{"translate":"chat.type.text","with":["Secret","hello"]}]
|
||||
""";
|
||||
assertFalse(masker.maskAnnouncement(json).contains("Secret"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void recognizesSplitNamesAndMasksWholeNameComponent() {
|
||||
String name = "{\"text\":\"Sec\",\"extra\":[{\"text\":\"ret\"}],\"insertion\":\"Secret\"}";
|
||||
assertTrue(masker.maskDisplayName(name).contains("Anonymous"));
|
||||
assertFalse(masker.maskDisplayName(name).contains("Secret"));
|
||||
assertEquals("\"NotSecret\"", masker.maskDisplayName("\"NotSecret\""));
|
||||
}
|
||||
}
|
||||
@@ -62,8 +62,9 @@ class StealthSessionListenerTest {
|
||||
QualifyingInvisibilityService progression = new QualifyingInvisibilityService(
|
||||
manager, Duration.ofHours(8), System::nanoTime, ignored -> { });
|
||||
IdentityPresentation presentation = mock(IdentityPresentation.class);
|
||||
StealthSessionService sessions = new StealthSessionService(manager, progression);
|
||||
StealthSessionListener listener = new StealthSessionListener(
|
||||
new StealthSessionService(manager, progression), presentation, "Stealth active");
|
||||
sessions, presentation, "Stealth active");
|
||||
Player player = player(playerId);
|
||||
PlayerJoinEvent event = mock(PlayerJoinEvent.class);
|
||||
when(event.getPlayer()).thenReturn(player);
|
||||
@@ -73,6 +74,10 @@ class StealthSessionListenerTest {
|
||||
verify(event).setJoinMessage(null);
|
||||
verify(presentation).conceal(player);
|
||||
verify(player).sendMessage("Stealth active");
|
||||
Player admin = player(UUID.randomUUID());
|
||||
when(admin.hasPermission("spigotstealth.admin")).thenReturn(true);
|
||||
new StealthAdminJoinListener(sessions, () -> java.util.List.of(player, admin)).onJoin(event);
|
||||
verify(admin).sendMessage("[Stealth] An invisible player joined. 1 player is now invisible. Use /stealthadmin list to see who.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user