From 70fadcc2971917253a7e85548edada92140db73a Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:35:19 +0100 Subject: [PATCH] Add hourly floor-item cleanup and world-scoped Paper Anti-Xray --- .forgejo/workflows/housekeeping.yml | 41 ++++++ DuneCleanup/build.gradle.kts | 20 +++ DuneCleanup/settings.gradle.kts | 1 + .../com/dunerealms/cleanup/DuneCleanup.java | 132 ++++++++++++++++++ DuneCleanup/src/main/resources/plugin.yml | 4 + .../dunerealms/cleanup/DuneCleanupTest.java | 30 ++++ tools/plugin_paper_antixray.py | 76 ++++++++++ tools/test_plugin_paper_antixray.py | 32 +++++ 8 files changed, 336 insertions(+) create mode 100644 .forgejo/workflows/housekeeping.yml create mode 100644 DuneCleanup/build.gradle.kts create mode 100644 DuneCleanup/settings.gradle.kts create mode 100644 DuneCleanup/src/main/java/com/dunerealms/cleanup/DuneCleanup.java create mode 100644 DuneCleanup/src/main/resources/plugin.yml create mode 100644 DuneCleanup/src/test/java/com/dunerealms/cleanup/DuneCleanupTest.java create mode 100644 tools/plugin_paper_antixray.py create mode 100644 tools/test_plugin_paper_antixray.py diff --git a/.forgejo/workflows/housekeeping.yml b/.forgejo/workflows/housekeeping.yml new file mode 100644 index 00000000..faff0906 --- /dev/null +++ b/.forgejo/workflows/housekeeping.yml @@ -0,0 +1,41 @@ +name: Server Housekeeping Build +on: + workflow_dispatch: + push: + branches: ['feat/hourly-floor-cleanup-*'] + +jobs: + housekeeping: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Test server housekeeping and package the standalone plugin + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p DuneCleanup test jar + python3 tools/test_plugin_paper_antixray.py -v + mkdir housekeeping-artifacts + cp DuneCleanup/build/libs/DuneCleanup.jar tools/plugin_paper_antixray.py housekeeping-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > housekeeping-artifacts/SOURCE_COMMIT + (cd housekeeping-artifacts && sha256sum -- *.jar *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Server-Housekeeping + path: housekeeping-artifacts/ + if-no-files-found: error diff --git a/DuneCleanup/build.gradle.kts b/DuneCleanup/build.gradle.kts new file mode 100644 index 00000000..ff854e27 --- /dev/null +++ b/DuneCleanup/build.gradle.kts @@ -0,0 +1,20 @@ +plugins { java } + +group = "com.dunerealms" +version = "1.0.0" + +repositories { + mavenCentral() + maven("https://repo.papermc.io/repository/maven-public/") +} + +dependencies { + compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") + testImplementation("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") + testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") +} + +java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) } +tasks.test { useJUnitPlatform() } +tasks.jar { archiveFileName.set("DuneCleanup.jar") } diff --git a/DuneCleanup/settings.gradle.kts b/DuneCleanup/settings.gradle.kts new file mode 100644 index 00000000..d57e5913 --- /dev/null +++ b/DuneCleanup/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "DuneCleanup" diff --git a/DuneCleanup/src/main/java/com/dunerealms/cleanup/DuneCleanup.java b/DuneCleanup/src/main/java/com/dunerealms/cleanup/DuneCleanup.java new file mode 100644 index 00000000..115b34f7 --- /dev/null +++ b/DuneCleanup/src/main/java/com/dunerealms/cleanup/DuneCleanup.java @@ -0,0 +1,132 @@ +package com.dunerealms.cleanup; + +import java.util.ArrayDeque; +import java.util.Arrays; +import java.util.Deque; +import java.util.Set; +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.entity.Item; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockDropItemEvent; +import org.bukkit.event.entity.ItemMergeEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.persistence.PersistentDataType; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitRunnable; + +public final class DuneCleanup extends JavaPlugin implements Listener { + static final long HOUR = 72_000L; + static final long MINIMUM_AGE_MS = 120_000L; + private static final int CHUNKS_PER_TICK = 12; + private static final int ITEMS_PER_TICK = 96; + private static final double PLAYER_DISTANCE_SQUARED = 16.0 * 16; + private static final Set DEBRIS = Set.of(Material.COBBLESTONE, Material.COBBLED_DEEPSLATE, + Material.DIRT, Material.COARSE_DIRT, Material.GRAVEL, Material.NETHERRACK); + private static final Set ORDINARY_METADATA = Set.of("dunerealms:origin_world", "dunerealms:quality", + "dunerealms:equipment_mark", "dunerealms:metadata_policy", "dunerealms:item_class", "dunerealms:metadata_lore_header"); + private NamespacedKey looseSince; + private boolean sweeping; + + @Override public void onEnable() { + looseSince = new NamespacedKey(this, "loose_since"); + getServer().getPluginManager().registerEvents(this, this); + getServer().getScheduler().runTaskTimer(this, this::startSweep, HOUR, HOUR); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void droppedBlock(BlockDropItemEvent event) { + if (event.getBlockState() instanceof org.bukkit.block.Container) return; + long now = System.currentTimeMillis(); + for (Item item : event.getItems()) { + if (ordinaryDebris(item.getItemStack())) + item.getPersistentDataContainer().set(looseSince, PersistentDataType.LONG, now); + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void merged(ItemMergeEvent event) { + var source = event.getEntity().getPersistentDataContainer(); + var target = event.getTarget().getPersistentDataContainer(); + Long since = mergedSince(source.get(looseSince, PersistentDataType.LONG), + target.get(looseSince, PersistentDataType.LONG)); + if (since == null) { + source.remove(looseSince); + target.remove(looseSince); + } else { + target.set(looseSince, PersistentDataType.LONG, since); + } + } + + static Long mergedSince(Long source, Long target) { + return source == null || target == null ? null : Math.max(source, target); + } + + static boolean oldEnough(Long since, long now) { + return since != null && since > 0 && now >= since && now - since >= MINIMUM_AGE_MS; + } + + static boolean debrisMaterial(Material material) { return DEBRIS.contains(material); } + + private static boolean ordinaryDebris(ItemStack stack) { + if (!debrisMaterial(stack.getType())) return false; + if (!stack.hasItemMeta()) return true; + var meta = stack.getItemMeta(); + return meta != null && !meta.hasDisplayName() && !meta.hasItemModel() && !meta.hasCustomModelData() + && !meta.hasEnchants() && meta.getPersistentDataContainer().getKeys().stream() + .map(NamespacedKey::toString).allMatch(ORDINARY_METADATA::contains); + } + + private boolean eligible(Item item, long now) { + if (!item.isValid() || !item.isOnGround() || item.getOwner() != null || item.getThrower() != null + || !item.willAge() || !item.canPlayerPickup() || item.getPickupDelay() > 0 + || !oldEnough(item.getPersistentDataContainer().get(looseSince, PersistentDataType.LONG), now) + || !ordinaryDebris(item.getItemStack())) return false; + var location = item.getLocation(); + for (var player : item.getWorld().getPlayers()) { + if (player.getLocation().distanceSquared(location) <= PLAYER_DISTANCE_SQUARED) return false; + } + return true; + } + + private void startSweep() { + if (sweeping) return; + sweeping = true; + Deque chunks = new ArrayDeque<>(); + for (var world : Bukkit.getWorlds()) chunks.addAll(Arrays.asList(world.getLoadedChunks())); + new BukkitRunnable() { + final Deque items = new ArrayDeque<>(); + int removed; + @Override public void run() { + long now = System.currentTimeMillis(); + int chunksChecked = 0; + for (int checked = 0; checked < ITEMS_PER_TICK;) { + if (items.isEmpty()) { + if (chunks.isEmpty() || chunksChecked == CHUNKS_PER_TICK) break; + Chunk chunk = chunks.removeFirst(); + chunksChecked++; + if (!chunk.isLoaded() || !chunk.isEntitiesLoaded()) continue; + for (var entity : chunk.getEntities()) + if (entity instanceof Item item) items.addLast(item); + continue; + } + Item item = items.removeFirst(); + checked++; + if (eligible(item, now)) { + item.remove(); + removed++; + } + } + if (chunks.isEmpty() && items.isEmpty()) { + sweeping = false; + if (removed > 0) getLogger().info("Cleared " + removed + " old loose debris stacks."); + cancel(); + } + } + }.runTaskTimer(this, 1L, 1L); + } +} diff --git a/DuneCleanup/src/main/resources/plugin.yml b/DuneCleanup/src/main/resources/plugin.yml new file mode 100644 index 00000000..bd2f4a77 --- /dev/null +++ b/DuneCleanup/src/main/resources/plugin.yml @@ -0,0 +1,4 @@ +name: DuneCleanup +main: com.dunerealms.cleanup.DuneCleanup +version: 1.0.0 +api-version: '1.21.8' diff --git a/DuneCleanup/src/test/java/com/dunerealms/cleanup/DuneCleanupTest.java b/DuneCleanup/src/test/java/com/dunerealms/cleanup/DuneCleanupTest.java new file mode 100644 index 00000000..0aef5f8c --- /dev/null +++ b/DuneCleanup/src/test/java/com/dunerealms/cleanup/DuneCleanupTest.java @@ -0,0 +1,30 @@ +package com.dunerealms.cleanup; + +import org.bukkit.Material; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +final class DuneCleanupTest { + @Test void onlyOldTrackedDropsAgeIntoEligibility() { + assertEquals(72_000L, DuneCleanup.HOUR); + assertFalse(DuneCleanup.oldEnough(null, 500_000L)); + assertFalse(DuneCleanup.oldEnough(380_001L, 500_000L)); + assertFalse(DuneCleanup.oldEnough(501_000L, 500_000L)); + assertTrue(DuneCleanup.oldEnough(380_000L, 500_000L)); + } + + @Test void mergingUntrackedLootProtectsTheStackAndNewerDebrisRestartsItsAge() { + assertNull(DuneCleanup.mergedSince(100L, null)); + assertNull(DuneCleanup.mergedSince(null, 100L)); + assertEquals(400L, DuneCleanup.mergedSince(100L, 400L)); + } + + @Test void oresAndEquipmentAreNeverDebris() { + assertTrue(DuneCleanup.debrisMaterial(Material.COBBLESTONE)); + assertFalse(DuneCleanup.debrisMaterial(Material.ORANGE_DYE)); + assertFalse(DuneCleanup.debrisMaterial(Material.RAW_IRON)); + assertFalse(DuneCleanup.debrisMaterial(Material.DIAMOND_PICKAXE)); + assertFalse(DuneCleanup.debrisMaterial(Material.CHEST_MINECART)); + } +} diff --git a/tools/plugin_paper_antixray.py b/tools/plugin_paper_antixray.py new file mode 100644 index 00000000..1825d49f --- /dev/null +++ b/tools/plugin_paper_antixray.py @@ -0,0 +1,76 @@ +"""Stage the Paper anti-xray subtree for reviewed DuneRealms mining worlds.""" +import argparse +from hashlib import sha256 +from pathlib import Path +import re + +OVERWORLD = { + "arrakis": ("coal", "emerald"), + "caladan": ("coal", "iron", "copper", "lapis"), + "giedi_prime": ("coal", "iron", "copper", "redstone"), + "kaitain": ("gold", "emerald", "diamond", "lapis"), + "sigma_draconis_iv": ("iron", "copper", "redstone", "diamond"), +} + + +def profile(server, dimension): + if dimension == "the_nether" and server == "giedi_prime": + return 128, ("ancient_debris", "nether_gold_ore", "nether_quartz_ore") + if dimension != "overworld" or server not in OVERWORLD: + raise ValueError("This world is outside the reviewed mining scope") + minerals = OVERWORLD[server] + hidden = [block for mineral in minerals for block in (mineral + "_ore", "deepslate_" + mineral + "_ore")] + hidden.extend("raw_" + mineral + "_block" for mineral in minerals if mineral in {"iron", "copper"}) + return 320, tuple(hidden) + + +def render(current, server, dimension): + height, hidden = profile(server, dimension) + text = current.decode("utf-8") + nl = "\r\n" if "\r\n" in text else "\n" + if re.search(r"(?m)^[ \t]*anti-xray[ \t]*:", text): + raise ValueError("Existing anti-xray override requires a separate reviewed preimage") + rows = [" anti-xray:", " enabled: true", " engine-mode: 1", f" max-block-height: {height}", + " update-radius: 2", " use-permission: false", " lava-obscures: false", + " replacement-blocks: []", " hidden-blocks:"] + rows.extend(" - " + ore for ore in hidden) + subtree = nl.join(rows) + nl + headers = list(re.finditer(r"(?m)^anticheat[ \t]*:[^\r\n]*(?:\r?\n|\Z)", text)) + if not headers: + suffix = "" if not text or text.endswith("\n") else nl + return (text + suffix + "anticheat:" + nl + subtree).encode("utf-8") + if len(headers) != 1: + raise ValueError("Expected one Paper anticheat mapping") + header = headers[0] + value = header.group().split(":", 1)[1].split("#", 1)[0].strip() + if value not in ("", "{}"): + raise ValueError("Existing anticheat node is not a writable block mapping") + insert_at = header.end() + if value == "{}": + start = text.index("{}", header.start(), header.end()) + text = text[:start] + text[start + 2:] + insert_at -= 2 + if not text[:insert_at].endswith("\n"): + subtree = nl + subtree + return (text[:insert_at] + subtree + text[insert_at:]).encode("utf-8") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("server") + parser.add_argument("dimension") + parser.add_argument("preimage", type=Path) + parser.add_argument("expected_sha") + parser.add_argument("output", type=Path) + args = parser.parse_args() + current = args.preimage.read_bytes() + if sha256(current).hexdigest() != args.expected_sha: + raise ValueError("Paper config differs from the verified preimage") + result = render(current, args.server, args.dimension) + with args.output.open("xb") as file: + file.write(result) + print(sha256(result).hexdigest()) + + +if __name__ == "__main__": + main() diff --git a/tools/test_plugin_paper_antixray.py b/tools/test_plugin_paper_antixray.py new file mode 100644 index 00000000..9364979b --- /dev/null +++ b/tools/test_plugin_paper_antixray.py @@ -0,0 +1,32 @@ +import unittest + +from plugin_paper_antixray import profile, render + + +class AntiXrayTests(unittest.TestCase): + def test_planet_only_protects_its_mined_palette(self): + height, hidden = profile("sigma_draconis_iv", "overworld") + self.assertEqual(height, 320) + self.assertIn("deepslate_diamond_ore", hidden) + self.assertIn("raw_copper_block", hidden) + self.assertNotIn("lapis_ore", hidden) + + def test_giedi_nether_is_distinct_and_end_and_lobby_are_out_of_scope(self): + self.assertEqual(profile("giedi_prime", "the_nether"), + (128, ("ancient_debris", "nether_gold_ore", "nether_quartz_ore"))) + for world in (("lobby", "overworld"), ("sigma_draconis_iv", "the_end"), ("caladan", "the_nether")): + with self.assertRaises(ValueError): + profile(*world) + + def test_stage_preserves_unrelated_lines_and_rejects_an_existing_override(self): + original = b"# paper\r\n_version: 30\r\nanticheat: # keep\r\n redstone: true\r\n" + staged = render(original, "arrakis", "overworld") + self.assertTrue(staged.startswith(b"# paper\r\n_version: 30\r\nanticheat: # keep\r\n")) + self.assertTrue(staged.endswith(b" redstone: true\r\n")) + self.assertIn(b" - emerald_ore\r\n", staged) + with self.assertRaisesRegex(ValueError, "Existing anti-xray override"): + render(staged, "arrakis", "overworld") + + +if __name__ == "__main__": + unittest.main()