Add private server control panel and display sandworm; document Arrakis reset

This commit is contained in:
unimatrixgit 2026-10-28 11:06:50 +01:00
commit d0d89e2cc1
19 changed files with 674 additions and 13 deletions

View file

@ -94,3 +94,9 @@ Expired missions consume no cargo and pay no reward. When the last mission expir
smuggler returns to green particles and normal roaming, and its temporary lighting is removed.
Contracts created before 1.0.8 receive one initial 30-minute window when first upgraded; subsequent
restarts preserve their saved deadline.
## Block-display sandworm (Core 1.0.13)
`sandworms.model: display` renders the existing Husk/Sniffer pair as a 27-part segmented block-display worm. The Sniffer remains the damageable hitbox, and the current AI, health and reward paths are retained. This model needs no custom resource pack. Use `sandworms.model: sniffer` for the original appearance.
The display model rises, follows the controller path, flashes on damage and sinks on death. Movement history is capped at 256 samples; initial terrain sampling avoids loading chunks. Model parts are non-persistent and are removed when the plugin stops. Display-spawn failure removes partial parts and keeps the Sniffer visible. Visual body segments have no additional collision hitboxes. Client appearance and large worm populations should be assessed in gameplay before raising the configured population cap.

View file

@ -1,6 +1,6 @@
plugins { java }
group = "com.example"
version = "1.0.12"
version = "1.0.13"
repositories { mavenCentral(); maven("https://repo.papermc.io/repository/maven-public/"); maven("https://jitpack.io") }
dependencies {
compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT")

View file

@ -165,6 +165,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
getLogger().info("DuneCore enabled. Gameplay, faction travel, Arrakis threats, and spice raiders ready.");
}
@Override public void onDisable() {
if (sandwormMobs != null) sandwormMobs.close();
for (UUID playerId : new ArrayList<>(ordosCloakedArmor.keySet())) restoreOrdosArmor(playerId);
if(serverJobs!=null)serverJobs.save();

View file

@ -8,21 +8,69 @@ import org.bukkit.event.entity.*;
import org.bukkit.persistence.PersistentDataType;
import java.util.*;
/** A damageable Sniffer body following an invisible Husk with native zombie AI. */
final class SandwormMobs implements Listener {
/**
* A damageable Sniffer body following an invisible Husk with native zombie AI.
* With {@code sandworms.model: display} (default) the Sniffer is invisible and a block-display worm
* ({@link SandwormModel}) follows the brain instead, so players need no resource pack.
*/
final class SandwormMobs implements Listener, AutoCloseable {
private final DuneCore plugin;
private final NamespacedKey wormKey, bodyKey, brainKey;
private final NamespacedKey wormKey, bodyKey, brainKey, modelKey;
private final Map<UUID, UUID> pairs = new HashMap<>(); // body -> brain
private final Map<UUID, SandwormModel> models = new HashMap<>(); // body -> visible model
private final List<SandwormModel> fading = new ArrayList<>(); // models sinking after their worm ended
SandwormMobs(DuneCore plugin, NamespacedKey wormKey) {
this.plugin = plugin;
this.wormKey = wormKey;
bodyKey = new NamespacedKey(plugin, "sandworm_body");
brainKey = new NamespacedKey(plugin, "sandworm_brain");
modelKey = new NamespacedKey(plugin, "sandworm_model");
Bukkit.getPluginManager().registerEvents(this, plugin);
Bukkit.getScheduler().runTaskTimer(plugin, this::tick, 1L, 1L);
World world = Bukkit.getWorld("arrakis");
if (world != null) for (Entity entity : new ArrayList<>(world.getEntities())) restore(entity);
if (world != null) for (Entity entity : new ArrayList<>(world.getEntities())) {
// Model parts are never saved, but a plugin reload can leave some behind; restored pairs get a fresh model.
if (entity.getPersistentDataContainer().has(modelKey, PersistentDataType.BYTE)) entity.remove();
else restore(entity);
}
}
@Override public void close() {
models.values().forEach(SandwormModel::removeNow);
fading.forEach(SandwormModel::removeNow);
models.clear(); fading.clear();
for (UUID id : pairs.keySet()) {
Entity entity = Bukkit.getEntity(id);
if (entity instanceof Sniffer body) body.setInvisible(false);
}
pairs.clear();
}
private boolean displayModel() {
return "display".equalsIgnoreCase(plugin.getConfig().getString("sandworms.model", "display"));
}
/** Attaches the block-display model; if it cannot be built (or the sniffer model is configured) the Sniffer stays visible. */
private void attachModel(Sniffer body, Husk brain) {
if (models.containsKey(body.getUniqueId())) return;
if (!displayModel()) { body.setInvisible(false); return; }
Location at = brain.getLocation();
if (at == null || at.getWorld() == null) return;
LivingEntity target = brain.getTarget();
Location away = target != null ? target.getLocation() : at.clone().add(at.getDirection());
try {
models.put(body.getUniqueId(), new SandwormModel(at, away, modelKey));
body.setInvisible(true);
} catch (RuntimeException ex) {
body.setInvisible(false);
}
}
/** The worm ended: its model sinks into the sand and is removed. */
private void fadeModel(UUID bodyId) {
SandwormModel model = models.remove(bodyId);
if (model != null) { model.sink(); fading.add(model); }
}
Sniffer spawn(Location location, Player target) {
@ -63,6 +111,7 @@ final class SandwormMobs implements Listener {
body.getPersistentDataContainer().set(brainKey, PersistentDataType.STRING, brain.getUniqueId().toString());
brain.getPersistentDataContainer().set(bodyKey, PersistentDataType.STRING, body.getUniqueId().toString());
pairs.put(body.getUniqueId(), brain.getUniqueId());
attachModel(body, brain);
}
private UUID id(Entity entity, NamespacedKey key) {
@ -103,24 +152,35 @@ final class SandwormMobs implements Listener {
}
private void tick() {
fading.removeIf(model -> !model.tick(null));
for (var entry : new ArrayList<>(pairs.entrySet())) {
Entity bodyEntity = Bukkit.getEntity(entry.getKey()), brainEntity = Bukkit.getEntity(entry.getValue());
if (!(bodyEntity instanceof Sniffer body)) {
if (brainEntity != null && brainEntity.isValid()) brainEntity.remove();
pairs.remove(entry.getKey()); continue;
pairs.remove(entry.getKey()); fadeModel(entry.getKey()); continue;
}
if (!(brainEntity instanceof Husk brain)) {
// On despawn remove the visual; chunk unload is handled by the delayed load repair.
if (body.isValid()) body.remove();
pairs.remove(entry.getKey()); continue;
pairs.remove(entry.getKey()); fadeModel(entry.getKey()); continue;
}
if (!body.isValid() || body.isDead() || !brain.isValid() || brain.isDead()) continue;
if (!brain.getWorld().getName().equalsIgnoreCase("arrakis")) { brain.remove(); body.remove(); pairs.remove(entry.getKey()); continue; }
if (!brain.getWorld().getName().equalsIgnoreCase("arrakis")) {
brain.remove(); body.remove(); pairs.remove(entry.getKey()); fadeModel(entry.getKey()); continue;
}
body.teleport(brain.getLocation());
body.setRotation(brain.getLocation().getYaw(), 0);
SandwormModel model = models.get(entry.getKey());
if (model != null) model.tick(brain.getLocation());
}
}
/** Hits on the Sniffer body flash the visible model red. */
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBodyDamage(EntityDamageEvent event) {
SandwormModel model = models.get(event.getEntity().getUniqueId());
if (model != null) model.flash();
}
@EventHandler(priority = EventPriority.HIGHEST) public void onBrainDamage(EntityDamageEvent event) {
if (event.getEntity().getPersistentDataContainer().has(bodyKey, PersistentDataType.STRING)) event.setCancelled(true);
}
@ -142,6 +202,8 @@ final class SandwormMobs implements Listener {
event.getDrops().clear(); event.setDroppedExp(0);
Entity other = Bukkit.getEntity(partner);
if (other != null) other.remove();
pairs.remove(entity instanceof Sniffer ? entity.getUniqueId() : partner);
UUID bodyId = entity instanceof Sniffer ? entity.getUniqueId() : partner;
pairs.remove(bodyId);
fadeModel(bodyId);
}
}

View file

@ -0,0 +1,152 @@
package com.example.dunerealms;
import org.bukkit.*;
import org.bukkit.entity.*;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.util.Transformation;
import org.joml.Quaternionf;
import org.joml.Vector3f;
import java.util.*;
/**
* The visible sandworm when {@code sandworms.model: display}: a chain of block displays that follows the
* Husk brain, so no resource pack is needed. The invisible Sniffer body keeps the hitbox, health and rewards.
* Head: terracotta skull, black mouth, glowing spice throat, ring of bone teeth. Body: fourteen rings that
* trace the brain's actual path and thin toward the tail. Rises out of the sand on arrival, sinks on death.
*/
final class SandwormModel {
private static final int SEGMENTS = 14, RISE_TICKS = 25, SINK_TICKS = 30;
private static final double GAP = 1.45, HEAD_LIFT = 2.0, HEAD = 3.4;
private final World world;
private final NamespacedKey partKey;
private final List<BlockDisplay> head = new ArrayList<>(), body = new ArrayList<>();
private final Deque<Location> path = new ArrayDeque<>(); // newest first
private Location last;
private float yaw;
private int age, sinking = -1, flash;
/** Throws IllegalStateException when the displays cannot be spawned; the caller keeps the Sniffer visible. */
SandwormModel(Location start, Location awayFrom, NamespacedKey partKey) {
this.world = start.getWorld();
this.partKey = partKey;
this.last = start.clone();
double dx = start.getX() - awayFrom.getX(), dz = start.getZ() - awayFrom.getZ(), len = Math.hypot(dx, dz);
if (len < 0.01) { dx = 1; dz = 0; len = 1; }
dx /= len; dz /= len;
yaw = yawOf(-dx, -dz);
// Lay the body out behind the head across the dunes, so the worm is whole from the first tick.
for (double d = 0; d <= SEGMENTS * GAP + 4; d += 0.5) {
int x = (int) Math.floor(start.getX() + dx * d), z = (int) Math.floor(start.getZ() + dz * d);
path.addLast(new Location(world, start.getX() + dx * d, world.isChunkLoaded(x >> 4, z >> 4) ? world.getHighestBlockYAt(x, z) + 1 : start.getY(), start.getZ() + dz * d));
}
Location hidden = start.clone().subtract(0, 8, 0);
try {
float h = (float) (HEAD / 2);
head.add(part(hidden, Material.TERRACOTTA, new Vector3f(-h, -h, -h), new Vector3f((float) HEAD, (float) HEAD, (float) HEAD)));
head.add(part(hidden, Material.BLACK_CONCRETE, new Vector3f(-1.35f, -1.35f, h), new Vector3f(2.7f, 2.7f, 0.12f)));
head.add(part(hidden, Material.SHROOMLIGHT, new Vector3f(-0.45f, -0.45f, h + 0.13f), new Vector3f(0.9f, 0.9f, 0.08f)));
for (int k = 0; k < 10; k++) {
double a = k * Math.PI * 2 / 10;
head.add(part(hidden, Material.BONE_BLOCK, new Vector3f((float) Math.cos(a) - 0.13f, (float) Math.sin(a) - 0.13f, h + 0.05f),
new Vector3f(0.26f, 0.26f, 0.55f)));
}
for (int i = 0; i < SEGMENTS; i++) {
float s = (float) (3.0 - 2.1 * i / (SEGMENTS - 1));
body.add(part(hidden, i % 2 == 0 ? Material.TERRACOTTA : Material.BROWN_TERRACOTTA,
new Vector3f(-s / 2, -s * 0.45f, -s / 2), new Vector3f(s, s, s)));
}
} catch (RuntimeException ex) { removeNow(); throw ex; }
}
private BlockDisplay part(Location at, Material material, Vector3f translation, Vector3f scale) {
BlockDisplay display = world.spawn(at, BlockDisplay.class, d -> {
d.setBlock(material.createBlockData());
d.setTransformation(new Transformation(translation, new Quaternionf(), scale, new Quaternionf()));
d.setPersistent(false); // never saved: a fresh model is attached when the pair is restored
d.setTeleportDuration(3);
d.setViewRange(2.0f);
if (material == Material.SHROOMLIGHT) d.setBrightness(new Display.Brightness(15, 15));
d.getPersistentDataContainer().set(partKey, PersistentDataType.BYTE, (byte) 1);
});
if (display == null) throw new IllegalStateException("block display could not be spawned");
return display;
}
void flash() { flash = 6; }
/** Starts the dive back under the sand; tick(...) returns false once it is gone. */
void sink() { if (sinking < 0) sinking = 0; }
void removeNow() {
head.forEach(Entity::remove); body.forEach(Entity::remove);
head.clear(); body.clear();
}
/** Advances one tick following the brain's location; pass null once the worm is gone. False when removed. */
boolean tick(Location brain) {
age++;
if (brain == null) sink();
else if (sinking < 0) {
Location newest = path.peekFirst();
if (newest == null || newest.distanceSquared(brain) > 0.04) {
if (newest != null) {
double mx = brain.getX() - newest.getX(), mz = brain.getZ() - newest.getZ();
if (mx * mx + mz * mz > 0.0004) yaw = yawOf(mx, mz);
}
path.addFirst(brain.clone());
trim();
}
last = brain.clone();
}
if (sinking >= 0 && ++sinking > SINK_TICKS) { removeNow(); return false; }
double sink = sinking >= 0 ? 8.0 * sinking / SINK_TICKS : Math.max(0, 8.0 * (1 - (double) age / RISE_TICKS));
Location headAt = last.clone().add(0, HEAD_LIFT - sink, 0);
headAt.setYaw(yaw); headAt.setPitch(-20f);
boolean glow = flash > 0;
if (flash > 0) flash--;
for (BlockDisplay d : head) {
d.teleport(headAt);
if (d.isGlowing() != glow) { d.setGlowing(glow); d.setGlowColorOverride(glow ? Color.RED : null); }
}
// Each ring sits at an even distance along the path the head travelled.
Iterator<Location> it = path.iterator();
Location prev = it.hasNext() ? it.next() : last, ahead = last;
double walked = 0;
for (int seg = 0; seg < body.size(); seg++) {
double want = HEAD / 2 + 0.6 + seg * GAP;
while (walked < want && it.hasNext()) {
Location next = it.next();
walked += Math.hypot(next.getX() - prev.getX(), next.getZ() - prev.getZ());
prev = next;
}
Location at = prev.clone().subtract(0, sink, 0);
at.setYaw(yawOf(ahead.getX() - prev.getX(), ahead.getZ() - prev.getZ())); at.setPitch(0f);
body.get(seg).teleport(at);
ahead = prev;
}
if (age % 4 == 0 && sinking < 0 && sink < 1)
world.spawnParticle(Particle.BLOCK, last, 25, 1.6, 0.2, 1.6, Material.SAND.createBlockData());
if (sinking >= 0 && sinking % 3 == 0)
world.spawnParticle(Particle.BLOCK, last, 60, 2.2, 0.5, 2.2, Material.SAND.createBlockData());
return true;
}
private void trim() {
double need = SEGMENTS * GAP + HEAD + 6, total = 0;
Location prev = null;
int keep = 0;
for (Location l : path) {
if (prev != null) total += Math.hypot(l.getX() - prev.getX(), l.getZ() - prev.getZ());
prev = l; keep++;
if (total > need) break;
}
// Bound vertical-only movement and tiny horizontal jitter as well.
keep = Math.min(keep, 254);
while (path.size() > keep + 2) path.removeLast();
}
/** Minecraft yaw for a horizontal direction (0 = +Z/south, 90 = -X/west). */
private static float yawOf(double dx, double dz) { return (float) Math.toDegrees(Math.atan2(-dx, dz)); }
}

View file

@ -3,6 +3,8 @@ spice-respawn-seconds: 120
# Sandworms spawn near players on Arrakis only, at most once per interval serverwide.
# A visible Sniffer body follows an invisible Husk with native zombie targeting and melee AI.
sandworms:
# Block-display visual; use sniffer to restore the original body.
model: display
enabled: true
health: 500.0
attack-damage: 8.0

View file

@ -1,5 +1,5 @@
name: DuneCore
version: 1.0.12
version: 1.0.13
main: com.example.dunerealms.DuneCore
api-version: '1.21.8'
depend: [Vault, DuneEss]

View file

@ -0,0 +1,136 @@
package com.example.dunerealms;
import org.bukkit.*;
import org.bukkit.attribute.Attribute;
import org.bukkit.attribute.AttributeInstance;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.*;
import org.bukkit.event.entity.*;
import org.bukkit.inventory.EntityEquipment;
import org.bukkit.persistence.*;
import org.bukkit.plugin.PluginManager;
import org.bukkit.scheduler.BukkitScheduler;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.MockedStatic;
import java.util.*;
import java.util.function.Consumer;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
class SandwormModelTest {
private PersistentDataContainer tags() {
PersistentDataContainer tags = mock(PersistentDataContainer.class);
Map<NamespacedKey, Object> values = new HashMap<>();
doAnswer(call -> { values.put(call.getArgument(0), call.getArgument(2)); return null; }).when(tags).set(any(), any(), any());
when(tags.get(any(), any())).thenAnswer(call -> values.get(call.getArgument(0)));
when(tags.has(any(), any())).thenAnswer(call -> values.containsKey(call.getArgument(0)));
return tags;
}
private record Rig(DuneCore plugin, World world, Location location, Husk brain, Sniffer body, BlockDisplay display) {}
private Rig rig(String model) {
DuneCore plugin = mock(DuneCore.class);
when(plugin.getName()).thenReturn("DuneCore");
when(plugin.namespace()).thenReturn("dunecore");
YamlConfiguration config = new YamlConfiguration();
if (model != null) config.set("sandworms.model", model);
when(plugin.getConfig()).thenReturn(config);
World world = mock(World.class); when(world.getName()).thenReturn("arrakis");
Location location = new Location(world, 12, 75, 34);
Husk brain = mock(Husk.class); Sniffer body = mock(Sniffer.class); BlockDisplay display = mock(BlockDisplay.class);
when(brain.getUniqueId()).thenReturn(UUID.randomUUID()); when(body.getUniqueId()).thenReturn(UUID.randomUUID());
when(brain.getWorld()).thenReturn(world); when(brain.getLocation()).thenReturn(location);
when(body.isValid()).thenReturn(true); when(brain.isValid()).thenReturn(true);
PersistentDataContainer brainTags = tags(), bodyTags = tags(), displayTags = tags();
EntityEquipment equipment = mock(EntityEquipment.class);
when(brain.getPersistentDataContainer()).thenReturn(brainTags); when(body.getPersistentDataContainer()).thenReturn(bodyTags);
when(display.getPersistentDataContainer()).thenReturn(displayTags);
when(brain.getEquipment()).thenReturn(equipment);
AttributeInstance attribute = mock(AttributeInstance.class); when(attribute.getValue()).thenReturn(500.0);
when(brain.getAttribute(any(Attribute.class))).thenReturn(attribute);
when(body.getAttribute(any(Attribute.class))).thenReturn(attribute);
when(world.spawn(any(Location.class), eq(Husk.class), any(Consumer.class))).thenReturn(brain);
when(world.spawn(any(Location.class), eq(Sniffer.class), any(Consumer.class))).thenReturn(body);
when(world.spawn(any(Location.class), eq(BlockDisplay.class), any(Consumer.class))).thenReturn(display);
return new Rig(plugin, world, location, brain, body, display);
}
@Test void displayModelHidesSnifferFollowsBrainAndSinksAfterDeath() {
Rig r = rig(null); // default is display
BukkitScheduler scheduler = mock(BukkitScheduler.class);
PluginManager plugins = mock(PluginManager.class);
Player target = mock(Player.class);
try (MockedStatic<Bukkit> bukkit = mockStatic(Bukkit.class)) {
bukkit.when(Bukkit::getScheduler).thenReturn(scheduler);
bukkit.when(Bukkit::getPluginManager).thenReturn(plugins);
bukkit.when(() -> Bukkit.getEntity(r.body().getUniqueId())).thenReturn(r.body());
bukkit.when(() -> Bukkit.getEntity(r.brain().getUniqueId())).thenReturn(r.brain());
SandwormMobs service = new SandwormMobs(r.plugin(), new NamespacedKey("dunerealms", "sandworm"));
service.spawn(r.location(), target);
verify(r.body()).setInvisible(true);
// Skull, mouth, throat, ten teeth and fourteen body rings.
verify(r.world(), times(27)).spawn(any(Location.class), eq(BlockDisplay.class), any(Consumer.class));
ArgumentCaptor<Runnable> tick = ArgumentCaptor.forClass(Runnable.class);
verify(scheduler).runTaskTimer(eq(r.plugin()), tick.capture(), eq(1L), eq(1L));
tick.getValue().run();
verify(r.display(), atLeastOnce()).teleport(any(Location.class));
verify(r.display(), never()).remove();
EntityDeathEvent death = mock(EntityDeathEvent.class); when(death.getEntity()).thenReturn(r.body());
when(death.getDrops()).thenReturn(new ArrayList<>());
service.onDeath(death);
for (int i = 0; i < 40; i++) tick.getValue().run();
verify(r.display(), atLeastOnce()).remove();
}
}
@Test void snifferModelKeepsTheBodyVisibleAndSpawnsNoDisplays() {
Rig r = rig("sniffer");
BukkitScheduler scheduler = mock(BukkitScheduler.class);
PluginManager plugins = mock(PluginManager.class);
try (MockedStatic<Bukkit> bukkit = mockStatic(Bukkit.class)) {
bukkit.when(Bukkit::getScheduler).thenReturn(scheduler);
bukkit.when(Bukkit::getPluginManager).thenReturn(plugins);
SandwormMobs service = new SandwormMobs(r.plugin(), new NamespacedKey("dunerealms", "sandworm"));
service.spawn(r.location(), null);
verify(r.body()).setInvisible(false);
verify(r.world(), never()).spawn(any(Location.class), eq(BlockDisplay.class), any(Consumer.class));
}
}
@Test void verticalOnlyMovementHasBoundedHistoryAndDoesNotLoadTerrain() throws Exception {
Rig r=rig("display");
try(MockedStatic<Bukkit> ignored=mockStatic(Bukkit.class)) {
SandwormModel model=new SandwormModel(r.location(),r.location().clone().add(1,0,0),new NamespacedKey("dunecore","sandworm_model"));
for(int i=0;i<600;i++) model.tick(r.location().clone().add(0,i%2,0));
var field=SandwormModel.class.getDeclaredField("path"); field.setAccessible(true);
org.junit.jupiter.api.Assertions.assertTrue(((Deque<?>)field.get(model)).size()<=256);
verify(r.world(),never()).getHighestBlockYAt(anyInt(),anyInt());
model.removeNow();
}
}
@Test void stoppingServiceRemovesModelsAndRestoresVisibleHitbox() {
Rig r=rig("display");
try(MockedStatic<Bukkit> b=mockStatic(Bukkit.class)) {
b.when(Bukkit::getScheduler).thenReturn(mock(BukkitScheduler.class));
b.when(Bukkit::getPluginManager).thenReturn(mock(PluginManager.class));
b.when(()->Bukkit.getEntity(r.body().getUniqueId())).thenReturn(r.body());
SandwormMobs service=new SandwormMobs(r.plugin(),new NamespacedKey("dunerealms","sandworm"));
service.spawn(r.location(),null); service.close();
verify(r.display(),times(27)).remove(); verify(r.body()).setInvisible(false);
}
}
@Test void partialDisplayFailureRemovesPartsAndKeepsSnifferVisible() {
Rig r=rig("display");
when(r.world().spawn(any(Location.class),eq(BlockDisplay.class),any(Consumer.class))).thenReturn(r.display()).thenThrow(new IllegalStateException("spawn unavailable"));
try(MockedStatic<Bukkit> b=mockStatic(Bukkit.class)) {
b.when(Bukkit::getScheduler).thenReturn(mock(BukkitScheduler.class));
b.when(Bukkit::getPluginManager).thenReturn(mock(PluginManager.class));
SandwormMobs service=new SandwormMobs(r.plugin(),new NamespacedKey("dunerealms","sandworm"));
service.spawn(r.location(),null);
verify(r.display()).remove(); verify(r.body()).setInvisible(false);
}
}
}

View file

@ -0,0 +1,15 @@
# Arrakis reset and sandworm deployment — 28 October 2026
Owner requested operator access for unimatrix999, an Arrakis-only reset, a server panel, and review/deployment of the supplied display-sandworm patch before resetting.
- Granted level-4 operator to verified cached UUID `49d2fe76-7977-4d49-bd39-e48fc8c648b8` on Arrakis and lobby. Retained through the reset.
- Reviewed the older patch instead of overwriting current build/config/plugin files. Preserved current shared-inventory/economy changes and current names. Added bounded model history, no initial unloaded-chunk height sampling and shutdown cleanup. Core is 1.0.13.
- Both Java 21/Paper 1.21.4 compatibility and main Paper 1.21.8 builds/tests passed, including five display-model tests. The uploaded patch's old version/build descriptors were not installed wholesale.
- Deployed compatible Core before resetting. Live console summon at 0/150/0 succeeded; `execute if entity @e[type=minecraft:block_display]` returned count 27. No visual/client claim is implied by entity-count verification. No startup errors found.
- Stopped only dune-arrakis with zero online players; full server archive plus PostgreSQL dump created under `/opt/dunerealms/backups/arrakis-reset-20261028-100119/`. Original world is also retained there as `world/`.
- Reset only `/opt/dunerealms/servers/arrakis/arrakis`. Kept seed `-9071110667412489906`, world identity and level metadata; all old terrain, entities and point-of-interest data remain in the backup. New terrain is generated by DuneTerrain. Kept playerdata, statistics and advancements, relocated saved player positions to spawn, removed stale bed/vehicle respawns. Compared old/new inventory, EnderItems and experience values exactly; all matched. Shared PostgreSQL inventory/account data remains intact.
- Cleared backed-up Arrakis event notices so the test worm and removed entities do not generate stale network alerts. Lobby and other worlds were not reset.
- Fresh terrain region files were saved, Arrakis completed startup in 54.047 seconds and proxy/lobby/Arrakis status returned online. Startup error scan was empty. Four other planet backends remain unconfigured.
- Core artifact SHA256: `dd932573488f216ba9d6c03cf4136bbc2a30c1863a8e7cb69c575c4bba600d4e`. Live legacy filename remains DuneCore-1.0.10.jar; plugin metadata is 1.0.13.
Server operations are documented in `network/server-control/README.md`. Website and account data are not part of the world reset. Player appearance/combat and Java/Bedrock rendering still need human gameplay checks.

View file

@ -0,0 +1,15 @@
# DuneRealms server controls
The separate server-operations page is https://cp.dunerealms.com/servers, linked from account Administration. It preserves the account panel at the root. It manages the three existing systemd services: Arrakis, the Vaerkring lobby and the Velocity gateway. It does not create or reset worlds.
Capabilities: status, player counts, service memory, recent journal output, start/stop/restart, and one-line console commands for the two Paper servers. Proxy console input is deliberately unavailable because that service has no console FIFO. Actions are asynchronous and their outcome appears in status. Console command acceptance means delivery to the server; inspect logs for command success.
Access requires the current website session, staff role and an explicit username in private `SERVER_CONTROL_OPERATORS`. Registration/staff membership alone cannot gain server control. Mutations require the exact CP Origin. The backend replaces any supplied actor with the signed-in username and audits action type/target before dispatch; command text and credentials are not written into account audit rows.
`agent.py` is a standard-library Python service on game-host loopback port 25573. It accepts a separate 64-character bearer from `/etc/dunerealms-server-control.secret`. Only fixed units and fixed FIFO paths are available; no shell command execution or arbitrary file paths. FIFO writes use non-blocking, no-follow opens and validate the descriptor type. Each server accepts one operation at a time with a cooldown. Journal credential patterns are redacted.
The existing SSH tunnel now also forwards website-loopback 15433 to game-loopback 25573. Its restricted account key permits only PostgreSQL 5432 and control 25573 destinations. Agent port 25573 is not public. Website private settings: `SERVER_CONTROL_TOKEN` and `SERVER_CONTROL_OPERATORS`. No credentials belong in this directory.
Agent systemd service: `dunerealms-server-control`; existing tunnel: `dunerealms-inventory-tunnel`. The agent needs system service control and console FIFO access, and runs under a read-only filesystem sandbox with private temporary files. Deploy agent changes to `/opt/dunerealms/server-control/agent.py` and restart its service. Tests: `python3 -m unittest discover -s network/server-control -p test_agent.py` and the website test suite.
Live deployment 28 October 2026: website release `20261028-server-panel`, 60 website tests and 4 Python agent tests passed. Authenticated status, logs, a harmless `list` command and an idempotent `start` of the active Arrakis service passed through the public HTTPS API. Foreign-origin writes returned 403; unauthenticated controls returned 401. Browser review confirmed the operator interface. No real restart was required for the panel acceptance test.

View file

@ -0,0 +1,137 @@
#!/usr/bin/env python3
"""Private server control. Bind loopback; reach only through the restricted SSH tunnel."""
import hmac
import json
import os
from pathlib import Path
import re
import stat
import subprocess
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.request import urlopen
from urllib.parse import urlsplit, parse_qs
SERVERS = {
'arrakis': ('dune-arrakis', '/opt/dunerealms/servers/arrakis/console.fifo', 'Arrakduin'),
'lobby': ('dune-lobby', '/opt/dunerealms/lobby/console.fifo', 'Vaerkring lobby'),
'proxy': ('dune-proxy', None, 'Network gateway'),
}
LOCK = threading.Lock()
JOBS = {}
LAST = {}
SECRET = None
def run(args, timeout=8):
return subprocess.run(args, capture_output=True, text=True, timeout=timeout, check=False)
def scrub(text):
return re.sub(r'(?i)((?:password|secret|token)\s*[=:]\s*)\S+', r'\1[redacted]', text)[-60000:]
def state():
rows = []
for key, (unit, fifo, name) in SERVERS.items():
result = run(['systemctl', 'show', unit, '--property=ActiveState,SubState,MemoryCurrent,ActiveEnterTimestamp'])
values = dict(line.split('=', 1) for line in result.stdout.splitlines() if '=' in line)
with LOCK:
job = dict(JOBS[key]) if key in JOBS else None
rows.append({'id': key, 'name': name, 'state': values.get('ActiveState', 'unknown'),
'detail': values.get('SubState', ''), 'memory': values.get('MemoryCurrent'),
'since': values.get('ActiveEnterTimestamp'), 'console': bool(fifo), 'job': job})
try:
with urlopen('http://127.0.0.1:25572/status', timeout=3) as response:
network = json.load(response)
except Exception:
network = None
return {'servers': rows, 'network': network, 'checkedAt': int(time.time() * 1000)}
def perform(server, action, command, actor):
unit, fifo, _ = SERVERS[server]
print(json.dumps({'actor': actor, 'server': server, 'action': action, 'event': 'started'}), flush=True)
try:
if action == 'command':
fd = os.open(fifo, os.O_WRONLY | os.O_NONBLOCK | os.O_NOFOLLOW)
try:
if not stat.S_ISFIFO(os.fstat(fd).st_mode):
raise ValueError('Console is not a pipe')
os.write(fd, (command + '\n').encode())
finally:
os.close(fd)
message = 'Command sent. Check the console log for its result.'
else:
result = run(['systemctl', action, unit], timeout=140)
if result.returncode:
raise RuntimeError('Service action failed; check the server log.')
message = 'Service action completed.'
outcome = {'state': 'complete', 'message': message}
except Exception:
outcome = {'state': 'failed', 'message': 'Action failed. Check the server log or retry after startup.'}
with LOCK:
JOBS[server].update(outcome)
print(json.dumps({'actor': actor, 'server': server, 'action': action, **outcome}), flush=True)
class Handler(BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def reply(self, status, body):
data = json.dumps(body).encode()
self.send_response(status)
self.send_header('Content-Type', 'application/json')
self.send_header('Cache-Control', 'no-store')
self.send_header('Content-Length', str(len(data)))
self.end_headers()
self.wfile.write(data)
def authorized(self):
received = self.headers.get('Authorization', '')
return hmac.compare_digest(received.encode(), ('Bearer ' + SECRET).encode())
def do_GET(self):
if not self.authorized():
return self.reply(401, {'message': 'Unauthorized'})
url = urlsplit(self.path)
if url.path == '/servers' and not url.query:
return self.reply(200, state())
args = parse_qs(url.query)
if url.path == '/logs' and set(args) == {'server'} and len(args['server']) == 1 and args['server'][0] in SERVERS:
unit = SERVERS[args['server'][0]][0]
result = run(['journalctl', '-u', unit, '-n', '160', '--no-pager', '-o', 'cat'])
return self.reply(200, {'log': scrub(result.stdout)})
return self.reply(404, {'message': 'Not found'})
def do_POST(self):
if not self.authorized():
return self.reply(401, {'message': 'Unauthorized'})
if self.path != '/action':
return self.reply(404, {'message': 'Not found'})
try:
length = int(self.headers.get('Content-Length', '0'))
if not 0 < length <= 4096:
raise ValueError()
data = json.loads(self.rfile.read(length))
server, action = data['server'], data['action']
if server not in SERVERS or action not in ('start', 'stop', 'restart', 'command'):
raise ValueError()
command = data.get('command', '')
actor = data['actor']
if not isinstance(actor, str) or not re.fullmatch(r'[A-Za-z0-9_]{3,32}', actor):
raise ValueError()
if action == 'command' and (not SERVERS[server][1] or not isinstance(command, str) or not re.fullmatch(r'[A-Za-z][ -~]{0,239}', command)):
raise ValueError()
except (ValueError, KeyError, TypeError):
return self.reply(400, {'message': 'Invalid server action'})
with LOCK:
if JOBS.get(server, {}).get('state') == 'running' or time.monotonic() - LAST.get(server, -100) < 5:
return self.reply(409, {'message': 'A server action is already running. Wait a moment.'})
LAST[server] = time.monotonic()
JOBS[server] = {'state': 'running', 'action': action, 'startedAt': int(time.time() * 1000)}
threading.Thread(target=perform, args=(server, action, command, actor), daemon=True).start()
return self.reply(202, {'ok': True, 'message': 'Action accepted. Status will update shortly.'})
if __name__ == '__main__':
SECRET = Path('/etc/dunerealms-server-control.secret').read_text().strip()
if len(SECRET) < 64:
raise SystemExit('Private control secret is missing')
ThreadingHTTPServer(('127.0.0.1', 25573), Handler).serve_forever()

View file

@ -0,0 +1,56 @@
import json
import threading
import unittest
from unittest.mock import patch
from http.server import ThreadingHTTPServer
from urllib.request import Request, urlopen
from urllib.error import HTTPError
import agent
class AgentTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
agent.SECRET = 't' * 64
cls.http = ThreadingHTTPServer(('127.0.0.1', 0), agent.Handler)
threading.Thread(target=cls.http.serve_forever, daemon=True).start()
cls.url = 'http://127.0.0.1:' + str(cls.http.server_port)
@classmethod
def tearDownClass(cls):
cls.http.shutdown()
cls.http.server_close()
def request(self, path, body=None, token='t' * 64):
data = None if body is None else json.dumps(body).encode()
request = Request(self.url + path, data=data, headers={'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'})
try:
with urlopen(request) as response:
return response.status, json.load(response)
except HTTPError as response:
return response.code, json.load(response)
def test_authentication_and_fixed_log_services(self):
self.assertEqual(self.request('/servers', token='wrong')[0], 401)
self.assertEqual(self.request('/logs?server=ssh')[0], 404)
self.assertEqual(self.request('/logs?server=arrakis&server=proxy')[0], 404)
def test_invalid_actions_never_start_worker(self):
with patch.object(agent, 'perform') as perform:
for data in [dict(server='ssh', action='restart', actor='owner'), dict(server='arrakis', action='shell', actor='owner'), dict(server='arrakis', action='command', command='list\nstop', actor='owner'), dict(server='proxy', action='command', command='list', actor='owner')]:
self.assertEqual(self.request('/action', data)[0], 400)
perform.assert_not_called()
def test_accepted_action_and_duplicate_block(self):
agent.JOBS.clear()
agent.LAST.clear()
with patch.object(agent, 'perform') as perform:
data = dict(server='arrakis', action='restart', actor='owner')
self.assertEqual(self.request('/action', data)[0], 202)
self.assertEqual(self.request('/action', data)[0], 409)
perform.assert_called_once_with('arrakis', 'restart', '', 'owner')
def test_redacts_credentials(self):
self.assertNotIn('hunter2', agent.scrub('rcon.password=hunter2'))
if __name__ == '__main__':
unittest.main()

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1 @@
.server-workspace{padding:clamp(18px,4vw,40px);background:#f7edcf;border:3px double #99835b;color:#283b35}.server-heading{display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap}.server-heading h2{margin:14px 0}.server-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:20px;margin:26px 0}.server-card{padding:22px;background:#e7dab4;border:2px solid #a58a56;box-shadow:inset 0 0 0 3px #f4e8c7}.server-card h3{margin-top:0}.server-actions{display:flex;gap:8px;flex-wrap:wrap}.server-state{font-weight:bold;color:#6b4933}.server-state.online{color:#28634f}.server-player-count{font-size:1.1em}.console-panel{border-top:2px solid #b19962;padding-top:20px}#console{height:390px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere;padding:20px;background:#142a28;color:#f2df9e;border:3px double #bd9c51;font:13px/1.6 ui-monospace,Consolas,monospace}#command-form{display:flex;gap:16px;align-items:end}#command-form label{flex:1}#command-form button{margin-bottom:0}#notice{min-height:24px;font-weight:bold}select{padding:10px;border:1px solid #8f7b53;background:#fff9e6;color:#19362e;font:inherit}[hidden]{display:none!important}@media(max-width:600px){#command-form{display:block}#console{height:320px}.server-heading{align-items:stretch}}

View file

@ -0,0 +1,7 @@
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#142a28"><title>Server controls · dunerealms.com</title><link rel="stylesheet" href="/panel.css"><link rel="stylesheet" href="/servers.css"><script src="/servers.js" defer></script></head>
<body><a class="skip" href="#servers">Skip to server controls</a><header class="site-header"><a class="brand" href="https://www.dunerealms.com/"><span class="sun"></span>dunerealms.com<small>DESERT WORLDS</small></a><nav><a href="/">Account panel</a><a href="https://www.dunerealms.com/manual.html">Manual/wiki</a></nav></header>
<main class="cp-shell"><section class="panel-hero"><div class="hero-copy"><p class="eyebrow">VAERKRING / NETWORK OPERATIONS</p><h1>Server controls</h1><p class="hero-description">Keep the routes open and the desert worlds running.</p><div class="hero-tags"><span>Live status</span><span>Console & logs</span><span>Operator access</span></div></div></section>
<section class="server-workspace"><p id="notice" role="status" aria-live="polite">Checking operator access…</p><div id="signin" hidden><p>Sign in using your website operator account, then return here.</p><a class="button" href="/">Sign in to the account panel</a></div><div id="controls" hidden><div class="server-heading"><h2>Game network</h2><button id="refresh">Refresh status</button></div><p>Service actions affect everyone on that server. Check the player count before stopping or restarting.</p><div id="servers" class="server-grid"></div>
<section class="console-panel"><div class="server-heading"><h2>Server console</h2><label>Server<select id="log-server"><option value="arrakis">Arrakduin</option><option value="lobby">Vaerkring lobby</option><option value="proxy">Network gateway</option></select></label><button id="refresh-log">Refresh log</button></div><pre id="console" tabindex="0" aria-label="Latest server log">Select a server to read its latest log.</pre><form id="command-form"><label>Console command · without a leading slash<input id="command" autocomplete="off" maxlength="240" placeholder="list" required></label><button type="submit">Send command</button></form><p id="command-note">Commands run with server-console permissions. Their results appear in the log.</p></section></div></section></main>
<footer class="site-footer"><p>dunerealms.com · private server operations</p><a href="https://www.dunerealms.com/wiki.html">Disclaimer & operator contact</a></footer></body></html>

View file

@ -0,0 +1,11 @@
'use strict';
const $=id=>document.getElementById(id),el=(tag,text)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;return n;};
let ready=false,busy=false;
function notice(text){$('notice').textContent=text;}
async function api(path,body){const response=await fetch('/api/servers'+path,{credentials:'same-origin',cache:'no-store',...(body?{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{})});let data;try{data=await response.json();}catch{throw Error('The server panel is temporarily unavailable.');}if(!response.ok){if(response.status===401){ready=false;$('controls').hidden=true;$('signin').hidden=false;}throw Error(data.message||'Request failed.');}return data;}
async function act(server,action,command){if(busy)return;if(!confirm(action==='command'?'Send this console command to '+server+'?':action[0].toUpperCase()+action.slice(1)+' '+server+'? Connected players may be disconnected.'))return;busy=true;try{const data=await api('/action',{server,action,...(command?{command}:{})});notice(data.message);await refresh();}catch(error){notice(error.message);}finally{busy=false;}}
async function refresh(){try{const data=await api('');ready=true;$('controls').hidden=false;$('signin').hidden=true;$('servers').replaceChildren();for(const row of data.servers){const card=el('article');card.className='server-card';card.append(el('h3',row.name));const state=el('p',row.state+' · '+row.detail);state.className='server-state'+(row.state==='active'?' online':'');card.append(state);const key={arrakis:'arrakis',lobby:'spacing-guild',proxy:'velocity'}[row.id],status=data.network?.servers?.[key];const players=el('p',status?.players!==undefined?status.players+' player'+(status.players===1?'':'s')+' online':'Player count unavailable');players.className='server-player-count';card.append(players);const memory=Number(row.memory);if(Number.isFinite(memory)&&memory>0)card.append(el('p',Math.round(memory/1048576)+' MB memory'));if(row.job)card.append(el('p',row.job.action+': '+row.job.state+(row.job.message?' · '+row.job.message:'')));const buttons=el('div');buttons.className='server-actions';for(const action of ['start','stop','restart']){const button=el('button',action[0].toUpperCase()+action.slice(1));button.disabled=row.job?.state==='running';button.onclick=()=>act(row.id,action);buttons.append(button);}const logs=el('button','View console');logs.onclick=()=>{$('log-server').value=row.id;readLog();$('console').focus();};buttons.append(logs);card.append(buttons);$('servers').append(card);}notice('Status checked '+new Date(data.checkedAt).toLocaleTimeString()+'.');}catch(error){notice(error.message);}}
async function readLog(){try{const id=$('log-server').value;const data=await api('/logs?server='+encodeURIComponent(id));const log=$('console'),atBottom=log.scrollHeight-log.scrollTop-log.clientHeight<40;log.textContent=data.log||'No log entries yet.';if(atBottom)log.scrollTop=log.scrollHeight;$('command-form').hidden=id==='proxy';$('command-note').textContent=id==='proxy'?'The gateway supports service controls; use the game-server console for Minecraft commands.':'Commands run with server-console permissions. Their results appear in the log.';}catch(error){notice(error.message);}}
$('refresh').onclick=refresh;$('refresh-log').onclick=readLog;$('log-server').onchange=readLog;
$('command-form').onsubmit=async event=>{event.preventDefault();const input=$('command'),command=input.value.trim();if(!/^[A-Za-z][ -~]{0,239}$/.test(command)){notice('Enter one command without a leading slash.');return;}await act($('log-server').value,'command',command);input.value='';setTimeout(readLog,1000);};
refresh().then(()=>{if(ready)readLog();});setInterval(()=>{if(ready&&!busy&&!document.hidden)refresh();},15000);

View file

@ -0,0 +1,29 @@
import {randomUUID} from 'node:crypto';
import {identity} from '../node/auth.mjs';
const json=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'private, no-store','Vary':'Cookie'}});
export function createServerControl(db,settings,{fetcher=fetch}={}){
const origin=new URL(settings.CP_ORIGIN||'https://cp.dunerealms.com').origin;
const operators=new Set((settings.SERVER_CONTROL_OPERATORS||'').split(',').map(x=>x.trim().toLowerCase()).filter(Boolean));
return async request=>{
const user=await identity(request,db);
if(!user)return json({message:'Sign in to the account panel first.'},401);
if(user.role!=='staff'||!operators.has(user.username.toLowerCase()))return json({message:'Server operator access is required.'},403);
if(!settings.SERVER_CONTROL_TOKEN||settings.SERVER_CONTROL_TOKEN.length<64)return json({message:'Server controls are not configured.'},503);
const url=new URL(request.url);let target,body;
if(request.method==='GET'&&url.pathname==='/api/servers'&&!url.search)target='/servers';
else if(request.method==='GET'&&url.pathname==='/api/servers/logs'&&[...url.searchParams.keys()].length===1&&url.searchParams.has('server')&&['arrakis','lobby','proxy'].includes(url.searchParams.get('server')))target='/logs?server='+url.searchParams.get('server');
else if(request.method==='POST'&&url.pathname==='/api/servers/action'&&!url.search){
if(request.headers.get('origin')!==origin)return json({message:'Origin rejected.'},403);
try{body=await request.json();}catch{return json({message:'Invalid action.'},400);}
if(!['arrakis','lobby','proxy'].includes(body?.server)||!['start','stop','restart','command'].includes(body?.action))return json({message:'Invalid action.'},400);
if(body.action==='command'&&(body.server==='proxy'||typeof body.command!=='string'||!/^[A-Za-z][ -~]{0,239}$/.test(body.command)))return json({message:'Enter one console command, without a leading slash.'},400);
body={server:body.server,action:body.action,...(body.action==='command'?{command:body.command}:{}),actor:user.username};target='/action';
// Record accepted intent before contacting the privileged agent. Never store command text or secrets.
await db.prepare('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)').bind(randomUUID(),user.id,'server-control',JSON.stringify({server:body.server,action:body.action}),Date.now()).run();
}else return json({message:'Invalid server request.'},400);
try{
const response=await fetcher('http://127.0.0.1:15433'+target,{method:body?'POST':'GET',headers:{Authorization:'Bearer '+settings.SERVER_CONTROL_TOKEN,...(body?{'Content-Type':'application/json'}:{})},...(body?{body:JSON.stringify(body)}:{}),signal:AbortSignal.timeout(10000)});
const result=await response.json();return json(result,response.status);
}catch{return json({message:'The game host is temporarily unavailable.'},503);}
};
}

View file

@ -9,18 +9,21 @@ import {createMarketBridge} from './inventory/market-bridge.mjs';
import {createGameLink,json} from '../node/game-link.mjs';
import {createCommunityRewards} from '../node/community-rewards.mjs';
import {createAccountAdmin} from '../node/account-admin.mjs';
import {createServerControl} from './server-control.mjs';
const types={'.html':'text/html; charset=utf-8','.js':'text/javascript; charset=utf-8','.mjs':'text/javascript; charset=utf-8','.css':'text/css; charset=utf-8'};
const sharedAssets=new Set(['ornament.webp','guild.webp','minecraft-hero.webp','menu-0.webp','menu-5.webp','menu-6.webp','menu-9.webp','menu-12.webp','item-23.webp','dunemark-icon-64.png','arrakis-lore-frieze.svg']);
export function createPanel(db,settings={},dependencies={}){
const origin=new URL(settings.CP_ORIGIN||'https://cp.dunerealms.com').origin;
const auth=createAuth(db,origin),links=createGameLink(db,settings,origin),rewards=createCommunityRewards(db,settings,origin);
const admin=createAccountAdmin(db,origin);
const servers=createServerControl(db,settings,dependencies.serverControl);
const pool=dependencies.inventoryPool||{async query(){throw Error('Inventory database is not configured');}};
const inventoryOptions={authenticate:request=>identity(request,db),verifiedMinecraftUuid:async accountId=>(await db.prepare('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?').bind(accountId).first())?.minecraft_uuid||null,pool,logger:dependencies.logger||console};
const inventory=createInventoryHandler(inventoryOptions),sales=createSalesHistoryHandler(inventoryOptions);
const market=(settings.EXCHANGE_READ_TOKEN||'').length>=32?createMarketBridge({pool,readToken:settings.EXCHANGE_READ_TOKEN}):null;
return async request=>{
const path=new URL(request.url).pathname;
if(path==='/api/servers'||path.startsWith('/api/servers/'))return servers(request);
if(path==='/api/inventory')return inventory(request);
if(path==='/api/exchange/sales-history')return sales(request);
if(path==='/internal/exchange/listings')return market?market(request):new Response('Not configured',{status:503,headers:{'Cache-Control':'no-store'}});
@ -31,8 +34,8 @@ export function createPanel(db,settings={},dependencies={}){
if(path.startsWith('/api/community/'))return rewards(request);
if(!['GET','HEAD'].includes(request.method))return new Response('Method not allowed',{status:405});
if(path.startsWith('/assets/')&&sharedAssets.has(path.slice(8))){const file=path.slice(8);return new Response(request.method==='HEAD'?null:await readFile(new URL('../web/assets/'+file,import.meta.url)),{headers:{'Content-Type':file.endsWith('.svg')?'image/svg+xml':file.endsWith('.png')?'image/png':'image/webp','Cache-Control':'public, max-age=3600'}});}
const file=path==='/'?'index.html':path.slice(1);
if(!['index.html','panel.js','panel.css','inventory/inventory-view.mjs','inventory/inventory-mount.mjs','inventory/inventory.css'].includes(file))return new Response('Not found',{status:404});
const file=path==='/'?'index.html':path==='/servers'?'servers.html':path.slice(1);
if(!['index.html','panel.js','panel.css','servers.html','servers.js','servers.css','inventory/inventory-view.mjs','inventory/inventory-mount.mjs','inventory/inventory.css'].includes(file))return new Response('Not found',{status:404});
return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/'+file,import.meta.url)),{headers:{'Content-Type':types[file.slice(file.lastIndexOf('.'))],'Cache-Control':'no-store'}});
};
}

View file

@ -0,0 +1,28 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {createServerControl} from '../control-panel/server-control.mjs';
const origin='https://cp.dunerealms.com',cookie='__Host-dune_session='+'a'.repeat(43);
function rig(user){const calls=[],audit=[];const db={prepare(sql){return{bind(...args){return{async first(){return user;},async run(){audit.push(args);}};}};}};const handle=createServerControl(db,{CP_ORIGIN:origin,SERVER_CONTROL_TOKEN:'t'.repeat(64),SERVER_CONTROL_OPERATORS:'owner'},{async fetcher(url,options){calls.push({url,options});return Response.json({ok:true});}});const request=(path='/api/servers',body,requestOrigin=origin)=>handle(new Request(origin+path,{method:body?'POST':'GET',headers:{Cookie:cookie,Origin:requestOrigin,'Content-Type':'application/json'},...(body?{body:JSON.stringify(body)}:{})}));return{request,calls,audit};}
test('server controls require session, staff role and explicit operator allowlist',async()=>{
for(const [user,status] of [[null,401],[{id:'1',username:'owner',role:'player'},403],[{id:'2',username:'otherstaff',role:'staff'},403]]){const r=rig(user);assert.equal((await r.request()).status,status);assert.equal(r.calls.length,0);}
});
test('operator status/log paths are fixed and reject arbitrary targets',async()=>{
const r=rig({id:'1',username:'owner',role:'staff'});
assert.equal((await r.request()).status,200);assert.equal(r.calls[0].url,'http://127.0.0.1:15433/servers');
assert.equal((await r.request('/api/servers/logs?server=lobby')).status,200);
for(const path of ['/api/servers?url=https://attacker.test','/api/servers/logs?server=ssh','/api/servers/logs?server=lobby&server=proxy'])assert.equal((await r.request(path)).status,400);
assert.equal(r.calls.length,2);
});
test('mutations enforce origin and single command, overwrite spoofed actor, and audit intent',async()=>{
const r=rig({id:'1',username:'owner',role:'staff'}),body={server:'arrakis',action:'command',command:'list',actor:'intruder'};
assert.equal((await r.request('/api/servers/action',body,'https://attacker.test')).status,403);
for(const command of ['list\nstop','/op player'])assert.equal((await r.request('/api/servers/action',{...body,command})).status,400);
assert.equal((await r.request('/api/servers/action',{...body,server:'proxy'})).status,400);
assert.equal((await r.request('/api/servers/action',body)).status,200);
assert.equal(JSON.parse(r.calls[0].options.body).actor,'owner');assert.equal(r.audit.length,1);assert.equal(r.audit[0][2],'server-control');assert.ok(!r.audit[0][3].includes('list'));
});
test('upstream failures do not expose secrets',async()=>{
const db={prepare(){return{bind(){return{async first(){return{id:'1',username:'owner',role:'staff'};}};}};}};
const handle=createServerControl(db,{SERVER_CONTROL_TOKEN:'t'.repeat(64),SERVER_CONTROL_OPERATORS:'owner'},{fetcher:async()=>{throw Error('password secret');}});
const response=await handle(new Request(origin+'/api/servers',{headers:{Cookie:cookie}}));assert.equal(response.status,503);assert.ok(!(await response.text()).includes('password'));
});