Add hourly floor-item cleanup and world-scoped Paper Anti-Xray
Some checks failed
Server Housekeeping Build / housekeeping (push) Successful in 1m7s
DuneRealms Plugin CI / plugins (push) Has been cancelled

This commit is contained in:
unimatrixgit 2026-12-03 22:35:19 +01:00
commit 70fadcc297
8 changed files with 336 additions and 0 deletions

View file

@ -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

View file

@ -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") }

View file

@ -0,0 +1 @@
rootProject.name = "DuneCleanup"

View file

@ -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<Material> DEBRIS = Set.of(Material.COBBLESTONE, Material.COBBLED_DEEPSLATE,
Material.DIRT, Material.COARSE_DIRT, Material.GRAVEL, Material.NETHERRACK);
private static final Set<String> 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<Chunk> chunks = new ArrayDeque<>();
for (var world : Bukkit.getWorlds()) chunks.addAll(Arrays.asList(world.getLoadedChunks()));
new BukkitRunnable() {
final Deque<Item> 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);
}
}

View file

@ -0,0 +1,4 @@
name: DuneCleanup
main: com.dunerealms.cleanup.DuneCleanup
version: 1.0.0
api-version: '1.21.8'

View file

@ -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));
}
}

View file

@ -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()

View file

@ -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()