feat(sentinel): alert on repeated suspicious movement
CI / build (pull_request) Successful in 1m16s
CI / build (push) Successful in 3m24s

This commit is contained in:
dmg committed 2026-10-29 08:28:27 -04:00
1 parent 8801e2f1b9
commit b211e9d337
54 files changed
+3272 -2

No files matched your search

@@ -0,0 +1,6 @@
package games.dmg.purpursentinel;
import java.util.UUID;
public record AlertDecision(UUID playerId, int breachCount, double peakSpeed, double capturedLimit) {
}
@@ -0,0 +1,72 @@
package games.dmg.purpursentinel;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.LinkedHashMap;
import org.bukkit.configuration.file.YamlConfiguration;
public final class AtomicYamlSettingsStore implements SettingsPersistence {
private final Path file;
public AtomicYamlSettingsStore(Path file) {
this.file = file;
}
public static void writeDefaults(Path file) throws IOException {
if (Files.notExists(file)) {
Files.createDirectories(file.getParent());
Files.writeString(file, """
horizontal-speed-limit: 0.80
breaches-to-alert: 6
evidence-window-seconds: 10
alert-cooldown-seconds: 60
minimum-tps: 18.0
exemption-grace-ticks: 20
""", StandardOpenOption.CREATE_NEW);
}
}
@Override public SettingsDocument load() throws IOException {
if (Files.notExists(file)) {
throw new IOException("Missing Sentinel configuration: " + file);
}
var yaml = YamlConfiguration.loadConfiguration(file.toFile());
var values = new LinkedHashMap<String, Object>();
for (String key : yaml.getKeys(false)) {
values.put(key, yaml.get(key));
}
return new SettingsDocument(values);
}
@Override public void save(SettingsDocument document) throws IOException {
var yaml = new YamlConfiguration();
document.values().forEach(yaml::set);
byte[] bytes = yaml.saveToString().getBytes(StandardCharsets.UTF_8);
Path parent = file.toAbsolutePath().getParent();
Files.createDirectories(parent);
Path temporary = Files.createTempFile(parent, file.getFileName().toString(), ".tmp");
boolean moved = false;
try {
try (var channel = FileChannel.open(temporary, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) {
var buffer = ByteBuffer.wrap(bytes);
while (buffer.hasRemaining()) channel.write(buffer);
channel.force(true);
}
try {
Files.move(temporary, file, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
} catch (AtomicMoveNotSupportedException exception) {
throw new IOException("Atomic configuration replacement is not supported", exception);
}
moved = true;
} finally {
if (!moved) Files.deleteIfExists(temporary);
}
}
}
@@ -0,0 +1,118 @@
package games.dmg.purpursentinel;
import java.util.Objects;
import java.util.function.BiPredicate;
import java.util.function.LongSupplier;
import java.util.function.Supplier;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.Pose;
import org.bukkit.Server;
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.EntityDamageEvent;
import org.bukkit.event.entity.EntityKnockbackEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerVelocityEvent;
public final class BukkitMovementListener implements Listener {
private final Server server;
private final MovementMonitor monitor;
private final Supplier<SentinelSettings> settings;
private final LongSupplier nanoTime;
private final BiPredicate<Location, Location> ordinaryEnvironment;
public BukkitMovementListener(Server server, MovementMonitor monitor, Supplier<SentinelSettings> settings, LongSupplier nanoTime) {
this(server, monitor, settings, nanoTime,
(from, to) -> MovementEnvironment.isOrdinary(from) && MovementEnvironment.isOrdinary(to));
}
BukkitMovementListener(Server server, MovementMonitor monitor, Supplier<SentinelSettings> settings,
LongSupplier nanoTime, BiPredicate<Location, Location> ordinaryEnvironment) {
this.server = server;
this.monitor = monitor;
this.settings = settings;
this.nanoTime = nanoTime;
this.ordinaryEnvironment = ordinaryEnvironment;
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false)
public void onMove(PlayerMoveEvent event) {
if (!event.hasExplicitlyChangedPosition()) return;
Location from = event.getFrom();
Location to = event.getTo();
var player = event.getPlayer();
ExclusionReason reason = classify(player, from, to, event.isCancelled());
monitor.record(player.getUniqueId(), new MovementFrame(
server.getCurrentTick(),
nanoTime.getAsLong(),
Objects.requireNonNull(from.getWorld()).getUID(),
Objects.requireNonNull(to.getWorld()).getUID(),
from.getX(), from.getZ(), to.getX(), to.getZ(), reason), settings.get());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false)
public void onTeleport(PlayerTeleportEvent event) { exempt(event.getPlayer(), ExclusionReason.LIFECYCLE); }
@EventHandler(priority = EventPriority.MONITOR)
public void onJoin(PlayerJoinEvent event) { exempt(event.getPlayer(), ExclusionReason.LIFECYCLE); }
@EventHandler(priority = EventPriority.MONITOR)
public void onRespawn(PlayerRespawnEvent event) { exempt(event.getPlayer(), ExclusionReason.LIFECYCLE); }
@EventHandler(priority = EventPriority.MONITOR)
public void onWorldChange(PlayerChangedWorldEvent event) { exempt(event.getPlayer(), ExclusionReason.LIFECYCLE); }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onVelocity(PlayerVelocityEvent event) { exempt(event.getPlayer(), ExclusionReason.VELOCITY); }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onKnockback(EntityKnockbackEvent event) {
if (event.getEntity() instanceof Player player) exempt(player, ExclusionReason.VELOCITY);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onDamage(EntityDamageEvent event) {
if (event.getEntity() instanceof Player player) exempt(player, ExclusionReason.DAMAGE);
}
@EventHandler(priority = EventPriority.MONITOR)
public void onQuit(PlayerQuitEvent event) { monitor.forget(event.getPlayer().getUniqueId()); }
private void exempt(Player player, ExclusionReason reason) {
monitor.exempt(player.getUniqueId(), server.getCurrentTick(), nanoTime.getAsLong(), reason, settings.get());
}
private ExclusionReason classify(Player player, Location from, Location to, boolean cancelled) {
if (cancelled) return ExclusionReason.CANCELLED;
if (from.getWorld() == null || to.getWorld() == null || !from.getWorld().equals(to.getWorld())) return ExclusionReason.INCOMPLETE;
if (!finite(from.getX(), from.getZ(), to.getX(), to.getZ())) return ExclusionReason.INCOMPLETE;
if (server.getTPS()[0] < settings.get().minimumTps()) return ExclusionReason.LOW_TPS;
if (player.getGameMode() != GameMode.SURVIVAL && player.getGameMode() != GameMode.ADVENTURE) return ExclusionReason.GAME_MODE;
if (player.isInsideVehicle()) return ExclusionReason.VEHICLE;
if (player.isFlying()) return ExclusionReason.FLYING;
if (player.isGliding() || player.getPose() == Pose.FALL_FLYING) return ExclusionReason.GLIDING;
if (player.isSwimming() || player.getPose() == Pose.SWIMMING || player.isInWater()
|| player.isInLava() || player.isInBubbleColumn()) return ExclusionReason.SWIMMING;
if (player.isClimbing()) return ExclusionReason.CLIMBING;
if (player.isRiptiding() || player.getPose() == Pose.SPIN_ATTACK) return ExclusionReason.RIPTIDE;
if (player.getActivePotionEffects().stream().map(effect -> effect.getType().getKey().getKey())
.anyMatch(key -> key.equals("speed") || key.equals("slowness"))) {
return ExclusionReason.POTION_EFFECT;
}
if (!ordinaryEnvironment.test(from, to)) return ExclusionReason.ENVIRONMENT;
return ExclusionReason.NONE;
}
private static boolean finite(double... values) {
for (double value : values) if (!Double.isFinite(value)) return false;
return true;
}
}
@@ -0,0 +1,30 @@
package games.dmg.purpursentinel;
public enum ExclusionReason {
NONE("none"),
CANCELLED("cancelled movement"),
INCOMPLETE("incomplete movement"),
GAME_MODE("game mode"),
VEHICLE("vehicle"),
FLYING("flight"),
GLIDING("gliding"),
SWIMMING("swimming or crawling"),
CLIMBING("climbing"),
RIPTIDE("riptide"),
POTION_EFFECT("speed or slowness effect"),
ENVIRONMENT("movement-altering environment"),
LOW_TPS("low server TPS"),
LIFECYCLE("join, teleport, respawn, or world change"),
VELOCITY("server-applied velocity or knockback"),
DAMAGE("damage or explosion");
private final String description;
ExclusionReason(String description) {
this.description = description;
}
public String description() {
return description;
}
}
@@ -0,0 +1,10 @@
package games.dmg.purpursentinel;
public record InspectionSnapshot(
int breachCount,
double evidenceAgeSeconds,
double peakSpeed,
double capturedLimit,
ExclusionReason currentExclusion,
double cooldownRemainingSeconds) {
}
@@ -0,0 +1,119 @@
package games.dmg.purpursentinel;
import java.util.ArrayDeque;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
public final class MovementDetector {
static final int MAX_EVIDENCE_PER_PLAYER = 1_200;
private final Map<UUID, PlayerState> players = new HashMap<>();
public Optional<AlertDecision> observe(UUID playerId, MovementSample sample, SentinelSettings settings) {
var state = players.computeIfAbsent(playerId, ignored -> new PlayerState());
expire(state, sample.observedAtNanos());
if (!sample.complete() || sample.cancelled() || sample.exclusionReason() != ExclusionReason.NONE
|| !Double.isFinite(sample.horizontalDistance()) || sample.horizontalDistance() < 0) {
state.currentExclusion = sample.cancelled() ? ExclusionReason.CANCELLED
: sample.exclusionReason() == ExclusionReason.NONE ? ExclusionReason.INCOMPLETE : sample.exclusionReason();
state.graceThroughTick = Math.max(state.graceThroughTick, sample.tick() + settings.exemptionGraceTicks());
return Optional.empty();
}
if (sample.tick() <= state.graceThroughTick) {
return Optional.empty();
}
state.currentExclusion = ExclusionReason.NONE;
if (sample.horizontalDistance() <= settings.horizontalSpeedLimit()) {
return Optional.empty();
}
if (state.evidence.size() == MAX_EVIDENCE_PER_PLAYER) {
state.evidence.removeFirst();
}
state.evidence.addLast(new Breach(
sample.observedAtNanos(),
sample.observedAtNanos() + seconds(settings.evidenceWindowSeconds()),
sample.horizontalDistance(),
settings.horizontalSpeedLimit()));
if (state.evidence.size() < settings.breachesToAlert() || sample.observedAtNanos() < state.cooldownUntilNanos) {
return Optional.empty();
}
state.cooldownUntilNanos = sample.observedAtNanos() + seconds(settings.alertCooldownSeconds());
var peak = state.evidence.stream().max(Comparator.comparingDouble(Breach::speed)).orElseThrow();
return Optional.of(new AlertDecision(playerId, state.evidence.size(), peak.speed(), peak.capturedLimit()));
}
public void exempt(UUID playerId, int currentTick, long nowNanos, ExclusionReason reason, SentinelSettings settings) {
var state = players.computeIfAbsent(playerId, ignored -> new PlayerState());
expire(state, nowNanos);
state.currentExclusion = reason;
state.graceThroughTick = Math.max(state.graceThroughTick, currentTick + settings.exemptionGraceTicks());
}
public Optional<InspectionSnapshot> inspect(UUID playerId, long nowNanos) {
var state = players.get(playerId);
if (state == null) {
return Optional.empty();
}
expire(state, nowNanos);
if (state.evidence.isEmpty()) {
return Optional.empty();
}
var first = state.evidence.getFirst();
var peak = state.evidence.stream().max(Comparator.comparingDouble(Breach::speed)).orElseThrow();
return Optional.of(new InspectionSnapshot(
state.evidence.size(),
Math.max(0, nowNanos - first.observedAtNanos()) / 1_000_000_000.0,
peak.speed(),
peak.capturedLimit(),
state.currentExclusion,
Math.max(0, state.cooldownUntilNanos - nowNanos) / 1_000_000_000.0));
}
public void cleanup(int currentTick, long nowNanos) {
players.entrySet().removeIf(entry -> {
var state = entry.getValue();
expire(state, nowNanos);
return state.evidence.isEmpty() && state.cooldownUntilNanos <= nowNanos
&& currentTick > state.graceThroughTick;
});
}
public void forget(UUID playerId) {
players.remove(playerId);
}
public void clear() {
players.clear();
}
int trackedPlayerCount() {
return players.size();
}
int evidenceCount(UUID playerId) {
var state = players.get(playerId);
return state == null ? 0 : state.evidence.size();
}
private static long seconds(int value) {
return value * 1_000_000_000L;
}
private static void expire(PlayerState state, long nowNanos) {
while (!state.evidence.isEmpty() && state.evidence.getFirst().expiresAtNanos() <= nowNanos) {
state.evidence.removeFirst();
}
}
private record Breach(long observedAtNanos, long expiresAtNanos, double speed, double capturedLimit) {
}
private static final class PlayerState {
private final ArrayDeque<Breach> evidence = new ArrayDeque<>();
private int graceThroughTick = Integer.MIN_VALUE;
private long cooldownUntilNanos;
private ExclusionReason currentExclusion = ExclusionReason.NONE;
}
}
@@ -0,0 +1,64 @@
package games.dmg.purpursentinel;
import java.util.Set;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.data.Waterlogged;
final class MovementEnvironment {
private static final Set<Material> ALTERING = Set.of(
Material.SLIME_BLOCK,
Material.HONEY_BLOCK,
Material.SOUL_SAND,
Material.SOUL_SOIL,
Material.BUBBLE_COLUMN,
Material.PISTON,
Material.STICKY_PISTON,
Material.PISTON_HEAD,
Material.MOVING_PISTON,
Material.COBWEB,
Material.POWDER_SNOW,
Material.SCAFFOLDING,
Material.SWEET_BERRY_BUSH);
private MovementEnvironment() {
}
static boolean isOrdinary(Location location) {
var world = location.getWorld();
if (world == null || !world.isChunkLoaded(location.getBlockX() >> 4, location.getBlockZ() >> 4)) {
return false;
}
int baseX = location.getBlockX();
int baseY = location.getBlockY();
int baseZ = location.getBlockZ();
for (int x = baseX - 1; x <= baseX + 1; x++) {
for (int z = baseZ - 1; z <= baseZ + 1; z++) {
for (int y = baseY - 1; y <= baseY + 1; y++) {
var block = world.getBlockAt(x, y, z);
var type = block.getType();
if (ALTERING.contains(type) || isIce(type) || isClimbable(type) || block.isLiquid()) {
return false;
}
if (block.getBlockData() instanceof Waterlogged waterlogged && waterlogged.isWaterlogged()) {
return false;
}
}
}
}
return true;
}
private static boolean isIce(Material type) {
return type == Material.ICE || type == Material.PACKED_ICE
|| type == Material.BLUE_ICE || type == Material.FROSTED_ICE;
}
private static boolean isClimbable(Material type) {
String name = type.name();
return type == Material.LADDER || type == Material.VINE || type == Material.SCAFFOLDING
|| name.equals("WEEPING_VINES") || name.equals("WEEPING_VINES_PLANT")
|| name.equals("TWISTING_VINES") || name.equals("TWISTING_VINES_PLANT")
|| name.equals("CAVE_VINES") || name.equals("CAVE_VINES_PLANT");
}
}
@@ -0,0 +1,18 @@
package games.dmg.purpursentinel;
import java.util.UUID;
public record MovementFrame(
int tick,
long observedAtNanos,
UUID fromWorld,
UUID toWorld,
double fromX,
double fromZ,
double toX,
double toZ,
ExclusionReason reason) {
public MovementFrame withReason(ExclusionReason replacement) {
return new MovementFrame(tick, observedAtNanos, fromWorld, toWorld, fromX, fromZ, toX, toZ, replacement);
}
}
@@ -0,0 +1,162 @@
package games.dmg.purpursentinel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
public final class MovementMonitor {
private static final double CHAIN_TOLERANCE = 1.0e-6;
private final MovementDetector detector;
private final Map<UUID, TickBucket> pending = new HashMap<>();
public MovementMonitor(MovementDetector detector) {
this.detector = detector;
}
public void record(UUID playerId, MovementFrame frame, SentinelSettings settings) {
var existing = pending.get(playerId);
if (existing != null && existing.tick != frame.tick()) {
finish(playerId, existing);
pending.remove(playerId);
existing = null;
}
if (existing == null) {
pending.put(playerId, TickBucket.start(frame, settings));
} else {
existing.add(frame);
}
}
public List<AlertDecision> finishBefore(int currentTick, long nowNanos) {
var alerts = new ArrayList<AlertDecision>();
var iterator = pending.entrySet().iterator();
while (iterator.hasNext()) {
var entry = iterator.next();
if (entry.getValue().tick < currentTick) {
finish(entry.getKey(), entry.getValue()).ifPresent(alerts::add);
iterator.remove();
}
}
detector.cleanup(currentTick, nowNanos);
return List.copyOf(alerts);
}
public void exempt(UUID playerId, int tick, long nowNanos, ExclusionReason reason, SentinelSettings settings) {
pending.remove(playerId);
detector.exempt(playerId, tick, nowNanos, reason, settings);
}
public Optional<InspectionSnapshot> inspect(UUID playerId, long nowNanos) {
return detector.inspect(playerId, nowNanos);
}
public void forget(UUID playerId) {
pending.remove(playerId);
detector.forget(playerId);
}
public void clear() {
pending.clear();
detector.clear();
}
int trackedPlayerCount() {
return detector.trackedPlayerCount();
}
private Optional<AlertDecision> finish(UUID playerId, TickBucket bucket) {
return detector.observe(playerId, new MovementSample(
bucket.tick,
bucket.observedAtNanos,
!bucket.invalid,
bucket.reason == ExclusionReason.CANCELLED,
bucket.maximumDistance,
bucket.reason), bucket.settings);
}
private static final class TickBucket {
private final int tick;
private final long observedAtNanos;
private final UUID world;
private final double anchorX;
private final double anchorZ;
private final SentinelSettings settings;
private double lastX;
private double lastZ;
private double previousFromX;
private double previousFromZ;
private double previousToX;
private double previousToZ;
private boolean hasPrevious;
private double maximumDistance;
private ExclusionReason reason;
private boolean invalid;
private TickBucket(MovementFrame frame, SentinelSettings settings) {
tick = frame.tick();
observedAtNanos = frame.observedAtNanos();
world = frame.fromWorld();
anchorX = frame.fromX();
anchorZ = frame.fromZ();
this.settings = settings;
lastX = frame.fromX();
lastZ = frame.fromZ();
reason = ExclusionReason.NONE;
add(frame);
}
static TickBucket start(MovementFrame frame, SentinelSettings settings) {
return new TickBucket(frame, settings);
}
void add(MovementFrame frame) {
if (!world.equals(frame.toWorld()) || !world.equals(frame.fromWorld())
|| !finite(frame.fromX(), frame.fromZ(), frame.toX(), frame.toZ())
|| !connected(frame.fromX(), frame.fromZ())) {
invalid = true;
reason = ExclusionReason.INCOMPLETE;
return;
}
if (frame.reason() != ExclusionReason.NONE) {
invalid = true;
reason = frame.reason();
}
maximumDistance = Math.max(maximumDistance, Math.hypot(frame.toX() - anchorX, frame.toZ() - anchorZ));
if (!duplicate(frame)) {
lastX = frame.toX();
lastZ = frame.toZ();
}
previousFromX = frame.fromX();
previousFromZ = frame.fromZ();
previousToX = frame.toX();
previousToZ = frame.toZ();
hasPrevious = true;
}
private boolean connected(double x, double z) {
return near(x, anchorX) && near(z, anchorZ)
|| near(x, lastX) && near(z, lastZ)
|| hasPrevious && near(x, previousFromX) && near(z, previousFromZ);
}
private boolean duplicate(MovementFrame frame) {
return hasPrevious
&& near(frame.fromX(), previousFromX) && near(frame.fromZ(), previousFromZ)
&& near(frame.toX(), previousToX) && near(frame.toZ(), previousToZ);
}
private static boolean near(double left, double right) {
return Math.abs(left - right) <= CHAIN_TOLERANCE;
}
private static boolean finite(double... values) {
for (double value : values) {
if (!Double.isFinite(value)) return false;
}
return true;
}
}
}
@@ -0,0 +1,10 @@
package games.dmg.purpursentinel;
public record MovementSample(
int tick,
long observedAtNanos,
boolean complete,
boolean cancelled,
double horizontalDistance,
ExclusionReason exclusionReason) {
}
@@ -0,0 +1,51 @@
package games.dmg.purpursentinel;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Objects;
import org.bukkit.event.HandlerList;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
public final class PurpurSentinelPlugin extends JavaPlugin {
private MovementMonitor monitor;
private BukkitMovementListener listener;
private BukkitTask tickTask;
@Override public void onEnable() {
try {
Files.createDirectories(getDataFolder().toPath());
var configPath = getDataFolder().toPath().resolve("config.yml");
AtomicYamlSettingsStore.writeDefaults(configPath);
var settings = SettingsService.load(new AtomicYamlSettingsStore(configPath));
monitor = new MovementMonitor(new MovementDetector());
listener = new BukkitMovementListener(getServer(), monitor, settings::current, System::nanoTime);
var command = Objects.requireNonNull(getCommand("sentinel"), "Missing sentinel command");
var handler = new SentinelCommand(getServer(), monitor, settings, System::nanoTime);
command.setExecutor(handler);
command.setTabCompleter(handler);
getServer().getPluginManager().registerEvents(listener, this);
var alerts = new SentinelAlerts(getServer());
tickTask = getServer().getScheduler().runTaskTimer(this, () -> monitor
.finishBefore(getServer().getCurrentTick(), System.nanoTime()).forEach(alerts::send), 1L, 1L);
} catch (IOException | IllegalArgumentException exception) {
getLogger().severe("Sentinel configuration is invalid or unavailable; observation was not activated: " + exception.getMessage());
getServer().getPluginManager().disablePlugin(this);
}
}
@Override public void onDisable() {
if (tickTask != null) {
tickTask.cancel();
tickTask = null;
}
if (listener != null) {
HandlerList.unregisterAll(listener);
listener = null;
}
if (monitor != null) {
monitor.clear();
monitor = null;
}
}
}
@@ -0,0 +1,23 @@
package games.dmg.purpursentinel;
import java.util.Locale;
import org.bukkit.Server;
final class SentinelAlerts {
private final Server server;
SentinelAlerts(Server server) {
this.server = server;
}
void send(AlertDecision alert) {
var subject = server.getPlayer(alert.playerId());
if (subject == null || !subject.isOnline()) return;
String message = String.format(Locale.ROOT,
"[Sentinel] %s: %d movement breaches; peak %.2f blocks/tick vs captured limit %.2f. Use /sentinel inspect %s.",
subject.getName(), alert.breachCount(), alert.peakSpeed(), alert.capturedLimit(), subject.getName());
server.getOnlinePlayers().stream()
.filter(recipient -> recipient.hasPermission("sentinel.alerts"))
.forEach(recipient -> recipient.sendMessage(message));
}
}
@@ -0,0 +1,137 @@
package games.dmg.purpursentinel;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.function.LongSupplier;
import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
public final class SentinelCommand implements CommandExecutor, TabCompleter {
private final Server server;
private final MovementMonitor monitor;
private final SettingsService settings;
private final LongSupplier nanoTime;
public SentinelCommand(Server server, MovementMonitor monitor, SettingsService settings, LongSupplier nanoTime) {
this.server = server;
this.monitor = monitor;
this.settings = settings;
this.nanoTime = nanoTime;
}
@Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command,
@NotNull String label, @NotNull String[] args) {
if (args.length == 0) {
sender.sendMessage("Usage: /sentinel <inspect|config> ...");
return true;
}
if (args[0].equalsIgnoreCase("inspect")) return inspect(sender, args);
if (args[0].equalsIgnoreCase("config")) return configure(sender, args);
sender.sendMessage("Unsupported Sentinel route: " + args[0] + '.');
return true;
}
@Override public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command,
@NotNull String alias, @NotNull String[] args) {
if (args.length == 1) {
var routes = new ArrayList<String>();
if (sender.hasPermission("sentinel.config")) routes.add("config");
if (sender.hasPermission("sentinel.inspect")) routes.add("inspect");
return filter(routes, args[0]);
}
if (args.length == 2 && args[0].equalsIgnoreCase("inspect") && sender.hasPermission("sentinel.inspect")) {
return filter(server.getOnlinePlayers().stream().map(Player::getName)
.sorted(String.CASE_INSENSITIVE_ORDER).toList(), args[1]);
}
if (args.length == 2 && args[0].equalsIgnoreCase("config") && sender.hasPermission("sentinel.config")) {
return filter(java.util.Arrays.stream(SettingKey.values()).map(SettingKey::key).toList(), args[1]);
}
if (args.length == 3 && args[0].equalsIgnoreCase("config") && sender.hasPermission("sentinel.config")) {
var key = SettingKey.find(args[1]);
if (key.isEmpty()) return List.of();
var values = new LinkedHashSet<String>();
values.add(key.get().minimum());
values.add(settings.value(key.get()));
values.add(key.get().maximum());
return filter(new ArrayList<>(values), args[2]);
}
return List.of();
}
private boolean inspect(CommandSender sender, String[] args) {
if (!sender.hasPermission("sentinel.inspect")) {
sender.sendMessage("You do not have permission to inspect Sentinel evidence.");
return true;
}
if (args.length != 2) {
sender.sendMessage("Usage: /sentinel inspect <player>");
return true;
}
var player = server.getOnlinePlayers().stream()
.filter(candidate -> candidate.getName().equalsIgnoreCase(args[1]))
.findFirst();
if (player.isEmpty()) {
if (server.getOfflinePlayerIfCached(args[1]) != null) {
sender.sendMessage(args[1] + " is offline; Sentinel retains no offline evidence.");
} else {
sender.sendMessage("Unknown player: " + args[1] + '.');
}
return true;
}
var snapshot = monitor.inspect(player.get().getUniqueId(), nanoTime.getAsLong());
if (snapshot.isEmpty()) {
sender.sendMessage("No current evidence for " + player.get().getName() + "; none was recorded or it expired.");
return true;
}
var evidence = snapshot.get();
sender.sendMessage(String.format(Locale.ROOT,
"%s: %d breaches; age %.1fs; peak %.2f blocks/tick vs captured limit %.2f; exclusion %s; cooldown %.1fs.",
player.get().getName(), evidence.breachCount(), evidence.evidenceAgeSeconds(), evidence.peakSpeed(),
evidence.capturedLimit(), evidence.currentExclusion().description(), evidence.cooldownRemainingSeconds()));
return true;
}
private boolean configure(CommandSender sender, String[] args) {
if (!sender.hasPermission("sentinel.config")) {
sender.sendMessage("You do not have permission to configure Sentinel.");
return true;
}
if (args.length < 2 || args.length > 3) {
sender.sendMessage("Usage: /sentinel config <key> [value]");
return true;
}
var key = SettingKey.find(args[1]);
if (key.isEmpty()) {
sender.sendMessage("Unknown Sentinel configuration key: " + args[1] + '.');
return true;
}
if (args.length == 2) {
sender.sendMessage(key.get().key() + " is " + settings.value(key.get()) + '.');
return true;
}
try {
String value = settings.update(key.get(), args[2]);
sender.sendMessage(key.get().key() + " updated to " + value + '.');
} catch (IllegalArgumentException exception) {
sender.sendMessage(exception.getMessage());
} catch (IOException exception) {
sender.sendMessage("Could not save Sentinel configuration; the prior value remains active.");
}
return true;
}
private static List<String> filter(List<String> options, String prefix) {
String normalized = prefix.toLowerCase(Locale.ROOT);
return options.stream().filter(value -> value.toLowerCase(Locale.ROOT).startsWith(normalized))
.sorted(Comparator.comparing(value -> value.toLowerCase(Locale.ROOT))).toList();
}
}
@@ -0,0 +1,34 @@
package games.dmg.purpursentinel;
public record SentinelSettings(
double horizontalSpeedLimit,
int breachesToAlert,
int evidenceWindowSeconds,
int alertCooldownSeconds,
double minimumTps,
int exemptionGraceTicks) {
public SentinelSettings {
requireFiniteRange(horizontalSpeedLimit, 0.40, 5.00, "horizontal-speed-limit");
requireRange(breachesToAlert, 3, 40, "breaches-to-alert");
requireRange(evidenceWindowSeconds, 2, 60, "evidence-window-seconds");
requireRange(alertCooldownSeconds, 5, 3600, "alert-cooldown-seconds");
requireFiniteRange(minimumTps, 10.0, 20.0, "minimum-tps");
requireRange(exemptionGraceTicks, 1, 200, "exemption-grace-ticks");
}
public static SentinelSettings defaults() {
return new SentinelSettings(0.80, 6, 10, 60, 18.0, 20);
}
private static void requireRange(int value, int minimum, int maximum, String key) {
if (value < minimum || value > maximum) {
throw new IllegalArgumentException(key + " must be between " + minimum + " and " + maximum + '.');
}
}
private static void requireFiniteRange(double value, double minimum, double maximum, String key) {
if (!Double.isFinite(value) || value < minimum || value > maximum) {
throw new IllegalArgumentException(key + " must be between " + minimum + " and " + maximum + '.');
}
}
}
@@ -0,0 +1,35 @@
package games.dmg.purpursentinel;
import java.util.Arrays;
import java.util.Locale;
import java.util.Optional;
public enum SettingKey {
HORIZONTAL_SPEED_LIMIT("horizontal-speed-limit", "0.40", "5.00", false),
BREACHES_TO_ALERT("breaches-to-alert", "3", "40", true),
EVIDENCE_WINDOW_SECONDS("evidence-window-seconds", "2", "60", true),
ALERT_COOLDOWN_SECONDS("alert-cooldown-seconds", "5", "3600", true),
MINIMUM_TPS("minimum-tps", "10.0", "20.0", false),
EXEMPTION_GRACE_TICKS("exemption-grace-ticks", "1", "200", true);
private final String key;
private final String minimum;
private final String maximum;
private final boolean integer;
SettingKey(String key, String minimum, String maximum, boolean integer) {
this.key = key;
this.minimum = minimum;
this.maximum = maximum;
this.integer = integer;
}
public String key() { return key; }
public String minimum() { return minimum; }
public String maximum() { return maximum; }
public boolean integer() { return integer; }
public static Optional<SettingKey> find(String value) {
return Arrays.stream(values()).filter(key -> key.key.equals(value.toLowerCase(Locale.ROOT))).findFirst();
}
}
@@ -0,0 +1,16 @@
package games.dmg.purpursentinel;
import java.util.LinkedHashMap;
import java.util.Map;
public record SettingsDocument(Map<String, Object> values) {
public SettingsDocument {
values = new LinkedHashMap<>(values);
}
public SettingsDocument with(SettingKey key, Object value) {
var copy = new LinkedHashMap<>(values);
copy.put(key.key(), value);
return new SettingsDocument(copy);
}
}
@@ -0,0 +1,8 @@
package games.dmg.purpursentinel;
import java.io.IOException;
public interface SettingsPersistence {
SettingsDocument load() throws IOException;
void save(SettingsDocument document) throws IOException;
}
@@ -0,0 +1,103 @@
package games.dmg.purpursentinel;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
public final class SettingsService {
private final SettingsPersistence persistence;
private final AtomicReference<SentinelSettings> current;
private SettingsService(SettingsPersistence persistence, SentinelSettings settings) {
this.persistence = persistence;
current = new AtomicReference<>(settings);
}
public static SettingsService load(SettingsPersistence persistence) throws IOException {
return new SettingsService(persistence, parse(persistence.load().values()));
}
public SentinelSettings current() {
return current.get();
}
public synchronized String update(SettingKey key, String rawValue) throws IOException {
Object parsedValue = parseValue(key, rawValue);
var latest = persistence.load();
var nextDocument = latest.with(key, parsedValue);
var nextSettings = parse(nextDocument.values());
persistence.save(nextDocument);
current.set(nextSettings);
return format(key, nextSettings);
}
public String value(SettingKey key) {
return format(key, current());
}
private static SentinelSettings parse(Map<String, Object> values) {
return new SentinelSettings(
decimal(values, SettingKey.HORIZONTAL_SPEED_LIMIT),
integer(values, SettingKey.BREACHES_TO_ALERT),
integer(values, SettingKey.EVIDENCE_WINDOW_SECONDS),
integer(values, SettingKey.ALERT_COOLDOWN_SECONDS),
decimal(values, SettingKey.MINIMUM_TPS),
integer(values, SettingKey.EXEMPTION_GRACE_TICKS));
}
private static Object parseValue(SettingKey key, String value) {
try {
if (key.integer()) {
if (!value.matches("-?(0|[1-9][0-9]*)")) throw new NumberFormatException();
return Integer.parseInt(value);
}
double parsed = Double.parseDouble(value);
if (!Double.isFinite(parsed)) throw new NumberFormatException();
return parsed;
} catch (NumberFormatException exception) {
throw new IllegalArgumentException("Invalid value for " + key.key() + '.', exception);
}
}
private static int integer(Map<String, Object> values, SettingKey key) {
Object value = required(values, key);
if (!(value instanceof Number number)) throw new IllegalArgumentException(key.key() + " must be an integer.");
double decimal = number.doubleValue();
if (!Double.isFinite(decimal) || decimal != Math.rint(decimal)) {
throw new IllegalArgumentException(key.key() + " must be an integer.");
}
return Math.toIntExact(number.longValue());
}
private static double decimal(Map<String, Object> values, SettingKey key) {
Object value = required(values, key);
if (!(value instanceof Number number) || !Double.isFinite(number.doubleValue())) {
throw new IllegalArgumentException(key.key() + " must be a finite number.");
}
return number.doubleValue();
}
private static Object required(Map<String, Object> values, SettingKey key) {
Object value = values.get(key.key());
if (value == null) throw new IllegalArgumentException("Missing " + key.key() + '.');
return value;
}
private static String format(SettingKey key, SentinelSettings settings) {
return switch (key) {
case HORIZONTAL_SPEED_LIMIT -> decimal(settings.horizontalSpeedLimit(), 2);
case BREACHES_TO_ALERT -> Integer.toString(settings.breachesToAlert());
case EVIDENCE_WINDOW_SECONDS -> Integer.toString(settings.evidenceWindowSeconds());
case ALERT_COOLDOWN_SECONDS -> Integer.toString(settings.alertCooldownSeconds());
case MINIMUM_TPS -> decimal(settings.minimumTps(), 1);
case EXEMPTION_GRACE_TICKS -> Integer.toString(settings.exemptionGraceTicks());
};
}
private static String decimal(double value, int minimumScale) {
var decimal = BigDecimal.valueOf(value).stripTrailingZeros();
if (decimal.scale() < minimumScale) decimal = decimal.setScale(minimumScale);
return decimal.toPlainString();
}
}