6 Commits
Author SHA1 Message Date
dmg 67942ced7c feat(stealth): earn and equip the Eye of True Seeing
Release / release (push) Successful in 7m15s
CI / build (push) Successful in 2m15s
Add independent eight-hour Night Vision progression, save-gated crafting and holder eligibility, authenticated helmet items and guarded inventory movement. Verify source attribution, native item/recipe/event adapters and actual plugin lifecycle. Drain final state asynchronously and reject stale lifecycle callbacks. Per-viewer revelation remains the next story; no deployment is included.
2026-09-12 17:35:01 -04:00
dmg 74b9ac59ff test(stealth): await complete main-thread admin callbacks
Release / release (push) Successful in 3m10s
CI / build (push) Successful in 1m31s
2026-09-12 13:02:36 -04:00
dmg b7db69d010 feat(stealth): migrate distribution to Java 25 and Purpur
CI / build (push) Successful in 3m31s
Release / release (push) Failing after 3m32s
BREAKING CHANGE: New releases require Java 25/Purpur 26.2 and use purpur-stealth-<version>.jar. Runtime SpigotStealth identity, existing data and permissions remain unchanged. Replace the old JAR rather than installing both.
2026-09-12 12:43:18 -04:00
dmg d0000810c1 chore(knowledge): move canonical docs to shared SoMC wiki
CI / build (push) Successful in 3m19s
Release / release (push) Successful in 4m50s
2026-09-09 23:18:21 -04:00
dmg 1addc93062 feat(stealth): mask identities and notify admins on login
Release / release (push) Successful in 2m8s
CI / build (push) Successful in 1m6s
2026-09-06 21:19:59 -04:00
dmg 831f6a2ce4 fix(ping): support Purpur NameAndId samples
Release / release (push) Successful in 2m24s
CI / build (push) Successful in 1m42s
2026-09-05 08:58:46 -04:00
57 changed files with 2696 additions and 549 deletions
+2 -2
View File
@@ -17,7 +17,7 @@ jobs:
uses: actions/setup-java@v4 uses: actions/setup-java@v4
with: with:
distribution: temurin distribution: temurin
java-version: 17 java-version: 25
cache: gradle cache: gradle
- name: Validate conventional commits - name: Validate conventional commits
@@ -35,6 +35,6 @@ jobs:
- name: Upload development artifact - name: Upload development artifact
uses: actions/upload-artifact@v3 uses: actions/upload-artifact@v3
with: with:
name: spigot-stealth-${{ github.sha }} name: purpur-stealth-${{ github.sha }}
path: build/libs/*.jar path: build/libs/*.jar
if-no-files-found: error if-no-files-found: error
+5 -5
View File
@@ -21,7 +21,7 @@ jobs:
uses: actions/setup-java@v4 uses: actions/setup-java@v4
with: with:
distribution: temurin distribution: temurin
java-version: 17 java-version: 25
cache: gradle cache: gradle
- name: Set up Node.js - name: Set up Node.js
@@ -86,8 +86,8 @@ jobs:
if: steps.release.outputs.created == 'true' if: steps.release.outputs.created == 'true'
uses: actions/upload-artifact@v3 uses: actions/upload-artifact@v3
with: with:
name: spigot-stealth-${{ steps.release.outputs.version }} name: purpur-stealth-${{ steps.release.outputs.version }}
path: build/libs/spigot-stealth-${{ steps.release.outputs.version }}.jar path: build/libs/purpur-stealth-${{ steps.release.outputs.version }}.jar
if-no-files-found: error if-no-files-found: error
- name: Create Gitea release and upload plugin - name: Create Gitea release and upload plugin
@@ -101,7 +101,7 @@ jobs:
PREVIOUS_TAG: ${{ steps.previous_tag.outputs.value }} PREVIOUS_TAG: ${{ steps.previous_tag.outputs.value }}
run: | run: |
api_url="${GITEA_SERVER_URL}/api/v1" api_url="${GITEA_SERVER_URL}/api/v1"
jar="build/libs/spigot-stealth-${VERSION}.jar" jar="build/libs/purpur-stealth-${VERSION}.jar"
export RELEASE_BODY export RELEASE_BODY
if [ -n "$PREVIOUS_TAG" ]; then if [ -n "$PREVIOUS_TAG" ]; then
RELEASE_BODY=$(git log --pretty='format:- %s (%h)' "${PREVIOUS_TAG}..HEAD") RELEASE_BODY=$(git log --pretty='format:- %s (%h)' "${PREVIOUS_TAG}..HEAD")
@@ -138,4 +138,4 @@ jobs:
-H "Authorization: token ${GITEA_TOKEN}" \ -H "Authorization: token ${GITEA_TOKEN}" \
-H "Content-Type: application/octet-stream" \ -H "Content-Type: application/octet-stream" \
--data-binary "@${jar}" \ --data-binary "@${jar}" \
"${api_url}/repos/${REPOSITORY}/releases/${release_id}/assets?name=spigot-stealth-${VERSION}.jar" "${api_url}/repos/${REPOSITORY}/releases/${release_id}/assets?name=purpur-stealth-${VERSION}.jar"
+5 -49
View File
@@ -1,53 +1,9 @@
# Repository Agent Guidance # purpur-stealth 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/purpur-stealth/index.md`, `engineering.md` in that project section, and relevant `../somc-okf/user-stories/purpur-stealth/` 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/purpur-stealth/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. 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.
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.
+33
View File
@@ -0,0 +1,33 @@
# Purpur Stealth
Progression-gated identity concealment for Purpur 26.2 build 2618, built and tested with Java 25. ProtocolLib 5.4.0 is required.
## Build
```sh
./gradlew clean check jar
```
Artifacts are written to `build/libs/purpur-stealth-<version>.jar`. Gitea CI verifies pushes/pull requests; approved main-branch conventional commits drive versioned releases. The distribution tests inspect the built JAR, embedded version/runtime identity, Java 25 bytecode, and workflow naming.
## Eye of True Seeing
Earn a separate, personal unlock through eight cumulative online hours of Night Vision from directly drunk potions. Splash/lingering potions, commands, plugins and other sources do not count. Rejected and cosmetic-only replacements do not change attribution. Unattributed restored effects cannot inherit the drink timer; a new effective drink can start a new interval. Offline time is excluded.
After the unlock is saved, craft an **Eye of True Seeing** with eight Netherite Blocks around an Eye of Ender. Right-click an authenticated Eye in either hand to move it into an empty helmet slot. Existing helmets are not replaced. Traded Eyes still require the holder's own saved unlock; renamed ordinary Eyes do not qualify. Automated crafters cannot bypass progression. Vanilla handles crafting ingredient consumption.
**Local name/body revelation is separate US-008 work and is not implemented by this acquisition story.** Eligibility is checked even for an Eye manually placed in the helmet slot.
Eye records are independently UUID-keyed in `plugins/SpigotStealth/state.yml` (schema 2). Legacy Stealth records and extension fields are preserved. Crafting/use wait for successful save acknowledgement. Shutdown queues a final snapshot without blocking the tick thread, and initialization callbacks cannot revive a disabled or superseded lifecycle. Unacknowledged progress at abrupt process/power loss is not guaranteed.
`check` includes `nativeStealthTest`, which downloads SHA-256-pinned Purpur 2618, patches it without starting a listening server, and exercises real potion events, items, recipes, event dispatch and plugin lifecycle with external platform doubles. Live-client appearance and gameplay checks remain separate follow-ups.
## Migration compatibility
The repository and checkout are now `purpur-stealth` (previously remote `spigot-stealth`, local `spigot-invisibilty`). Runtime identity remains **SpigotStealth**, including `plugins/SpigotStealth/`, the existing Java entrypoint/packages, command names, `spigotstealth` permission/namespace identifiers, and persisted progression/session data. Java 17 is no longer supported for new builds or artifacts.
Replace the old plugin JAR when installing the new distribution; never load both JARs together. Old tags and `spigot-stealth-*` release assets are preserved. Repository rename redirects have been checked against the previously deployed v1.5.0 download. Publishing a release does not authorize deployment.
The v2.0.0 migration itself left the Eye, combat reveal and concealed-chat stories pending. Subsequent Eye acquisition work is described above; Eye revelation, combat reveal and system-chat routing remain separate unfinished stories. Runtime plugin metadata is unchanged.
See the [canonical project](https://git.garvis.dev/dmg/somc-okf/src/branch/main/projects/purpur-stealth/index.md), [stories](https://git.garvis.dev/dmg/somc-okf/src/branch/main/user-stories/purpur-stealth/index.md), and [development cycle](https://git.garvis.dev/dmg/somc-okf/src/branch/main/runbooks/development-cycle.md).
+66 -13
View File
@@ -1,3 +1,6 @@
import java.net.URI
import java.security.MessageDigest
plugins { plugins {
java java
} }
@@ -9,24 +12,25 @@ version = providers.gradleProperty("releaseVersion")
repositories { repositories {
mavenCentral() mavenCentral()
maven("https://hub.spigotmc.org/nexus/content/repositories/snapshots/") maven("https://repo.purpurmc.org/snapshots/")
} }
java { java {
toolchain { toolchain {
languageVersion = JavaLanguageVersion.of(17) languageVersion = JavaLanguageVersion.of(25)
} }
} }
tasks.withType<JavaCompile>().configureEach { tasks.withType<JavaCompile>().configureEach {
options.compilerArgs.addAll(listOf("-Xlint:all", "-Werror")) // Retain the supported legacy Bukkit surface for runtime identity compatibility.
options.compilerArgs.addAll(listOf("-Xlint:all,-deprecation,-removal", "-Werror"))
} }
dependencies { dependencies {
compileOnly("org.spigotmc:spigot-api:26.2-R0.1-SNAPSHOT") compileOnly("org.purpurmc.purpur:purpur-api:26.2.build.2618-stable")
compileOnly("net.dmulloy2:ProtocolLib:5.4.0") compileOnly("net.dmulloy2:ProtocolLib:5.4.0")
testImplementation("org.spigotmc:spigot-api:26.2-R0.1-SNAPSHOT") testImplementation("org.purpurmc.purpur:purpur-api:26.2.build.2618-stable")
testImplementation("net.dmulloy2:ProtocolLib:5.4.0") testImplementation("net.dmulloy2:ProtocolLib:5.4.0")
testImplementation(platform("org.junit:junit-bom:5.13.4")) testImplementation(platform("org.junit:junit-bom:5.13.4"))
testImplementation("org.junit.jupiter:junit-jupiter") testImplementation("org.junit.jupiter:junit-jupiter")
@@ -37,8 +41,65 @@ dependencies {
tasks.test { tasks.test {
useJUnitPlatform() useJUnitPlatform()
dependsOn(tasks.jar)
systemProperty("distribution.jar", tasks.jar.get().archiveFile.get().asFile.absolutePath)
systemProperty("distribution.version", project.version.toString())
} }
// Exercise real potion events, item components and recipes without starting a listening server.
val stealthRuntime = layout.buildDirectory.dir("stealth-runtime")
val downloadStealthRuntime = tasks.register("downloadStealthRuntime") {
val launcher = stealthRuntime.map { it.file("purpur-26.2-2618.jar") }
outputs.file(launcher)
doLast {
val file = launcher.get().asFile
file.parentFile.mkdirs()
val connection = URI("https://api.purpurmc.org/v2/purpur/26.2/2618/download").toURL().openConnection()
connection.connectTimeout = 30_000
connection.readTimeout = 120_000
val bytes = connection.getInputStream().use { it.readBytes() }
val digest = MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }
check(digest == "4a32d046a118804d89ca74ba89b798c98f6d8d1f310c18077ac573597049de31") {
"Purpur 2618 checksum mismatch"
}
file.writeBytes(bytes)
}
}
val prepareStealthRuntime = tasks.register<JavaExec>("prepareStealthRuntime") {
dependsOn(downloadStealthRuntime)
javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) }
classpath = files(stealthRuntime.map { it.file("purpur-26.2-2618.jar") })
mainClass = "io.papermc.paperclip.Main"
jvmArgs("-Dpaperclip.patchonly=true")
workingDir(stealthRuntime)
outputs.dir(stealthRuntime.map { it.dir("versions") })
outputs.dir(stealthRuntime.map { it.dir("libraries") })
}
val nativeTest = sourceSets.create("nativeTest")
dependencies {
add(nativeTest.implementationConfigurationName, platform("org.junit:junit-bom:5.13.4"))
add(nativeTest.implementationConfigurationName, "org.junit.jupiter:junit-jupiter")
add(nativeTest.implementationConfigurationName, "org.mockito:mockito-core:5.18.0")
add(nativeTest.implementationConfigurationName, "net.dmulloy2:ProtocolLib:5.4.0")
add(nativeTest.compileOnlyConfigurationName, "org.jetbrains:annotations:26.0.2")
add(nativeTest.compileOnlyConfigurationName, "org.checkerframework:checker-qual:3.49.2")
add(nativeTest.runtimeOnlyConfigurationName, "org.junit.platform:junit-platform-launcher")
}
val nativeRuntimeJars = files(fileTree(stealthRuntime) {
include("versions/**/*.jar", "libraries/**/*.jar")
}).builtBy(prepareStealthRuntime)
nativeTest.compileClasspath += sourceSets.main.get().output + nativeRuntimeJars
nativeTest.runtimeClasspath += sourceSets.main.get().output + nativeRuntimeJars
val nativeStealthTest = tasks.register<Test>("nativeStealthTest") {
description = "Runs native Purpur adapter regressions without starting a server"
testClassesDirs = nativeTest.output.classesDirs
classpath = nativeTest.runtimeClasspath
useJUnitPlatform()
maxHeapSize = "1G"
workingDir(stealthRuntime)
}
tasks.check { dependsOn(nativeStealthTest) }
val pluginVersion = version val pluginVersion = version
tasks.processResources { tasks.processResources {
@@ -46,11 +107,3 @@ tasks.processResources {
expand("version" to pluginVersion) expand("version" to pluginVersion)
} }
} }
tasks.register<Exec>("validateOkf") {
commandLine("./scripts/validate-okf.sh")
}
tasks.check {
dependsOn("validateOkf")
}
-12
View File
@@ -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.
-32
View File
@@ -1,32 +0,0 @@
# Spigot Stealth Design Log
## 2026-09-05
- **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.
-8
View File
@@ -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,46 +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] 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, public server-list count and sample filtering, 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)
-23
View File
@@ -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
-111
View File
@@ -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
+1 -1
View File
@@ -1 +1 @@
rootProject.name = "spigot-stealth" rootProject.name = "purpur-stealth"
@@ -18,6 +18,18 @@ public final class BukkitIdentityPresentation implements IdentityPresentation {
private final Supplier<SleepCountPolicy> sleepCountPolicy; private final Supplier<SleepCountPolicy> sleepCountPolicy;
private final Map<UUID, Player> concealedPlayers = new LinkedHashMap<>(); private final Map<UUID, Player> concealedPlayers = new LinkedHashMap<>();
private final Map<UUID, Boolean> previousSleepingIgnored = 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( public BukkitIdentityPresentation(
Supplier<? extends Collection<? extends Player>> onlinePlayers, Supplier<? extends Collection<? extends Player>> onlinePlayers,
@@ -40,12 +52,17 @@ public final class BukkitIdentityPresentation implements IdentityPresentation {
@Override @Override
public void conceal(Player player) { public void conceal(Player player) {
concealedPlayers.put(player.getUniqueId(), player); concealedPlayers.put(player.getUniqueId(), player);
publishNames();
previousDisplayNames.putIfAbsent(player.getUniqueId(), player.getDisplayName());
player.setDisplayName("§kAnonymous§r");
applySleepCountPolicy(player); applySleepCountPolicy(player);
Team team = scoreboard.getTeam(teamName(player.getUniqueId())); Team team = scoreboard.getTeam(teamName(player.getUniqueId()));
if (team == null) { if (team == null) {
team = scoreboard.registerNewTeam(teamName(player.getUniqueId())); 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()); team.addEntry(player.getName());
for (Player observer : onlinePlayers.get()) { for (Player observer : onlinePlayers.get()) {
if (!observer.getUniqueId().equals(player.getUniqueId())) { if (!observer.getUniqueId().equals(player.getUniqueId())) {
@@ -57,6 +74,10 @@ public final class BukkitIdentityPresentation implements IdentityPresentation {
@Override @Override
public void reveal(Player player) { public void reveal(Player player) {
boolean wasConcealed = concealedPlayers.remove(player.getUniqueId()) != null; boolean wasConcealed = concealedPlayers.remove(player.getUniqueId()) != null;
publishNames();
if (previousDisplayNames.containsKey(player.getUniqueId())) {
player.setDisplayName(previousDisplayNames.remove(player.getUniqueId()));
}
restoreSleepingIgnored(player); restoreSleepingIgnored(player);
Team team = scoreboard.getTeam(teamName(player.getUniqueId())); Team team = scoreboard.getTeam(teamName(player.getUniqueId()));
if (team != null) { if (team != null) {
@@ -0,0 +1,66 @@
package games.dmg.spigotstealth;
import java.util.Objects;
import org.bukkit.Keyed;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.PrepareItemCraftEvent;
import org.bukkit.inventory.ShapedRecipe;
/** Personal crafting unlock for the transferable Eye. Vanilla owns ingredient consumption. */
public final class EyeCrafting implements Listener {
public static final NamespacedKey RECIPE_KEY = new NamespacedKey("spigotstealth", "eye_of_true_seeing");
private final EyeItems items;
private final EyeProgressionService progression;
public EyeCrafting(EyeProgressionService progression, EyeItems items) {
this.progression = Objects.requireNonNull(progression, "progression");
this.items = Objects.requireNonNull(items, "items");
}
public ShapedRecipe recipe() {
return new ShapedRecipe(RECIPE_KEY, items.create()).shape("NNN", "NEN", "NNN")
.setIngredient('N', Material.NETHERITE_BLOCK).setIngredient('E', Material.ENDER_EYE);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onCraft(org.bukkit.event.inventory.CraftItemEvent event) {
if (event.isCancelled() || !matches(event.getRecipe())) { return; }
if (!(event.getWhoClicked() instanceof Player player) || !progression.isUnlocked(player.getUniqueId())
|| !accepts(event.getInventory().getMatrix()) || !items.isEye(event.getInventory().getResult())
|| event.getInventory().getResult().getAmount() != 1) {
event.setCancelled(true);
event.getInventory().setResult(null);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onCrafter(org.bukkit.event.block.CrafterCraftEvent event) {
if (matches(event.getRecipe())) { event.setCancelled(true); }
}
private static boolean matches(org.bukkit.inventory.Recipe recipe) {
return recipe instanceof Keyed keyed && RECIPE_KEY.equals(keyed.getKey());
}
private static boolean accepts(org.bukkit.inventory.ItemStack[] matrix) {
if (matrix.length != 9) { return false; }
for (int index = 0; index < matrix.length; index++) {
if (matrix[index] == null || matrix[index].getAmount() <= 0
|| matrix[index].getType() != (index == 4 ? Material.ENDER_EYE : Material.NETHERITE_BLOCK)) { return false; }
}
return true;
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPrepare(PrepareItemCraftEvent event) {
if (!(event.getInventory().getRecipe() instanceof Keyed keyed) || !RECIPE_KEY.equals(keyed.getKey())) { return; }
if (!(event.getView().getPlayer() instanceof Player player) || !progression.isUnlocked(player.getUniqueId())) {
event.getInventory().setResult(null);
}
}
}
@@ -0,0 +1,47 @@
package games.dmg.spigotstealth;
import java.util.Objects;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.EquipmentSlot;
/** Player-specific eligibility and inventory movement; never invokes native Ender Eye use. */
public final class EyeEquipment implements Listener {
private final EyeProgressionService progression;
private final EyeItems items;
public EyeEquipment(EyeProgressionService progression, EyeItems items) {
this.progression = Objects.requireNonNull(progression, "progression");
this.items = Objects.requireNonNull(items, "items");
}
public boolean isEligibleWearer(Player player) {
return progression.isUnlocked(player.getUniqueId()) && items.isEye(player.getInventory().getHelmet());
}
// Interact-in-air may start with block use denied; respect item-use denial rather than isCancelled().
@EventHandler(priority = EventPriority.HIGHEST)
public void onUse(PlayerInteractEvent event) {
if (!event.getAction().isRightClick() || event.useItemInHand() == Event.Result.DENY || !items.isEye(event.getItem())) { return; }
event.setUseItemInHand(Event.Result.DENY);
event.setUseInteractedBlock(Event.Result.DENY);
Player player = event.getPlayer();
if (player.isDead() || !progression.isUnlocked(player.getUniqueId())
|| (event.getHand() != EquipmentSlot.HAND && event.getHand() != EquipmentSlot.OFF_HAND)) { return; }
var inventory = player.getInventory();
var helmet = inventory.getHelmet();
if (helmet != null && helmet.getAmount() > 0 && !helmet.getType().isAir()) { return; }
var held = inventory.getItem(event.getHand());
if (!items.isEye(held)) { return; }
var equipped = held.clone();
equipped.setAmount(1);
var remaining = held.clone();
remaining.setAmount(held.getAmount() - 1);
inventory.setItem(event.getHand(), remaining.getAmount() == 0 ? null : remaining);
inventory.setHelmet(equipped);
}
}
@@ -0,0 +1,34 @@
package games.dmg.spigotstealth;
import net.kyori.adventure.text.Component;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.bukkit.persistence.PersistentDataType;
/** Creates and identifies the transferable Eye; eligibility belongs to the holder's durable progression. */
public final class EyeItems {
private static final NamespacedKey IDENTITY = new NamespacedKey("spigotstealth", "eye_of_true_seeing");
public ItemStack create() {
var eye = new ItemStack(Material.ENDER_EYE);
var meta = eye.getItemMeta();
meta.displayName(Component.text("Eye of True Seeing"));
meta.getPersistentDataContainer().set(IDENTITY, PersistentDataType.BYTE, (byte) 1);
meta.setMaxStackSize(1);
var equippable = meta.getEquippable();
equippable.setSlot(EquipmentSlot.HEAD);
equippable.setDispensable(false);
equippable.setEquipOnInteract(false);
equippable.setDamageOnHurt(false);
meta.setEquippable(equippable);
eye.setItemMeta(meta);
return eye;
}
public boolean isEye(ItemStack item) {
return item != null && item.getAmount() > 0 && item.getType() == Material.ENDER_EYE && item.hasItemMeta()
&& Byte.valueOf((byte) 1).equals(item.getItemMeta().getPersistentDataContainer().get(IDENTITY, PersistentDataType.BYTE));
}
}
@@ -0,0 +1,101 @@
package games.dmg.spigotstealth;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.function.Function;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityPotionEffectEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
/** Night Vision potion-event adapter; progression and persistence are owned by the service. */
public final class EyePotionListener implements Listener {
private final EyeProgressionService progression;
private final Consumer<Throwable> saveFailure;
private final Map<UUID, PotionEffect> expectedEffects = new HashMap<>();
public EyePotionListener(EyeProgressionService progression, Consumer<Throwable> saveFailure) {
this.progression = Objects.requireNonNull(progression, "progression");
this.saveFailure = Objects.requireNonNull(saveFailure, "saveFailure");
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPotionEffect(EntityPotionEffectEvent event) {
if (event.isCancelled() || !(event.getEntity() instanceof Player player)
|| !PotionEffectType.NIGHT_VISION.equals(event.getModifiedType())) {
return;
}
if (event.getAction() == EntityPotionEffectEvent.Action.CHANGED && !replacesActiveEffect(event)) {
return;
}
boolean addedOrChanged = event.getAction() == EntityPotionEffectEvent.Action.ADDED
|| event.getAction() == EntityPotionEffectEvent.Action.CHANGED;
if (addedOrChanged && event.getCause() == EntityPotionEffectEvent.Cause.POTION_DRINK) {
if (!continuesEffect(expectedEffects.get(player.getUniqueId()), event.getOldEffect())) {
progression.abandon(player.getUniqueId());
}
expectedEffects.put(player.getUniqueId(), event.getNewEffect());
observe(progression.begin(player.getUniqueId()));
} else {
finish(player.getUniqueId(), event.getOldEffect());
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onQuit(PlayerQuitEvent event) {
finish(event.getPlayer().getUniqueId(), event.getPlayer().getPotionEffect(PotionEffectType.NIGHT_VISION));
}
/** Server-thread observation; a missing/unattributed effect cannot inherit an old drink interval. */
public void checkpoint(Function<UUID, Player> onlinePlayer) {
for (var id : progression.activePlayerIds()) {
Player player = onlinePlayer.apply(id);
var actual = player == null || !player.isOnline() || player.isDead()
? null : player.getPotionEffect(PotionEffectType.NIGHT_VISION);
var expected = expectedEffects.get(id);
if (!continuesEffect(expected, actual) || (!actual.isInfinite() && actual.getDuration() <= 0)) {
expectedEffects.remove(id);
progression.abandon(id); // Discard the unobserved tail, never attribute it to the old source.
} else {
expectedEffects.put(id, actual);
observe(progression.checkpoint(id));
}
}
}
private void finish(UUID id, PotionEffect finalEffect) {
var expected = expectedEffects.remove(id);
if (continuesEffect(expected, finalEffect)) { observe(progression.stop(id)); }
else { progression.abandon(id); }
}
private static boolean continuesEffect(PotionEffect expected, PotionEffect actual) {
return actual != null && expected != null && actual.getAmplifier() == expected.getAmplifier()
&& (expected.isInfinite() ? actual.isInfinite()
: !actual.isInfinite() && actual.getDuration() <= expected.getDuration());
}
private void observe(CompletableFuture<Void> saved) {
saved.whenComplete((ignored, failure) -> {
if (failure != null) { saveFailure.accept(failure); }
});
}
private static boolean replacesActiveEffect(EntityPotionEffectEvent event) {
if (!event.isOverride() || event.getOldEffect() == null || event.getNewEffect() == null) { return false; }
var previous = event.getOldEffect();
var next = event.getNewEffect();
// Native update can return true for particles/icons alone. Hidden weaker effects are not active yet.
return next.getAmplifier() > previous.getAmplifier()
|| (next.getAmplifier() == previous.getAmplifier() && !previous.isInfinite()
&& (next.isInfinite() || next.getDuration() > previous.getDuration()));
}
}
@@ -0,0 +1,13 @@
package games.dmg.spigotstealth;
import java.util.Map;
/** Independent durable Eye of True Seeing progress. Active potion intervals are never resumed from disk. */
public record EyeProgress(long accumulatedMillis, boolean unlocked, Map<String, Object> unknownFields) {
public EyeProgress {
if (accumulatedMillis < 0) { throw new IllegalArgumentException("Eye progress cannot be negative"); }
unknownFields = Map.copyOf(unknownFields);
}
public EyeProgress(long accumulatedMillis, boolean unlocked) { this(accumulatedMillis, unlocked, Map.of()); }
public static EyeProgress empty() { return new EyeProgress(0, false); }
}
@@ -0,0 +1,73 @@
package games.dmg.spigotstealth;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.LongSupplier;
/** Server-thread qualifying intervals; durable rewards are acknowledged by the existing I/O executor. */
public final class EyeProgressionService {
public static final Duration UNLOCK_THRESHOLD = Duration.ofHours(8);
private record Interval(long startedNanos, long creditedMillis) { }
private final StealthStateManager states;
private final LongSupplier nanoTime;
private final Consumer<UUID> unlocked;
private final Map<UUID, Interval> active = new HashMap<>();
private final Set<UUID> announced = ConcurrentHashMap.newKeySet();
/** The notification callback must marshal Bukkit work onto the server thread. */
public EyeProgressionService(StealthStateManager states, LongSupplier nanoTime, Consumer<UUID> unlocked) {
this.states = Objects.requireNonNull(states, "states");
this.nanoTime = Objects.requireNonNull(nanoTime, "nanoTime");
this.unlocked = Objects.requireNonNull(unlocked, "unlocked");
states.durableSnapshot().eyes().forEach((id, progress) -> {
if (progress.unlocked()) { announced.add(id); }
});
}
public CompletableFuture<Void> begin(UUID id) {
Objects.requireNonNull(id, "id");
if (active.containsKey(id)) { return checkpoint(id); }
active.put(id, new Interval(nanoTime.getAsLong(), 0));
return CompletableFuture.completedFuture(null);
}
public CompletableFuture<Void> checkpoint(UUID id) {
Interval interval = active.get(id);
if (interval == null) { return CompletableFuture.completedFuture(null); }
// Keep the original start: repeated checkpoints must not discard fractional milliseconds.
long total = Math.max(interval.creditedMillis(), Math.max(0, nanoTime.getAsLong() - interval.startedNanos()) / 1_000_000);
long elapsed = total - interval.creditedMillis();
if (elapsed == 0) { return CompletableFuture.completedFuture(null); }
active.put(id, new Interval(interval.startedNanos(), total));
return states.update(state -> {
EyeProgress previous = state.eyeProgress(id);
long accumulated = Math.addExact(previous.accumulatedMillis(), elapsed);
return state.withEyeProgress(id, new EyeProgress(accumulated,
previous.unlocked() || accumulated >= UNLOCK_THRESHOLD.toMillis(), previous.unknownFields()));
}).thenRun(() -> {
if (isUnlocked(id) && announced.add(id)) { unlocked.accept(id); }
});
}
public CompletableFuture<Void> stop(UUID id) {
CompletableFuture<Void> saved = checkpoint(id);
active.remove(id);
return saved;
}
public CompletableFuture<Void> stopAll() {
return CompletableFuture.allOf(activePlayerIds().stream().map(this::stop).toArray(CompletableFuture[]::new));
}
/** Defensive offline sweep: do not invent credit for the unobserved interval after the last checkpoint. */
public void abandon(UUID id) { active.remove(id); }
public boolean isUnlocked(UUID id) { return states.durableSnapshot().eyeProgress(id).unlocked(); }
public Set<UUID> activePlayerIds() { return Set.copyOf(active.keySet()); }
}
@@ -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);
}
}
@@ -9,11 +9,18 @@ import java.util.UUID;
public record PersistentStealthState( public record PersistentStealthState(
Map<UUID, PlayerStealthState> players, Map<UUID, PlayerStealthState> players,
SleepCountPolicy sleepCountPolicy, SleepCountPolicy sleepCountPolicy,
Map<String, Object> unknownFields) { Map<String, Object> unknownFields,
Map<UUID, EyeProgress> eyes) {
public PersistentStealthState { public PersistentStealthState {
players = Map.copyOf(new LinkedHashMap<>(Objects.requireNonNull(players, "players"))); players = Map.copyOf(new LinkedHashMap<>(Objects.requireNonNull(players, "players")));
Objects.requireNonNull(sleepCountPolicy, "sleepCountPolicy"); Objects.requireNonNull(sleepCountPolicy, "sleepCountPolicy");
unknownFields = Map.copyOf(new LinkedHashMap<>(Objects.requireNonNull(unknownFields, "unknownFields"))); unknownFields = Map.copyOf(new LinkedHashMap<>(Objects.requireNonNull(unknownFields, "unknownFields")));
eyes = Map.copyOf(Objects.requireNonNull(eyes, "eyes"));
}
public PersistentStealthState(Map<UUID, PlayerStealthState> players, SleepCountPolicy sleepCountPolicy,
Map<String, Object> unknownFields) {
this(players, sleepCountPolicy, unknownFields, Map.of());
} }
public PersistentStealthState( public PersistentStealthState(
@@ -22,6 +29,14 @@ public record PersistentStealthState(
this(players, SleepCountPolicy.EXCLUDE, unknownFields); this(players, SleepCountPolicy.EXCLUDE, unknownFields);
} }
public EyeProgress eyeProgress(UUID playerId) { return eyes.getOrDefault(playerId, EyeProgress.empty()); }
public PersistentStealthState withEyeProgress(UUID playerId, EyeProgress progress) {
Map<UUID, EyeProgress> updated = new LinkedHashMap<>(eyes);
updated.put(playerId, progress);
return new PersistentStealthState(players, sleepCountPolicy, unknownFields, updated);
}
public PlayerStealthState player(UUID playerId) { public PlayerStealthState player(UUID playerId) {
return players.getOrDefault(playerId, PlayerStealthState.empty(playerId)); return players.getOrDefault(playerId, PlayerStealthState.empty(playerId));
} }
@@ -29,10 +44,10 @@ public record PersistentStealthState(
public PersistentStealthState withPlayer(PlayerStealthState player) { public PersistentStealthState withPlayer(PlayerStealthState player) {
Map<UUID, PlayerStealthState> updated = new LinkedHashMap<>(players); Map<UUID, PlayerStealthState> updated = new LinkedHashMap<>(players);
updated.put(player.playerId(), player); updated.put(player.playerId(), player);
return new PersistentStealthState(updated, sleepCountPolicy, unknownFields); return new PersistentStealthState(updated, sleepCountPolicy, unknownFields, eyes);
} }
public PersistentStealthState withSleepCountPolicy(SleepCountPolicy policy) { public PersistentStealthState withSleepCountPolicy(SleepCountPolicy policy) {
return new PersistentStealthState(players, policy, unknownFields); return new PersistentStealthState(players, policy, unknownFields, eyes);
} }
} }
@@ -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");
}
}
@@ -3,42 +3,35 @@ package games.dmg.spigotstealth;
import com.comphenix.protocol.PacketType; import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.events.PacketAdapter; import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketEvent; import com.comphenix.protocol.events.PacketEvent;
import com.comphenix.protocol.wrappers.WrappedGameProfile;
import com.comphenix.protocol.wrappers.WrappedServerPing; import com.comphenix.protocol.wrappers.WrappedServerPing;
import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.Supplier; import java.util.function.Supplier;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
/** Rewrites outgoing server-list responses without changing actual online-player state. */ /** Adjusts only the count in outgoing server-list responses through ProtocolLib. */
public final class ProtocolLibServerListPingListener extends PacketAdapter { public final class ProtocolLibServerListPingListener extends PacketAdapter {
private final Supplier<Set<UUID>> concealedPlayerIds; private final Supplier<Set<UUID>> concealedPlayerIds;
private final ServerPingCompatibilityGuard compatibilityGuard;
public ProtocolLibServerListPingListener(Plugin plugin, Supplier<Set<UUID>> concealedPlayerIds) { public ProtocolLibServerListPingListener(
Plugin plugin,
Supplier<Set<UUID>> concealedPlayerIds,
Consumer<String> warningLog) {
super(plugin, PacketType.Status.Server.SERVER_INFO); super(plugin, PacketType.Status.Server.SERVER_INFO);
this.concealedPlayerIds = Objects.requireNonNull(concealedPlayerIds, "concealedPlayerIds"); this.concealedPlayerIds = Objects.requireNonNull(concealedPlayerIds, "concealedPlayerIds");
this.compatibilityGuard = new ServerPingCompatibilityGuard(warningLog);
} }
@Override @Override
public void onPacketSending(PacketEvent event) { public void onPacketSending(PacketEvent event) {
WrappedServerPing visiblePing = event.getPacket().getServerPings().read(0).deepClone(); compatibilityGuard.run(() -> {
boolean sampleVisible = visiblePing.isPlayersVisible(); WrappedServerPing ping = event.getPacket().getServerPings().read(0);
List<WrappedGameProfile> sample = sampleVisible ? visiblePing.getPlayers() : List.of(); int visiblePlayers = ServerListPingVisibility.visibleOnlineCount(
Set<UUID> concealed = concealedPlayerIds.get(); ping.getPlayersOnline(), concealedPlayerIds.get().size());
ServerListPingVisibility.Snapshot visible = ServerListPingVisibility.adjust( ping.setPlayersOnline(visiblePlayers);
visiblePing.getPlayersOnline(), });
visiblePing.getPlayersMaximum(),
sample.stream().map(WrappedGameProfile::getUUID).toList(),
concealed);
Set<UUID> visibleSampleIds = Set.copyOf(visible.samplePlayerIds());
visiblePing.setPlayersOnline(visible.playersOnline());
if (sampleVisible) {
visiblePing.setPlayers(sample.stream()
.filter(profile -> visibleSampleIds.contains(profile.getUUID()))
.toList());
}
event.getPacket().getServerPings().write(0, visiblePing);
} }
} }
@@ -0,0 +1,32 @@
package games.dmg.spigotstealth;
import java.util.Iterator;
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.server.ServerListPingEvent;
/** Filters concealed players through Bukkit's native server-list sample representation. */
public final class ServerListPingListener implements Listener {
private final Supplier<Set<UUID>> concealedPlayerIds;
public ServerListPingListener(Supplier<Set<UUID>> concealedPlayerIds) {
this.concealedPlayerIds = Objects.requireNonNull(concealedPlayerIds, "concealedPlayerIds");
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onServerListPing(ServerListPingEvent event) {
Set<UUID> concealed = concealedPlayerIds.get();
Iterator<Player> sample = event.iterator();
while (sample.hasNext()) {
if (concealed.contains(sample.next().getUniqueId())) {
sample.remove();
}
}
}
}
@@ -20,11 +20,15 @@ public final class ServerListPingVisibility {
.filter(playerId -> !concealedPlayerIds.contains(playerId)) .filter(playerId -> !concealedPlayerIds.contains(playerId))
.toList(); .toList();
return new Snapshot( return new Snapshot(
Math.max(0, playersOnline - concealedPlayerIds.size()), visibleOnlineCount(playersOnline, concealedPlayerIds.size()),
playersMaximum, playersMaximum,
visibleSample); visibleSample);
} }
public static int visibleOnlineCount(int playersOnline, int concealedPlayers) {
return Math.max(0, playersOnline - concealedPlayers);
}
public record Snapshot(int playersOnline, int playersMaximum, List<UUID> samplePlayerIds) { public record Snapshot(int playersOnline, int playersMaximum, List<UUID> samplePlayerIds) {
public Snapshot { public Snapshot {
samplePlayerIds = List.copyOf(samplePlayerIds); samplePlayerIds = List.copyOf(samplePlayerIds);
@@ -0,0 +1,26 @@
package games.dmg.spigotstealth;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
/** Keeps an incompatible server-ping adapter from breaking responses or flooding logs. */
public final class ServerPingCompatibilityGuard {
private final Consumer<String> warningLog;
private final AtomicBoolean warningLogged = new AtomicBoolean();
public ServerPingCompatibilityGuard(Consumer<String> warningLog) {
this.warningLog = Objects.requireNonNull(warningLog, "warningLog");
}
public void run(Runnable edit) {
try {
edit.run();
} catch (RuntimeException exception) {
if (warningLogged.compareAndSet(false, true)) {
warningLog.accept("Unable to adjust the public server-list player count; "
+ "the original response will be used: " + exception.getMessage());
}
}
}
}
@@ -12,14 +12,20 @@ import org.bukkit.plugin.java.JavaPlugin;
/** Bukkit entry point for Spigot Stealth. */ /** Bukkit entry point for Spigot Stealth. */
public final class SpigotStealthPlugin extends JavaPlugin { public final class SpigotStealthPlugin extends JavaPlugin {
private CompletableFuture<StealthStateManager> stateManagerFuture; private CompletableFuture<StealthStateManager> stateManagerFuture;
private CompletableFuture<Void> shutdown;
private volatile long lifecycleEpoch;
private StealthSettings settings; private StealthSettings settings;
private QualifyingInvisibilityService progression; private QualifyingInvisibilityService progression;
private StealthSessionService sessions; private StealthSessionService sessions;
private IdentityPresentation identityPresentation; private IdentityPresentation identityPresentation;
private ProtocolManager protocolManager; private ProtocolManager protocolManager;
private EyeProgressionService eyeProgression;
private EyePotionListener eyePotions;
private boolean eyeRecipeRegistered;
@Override @Override
public void onEnable() { public void onEnable() {
long epoch = ++lifecycleEpoch;
saveDefaultConfig(); saveDefaultConfig();
try { try {
settings = StealthSettings.from(getConfig().getValues(true)); settings = StealthSettings.from(getConfig().getValues(true));
@@ -30,45 +36,73 @@ public final class SpigotStealthPlugin extends JavaPlugin {
} }
Path stateFile = getDataFolder().toPath().resolve("state.yml"); Path stateFile = getDataFolder().toPath().resolve("state.yml");
stateManagerFuture = StealthStateManager.load(new YamlStealthStateRepository(stateFile)); stateManagerFuture = shutdownCompletion().thenCompose(ignored ->
StealthStateManager.load(new YamlStealthStateRepository(stateFile)));
stateManagerFuture.whenComplete((manager, failure) -> { stateManagerFuture.whenComplete((manager, failure) -> {
if (failure != null) { if (failure != null) {
getLogger().severe("Unable to load Spigot Stealth state: " + rootMessage(failure)); getLogger().severe("Unable to load Spigot Stealth state: " + rootMessage(failure));
getServer().getScheduler().runTask(this, () -> getServer().getPluginManager().disablePlugin(this)); onServer(epoch, () -> getServer().getPluginManager().disablePlugin(this));
return; return;
} }
getServer().getScheduler().runTask(this, () -> finishInitialization(manager)); if (!isEnabled() || epoch != lifecycleEpoch) {
logSaveFailure(manager.closeAsync());
return;
}
try {
getServer().getScheduler().runTask(this, () -> {
if (!isEnabled() || epoch != lifecycleEpoch) { logSaveFailure(manager.closeAsync()); }
else { finishInitialization(manager, epoch); }
});
} catch (org.bukkit.plugin.IllegalPluginAccessException ignored) {
logSaveFailure(manager.closeAsync());
}
}); });
} }
@Override @Override
public void onDisable() { public void onDisable() {
if (protocolManager != null) { ++lifecycleEpoch;
protocolManager.removePacketListeners(this); try {
if (eyePotions != null) {
eyePotions.checkpoint(getServer()::getPlayer);
logSaveFailure(eyeProgression.stopAll());
} }
if (progression != null) { logSaveFailure(progression.stopAll()); }
if (protocolManager != null) { protocolManager.removePacketListeners(this); }
if (identityPresentation != null && sessions != null) { if (identityPresentation != null && sessions != null) {
for (org.bukkit.entity.Player player : getServer().getOnlinePlayers()) { for (org.bukkit.entity.Player player : getServer().getOnlinePlayers()) {
if (sessions.isConcealed(player.getUniqueId())) { if (sessions.isConcealed(player.getUniqueId())) {
identityPresentation.reveal(player); try { identityPresentation.reveal(player); }
sessions.endConcealment(player.getUniqueId()); finally { logSaveFailure(sessions.endConcealment(player.getUniqueId())); }
} }
} }
} }
if (progression != null) { } finally {
progression.stopAll().join(); try {
if (eyeRecipeRegistered) {
getServer().removeRecipe(EyeCrafting.RECIPE_KEY);
eyeRecipeRegistered = false;
} }
if (stateManagerFuture != null && stateManagerFuture.isDone() && !stateManagerFuture.isCompletedExceptionally()) { } finally {
stateManagerFuture.join().close(); if (stateManagerFuture != null) {
shutdown = stateManagerFuture.thenCompose(StealthStateManager::closeAsync);
logSaveFailure(shutdown);
} }
} }
}
}
/** Durable shutdown acknowledgement; never wait for it on the server thread. */
CompletableFuture<Void> shutdownCompletion() {
return shutdown == null ? CompletableFuture.completedFuture(null) : shutdown;
}
public StealthSettings settings() { public StealthSettings settings() {
return settings; return settings;
} }
private void finishInitialization(StealthStateManager manager) { private void finishInitialization(StealthStateManager manager, long epoch) {
java.util.function.Consumer<Runnable> mainThread = java.util.function.Consumer<Runnable> mainThread = runnable -> onServer(epoch, runnable);
runnable -> getServer().getScheduler().runTask(this, runnable);
BukkitUnlockNotifier notifier = new BukkitUnlockNotifier( BukkitUnlockNotifier notifier = new BukkitUnlockNotifier(
getServer()::getPlayer, getServer()::getPlayer,
mainThread, mainThread,
@@ -77,17 +111,24 @@ public final class SpigotStealthPlugin extends JavaPlugin {
manager, settings.unlockThreshold(), System::nanoTime, notifier); manager, settings.unlockThreshold(), System::nanoTime, notifier);
sessions = new StealthSessionService(manager, progression); sessions = new StealthSessionService(manager, progression);
protocolManager = ProtocolLibrary.getProtocolManager(); protocolManager = ProtocolLibrary.getProtocolManager();
identityPresentation = new BukkitIdentityPresentation( BukkitIdentityPresentation bukkitPresentation = new BukkitIdentityPresentation(
getServer()::getOnlinePlayers, getServer()::getOnlinePlayers,
Objects.requireNonNull(getServer().getScoreboardManager(), "scoreboard manager").getMainScoreboard(), Objects.requireNonNull(getServer().getScoreboardManager(), "scoreboard manager").getMainScoreboard(),
new ProtocolLibTabListController(protocolManager), new ProtocolLibTabListController(protocolManager),
() -> manager.snapshot().sleepCountPolicy()); () -> manager.snapshot().sleepCountPolicy());
protocolManager.addPacketListener( identityPresentation = bukkitPresentation;
new ProtocolLibServerListPingListener(this, sessions::concealedPlayerIds)); protocolManager.addPacketListener(new ProtocolLibIdentityMaskingListener(
this, bukkitPresentation::concealedNames, getLogger()::warning));
protocolManager.addPacketListener(new ProtocolLibServerListPingListener(
this, sessions::concealedPlayerIds, getLogger()::warning));
getServer().getPluginManager().registerEvents(
new ServerListPingListener(sessions::concealedPlayerIds), this);
getServer().getPluginManager().registerEvents( getServer().getPluginManager().registerEvents(
new InvisibilityEffectListener(progression, Clock.systemUTC()), this); new InvisibilityEffectListener(progression, Clock.systemUTC()), this);
getServer().getPluginManager().registerEvents( getServer().getPluginManager().registerEvents(
new StealthSessionListener(sessions, identityPresentation, settings.concealedMessage()), this); new StealthSessionListener(sessions, identityPresentation, settings.concealedMessage()), this);
getServer().getPluginManager().registerEvents(
new StealthAdminJoinListener(sessions, getServer()::getOnlinePlayers), this);
org.bukkit.command.PluginCommand stealthPluginCommand = org.bukkit.command.PluginCommand stealthPluginCommand =
Objects.requireNonNull(getCommand("stealth"), "stealth command"); Objects.requireNonNull(getCommand("stealth"), "stealth command");
StealthCommand stealthCommand = new StealthCommand(manager, progression, settings); StealthCommand stealthCommand = new StealthCommand(manager, progression, settings);
@@ -106,6 +147,36 @@ public final class SpigotStealthPlugin extends JavaPlugin {
settings.unlockThreshold()); settings.unlockThreshold());
stealthAdminPluginCommand.setExecutor(stealthAdminCommand); stealthAdminPluginCommand.setExecutor(stealthAdminCommand);
stealthAdminPluginCommand.setTabCompleter(stealthAdminCommand); stealthAdminPluginCommand.setTabCompleter(stealthAdminCommand);
eyeProgression = new EyeProgressionService(manager, this::monotonicNanos, id -> mainThread.accept(() -> {
var player = getServer().getPlayer(id);
if (player != null) {
player.discoverRecipe(EyeCrafting.RECIPE_KEY);
player.sendMessage("You unlocked the Eye of True Seeing! Craft it with eight Netherite Blocks around an Eye of Ender.");
}
}));
eyePotions = new EyePotionListener(eyeProgression,
failure -> getLogger().severe("Unable to save Eye progression: " + rootMessage(failure)));
var eyeItems = new EyeItems();
var eyeCrafting = new EyeCrafting(eyeProgression, eyeItems);
if (!getServer().addRecipe(eyeCrafting.recipe())) {
getLogger().severe("Unable to register the Eye recipe; disabling Stealth rather than replacing another recipe.");
getServer().getPluginManager().disablePlugin(this);
return;
}
eyeRecipeRegistered = true;
getServer().getPluginManager().registerEvents(eyePotions, this);
getServer().getPluginManager().registerEvents(eyeCrafting, this);
getServer().getPluginManager().registerEvents(new EyeEquipment(eyeProgression, eyeItems), this);
getServer().getScheduler().runTaskTimer(this, ignored -> {
eyePotions.checkpoint(getServer()::getPlayer);
for (var player : getServer().getOnlinePlayers()) {
if (eyeProgression.isUnlocked(player.getUniqueId())) {
if (!player.hasDiscoveredRecipe(EyeCrafting.RECIPE_KEY)) { player.discoverRecipe(EyeCrafting.RECIPE_KEY); }
} else if (player.hasDiscoveredRecipe(EyeCrafting.RECIPE_KEY)) {
player.undiscoverRecipe(EyeCrafting.RECIPE_KEY);
}
}
}, 20L, 20L);
getServer().getScheduler().runTaskTimer(this, ignored -> { getServer().getScheduler().runTaskTimer(this, ignored -> {
for (java.util.UUID playerId : progression.activePlayerIds()) { for (java.util.UUID playerId : progression.activePlayerIds()) {
logSaveFailure(progression.checkpoint(playerId)); logSaveFailure(progression.checkpoint(playerId));
@@ -120,6 +191,20 @@ public final class SpigotStealthPlugin extends JavaPlugin {
getLogger().info("Spigot Stealth enabled"); getLogger().info("Spigot Stealth enabled");
} }
/** Clock boundary for deterministic gameplay lifecycle verification. */
long monotonicNanos() { return System.nanoTime(); }
private void onServer(long epoch, Runnable action) {
if (!isEnabled() || epoch != lifecycleEpoch) { return; }
try {
getServer().getScheduler().runTask(this, () -> {
if (isEnabled() && epoch == lifecycleEpoch) { action.run(); }
});
} catch (org.bukkit.plugin.IllegalPluginAccessException ignored) {
// A durable unlock remains saved even if disable races its notification.
}
}
private void logSaveFailure(CompletableFuture<Void> save) { private void logSaveFailure(CompletableFuture<Void> save) {
save.exceptionally(failure -> { save.exceptionally(failure -> {
getLogger().severe("Unable to save Spigot Stealth state: " + rootMessage(failure)); getLogger().severe("Unable to save Spigot Stealth state: " + rootMessage(failure));
@@ -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;
}
}
@@ -14,7 +14,9 @@ import java.util.function.UnaryOperator;
public final class StealthStateManager implements AutoCloseable { public final class StealthStateManager implements AutoCloseable {
private final StealthStateRepository repository; private final StealthStateRepository repository;
private final AtomicReference<PersistentStealthState> state; private final AtomicReference<PersistentStealthState> state;
private final AtomicReference<PersistentStealthState> durableState;
private final ExecutorService ioExecutor; private final ExecutorService ioExecutor;
private CompletableFuture<Void> closing;
public StealthStateManager(StealthStateRepository repository, PersistentStealthState initialState) { public StealthStateManager(StealthStateRepository repository, PersistentStealthState initialState) {
this(repository, initialState, newIoExecutor()); this(repository, initialState, newIoExecutor());
@@ -26,6 +28,7 @@ public final class StealthStateManager implements AutoCloseable {
ExecutorService ioExecutor) { ExecutorService ioExecutor) {
this.repository = Objects.requireNonNull(repository, "repository"); this.repository = Objects.requireNonNull(repository, "repository");
this.state = new AtomicReference<>(Objects.requireNonNull(initialState, "initialState")); this.state = new AtomicReference<>(Objects.requireNonNull(initialState, "initialState"));
this.durableState = new AtomicReference<>(initialState);
this.ioExecutor = ioExecutor; this.ioExecutor = ioExecutor;
} }
@@ -35,7 +38,7 @@ public final class StealthStateManager implements AutoCloseable {
return CompletableFuture.supplyAsync(() -> { return CompletableFuture.supplyAsync(() -> {
try { try {
return new StealthStateManager(repository, repository.load(), executor); return new StealthStateManager(repository, repository.load(), executor);
} catch (IOException exception) { } catch (IOException | RuntimeException exception) {
executor.shutdown(); executor.shutdown();
throw new CompletionException(exception); throw new CompletionException(exception);
} }
@@ -46,38 +49,53 @@ public final class StealthStateManager implements AutoCloseable {
return state.get(); return state.get();
} }
public CompletableFuture<Void> update(UnaryOperator<PersistentStealthState> operation) { /** Last successfully written snapshot, for rewards that must not precede persistence acknowledgement. */
public PersistentStealthState durableSnapshot() { return durableState.get(); }
public synchronized CompletableFuture<Void> update(UnaryOperator<PersistentStealthState> operation) {
if (closing != null) { return CompletableFuture.failedFuture(new IllegalStateException("Stealth state is closing")); }
PersistentStealthState updated = state.updateAndGet(operation); PersistentStealthState updated = state.updateAndGet(operation);
return persist(updated); return persist(updated);
} }
public CompletableFuture<Void> save() { public synchronized CompletableFuture<Void> save() {
return persist(state.get()); return closing == null ? persist(state.get()) : closing;
} }
private CompletableFuture<Void> persist(PersistentStealthState snapshot) { private CompletableFuture<Void> persist(PersistentStealthState snapshot) {
return CompletableFuture.runAsync(() -> { return CompletableFuture.runAsync(() -> {
try { try {
repository.save(snapshot); repository.save(snapshot);
durableState.set(snapshot);
} catch (IOException exception) { } catch (IOException exception) {
throw new CompletionException(exception); throw new CompletionException(exception);
} }
}, ioExecutor); }, ioExecutor);
} }
/** Queue the final snapshot and stop accepting mutations, without waiting on the caller's thread. */
public synchronized CompletableFuture<Void> closeAsync() {
if (closing == null) {
closing = persist(state.get());
ioExecutor.shutdown();
}
return closing;
}
/** Blocking convenience for non-server callers such as tests; server lifecycle callers should use closeAsync. */
@Override @Override
public void close() { public void close() {
save().join();
ioExecutor.shutdown();
try { try {
if (!ioExecutor.awaitTermination(10L, TimeUnit.SECONDS)) { closeAsync().join();
ioExecutor.shutdownNow(); } finally {
} try {
if (!ioExecutor.awaitTermination(10L, TimeUnit.SECONDS)) { ioExecutor.shutdownNow(); }
} catch (InterruptedException exception) { } catch (InterruptedException exception) {
ioExecutor.shutdownNow(); ioExecutor.shutdownNow();
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} }
} }
}
private static ExecutorService newIoExecutor() { private static ExecutorService newIoExecutor() {
return Executors.newSingleThreadExecutor(runnable -> { return Executors.newSingleThreadExecutor(runnable -> {
@@ -17,7 +17,8 @@ import org.bukkit.configuration.file.YamlConfiguration;
/** Defensive YAML repository using atomic file replacement where available. */ /** Defensive YAML repository using atomic file replacement where available. */
public final class YamlStealthStateRepository implements StealthStateRepository { public final class YamlStealthStateRepository implements StealthStateRepository {
private static final Set<String> ROOT_FIELDS = Set.of("schema-version", "sleep-count-policy", "players"); private static final Set<String> ROOT_FIELDS = Set.of("schema-version", "sleep-count-policy", "players", "eye-progress");
private static final Set<String> EYE_FIELDS = Set.of("accumulated-millis", "unlocked");
private static final Set<String> PLAYER_FIELDS = Set.of( private static final Set<String> PLAYER_FIELDS = Set.of(
"last-known-name", "accumulated-millis", "unlocked", "prepared-login", "concealed", "qualifying-since"); "last-known-name", "accumulated-millis", "unlocked", "prepared-login", "concealed", "qualifying-since");
private final Path stateFile; private final Path stateFile;
@@ -56,14 +57,15 @@ public final class YamlStealthStateRepository implements StealthStateRepository
return new PersistentStealthState( return new PersistentStealthState(
players, players,
SleepCountPolicy.fromPersisted(yaml.get("sleep-count-policy")), SleepCountPolicy.fromPersisted(yaml.get("sleep-count-policy")),
unknownRoot); unknownRoot,
parseEyes(yaml.getConfigurationSection("eye-progress")));
} }
@Override @Override
public void save(PersistentStealthState state) throws IOException { public void save(PersistentStealthState state) throws IOException {
YamlConfiguration yaml = new YamlConfiguration(); YamlConfiguration yaml = new YamlConfiguration();
state.unknownFields().forEach(yaml::set); state.unknownFields().forEach(yaml::set);
yaml.set("schema-version", 1); yaml.set("schema-version", 2);
yaml.set("sleep-count-policy", state.sleepCountPolicy().persistedValue()); yaml.set("sleep-count-policy", state.sleepCountPolicy().persistedValue());
for (PlayerStealthState player : state.players().values()) { for (PlayerStealthState player : state.players().values()) {
String base = "players." + player.playerId() + "."; String base = "players." + player.playerId() + ".";
@@ -75,6 +77,12 @@ public final class YamlStealthStateRepository implements StealthStateRepository
yaml.set(base + "concealed", player.concealed()); yaml.set(base + "concealed", player.concealed());
yaml.set(base + "qualifying-since", player.qualifyingSince() == null ? null : player.qualifyingSince().toString()); yaml.set(base + "qualifying-since", player.qualifyingSince() == null ? null : player.qualifyingSince().toString());
} }
state.eyes().forEach((id, progress) -> {
String base = "eye-progress." + id + ".";
progress.unknownFields().forEach((key, value) -> yaml.set(base + key, value));
yaml.set(base + "accumulated-millis", progress.accumulatedMillis());
yaml.set(base + "unlocked", progress.unlocked());
});
Path parent = stateFile.toAbsolutePath().getParent(); Path parent = stateFile.toAbsolutePath().getParent();
if (parent != null) { if (parent != null) {
Files.createDirectories(parent); Files.createDirectories(parent);
@@ -88,6 +96,27 @@ public final class YamlStealthStateRepository implements StealthStateRepository
} }
} }
private static Map<UUID, EyeProgress> parseEyes(ConfigurationSection section) {
Map<UUID, EyeProgress> eyes = new LinkedHashMap<>();
if (section == null) { return eyes; }
for (String key : section.getKeys(false)) {
try {
UUID id = UUID.fromString(key);
ConfigurationSection entry = section.getConfigurationSection(key);
if (entry == null) { continue; }
Object raw = entry.get("accumulated-millis");
if (!(raw instanceof Long || raw instanceof Integer || raw instanceof Short || raw instanceof Byte)) {
continue;
}
eyes.put(id, new EyeProgress(requireNonNegativeLong(entry, "accumulated-millis"),
requireBoolean(entry, "unlocked"), unknownValues(entry, EYE_FIELDS)));
} catch (IllegalArgumentException ignored) {
// A malformed Eye record cannot grant an unlock or erase independent Stealth records.
}
}
return eyes;
}
private static PlayerStealthState parsePlayer(UUID playerId, ConfigurationSection section) { private static PlayerStealthState parsePlayer(UUID playerId, ConfigurationSection section) {
long accumulated = requireNonNegativeLong(section, "accumulated-millis"); long accumulated = requireNonNegativeLong(section, "accumulated-millis");
boolean unlocked = requireBoolean(section, "unlocked"); boolean unlocked = requireBoolean(section, "unlocked");
@@ -0,0 +1,215 @@
package games.dmg.spigotstealth;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.nio.file.Path;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.PrepareItemCraftEvent;
import org.bukkit.inventory.CraftingInventory;
import org.bukkit.inventory.InventoryView;
import org.bukkit.inventory.ItemStack;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class EyeCraftingTest {
@TempDir Path directory;
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
@Test
void eightNetheriteBlocksAroundAnEnderEyeCanOnlyBeCraftedAfterThePersonalUnlock() throws Exception {
var repository = new YamlStealthStateRepository(directory.resolve("state.yml"));
UUID id = UUID.randomUUID();
try (var states = new StealthStateManager(repository, repository.load())) {
var progression = new EyeProgressionService(states, () -> 0L, ignored -> { });
var items = new EyeItems();
var crafting = new EyeCrafting(progression, items);
var recipe = crafting.recipe();
assertArrayEquals(new String[] {"NNN", "NEN", "NNN"}, recipe.getShape());
assertEquals(Material.NETHERITE_BLOCK, recipe.getIngredientMap().get('N').getType());
assertEquals(Material.ENDER_EYE, recipe.getIngredientMap().get('E').getType());
assertTrue(items.isEye(recipe.getResult()));
var player = mock(Player.class);
when(player.getUniqueId()).thenReturn(id);
var inventory = mock(CraftingInventory.class);
when(inventory.getRecipe()).thenReturn(recipe);
when(inventory.getMatrix()).thenReturn(matrix());
var result = new AtomicReference<>(recipe.getResult());
when(inventory.getResult()).thenAnswer(ignored -> result.get());
doAnswer(call -> { result.set(call.getArgument(0)); return null; }).when(inventory).setResult(any());
var view = mock(InventoryView.class);
when(view.getPlayer()).thenReturn(player);
when(view.getTopInventory()).thenReturn(inventory);
var event = new PrepareItemCraftEvent(inventory, view, false);
crafting.onPrepare(event);
assertNull(result.get(), "a locked player cannot obtain the recipe result");
states.update(state -> state.withEyeProgress(id, new EyeProgress(28_800_000, true))).get(3, TimeUnit.SECONDS);
result.set(recipe.getResult()); // A fresh native recipe preparation after earning the unlock.
crafting.onPrepare(event);
assertTrue(items.isEye(result.get()));
assertEquals(1, result.get().getAmount());
verify(inventory, never()).setMatrix(any()); // Vanilla owns all ingredient consumption.
}
}
@Test
void resultClicksRecheckEligibilityIngredientsAndIdentityWithoutBypassingCancellation() throws Exception {
var repository = new YamlStealthStateRepository(directory.resolve("state.yml"));
UUID id = UUID.randomUUID();
try (var states = new StealthStateManager(repository, repository.load())) {
var progression = new EyeProgressionService(states, () -> 0L, ignored -> { });
var items = new EyeItems();
var crafting = new EyeCrafting(progression, items);
var recipe = crafting.recipe();
var player = mock(Player.class);
when(player.getUniqueId()).thenReturn(id);
var inventory = mock(CraftingInventory.class);
when(inventory.getRecipe()).thenReturn(recipe);
ItemStack[] ingredients = matrix();
when(inventory.getMatrix()).thenReturn(ingredients);
var result = new AtomicReference<>(recipe.getResult());
when(inventory.getResult()).thenAnswer(ignored -> result.get());
doAnswer(call -> { result.set(call.getArgument(0)); return null; }).when(inventory).setResult(any());
var view = mock(InventoryView.class);
when(view.getPlayer()).thenReturn(player);
when(view.getTopInventory()).thenReturn(inventory);
var locked = click(recipe, view);
crafting.onCraft(locked);
assertTrue(locked.isCancelled(), "a stale preview must not bypass the personal unlock on shift-click");
assertNull(result.get());
states.update(state -> state.withEyeProgress(id, new EyeProgress(28_800_000, true))).get(3, TimeUnit.SECONDS);
result.set(recipe.getResult());
var allowed = click(recipe, view);
crafting.onCraft(allowed);
assertFalse(allowed.isCancelled());
assertTrue(items.isEye(result.get()));
ingredients[0] = new ItemStack(Material.DIRT);
var invalidIngredients = click(recipe, view);
crafting.onCraft(invalidIngredients);
assertTrue(invalidIngredients.isCancelled());
assertNull(result.get());
ingredients[0] = new ItemStack(Material.NETHERITE_BLOCK);
result.set(new ItemStack(Material.ENDER_EYE));
var invalidResult = click(recipe, view);
crafting.onCraft(invalidResult);
assertTrue(invalidResult.isCancelled());
result.set(recipe.getResult());
result.get().setAmount(2);
var inflatedResult = click(recipe, view);
crafting.onCraft(inflatedResult);
assertTrue(inflatedResult.isCancelled());
result.set(recipe.getResult());
var cancelled = click(recipe, view);
cancelled.setCancelled(true);
crafting.onCraft(cancelled);
assertTrue(cancelled.isCancelled());
var otherRecipe = new org.bukkit.inventory.ShapedRecipe(new org.bukkit.NamespacedKey("other", "eye"),
new ItemStack(Material.ENDER_EYE)).shape("E").setIngredient('E', Material.ENDER_EYE);
var unrelated = click(otherRecipe, view);
crafting.onCraft(unrelated);
assertFalse(unrelated.isCancelled());
verify(inventory, never()).setMatrix(any());
}
}
@Test
void pendingOrFailedUnlockWritesCannotExposeACraftableResult() throws Exception {
var disk = new YamlStealthStateRepository(directory.resolve("state.yml"));
var started = new java.util.concurrent.CountDownLatch(1);
var release = new java.util.concurrent.CountDownLatch(1);
var firstWrite = new java.util.concurrent.atomic.AtomicBoolean(true);
StealthStateRepository repository = new StealthStateRepository() {
@Override public PersistentStealthState load() throws java.io.IOException { return disk.load(); }
@Override public void save(PersistentStealthState state) throws java.io.IOException {
if (firstWrite.getAndSet(false)) {
started.countDown();
try {
if (!release.await(3, TimeUnit.SECONDS)) { throw new java.io.IOException("Test write gate timed out"); }
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
throw new java.io.IOException(exception);
}
throw new java.io.IOException("Injected write failure");
}
disk.save(state);
}
};
UUID id = UUID.randomUUID();
try (var states = new StealthStateManager(repository, repository.load())) {
try {
var items = new EyeItems();
var crafting = new EyeCrafting(new EyeProgressionService(states, () -> 0L, ignored -> { }), items);
var recipe = crafting.recipe();
var player = mock(Player.class);
when(player.getUniqueId()).thenReturn(id);
var inventory = mock(CraftingInventory.class);
when(inventory.getRecipe()).thenReturn(recipe);
when(inventory.getMatrix()).thenReturn(matrix());
var result = new AtomicReference<>(recipe.getResult());
when(inventory.getResult()).thenAnswer(ignored -> result.get());
doAnswer(call -> { result.set(call.getArgument(0)); return null; }).when(inventory).setResult(any());
var view = mock(InventoryView.class);
when(view.getPlayer()).thenReturn(player);
when(view.getTopInventory()).thenReturn(inventory);
var event = new PrepareItemCraftEvent(inventory, view, false);
var pending = states.update(state -> state.withEyeProgress(id, new EyeProgress(28_800_000, true)));
assertTrue(started.await(3, TimeUnit.SECONDS));
assertTrue(states.snapshot().eyeProgress(id).unlocked());
crafting.onPrepare(event);
assertNull(result.get(), "in-memory progress is not a durable crafting unlock");
release.countDown();
assertThrows(java.util.concurrent.ExecutionException.class, () -> pending.get(3, TimeUnit.SECONDS));
result.set(recipe.getResult());
crafting.onPrepare(event);
assertNull(result.get(), "failed writes must not grant the recipe");
var denied = click(recipe, view);
crafting.onCraft(denied);
assertTrue(denied.isCancelled());
states.save().get(3, TimeUnit.SECONDS);
result.set(recipe.getResult());
crafting.onPrepare(event);
assertTrue(items.isEye(result.get()));
var allowed = click(recipe, view);
crafting.onCraft(allowed);
assertFalse(allowed.isCancelled());
} finally { release.countDown(); }
}
}
@Test
void automatedCraftersCannotBypassPersonalProgression() throws Exception {
var repository = new YamlStealthStateRepository(directory.resolve("state.yml"));
try (var states = new StealthStateManager(repository, repository.load())) {
var items = new EyeItems();
var crafting = new EyeCrafting(new EyeProgressionService(states, () -> 0L, ignored -> { }), items);
var block = mock(org.bukkit.block.Block.class);
var event = new org.bukkit.event.block.CrafterCraftEvent(block, crafting.recipe(), items.create());
crafting.onCrafter(event);
assertTrue(event.isCancelled(), "a block has no personal Eye unlock");
var other = new org.bukkit.inventory.ShapedRecipe(new org.bukkit.NamespacedKey("other", "eye"),
new ItemStack(Material.ENDER_EYE)).shape("E").setIngredient('E', Material.ENDER_EYE);
var unrelated = new org.bukkit.event.block.CrafterCraftEvent(block, other, other.getResult());
crafting.onCrafter(unrelated);
assertFalse(unrelated.isCancelled());
}
}
private static org.bukkit.event.inventory.CraftItemEvent click(org.bukkit.inventory.Recipe recipe, InventoryView view) {
return new org.bukkit.event.inventory.CraftItemEvent(recipe, view,
org.bukkit.event.inventory.InventoryType.SlotType.RESULT, 0,
org.bukkit.event.inventory.ClickType.SHIFT_LEFT, org.bukkit.event.inventory.InventoryAction.MOVE_TO_OTHER_INVENTORY);
}
private static ItemStack[] matrix() {
var result = new ItemStack[9];
for (int index = 0; index < result.length; index++) {
result[index] = new ItemStack(index == 4 ? Material.ENDER_EYE : Material.NETHERITE_BLOCK);
}
return result;
}
}
@@ -0,0 +1,92 @@
package games.dmg.spigotstealth;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.nio.file.Path;
import java.util.EnumMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class EyeEquipmentTest {
@TempDir Path directory;
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
@Test
void tradedEyesRequireTheHoldersOwnUnlockAndEquipWithoutThrowingOrReplacingAHelmet() throws Exception {
UUID earner = UUID.randomUUID(), holder = UUID.randomUUID();
var repository = new YamlStealthStateRepository(directory.resolve("state.yml"));
try (var states = new StealthStateManager(repository, repository.load())) {
states.update(state -> state.withEyeProgress(earner, new EyeProgress(28_800_000, true))).get(3, TimeUnit.SECONDS);
var items = new EyeItems();
var equipment = new EyeEquipment(new EyeProgressionService(states, () -> 0L, ignored -> { }), items);
var player = mock(Player.class);
when(player.getUniqueId()).thenReturn(holder);
var inventory = mock(PlayerInventory.class);
when(player.getInventory()).thenReturn(inventory);
var helmet = new AtomicReference<ItemStack>();
when(inventory.getHelmet()).thenAnswer(ignored -> helmet.get());
doAnswer(call -> { helmet.set(call.getArgument(0)); return null; }).when(inventory).setHelmet(any());
var hands = new EnumMap<EquipmentSlot, ItemStack>(EquipmentSlot.class);
when(inventory.getItem(any(EquipmentSlot.class))).thenAnswer(call -> hands.get(call.getArgument(0)));
doAnswer(call -> { hands.put(call.getArgument(0), call.getArgument(1)); return null; })
.when(inventory).setItem(any(EquipmentSlot.class), nullable(ItemStack.class));
ItemStack traded = items.create();
hands.put(EquipmentSlot.HAND, traded);
helmet.set(traded.clone());
assertFalse(equipment.isEligibleWearer(player), "equipping somebody else's Eye must not bypass the personal unlock");
helmet.set(null);
var denied = use(player, traded, EquipmentSlot.HAND);
equipment.onUse(denied);
assertEquals(Event.Result.DENY, denied.useItemInHand(), "custom Eyes must never fall through to vanilla Ender Eye use");
assertNull(helmet.get());
assertSame(traded, hands.get(EquipmentSlot.HAND));
states.update(state -> state.withEyeProgress(holder, new EyeProgress(28_800_000, true))).get(3, TimeUnit.SECONDS);
var allowed = use(player, traded, EquipmentSlot.HAND);
equipment.onUse(allowed);
assertEquals(Event.Result.DENY, allowed.useItemInHand());
assertNull(hands.get(EquipmentSlot.HAND));
assertTrue(items.isEye(helmet.get()));
assertEquals(1, helmet.get().getAmount());
assertTrue(equipment.isEligibleWearer(player));
var ordinaryHelmet = new ItemStack(Material.IRON_HELMET);
helmet.set(ordinaryHelmet);
hands.put(EquipmentSlot.OFF_HAND, items.create());
equipment.onUse(use(player, hands.get(EquipmentSlot.OFF_HAND), EquipmentSlot.OFF_HAND));
assertSame(ordinaryHelmet, helmet.get());
assertTrue(items.isEye(hands.get(EquipmentSlot.OFF_HAND)));
assertFalse(equipment.isEligibleWearer(player), "holding an Eye is not wearing it");
helmet.set(null);
equipment.onUse(use(player, hands.get(EquipmentSlot.OFF_HAND), EquipmentSlot.OFF_HAND));
assertNull(hands.get(EquipmentSlot.OFF_HAND));
assertTrue(equipment.isEligibleWearer(player));
helmet.set(null);
hands.put(EquipmentSlot.HAND, items.create());
var cancelled = use(player, hands.get(EquipmentSlot.HAND), EquipmentSlot.HAND);
cancelled.setUseItemInHand(Event.Result.DENY);
equipment.onUse(cancelled);
assertNull(helmet.get());
assertTrue(items.isEye(hands.get(EquipmentSlot.HAND)));
var ordinary = use(player, new ItemStack(Material.ENDER_EYE), EquipmentSlot.HAND);
equipment.onUse(ordinary);
assertEquals(Event.Result.DEFAULT, ordinary.useItemInHand());
}
}
private static PlayerInteractEvent use(Player player, ItemStack item, EquipmentSlot hand) {
return new PlayerInteractEvent(player, Action.RIGHT_CLICK_AIR, item, null, BlockFace.SELF, hand);
}
}
@@ -0,0 +1,39 @@
package games.dmg.spigotstealth;
import static org.junit.jupiter.api.Assertions.*;
import net.kyori.adventure.text.Component;
import org.bukkit.Material;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class EyeItemsTest {
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
@Test
void createdEyeIsAnAuthenticatedHelmetItemButPlainAndRenamedEyesAreNot() {
var items = new EyeItems();
ItemStack eye = items.create();
assertEquals(Material.ENDER_EYE, eye.getType());
assertEquals(Component.text("Eye of True Seeing"), eye.getItemMeta().displayName());
assertTrue(items.isEye(eye));
assertTrue(items.isEye(eye.clone()), "ordinary inventory transfer must retain item identity");
assertEquals(EquipmentSlot.HEAD, eye.getItemMeta().getEquippable().getSlot());
assertEquals(1, eye.getMaxStackSize());
assertFalse(eye.getItemMeta().getEquippable().isDispensable());
assertFalse(eye.getItemMeta().getEquippable().isEquipOnInteract(),
"the eligibility-checked interaction handler, not native item use, equips the Eye");
var ordinary = new ItemStack(Material.ENDER_EYE);
assertFalse(items.isEye(ordinary));
var renamed = ordinary.getItemMeta();
renamed.displayName(eye.getItemMeta().displayName());
ordinary.setItemMeta(renamed);
assertFalse(items.isEye(ordinary), "anvil/display names cannot authenticate an Eye");
var wrongMaterial = eye.clone();
wrongMaterial.setType(Material.STONE);
assertFalse(items.isEye(wrongMaterial));
assertFalse(items.isEye(null));
}
}
@@ -0,0 +1,216 @@
package games.dmg.spigotstealth;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.ProtocolManager;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.logging.Logger;
import org.bukkit.Server;
import org.bukkit.command.PluginCommand;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.PrepareItemCraftEvent;
import org.bukkit.inventory.CraftingInventory;
import org.bukkit.inventory.InventoryView;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.Recipe;
import org.bukkit.plugin.EventExecutor;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.RegisteredListener;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.ScoreboardManager;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class EyePluginLifecycleTest {
@TempDir Path directory;
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(strings = {"normal", "disabled", "reenabled", "presentation-failure"})
@SuppressWarnings("try") // The scoped Bukkit boundary delegates non-server-metadata operations to native code.
void startupAndLateCallbacksRespectSavedUnlocksAndDisable(String mode) throws Exception {
UUID id = UUID.randomUUID(), learner = UUID.randomUUID();
var disk = new YamlStealthStateRepository(directory.resolve("state.yml"));
disk.save(new PersistentStealthState(Map.of(), Map.of()).withEyeProgress(id, new EyeProgress(28_800_000, true)));
var plugin = mock(SpigotStealthPlugin.class, CALLS_REAL_METHODS);
var clock = new java.util.concurrent.atomic.AtomicLong();
doAnswer(ignored -> clock.get()).when(plugin).monotonicNanos();
Server server = mock(org.bukkit.craftbukkit.CraftServer.class);
var plugins = mock(PluginManager.class);
BukkitScheduler scheduler = mock(org.bukkit.craftbukkit.scheduler.CraftScheduler.class);
var player = mock(Player.class);
when(player.getUniqueId()).thenReturn(id);
doReturn(List.of(player)).when(server).getOnlinePlayers();
when(server.getPlayer(id)).thenReturn(player);
doReturn(server).when(plugin).getServer();
doReturn(true).when(plugin).isEnabled();
doReturn(directory.toFile()).when(plugin).getDataFolder();
doReturn(new YamlConfiguration()).when(plugin).getConfig();
doReturn(Logger.getAnonymousLogger()).when(plugin).getLogger();
doReturn(new PluginDescriptionFile("SpigotStealth", "test", SpigotStealthPlugin.class.getName()))
.when(plugin).getDescription();
doNothing().when(plugin).saveDefaultConfig();
doReturn(mock(PluginCommand.class)).when(plugin).getCommand("stealth");
doReturn(mock(PluginCommand.class)).when(plugin).getCommand("stealthadmin");
when(server.getPluginManager()).thenReturn(plugins);
when(server.getScheduler()).thenReturn(scheduler);
ScoreboardManager boards = mock(org.bukkit.craftbukkit.scoreboard.CraftScoreboardManager.class);
when(server.getScoreboardManager()).thenReturn(boards);
when(boards.getMainScoreboard()).thenReturn(mock(org.bukkit.craftbukkit.scoreboard.CraftScoreboard.class));
var main = new LinkedBlockingQueue<Runnable>();
when(scheduler.runTask(eq(plugin), any(Runnable.class))).thenAnswer(call -> {
main.add(call.getArgument(1)); return mock(BukkitTask.class);
});
var timers = new ArrayList<Runnable>();
doAnswer(call -> {
Consumer<BukkitTask> action = call.getArgument(1);
timers.add(() -> action.accept(mock(BukkitTask.class)));
return null;
}).when(scheduler).runTaskTimer(eq(plugin), org.mockito.ArgumentMatchers.<Consumer<BukkitTask>>any(), anyLong(), anyLong());
when(scheduler.runTaskTimer(eq(plugin), any(Runnable.class), anyLong(), anyLong())).thenAnswer(call -> {
timers.add(call.getArgument(1)); return mock(BukkitTask.class);
});
var recipe = new AtomicReference<Recipe>();
when(server.addRecipe(any(Recipe.class))).thenAnswer(call -> { recipe.set(call.getArgument(0)); return true; });
var listeners = new ArrayList<Listener>();
doAnswer(call -> { listeners.add(call.getArgument(0)); return null; }).when(plugins).registerEvents(any(), eq(plugin));
try (var platform = mockStatic(org.bukkit.Bukkit.class, call -> switch (call.getMethod().getName()) {
case "getServer" -> server;
case "getVersion" -> "Purpur 2618 (MC: 26.2)";
case "getMinecraftVersion" -> "26.2";
case "getBukkitVersion" -> "26.2-R0.1-SNAPSHOT";
default -> call.callRealMethod();
}); var protocol = mockStatic(ProtocolLibrary.class)) {
var protocolManager = mock(ProtocolManager.class);
protocol.when(ProtocolLibrary::getProtocolManager).thenReturn(protocolManager);
try {
plugin.onEnable();
assertNull(recipe.get(), "Bukkit registration must wait for durable state initialization and main-thread dispatch");
Runnable initialization = main.poll(3, TimeUnit.SECONDS);
assertNotNull(initialization);
if (mode.equals("disabled") || mode.equals("reenabled")) {
doReturn(false).when(plugin).isEnabled();
plugin.onDisable();
if (mode.equals("reenabled")) {
doReturn(true).when(plugin).isEnabled();
plugin.onEnable();
Runnable currentInitialization = main.poll(3, TimeUnit.SECONDS);
assertNotNull(currentInitialization);
currentInitialization.run();
int registeredCount = listeners.size();
assertNotNull(recipe.get());
initialization.run();
assertEquals(registeredCount, listeners.size(), "an old lifecycle callback must not touch a re-enabled plugin");
verify(server, times(1)).addRecipe(any(Recipe.class));
return;
}
initialization.run();
assertTrue(listeners.isEmpty(), "a queued initialization must not register listeners after disable");
assertNull(recipe.get());
verify(server, never()).removeRecipe(any());
return;
}
initialization.run();
assertNotNull(recipe.get(), "plugin startup must register the Eye recipe");
assertTrue(new EyeItems().isEye(recipe.get().getResult()));
assertTrue(listeners.stream().anyMatch(EyePotionListener.class::isInstance));
assertTrue(listeners.stream().anyMatch(EyeEquipment.class::isInstance));
var inventory = mock(CraftingInventory.class);
when(inventory.getRecipe()).thenAnswer(ignored -> recipe.get());
var result = new AtomicReference<>(recipe.get().getResult());
when(inventory.getResult()).thenAnswer(ignored -> result.get());
doAnswer(call -> { result.set(call.getArgument(0)); return null; }).when(inventory).setResult(any());
var view = mock(InventoryView.class);
when(view.getPlayer()).thenReturn(player);
when(view.getTopInventory()).thenReturn(inventory);
var prepare = new PrepareItemCraftEvent(inventory, view, false);
dispatch(plugin, listeners, prepare);
assertTrue(new EyeItems().isEye(result.get()), "the restored personal unlock must permit crafting");
when(player.getUniqueId()).thenReturn(learner);
when(server.getPlayer(learner)).thenReturn(player);
dispatch(plugin, listeners, prepare);
assertNull(result.get(), "registered handlers must deny an unearned player's result");
var effect = new org.bukkit.potion.PotionEffect(org.bukkit.potion.PotionEffectType.NIGHT_VISION, 9600, 0);
dispatch(plugin, listeners, new org.bukkit.event.entity.EntityPotionEffectEvent(player, null, effect, player,
org.bukkit.event.entity.EntityPotionEffectEvent.Cause.POTION_DRINK,
org.bukkit.event.entity.EntityPotionEffectEvent.Action.ADDED, false));
clock.set(java.time.Duration.ofHours(8).toNanos());
dispatch(plugin, listeners, new org.bukkit.event.entity.EntityPotionEffectEvent(player, effect, null, null,
org.bukkit.event.entity.EntityPotionEffectEvent.Cause.EXPIRATION,
org.bukkit.event.entity.EntityPotionEffectEvent.Action.REMOVED, false));
Runnable unlocked = main.poll(3, TimeUnit.SECONDS);
assertNotNull(unlocked, "the registered potion listener must persist the unlock and schedule its notification");
assertTrue(disk.load().eyeProgress(learner).unlocked());
unlocked.run();
result.set(recipe.get().getResult());
dispatch(plugin, listeners, prepare);
assertTrue(new EyeItems().isEye(result.get()), "the registered crafting listener must see the newly saved unlock");
clearInvocations(player);
when(player.getUniqueId()).thenReturn(id);
timers.forEach(Runnable::run);
verify(player).discoverRecipe(EyeCrafting.RECIPE_KEY);
// Disable must checkpoint and drain an in-flight qualifying interval, not just remove the recipe.
when(player.getUniqueId()).thenReturn(learner);
when(player.isOnline()).thenReturn(true);
when(player.getPotionEffect(org.bukkit.potion.PotionEffectType.NIGHT_VISION)).thenReturn(effect);
dispatch(plugin, listeners, new org.bukkit.event.entity.EntityPotionEffectEvent(player, null, effect, player,
org.bukkit.event.entity.EntityPotionEffectEvent.Cause.POTION_DRINK,
org.bukkit.event.entity.EntityPotionEffectEvent.Action.ADDED, false));
clock.addAndGet(1_234_000_000L);
} finally {
if (mode.equals("presentation-failure")) {
doThrow(new IllegalStateException("Injected presentation cleanup failure"))
.when(protocolManager).removePacketListeners(plugin);
try {
assertThrows(IllegalStateException.class, plugin::onDisable);
plugin.shutdownCompletion().get(3, TimeUnit.SECONDS);
assertEquals(28_801_234, disk.load().eyeProgress(learner).accumulatedMillis(),
"presentation cleanup failure must not prevent Eye progress from draining");
} finally {
doNothing().when(protocolManager).removePacketListeners(plugin);
plugin.onDisable();
plugin.shutdownCompletion().get(3, TimeUnit.SECONDS);
}
} else {
plugin.onDisable();
plugin.shutdownCompletion().get(3, TimeUnit.SECONDS);
}
}
}
verify(server).removeRecipe(EyeCrafting.RECIPE_KEY);
assertEquals(28_801_234, disk.load().eyeProgress(learner).accumulatedMillis());
}
private static void dispatch(SpigotStealthPlugin plugin, List<Listener> listeners, Event event) throws Exception {
var registered = new ArrayList<RegisteredListener>();
for (var listener : listeners) {
for (var method : listener.getClass().getMethods()) {
var handler = method.getAnnotation(EventHandler.class);
if (handler == null || method.getParameterCount() != 1 || !method.getParameterTypes()[0].isInstance(event)) { continue; }
registered.add(new RegisteredListener(listener,
EventExecutor.create(method, method.getParameterTypes()[0].asSubclass(Event.class)),
handler.priority(), plugin, handler.ignoreCancelled()));
}
}
registered.sort(java.util.Comparator.comparing(RegisteredListener::getPriority));
for (var handler : registered) { handler.callEvent(event); }
}
}
@@ -0,0 +1,302 @@
package games.dmg.spigotstealth;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.nio.file.Path;
import java.time.Duration;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityPotionEffectEvent;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/** Real Purpur effect/event objects, real progression/persistence, only player and clock are external doubles. */
class EyePotionProgressionTest {
@TempDir Path directory;
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
@Test
void aTransitionBeforeTheNextObservationCannotCreditAnUnattributedRestoredEffect() throws Exception {
for (String transition : java.util.List.of("quit", "remove", "refresh")) {
UUID id = UUID.randomUUID();
var player = mock(Player.class);
when(player.getUniqueId()).thenReturn(id);
when(player.isOnline()).thenReturn(true);
var clock = new AtomicLong();
var repository = new YamlStealthStateRepository(directory.resolve(transition + ".yml"));
try (var states = new StealthStateManager(repository, repository.load())) {
var progression = new EyeProgressionService(states, clock::get, ignored -> { });
var listener = new EyePotionListener(progression, failure -> fail(failure));
var strong = new PotionEffect(PotionEffectType.NIGHT_VISION, 100, 1);
var restored = new PotionEffect(PotionEffectType.NIGHT_VISION, 400, 0);
listener.onPotionEffect(new EntityPotionEffectEvent(player, null, strong, player,
EntityPotionEffectEvent.Cause.POTION_DRINK, EntityPotionEffectEvent.Action.ADDED, false));
when(player.getPotionEffect(PotionEffectType.NIGHT_VISION)).thenReturn(strong);
clock.set(Duration.ofSeconds(1).toNanos());
listener.checkpoint(ignored -> player);
clock.set(Duration.ofSeconds(3).toNanos());
when(player.getPotionEffect(PotionEffectType.NIGHT_VISION)).thenReturn(restored);
switch (transition) {
case "quit" -> listener.onQuit(new org.bukkit.event.player.PlayerQuitEvent(
player, net.kyori.adventure.text.Component.empty()));
case "remove" -> listener.onPotionEffect(new EntityPotionEffectEvent(player, restored, null, null,
EntityPotionEffectEvent.Cause.EXPIRATION, EntityPotionEffectEvent.Action.REMOVED, false));
case "refresh" -> listener.onPotionEffect(new EntityPotionEffectEvent(player, restored,
new PotionEffect(PotionEffectType.NIGHT_VISION, 800, 0), player,
EntityPotionEffectEvent.Cause.POTION_DRINK, EntityPotionEffectEvent.Action.CHANGED, true));
default -> throw new AssertionError(transition);
}
states.save().get(3, TimeUnit.SECONDS);
assertEquals(1000, repository.load().eyeProgress(id).accumulatedMillis(), transition);
}
}
}
@Test
void periodicObservationStopsAtUnattributedHiddenEffectRestorationOrMissingPlayer() throws Exception {
UUID id = UUID.randomUUID();
var player = mock(Player.class);
when(player.getUniqueId()).thenReturn(id);
when(player.isOnline()).thenReturn(true);
var clock = new AtomicLong();
var repository = new YamlStealthStateRepository(directory.resolve("state.yml"));
try (var states = new StealthStateManager(repository, repository.load())) {
var progression = new EyeProgressionService(states, clock::get, ignored -> { });
var listener = new EyePotionListener(progression, failure -> fail(failure));
var strong = new PotionEffect(PotionEffectType.NIGHT_VISION, 100, 1);
listener.onPotionEffect(new EntityPotionEffectEvent(player, null, strong, player,
EntityPotionEffectEvent.Cause.POTION_DRINK, EntityPotionEffectEvent.Action.ADDED, false));
when(player.getPotionEffect(PotionEffectType.NIGHT_VISION)).thenReturn(
new PotionEffect(PotionEffectType.NIGHT_VISION, 80, 1));
clock.set(Duration.ofSeconds(1).toNanos());
listener.checkpoint(ignored -> player);
states.save().get(3, TimeUnit.SECONDS);
assertEquals(1000, repository.load().eyeProgress(id).accumulatedMillis());
// Native hidden-effect promotion need not emit a new potion-source event.
when(player.getPotionEffect(PotionEffectType.NIGHT_VISION)).thenReturn(
new PotionEffect(PotionEffectType.NIGHT_VISION, 400, 0));
clock.set(Duration.ofSeconds(2).toNanos());
listener.checkpoint(ignored -> player);
clock.set(Duration.ofHours(12).toNanos());
listener.checkpoint(ignored -> player);
states.save().get(3, TimeUnit.SECONDS);
assertEquals(1000, repository.load().eyeProgress(id).accumulatedMillis(),
"unattributed restored effects must not inherit the drink timer");
assertTrue(progression.activePlayerIds().isEmpty());
listener.onPotionEffect(new EntityPotionEffectEvent(player, null, strong, player,
EntityPotionEffectEvent.Cause.POTION_DRINK, EntityPotionEffectEvent.Action.ADDED, false));
clock.addAndGet(Duration.ofDays(1).toNanos());
listener.checkpoint(ignored -> null);
states.save().get(3, TimeUnit.SECONDS);
assertEquals(1000, repository.load().eyeProgress(id).accumulatedMillis());
assertTrue(progression.activePlayerIds().isEmpty());
}
}
@Test
void disconnectClosesTheIntervalAndRestartDoesNotCountTheOfflineGap() throws Exception {
UUID id = UUID.randomUUID();
var player = mock(Player.class);
when(player.getUniqueId()).thenReturn(id);
var clock = new AtomicLong();
var repository = new YamlStealthStateRepository(directory.resolve("state.yml"));
try (var states = new StealthStateManager(repository, repository.load())) {
var progression = new EyeProgressionService(states, clock::get, ignored -> { });
var listener = new EyePotionListener(progression, failure -> fail(failure));
var effect = new PotionEffect(PotionEffectType.NIGHT_VISION, 200, 0);
listener.onPotionEffect(new EntityPotionEffectEvent(player, null, effect, player,
EntityPotionEffectEvent.Cause.POTION_DRINK, EntityPotionEffectEvent.Action.ADDED, false));
clock.set(Duration.ofSeconds(1).toNanos());
when(player.getPotionEffect(PotionEffectType.NIGHT_VISION)).thenReturn(effect);
listener.onQuit(new org.bukkit.event.player.PlayerQuitEvent(player, net.kyori.adventure.text.Component.empty()));
clock.addAndGet(Duration.ofDays(7).toNanos());
progression.checkpoint(id).get(3, TimeUnit.SECONDS);
states.save().get(3, TimeUnit.SECONDS);
assertEquals(1000, repository.load().eyeProgress(id).accumulatedMillis(),
"disconnect must close the qualifying interval before offline time passes");
assertFalse(progression.isUnlocked(id));
}
try (var restarted = new StealthStateManager(repository, repository.load())) {
var progression = new EyeProgressionService(restarted, clock::get, ignored -> { });
assertEquals(1000, restarted.snapshot().eyeProgress(id).accumulatedMillis());
assertTrue(progression.activePlayerIds().isEmpty());
assertFalse(progression.isUnlocked(id));
}
}
@Test
void everyNonDrinkSourceIsExcludedAndAnEffectiveExternalReplacementStopsCredit() throws Exception {
UUID id = UUID.randomUUID();
var player = mock(Player.class);
when(player.getUniqueId()).thenReturn(id);
var clock = new AtomicLong();
var repository = new YamlStealthStateRepository(directory.resolve("state.yml"));
try (var states = new StealthStateManager(repository, repository.load())) {
var progression = new EyeProgressionService(states, clock::get, ignored -> { });
var listener = new EyePotionListener(progression, failure -> fail(failure));
var effect = new PotionEffect(PotionEffectType.NIGHT_VISION, 200, 0);
for (var cause : EntityPotionEffectEvent.Cause.values()) {
if (cause == EntityPotionEffectEvent.Cause.POTION_DRINK) { continue; }
listener.onPotionEffect(new EntityPotionEffectEvent(player, null, effect, null,
cause, EntityPotionEffectEvent.Action.ADDED, false));
clock.addAndGet(Duration.ofSeconds(1).toNanos());
progression.checkpoint(id).get(3, TimeUnit.SECONDS);
assertEquals(0, states.snapshot().eyeProgress(id).accumulatedMillis(), cause.toString());
listener.onPotionEffect(new EntityPotionEffectEvent(player, effect, null, null,
EntityPotionEffectEvent.Cause.EXPIRATION, EntityPotionEffectEvent.Action.REMOVED, false));
}
listener.onPotionEffect(new EntityPotionEffectEvent(player, null, effect, player,
EntityPotionEffectEvent.Cause.POTION_DRINK, EntityPotionEffectEvent.Action.ADDED, false));
clock.addAndGet(Duration.ofSeconds(1).toNanos());
listener.onPotionEffect(new EntityPotionEffectEvent(player, effect,
new PotionEffect(PotionEffectType.NIGHT_VISION, 400, 0), null,
EntityPotionEffectEvent.Cause.PLUGIN, EntityPotionEffectEvent.Action.CHANGED, true));
clock.addAndGet(Duration.ofHours(12).toNanos());
progression.checkpoint(id).get(3, TimeUnit.SECONDS);
states.save().get(3, TimeUnit.SECONDS);
assertEquals(1000, repository.load().eyeProgress(id).accumulatedMillis());
assertFalse(progression.isUnlocked(id));
}
}
@Test
void cancelledAndUnrelatedEffectEventsCannotStartOrInterruptCredit() throws Exception {
UUID id = UUID.randomUUID();
var player = mock(Player.class);
when(player.getUniqueId()).thenReturn(id);
var clock = new AtomicLong();
var repository = new YamlStealthStateRepository(directory.resolve("state.yml"));
try (var states = new StealthStateManager(repository, repository.load())) {
var progression = new EyeProgressionService(states, clock::get, ignored -> { });
var listener = new EyePotionListener(progression, failure -> fail(failure));
var effect = new PotionEffect(PotionEffectType.NIGHT_VISION, 200, 0);
var cancelled = new EntityPotionEffectEvent(player, null, effect, player,
EntityPotionEffectEvent.Cause.POTION_DRINK, EntityPotionEffectEvent.Action.ADDED, false);
cancelled.setCancelled(true);
listener.onPotionEffect(cancelled);
clock.set(Duration.ofSeconds(1).toNanos());
progression.checkpoint(id).get(3, TimeUnit.SECONDS);
assertEquals(0, states.snapshot().eyeProgress(id).accumulatedMillis());
cancelled.setCancelled(false);
listener.onPotionEffect(cancelled);
clock.set(Duration.ofSeconds(2).toNanos());
var cancelledRemoval = new EntityPotionEffectEvent(player, effect, null, null,
EntityPotionEffectEvent.Cause.MILK, EntityPotionEffectEvent.Action.CLEARED, false);
cancelledRemoval.setCancelled(true);
listener.onPotionEffect(cancelledRemoval);
listener.onPotionEffect(new EntityPotionEffectEvent(player, null,
new PotionEffect(PotionEffectType.INVISIBILITY, 200, 0), null,
EntityPotionEffectEvent.Cause.PLUGIN, EntityPotionEffectEvent.Action.ADDED, false));
clock.set(Duration.ofSeconds(3).toNanos());
progression.stop(id).get(3, TimeUnit.SECONDS);
assertEquals(2000, repository.load().eyeProgress(id).accumulatedMillis());
}
}
@Test
void cosmeticOnlyOverridesDoNotReassignTheActiveEffectsSource() throws Exception {
// Purpur reports override=true even when only particle/icon flags change.
var nativeActive = new net.minecraft.world.effect.MobEffectInstance(
net.minecraft.world.effect.MobEffects.NIGHT_VISION, 200, 1);
assertTrue(nativeActive.update(new net.minecraft.world.effect.MobEffectInstance(
net.minecraft.world.effect.MobEffects.NIGHT_VISION, 100, 0, false, false, false)));
assertEquals(1, nativeActive.getAmplifier());
assertEquals(200, nativeActive.getDuration());
UUID id = UUID.randomUUID();
var player = mock(Player.class);
when(player.getUniqueId()).thenReturn(id);
var clock = new AtomicLong();
var repository = new YamlStealthStateRepository(directory.resolve("state.yml"));
try (var states = new StealthStateManager(repository, repository.load())) {
var progression = new EyeProgressionService(states, clock::get, ignored -> { });
var listener = new EyePotionListener(progression, failure -> fail(failure));
var weak = new PotionEffect(PotionEffectType.NIGHT_VISION, 100, 0, false, false, false);
var strong = new PotionEffect(PotionEffectType.NIGHT_VISION, 200, 1);
listener.onPotionEffect(new EntityPotionEffectEvent(player, strong, weak, player,
EntityPotionEffectEvent.Cause.POTION_DRINK, EntityPotionEffectEvent.Action.CHANGED, true));
clock.set(Duration.ofSeconds(1).toNanos());
progression.checkpoint(id).get(3, TimeUnit.SECONDS);
assertEquals(0, states.snapshot().eyeProgress(id).accumulatedMillis(),
"a cosmetic drink change must not claim the stronger existing effect");
listener.onPotionEffect(new EntityPotionEffectEvent(player, null, strong, player,
EntityPotionEffectEvent.Cause.POTION_DRINK, EntityPotionEffectEvent.Action.ADDED, false));
clock.set(Duration.ofSeconds(2).toNanos());
listener.onPotionEffect(new EntityPotionEffectEvent(player, strong, weak, null,
EntityPotionEffectEvent.Cause.PLUGIN, EntityPotionEffectEvent.Action.CHANGED, true));
clock.set(Duration.ofSeconds(3).toNanos());
listener.onPotionEffect(new EntityPotionEffectEvent(player, strong, null, null,
EntityPotionEffectEvent.Cause.EXPIRATION, EntityPotionEffectEvent.Action.REMOVED, false));
states.save().get(3, TimeUnit.SECONDS);
assertEquals(2000, states.snapshot().eyeProgress(id).accumulatedMillis());
}
}
@Test
void rejectedReplacementsNeitherStartNorStopQualifyingTime() throws Exception {
UUID id = UUID.randomUUID();
var player = mock(Player.class);
when(player.getUniqueId()).thenReturn(id);
var clock = new AtomicLong();
var repository = new YamlStealthStateRepository(directory.resolve("state.yml"));
try (var states = new StealthStateManager(repository, repository.load())) {
var progression = new EyeProgressionService(states, clock::get, ignored -> { });
var listener = new EyePotionListener(progression, failure -> fail(failure));
var weak = new PotionEffect(PotionEffectType.NIGHT_VISION, 100, 0);
var strong = new PotionEffect(PotionEffectType.NIGHT_VISION, 200, 1);
listener.onPotionEffect(new EntityPotionEffectEvent(player, strong, weak, player,
EntityPotionEffectEvent.Cause.POTION_DRINK, EntityPotionEffectEvent.Action.CHANGED, false));
clock.set(Duration.ofSeconds(1).toNanos());
progression.checkpoint(id).get(3, TimeUnit.SECONDS);
assertEquals(0, states.snapshot().eyeProgress(id).accumulatedMillis(),
"a rejected drink must not claim an existing non-drink effect");
listener.onPotionEffect(new EntityPotionEffectEvent(player, null, strong, player,
EntityPotionEffectEvent.Cause.POTION_DRINK, EntityPotionEffectEvent.Action.ADDED, false));
clock.set(Duration.ofSeconds(2).toNanos());
listener.onPotionEffect(new EntityPotionEffectEvent(player, strong, weak, null,
EntityPotionEffectEvent.Cause.PLUGIN, EntityPotionEffectEvent.Action.CHANGED, false));
clock.set(Duration.ofSeconds(3).toNanos());
listener.onPotionEffect(new EntityPotionEffectEvent(player, strong, null, null,
EntityPotionEffectEvent.Cause.EXPIRATION, EntityPotionEffectEvent.Action.REMOVED, false));
states.save().get(3, TimeUnit.SECONDS);
assertEquals(2000, states.snapshot().eyeProgress(id).accumulatedMillis(),
"a rejected plugin replacement must not interrupt the effective drunk potion");
}
}
@Test
void effectiveDirectDrinkAccumulatesAcrossRefreshAndDurablyUnlocksAtEightHours() throws Exception {
UUID id = UUID.randomUUID();
var player = mock(Player.class);
when(player.getUniqueId()).thenReturn(id);
var clock = new AtomicLong();
var repository = new YamlStealthStateRepository(directory.resolve("state.yml"));
try (var states = new StealthStateManager(repository, repository.load())) {
var progression = new EyeProgressionService(states, clock::get, ignored -> { });
var listener = new EyePotionListener(progression, failure -> fail(failure));
var nightVision = new PotionEffect(PotionEffectType.NIGHT_VISION, 9600, 0);
listener.onPotionEffect(new EntityPotionEffectEvent(player, null, nightVision, player,
EntityPotionEffectEvent.Cause.POTION_DRINK, EntityPotionEffectEvent.Action.ADDED, true));
for (int refresh = 1; refresh < 60; refresh++) {
clock.set(Duration.ofSeconds(refresh * 480L).toNanos());
listener.onPotionEffect(new EntityPotionEffectEvent(player, new PotionEffect(PotionEffectType.NIGHT_VISION, 1, 0), nightVision, player,
EntityPotionEffectEvent.Cause.POTION_DRINK, EntityPotionEffectEvent.Action.CHANGED, true));
}
clock.set(Duration.ofHours(8).toNanos() - 1_000_000);
progression.checkpoint(id).get(3, TimeUnit.SECONDS);
assertFalse(progression.isUnlocked(id));
clock.addAndGet(1_000_000);
listener.onPotionEffect(new EntityPotionEffectEvent(player, nightVision, null, null,
EntityPotionEffectEvent.Cause.EXPIRATION, EntityPotionEffectEvent.Action.REMOVED, false));
states.save().get(3, TimeUnit.SECONDS);
assertTrue(progression.isUnlocked(id), "eight hours of effective drink events must unlock the Eye");
assertEquals(28_800_000, repository.load().eyeProgress(id).accumulatedMillis());
assertTrue(progression.activePlayerIds().isEmpty());
}
}
}
@@ -0,0 +1,61 @@
package games.dmg.spigotstealth;
import java.util.List;
import java.util.stream.Stream;
import net.minecraft.SharedConstants;
import net.minecraft.commands.Commands;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.LayeredRegistryAccess;
import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.RegistryDataLoader;
import net.minecraft.server.Bootstrap;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.RegistryLayer;
import net.minecraft.server.ReloadableServerResources;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.repository.ServerPacksSource;
import net.minecraft.server.packs.resources.MultiPackResourceManager;
import net.minecraft.server.permissions.LevelBasedPermissionSet;
import net.minecraft.tags.TagLoader;
import net.minecraft.util.Util;
import net.minecraft.world.flag.FeatureFlags;
import net.minecraft.world.level.DataPackConfig;
import net.minecraft.world.level.WorldDataConfiguration;
import org.bukkit.craftbukkit.CraftRegistry;
/** Loads vanilla registries/tags/components using the same path as the server's own tests. */
final class NativeRuntime {
private NativeRuntime() {}
private static boolean ready;
static synchronized void bootstrap() throws Exception {
if (ready) { return; }
SharedConstants.tryDetectVersion();
Bootstrap.bootStrap();
var flags = FeatureFlags.VANILLA_SET;
var packs = ServerPacksSource.createVanillaTrustedRepository();
MinecraftServer.configurePackRepository(packs, new WorldDataConfiguration(new DataPackConfig(
FeatureFlags.REGISTRY.toNames(flags).stream().map(Identifier::getPath).toList(), List.of()), flags), true, false);
try (var resources = new MultiPackResourceManager(PackType.SERVER_DATA, packs.openAllSelected())) {
LayeredRegistryAccess<RegistryLayer> layers = RegistryLayer.createRegistryAccess();
List<Registry.PendingTags<?>> tags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC));
List<HolderLookup.RegistryLookup<?>> lookups = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLDGEN), tags);
RegistryAccess.Frozen worldgen = RegistryDataLoader.load(resources, lookups,
RegistryDataLoader.WORLDGEN_REGISTRIES, Util.backgroundExecutor()).join();
layers = layers.replaceFrom(RegistryLayer.WORLDGEN, worldgen);
RegistryAccess.Frozen dimensions = RegistryDataLoader.load(resources,
Stream.concat(lookups.stream(), worldgen.listRegistries()).toList(),
RegistryDataLoader.DIMENSION_REGISTRIES, Util.backgroundExecutor()).join();
layers = layers.replaceFrom(RegistryLayer.DIMENSIONS, dimensions);
Class.forName(org.bukkit.Registry.class.getName());
var datapack = ReloadableServerResources.loadResources(resources, layers, tags, flags,
Commands.CommandSelection.DEDICATED, LevelBasedPermissionSet.ALL_PERMISSIONS,
Util.backgroundExecutor(), Runnable::run).join();
datapack.updateComponentsAndStaticRegistryTags();
CraftRegistry.setMinecraftRegistry(layers.compositeAccess().freeze());
}
ready = true;
}
}
@@ -25,10 +25,14 @@ class BukkitIdentityPresentationTest {
BukkitIdentityPresentation presentation = new BukkitIdentityPresentation( BukkitIdentityPresentation presentation = new BukkitIdentityPresentation(
() -> List.of(target), scoreboard, mock(TabListController.class)); () -> List.of(target), scoreboard, mock(TabListController.class));
when(target.getDisplayName()).thenReturn("Original Alex");
presentation.conceal(target);
presentation.conceal(target); presentation.conceal(target);
presentation.reveal(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); verify(target).setSleepingIgnored(false);
} }
@@ -73,7 +77,7 @@ class BukkitIdentityPresentationTest {
} }
@Test @Test
void concealRemovesTabEntryAndHidesNameTagWithoutHidingEntity() { void concealRemovesTabEntryAndScramblesNameTagWithoutHidingEntity() {
UUID targetId = UUID.randomUUID(); UUID targetId = UUID.randomUUID();
Player target = player(targetId, "Alex"); Player target = player(targetId, "Alex");
Player observer = player(UUID.randomUUID(), "Morgan"); Player observer = player(UUID.randomUUID(), "Morgan");
@@ -87,7 +91,11 @@ class BukkitIdentityPresentationTest {
presentation.conceal(target); 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(team).addEntry("Alex");
verify(tabLists).remove(observer, targetId); verify(tabLists).remove(observer, targetId);
verify(observer, never()).hidePlayer(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()); verify(observer, never()).hidePlayer(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any());
@@ -13,7 +13,7 @@ class DeliveryConfigurationTest {
String workflow = Files.readString(Path.of(".gitea/workflows/ci.yml")); String workflow = Files.readString(Path.of(".gitea/workflows/ci.yml"));
assertTrue(workflow.contains("./gradlew clean check jar")); assertTrue(workflow.contains("./gradlew clean check jar"));
assertTrue(workflow.contains("commitlint")); assertTrue(workflow.contains("commitlint"));
assertTrue(workflow.contains("spigot-stealth-${{ github.sha }}")); assertTrue(workflow.contains("purpur-stealth-${{ github.sha }}"));
} }
@Test @Test
@@ -21,7 +21,7 @@ class DeliveryConfigurationTest {
String workflow = Files.readString(Path.of(".gitea/workflows/release.yml")); String workflow = Files.readString(Path.of(".gitea/workflows/release.yml"));
assertTrue(workflow.contains("semantic-release")); assertTrue(workflow.contains("semantic-release"));
assertTrue(workflow.contains("-PreleaseVersion=\"$VERSION\"")); assertTrue(workflow.contains("-PreleaseVersion=\"$VERSION\""));
assertTrue(workflow.contains("spigot-stealth-${VERSION}.jar")); assertTrue(workflow.contains("purpur-stealth-${VERSION}.jar"));
assertTrue(workflow.contains("/releases/${release_id}/assets")); assertTrue(workflow.contains("/releases/${release_id}/assets"));
} }
} }
@@ -0,0 +1,37 @@
package games.dmg.spigotstealth;
import static org.junit.jupiter.api.Assertions.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.junit.jupiter.api.Test;
class EyeProgressStateTest {
@Test
void eyeProgressRemainsIndependentAcrossExistingStealthAndSleepUpdates() {
UUID id = UUID.randomUUID();
var original = new PersistentStealthState(Map.of(), Map.of("future-root", "preserved"));
var eye = new EyeProgress(28_800_123, true, Map.of("future-eye", "preserved"));
var withEye = original.withEyeProgress(id, eye);
assertEquals(eye, withEye.eyeProgress(id));
assertEquals(EyeProgress.empty(), original.eyeProgress(id), "Updates must leave old snapshots immutable");
var changed = withEye.withPlayer(PlayerStealthState.empty(id).withProgress(123, true))
.withSleepCountPolicy(SleepCountPolicy.INCLUDE);
assertEquals(eye, changed.eyeProgress(id));
assertEquals(123, changed.player(id).accumulatedMillis());
assertEquals("preserved", changed.unknownFields().get("future-root"));
assertEquals(EyeProgress.empty(), changed.eyeProgress(UUID.randomUUID()));
}
@Test
void progressRejectsNegativeTimeAndCopiesUnknownFields() {
assertThrows(IllegalArgumentException.class, () -> new EyeProgress(-1, false));
var extras = new HashMap<String, Object>();
extras.put("extension", "old");
var progress = new EyeProgress(1, false, extras);
extras.put("extension", "new");
assertEquals("old", progress.unknownFields().get("extension"));
assertThrows(UnsupportedOperationException.class, () -> progress.unknownFields().put("other", 1));
}
}
@@ -0,0 +1,90 @@
package games.dmg.spigotstealth;
import static org.junit.jupiter.api.Assertions.*;
import java.nio.file.Path;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class EyeProgressionServiceTest {
@TempDir Path directory;
private final UUID id = UUID.randomUUID();
private final AtomicLong clock = new AtomicLong();
private final List<UUID> notifications = new CopyOnWriteArrayList<>();
@Test
void exactEightHoursUnlocksOnceWithoutOverlapOrLostSubmillisecondCredit() throws Exception {
var repository = new YamlStealthStateRepository(directory.resolve("state.yml"));
try (var states = new StealthStateManager(repository, repository.load())) {
var progression = new EyeProgressionService(states, clock::get, notifications::add);
progression.begin(id).join();
clock.set(600_000);
progression.checkpoint(id).join();
clock.set(1_200_000);
progression.begin(id).join(); // A refresh, not an overlapping timer.
assertEquals(1, states.snapshot().eyeProgress(id).accumulatedMillis());
clock.set(Duration.ofHours(8).toNanos() - 1);
progression.checkpoint(id).join();
assertFalse(progression.isUnlocked(id));
clock.incrementAndGet();
progression.checkpoint(id).join();
assertTrue(progression.isUnlocked(id));
assertEquals(List.of(id), notifications);
clock.addAndGet(Duration.ofSeconds(3).toNanos());
progression.stop(id).join();
assertEquals(28_803_000, states.snapshot().eyeProgress(id).accumulatedMillis());
assertEquals(List.of(id), notifications);
assertTrue(progression.activePlayerIds().isEmpty());
}
}
@Test
void intervalsAndRestartPreserveProgressWithoutOfflineOrUnobservedCredit() throws Exception {
var repository = new YamlStealthStateRepository(directory.resolve("state.yml"));
try (var states = new StealthStateManager(repository, repository.load())) {
var progression = new EyeProgressionService(states, clock::get, notifications::add);
progression.begin(id).join();
clock.addAndGet(Duration.ofHours(2).toNanos());
progression.stop(id).join();
clock.addAndGet(Duration.ofDays(30).toNanos());
progression.checkpoint(id).join();
assertEquals(Duration.ofHours(2).toMillis(), states.snapshot().eyeProgress(id).accumulatedMillis());
}
try (var states = new StealthStateManager(repository, repository.load())) {
var restarted = new EyeProgressionService(states, clock::get, notifications::add);
assertTrue(restarted.activePlayerIds().isEmpty());
restarted.begin(id).join();
clock.addAndGet(Duration.ofHours(6).toNanos());
restarted.stopAll().join();
assertTrue(restarted.isUnlocked(id));
assertEquals(28_800_000, repository.load().eyeProgress(id).accumulatedMillis());
assertTrue(restarted.activePlayerIds().isEmpty());
}
}
@Test
void missingDisconnectObservationDiscardsUnobservedTailAndExistingUnlocksDoNotRenotify() throws Exception {
var repository = new YamlStealthStateRepository(directory.resolve("state.yml"));
var existing = new PersistentStealthState(Map.of(), Map.of())
.withEyeProgress(id, new EyeProgress(28_800_000, true));
try (var states = new StealthStateManager(repository, existing)) {
var progression = new EyeProgressionService(states, clock::get, notifications::add);
assertTrue(progression.isUnlocked(id));
progression.begin(id).join();
clock.addAndGet(Duration.ofSeconds(1).toNanos());
progression.checkpoint(id).join();
clock.addAndGet(Duration.ofHours(1).toNanos());
progression.abandon(id);
progression.checkpoint(id).join();
assertEquals(28_801_000, states.snapshot().eyeProgress(id).accumulatedMillis());
assertTrue(progression.activePlayerIds().isEmpty());
assertTrue(notifications.isEmpty());
}
}
}
@@ -0,0 +1,103 @@
package games.dmg.spigotstealth;
import static org.junit.jupiter.api.Assertions.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class EyeStatePersistenceTest {
@TempDir Path directory;
@Test
void yamlRoundTripPreservesEyeAndStealthProgressAndUnknownFields() throws Exception {
UUID id = UUID.randomUUID();
var repository = new YamlStealthStateRepository(directory.resolve("state.yml"));
var eye = new EyeProgress(28_800_123, true, Map.of("future-eye", "keep"));
var state = new PersistentStealthState(Map.of(id, PlayerStealthState.empty(id).withProgress(456, true)),
Map.of("future-root", "keep")).withEyeProgress(id, eye);
repository.save(state);
var loaded = repository.load();
assertEquals(eye, loaded.eyeProgress(id));
assertEquals(state.player(id), loaded.player(id));
assertEquals(state.unknownFields(), loaded.unknownFields());
}
@Test
void legacyFilesStartAtZeroAndMalformedEyeRecordsCannotGrantUnlocksOrEraseStealth() throws Exception {
UUID id = UUID.randomUUID();
Path file = directory.resolve("state.yml");
var repository = new YamlStealthStateRepository(file);
var legacy = new PersistentStealthState(Map.of(id, PlayerStealthState.empty(id).withProgress(456, true)), Map.of());
repository.save(legacy);
assertEquals(EyeProgress.empty(), repository.load().eyeProgress(id));
// Deliberately malformed independent section, not a malformed existing player record.
Files.writeString(file, Files.readString(file) + "\neye-progress:\n " + id
+ ":\n accumulated-millis: -1\n unlocked: true\n");
var loaded = repository.load();
assertEquals(EyeProgress.empty(), loaded.eyeProgress(id));
assertEquals(legacy.player(id), loaded.player(id));
}
@Test
void pendingWriteDoesNotExposeDurableUnlockAndSavesOffTheCallingThread() throws Exception {
UUID id = UUID.randomUUID();
var initial = new PersistentStealthState(Map.of(), Map.of());
var entered = new CountDownLatch(1);
var release = new CountDownLatch(1);
Thread caller = Thread.currentThread();
var repository = new StealthStateRepository() {
@Override public PersistentStealthState load() { return initial; }
@Override public void save(PersistentStealthState state) throws IOException {
assertNotEquals(caller, Thread.currentThread());
entered.countDown();
try {
if (!release.await(5, TimeUnit.SECONDS)) { throw new IOException("test write timeout"); }
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
throw new IOException(exception);
}
}
};
var manager = new StealthStateManager(repository, initial);
try {
var saved = manager.update(state -> state.withEyeProgress(id, new EyeProgress(28_800_000, true)));
assertTrue(entered.await(5, TimeUnit.SECONDS));
assertTrue(manager.snapshot().eyeProgress(id).unlocked());
assertFalse(manager.durableSnapshot().eyeProgress(id).unlocked());
release.countDown();
saved.join();
assertTrue(manager.durableSnapshot().eyeProgress(id).unlocked());
} finally { release.countDown(); manager.close(); }
}
@Test
void failedWriteCannotGrantDurableUnlockAndSuccessfulRetryCan() {
UUID id = UUID.randomUUID();
var initial = new PersistentStealthState(Map.of(), Map.of());
var fail = new AtomicBoolean(true);
var repository = new StealthStateRepository() {
@Override public PersistentStealthState load() { return initial; }
@Override public void save(PersistentStealthState state) throws IOException {
if (fail.get()) { throw new IOException("test disk failure"); }
}
};
var manager = new StealthStateManager(repository, initial);
try {
assertThrows(CompletionException.class, () -> manager.update(state ->
state.withEyeProgress(id, new EyeProgress(28_800_000, true))).join());
assertFalse(manager.durableSnapshot().eyeProgress(id).unlocked());
fail.set(false);
manager.save().join();
assertTrue(manager.durableSnapshot().eyeProgress(id).unlocked());
} finally { fail.set(false); manager.close(); }
}
}
@@ -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,53 @@
package games.dmg.spigotstealth;
import static org.junit.jupiter.api.Assertions.*;
import java.io.DataInputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.jar.JarFile;
import org.junit.jupiter.api.Test;
import org.yaml.snakeyaml.Yaml;
class PurpurDistributionTest {
@Test
void packagesNewNameWithoutChangingRuntimeIdentityOrBundlingTheApi() throws Exception {
Path artifact = Path.of(System.getProperty("distribution.jar"));
String version = System.getProperty("distribution.version");
assertEquals("purpur-stealth-" + version + ".jar", artifact.getFileName().toString());
try (var jar = new JarFile(artifact.toFile())) {
Map<?, ?> metadata = new Yaml().load(jar.getInputStream(jar.getJarEntry("plugin.yml")));
assertEquals(version, metadata.get("version"));
assertEquals("SpigotStealth", metadata.get("name"), "Retain the data directory and persistent namespace");
assertEquals("games.dmg.spigotstealth.SpigotStealthPlugin", metadata.get("main"));
assertTrue(((Map<?, ?>) metadata.get("permissions")).containsKey("spigotstealth.admin"));
assertFalse(jar.stream().anyMatch(entry -> entry.getName().startsWith("org/bukkit/")
|| entry.getName().startsWith("org/purpurmc/") || entry.getName().endsWith("Test.class")));
}
}
@Test
void pluginBytecodeTargetsJava25() throws Exception {
try (var jar = new JarFile(System.getProperty("distribution.jar"));
var bytecode = new DataInputStream(jar.getInputStream(
jar.getJarEntry("games/dmg/spigotstealth/SpigotStealthPlugin.class")))) {
assertEquals(0xCAFEBABE, bytecode.readInt());
bytecode.readUnsignedShort();
assertEquals(69, bytecode.readUnsignedShort());
}
}
@Test
void releaseAndCiAgreeWithThePurpurDistributionNameAndToolchain() throws Exception {
String build = Files.readString(Path.of("build.gradle.kts"));
assertTrue(build.contains("purpur-api:26.2.build.2618-stable"));
assertFalse(build.contains("org.spigotmc:spigot-api"));
for (String workflow : new String[] {"ci.yml", "release.yml"}) {
String content = Files.readString(Path.of(".gitea/workflows", workflow));
assertTrue(content.contains("java-version: 25"));
assertTrue(content.contains("purpur-stealth-"), workflow);
assertFalse(content.contains("spigot-stealth-"), workflow);
}
}
}
@@ -0,0 +1,36 @@
package games.dmg.spigotstealth;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.bukkit.entity.Player;
import org.bukkit.event.server.ServerListPingEvent;
import org.junit.jupiter.api.Test;
class ServerListPingListenerTest {
@Test
void removesOnlyConcealedPlayersFromNativeServerPingSample() {
UUID concealedId = UUID.randomUUID();
Player visible = player(UUID.randomUUID());
Player concealed = player(concealedId);
ArrayList<Player> sample = new ArrayList<>(List.of(visible, concealed));
ServerListPingEvent event = mock(ServerListPingEvent.class);
when(event.iterator()).thenReturn(sample.iterator());
ServerListPingListener listener = new ServerListPingListener(() -> Set.of(concealedId));
listener.onServerListPing(event);
assertEquals(List.of(visible), sample);
}
private static Player player(UUID playerId) {
Player player = mock(Player.class);
when(player.getUniqueId()).thenReturn(playerId);
return player;
}
}
@@ -0,0 +1,24 @@
package games.dmg.spigotstealth;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import java.util.ArrayList;
import org.junit.jupiter.api.Test;
class ServerPingCompatibilityGuardTest {
@Test
void compatibilityFailureLeavesPingHandlingUsableAndWarnsOnlyOnce() {
ArrayList<String> warnings = new ArrayList<>();
ServerPingCompatibilityGuard guard = new ServerPingCompatibilityGuard(warnings::add);
assertDoesNotThrow(() -> guard.run(() -> {
throw new IllegalArgumentException("unsupported profile representation");
}));
assertDoesNotThrow(() -> guard.run(() -> {
throw new IllegalArgumentException("unsupported profile representation");
}));
assertEquals(1, warnings.size());
}
}
@@ -80,7 +80,10 @@ class StealthAdminCommandTest {
fixture.command.onCommand( fixture.command.onCommand(
sender, command, "stealthadmin", new String[] {"sleepcount", "include"}); sender, command, "stealthadmin", new String[] {"sleepcount", "include"});
verify(sender, org.mockito.Mockito.timeout(1000)).sendMessage(contains("now included")); verify(sender, never()).sendMessage(contains("now included"));
assertEquals(List.of(), fixture.audit);
fixture.runMainThreadCallback();
verify(sender).sendMessage(contains("now included"));
assertEquals(SleepCountPolicy.INCLUDE, fixture.manager.snapshot().sleepCountPolicy()); assertEquals(SleepCountPolicy.INCLUDE, fixture.manager.snapshot().sleepCountPolicy());
verify(fixture.presentation).refreshSleepCountPolicy(); verify(fixture.presentation).refreshSleepCountPolicy();
org.junit.jupiter.api.Assertions.assertTrue(fixture.audit.stream() org.junit.jupiter.api.Assertions.assertTrue(fixture.audit.stream()
@@ -125,7 +128,10 @@ class StealthAdminCommandTest {
try (Fixture fixture = fixture(playerId)) { try (Fixture fixture = fixture(playerId)) {
CommandSender sender = sender(true); CommandSender sender = sender(true);
fixture.command.onCommand(sender, mock(Command.class), "stealthadmin", new String[] {"grant", playerId.toString()}); fixture.command.onCommand(sender, mock(Command.class), "stealthadmin", new String[] {"grant", playerId.toString()});
verify(sender, org.mockito.Mockito.timeout(1000)).sendMessage(contains("granted")); verify(sender, never()).sendMessage(contains("granted"));
assertEquals(List.of(), fixture.audit);
fixture.runMainThreadCallback();
verify(sender).sendMessage(contains("granted"));
org.junit.jupiter.api.Assertions.assertTrue(fixture.manager.snapshot().player(playerId).unlocked()); org.junit.jupiter.api.Assertions.assertTrue(fixture.manager.snapshot().player(playerId).unlocked());
org.junit.jupiter.api.Assertions.assertTrue(fixture.audit.stream().anyMatch(message -> message.contains("grant") && message.contains(playerId.toString()))); org.junit.jupiter.api.Assertions.assertTrue(fixture.audit.stream().anyMatch(message -> message.contains("grant") && message.contains(playerId.toString())));
} }
@@ -167,16 +173,30 @@ class StealthAdminCommandTest {
manager, progression, presentation, ignored -> { }, List::of); manager, progression, presentation, ignored -> { }, List::of);
KnownPlayerResolver resolver = new KnownPlayerResolver(manager::snapshot, List::of); KnownPlayerResolver resolver = new KnownPlayerResolver(manager::snapshot, List::of);
ArrayList<String> audit = new ArrayList<>(); ArrayList<String> audit = new ArrayList<>();
var mainThread = new java.util.concurrent.LinkedBlockingQueue<Runnable>();
StealthAdminCommand command = new StealthAdminCommand( StealthAdminCommand command = new StealthAdminCommand(
administration, resolver, Runnable::run, audit::add, Duration.ofHours(8)); administration, resolver, mainThread::add, audit::add, Duration.ofHours(8));
return new Fixture(manager, command, presentation, audit); return new Fixture(manager, command, presentation, audit, mainThread);
} }
private record Fixture( private record Fixture(
StealthStateManager manager, StealthStateManager manager,
StealthAdminCommand command, StealthAdminCommand command,
IdentityPresentation presentation, IdentityPresentation presentation,
ArrayList<String> audit) implements AutoCloseable { ArrayList<String> audit,
java.util.concurrent.BlockingQueue<Runnable> mainThread) implements AutoCloseable {
void runMainThreadCallback() {
// A reply is emitted before the audit append. Await and run the whole scheduled callback,
// not just the reply invocation, and never read the ArrayList concurrently with the I/O thread.
try {
Runnable callback = mainThread.poll(5, java.util.concurrent.TimeUnit.SECONDS);
org.junit.jupiter.api.Assertions.assertNotNull(callback, "Expected a scheduled main-thread completion");
callback.run();
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
throw new AssertionError("Interrupted waiting for command completion", exception);
}
}
@Override public void close() { manager.close(); } @Override public void close() { manager.close(); }
} }
} }
@@ -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( QualifyingInvisibilityService progression = new QualifyingInvisibilityService(
manager, Duration.ofHours(8), System::nanoTime, ignored -> { }); manager, Duration.ofHours(8), System::nanoTime, ignored -> { });
IdentityPresentation presentation = mock(IdentityPresentation.class); IdentityPresentation presentation = mock(IdentityPresentation.class);
StealthSessionService sessions = new StealthSessionService(manager, progression);
StealthSessionListener listener = new StealthSessionListener( StealthSessionListener listener = new StealthSessionListener(
new StealthSessionService(manager, progression), presentation, "Stealth active"); sessions, presentation, "Stealth active");
Player player = player(playerId); Player player = player(playerId);
PlayerJoinEvent event = mock(PlayerJoinEvent.class); PlayerJoinEvent event = mock(PlayerJoinEvent.class);
when(event.getPlayer()).thenReturn(player); when(event.getPlayer()).thenReturn(player);
@@ -73,6 +74,10 @@ class StealthSessionListenerTest {
verify(event).setJoinMessage(null); verify(event).setJoinMessage(null);
verify(presentation).conceal(player); verify(presentation).conceal(player);
verify(player).sendMessage("Stealth active"); 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.");
} }
} }
@@ -0,0 +1,57 @@
package games.dmg.spigotstealth;
import static org.junit.jupiter.api.Assertions.*;
import java.io.IOException;
import java.nio.file.Path;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class StealthStateShutdownTest {
@TempDir Path directory;
@Test
void shutdownReturnsWithoutWaitingForDiskButDrainsTheFinalSnapshotAndRejectsLaterMutations() throws Exception {
var disk = new YamlStealthStateRepository(directory.resolve("state.yml"));
var saving = new CountDownLatch(1);
var release = new CountDownLatch(1);
StealthStateRepository repository = new StealthStateRepository() {
@Override public PersistentStealthState load() throws IOException { return disk.load(); }
@Override public void save(PersistentStealthState state) throws IOException {
saving.countDown();
try {
if (!release.await(5, TimeUnit.SECONDS)) { throw new IOException("Test disk gate timed out"); }
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
throw new IOException(exception);
}
disk.save(state);
}
};
var states = new StealthStateManager(repository, repository.load());
UUID id = UUID.randomUUID();
try {
states.update(state -> state.withEyeProgress(id, new EyeProgress(1234, false)));
assertTrue(saving.await(3, TimeUnit.SECONDS));
// A blocked save must not block the lifecycle caller. The test thread still releases the disk on failure.
var closing = CompletableFuture.supplyAsync(states::closeAsync).get(1, TimeUnit.SECONDS);
assertFalse(closing.isDone(), "shutdown completion must await the queued durable snapshot");
assertSame(closing, states.closeAsync());
assertThrows(ExecutionException.class, () -> states.update(state ->
state.withEyeProgress(id, new EyeProgress(28_800_000, true))).get(1, TimeUnit.SECONDS));
assertEquals(1234, states.snapshot().eyeProgress(id).accumulatedMillis());
release.countDown();
closing.get(3, TimeUnit.SECONDS);
assertEquals(1234, disk.load().eyeProgress(id).accumulatedMillis());
assertEquals(disk.load(), states.durableSnapshot());
} finally {
release.countDown();
states.close();
}
}
}