// AP1X SENTINEL collector for Rust dedicated servers (Oxide/uMod). // // * Observes server-side state only: player presence, server-received view angles, weapon-fired // timestamps, server-authoritative positions, item drop/pickup transfers, gathering and crafting. // * Batches telemetry and sends it with Oxide's asynchronous WebRequests (never blocks the main thread). // * Polls the AP1X API for moderation commands, executes ban/unban/kick/inventory-freeze with native // server APIs and reports the real outcome. Commands are executed at most once (persisted ledger). // // Verification status: this file has not been compiled in this repository's CI because Oxide and Rust // server assemblies are not redistributable. Oxide compiles plugins on load; see README.md for the // live-server verification procedure. Hook signatures follow the current Oxide Rust hook reference. using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Oxide.Core; using Oxide.Core.Libraries; using UnityEngine; namespace Oxide.Plugins { [Info("AP1XSentinel", "AP1X", "1.0.0")] [Description("AP1X SENTINEL telemetry collector and web-dashboard moderation bridge")] public class AP1XSentinel : RustPlugin { private const string CollectorVersion = "1.0.0"; private const int SchemaVersion = 1; #region Configuration private PluginConfig config; private class PluginConfig { [JsonProperty("ApiBaseUrl")] public string ApiBaseUrl = "https://sentinel.example.com/api/v1"; [JsonProperty("CollectorKey")] public string CollectorKey = ""; [JsonProperty("FlushIntervalSeconds")] public float FlushIntervalSeconds = 1f; [JsonProperty("MaxBatchEvents")] public int MaxBatchEvents = 400; [JsonProperty("MaxQueuedEvents")] public int MaxQueuedEvents = 20000; [JsonProperty("AimSampleHz")] public float AimSampleHz = 10f; [JsonProperty("MovementSampleHz")] public float MovementSampleHz = 4f; [JsonProperty("CommandPollSeconds")] public float CommandPollSeconds = 3f; [JsonProperty("HeartbeatSeconds")] public float HeartbeatSeconds = 30f; [JsonProperty("RequestTimeoutSeconds")] public float RequestTimeoutSeconds = 15f; [JsonProperty("TransferPickupWindowSeconds")] public float TransferPickupWindowSeconds = 120f; [JsonProperty("Debug")] public bool Debug = false; } protected override void LoadDefaultConfig() { config = new PluginConfig(); SaveConfig(); } protected override void LoadConfig() { base.LoadConfig(); try { config = Config.ReadObject(); if (config == null) throw new JsonException("empty configuration"); } catch (Exception ex) { PrintError($"Configuration invalid ({ex.Message}); using defaults. Fix oxide/config/AP1XSentinel.json."); LoadDefaultConfig(); } SaveConfig(); } protected override void SaveConfig() => Config.WriteObject(config, true); private string ConfigurationProblem() { if (string.IsNullOrEmpty(config.ApiBaseUrl) || !(config.ApiBaseUrl.StartsWith("https://") || config.ApiBaseUrl.StartsWith("http://"))) return "ApiBaseUrl must be an http(s) URL ending in /api/v1"; var parts = (config.CollectorKey ?? "").Split(new[] { '_' }, 3); if (parts.Length != 3 || parts[0] != "ap1x" || parts[1].Length != 8 || parts[2].Length < 32) return "CollectorKey is missing or malformed (issue one from the AP1X dashboard)"; if (config.MaxBatchEvents < 1 || config.MaxBatchEvents > 500) return "MaxBatchEvents must be between 1 and 500"; if (config.MaxQueuedEvents < config.MaxBatchEvents) return "MaxQueuedEvents must be >= MaxBatchEvents"; if (config.AimSampleHz <= 0 || config.MovementSampleHz <= 0 || config.FlushIntervalSeconds <= 0 || config.CommandPollSeconds <= 0 || config.HeartbeatSeconds <= 0) return "Sampling and polling intervals must be positive"; return null; } #endregion #region State private readonly LinkedList> queue = new LinkedList>(); private long droppedEvents; private long sequenceNumber; private string instanceId; private PendingBatch inFlight; private bool requestInProgress; private bool pollInProgress; private readonly List timers = new List(); private readonly Dictionary lastShotAt = new Dictionary(); private readonly Dictionary exemptUntilNextSample = new Dictionary(); private readonly Dictionary drops = new Dictionary(); private CommandLedger ledger; private FreezeState freezes; private bool running; private class PendingBatch { public Dictionary Payload; public int Attempts; public float NextAttemptAt; } private class PendingDrop { public ulong DropperId; public float At; } private class CommandLedger { public Dictionary Outcomes = new Dictionary(); } private class FreezeState { public Dictionary FrozenUntilUtc = new Dictionary(); } private Dictionary Headers() => new Dictionary { ["Authorization"] = "Bearer " + config.CollectorKey, ["Content-Type"] = "application/json", }; #endregion #region Lifecycle private void OnServerInitialized() { var problem = ConfigurationProblem(); if (problem != null) { PrintError($"Collector disabled: {problem}."); return; } instanceId = Guid.NewGuid().ToString(); ledger = Interface.Oxide.DataFileSystem.ReadObject("AP1XSentinel_commands") ?? new CommandLedger(); freezes = Interface.Oxide.DataFileSystem.ReadObject("AP1XSentinel_freezes") ?? new FreezeState(); running = true; Enqueue("collector.capabilities", null, new Dictionary { ["signals"] = new Dictionary { ["presence"] = true, ["aim"] = true, ["combat_interval"] = true, ["movement"] = true, ["economy_transfer"] = new Dictionary { ["available"] = true, ["reason"] = "drop/pickup transfers only" }, ["resource_lifecycle"] = true, }, ["features"] = new Dictionary { ["inventory_freeze"] = true }, }); foreach (var player in BasePlayer.activePlayerList) Enqueue("player.join", player.UserIDString, new Dictionary { ["display_name"] = player.displayName }); timers.Add(timer.Every(1f / config.AimSampleHz, SampleAim)); timers.Add(timer.Every(1f / config.MovementSampleHz, SampleMovement)); timers.Add(timer.Every(config.FlushIntervalSeconds, Flush)); timers.Add(timer.Every(config.CommandPollSeconds, PollCommands)); timers.Add(timer.Every(config.HeartbeatSeconds, SendHeartbeat)); timers.Add(timer.Every(30f, ExpireFreezes)); Puts($"AP1X SENTINEL collector {CollectorVersion} started (instance {instanceId})."); } private void Unload() { running = false; foreach (var t in timers) t?.Destroy(); timers.Clear(); if (ledger != null) Interface.Oxide.DataFileSystem.WriteObject("AP1XSentinel_commands", ledger); if (freezes != null) Interface.Oxide.DataFileSystem.WriteObject("AP1XSentinel_freezes", freezes); } #endregion #region Telemetry queue and transport private static string IsoNow() => DateTime.UtcNow.ToString("o"); private void Enqueue(string eventType, string playerId, Dictionary data) { if (!running) return; if (queue.Count >= config.MaxQueuedEvents) { queue.RemoveFirst(); droppedEvents++; } queue.AddLast(new Dictionary { ["event_id"] = Guid.NewGuid().ToString(), ["event_type"] = eventType, ["occurred_at"] = IsoNow(), ["player_id"] = playerId, ["data"] = data, }); } private void Flush() { if (!running || requestInProgress) return; if (inFlight == null) { if (queue.Count == 0) return; var events = new List>(); while (events.Count < config.MaxBatchEvents && queue.Count > 0) { events.Add(queue.First.Value); queue.RemoveFirst(); } sequenceNumber++; inFlight = new PendingBatch { Payload = new Dictionary { ["batch_id"] = Guid.NewGuid().ToString(), ["schema_version"] = SchemaVersion, ["collector"] = new Dictionary { ["platform"] = "rust", ["version"] = CollectorVersion, ["instance_id"] = instanceId, ["sequence_number"] = sequenceNumber, }, ["sent_at"] = IsoNow(), ["events"] = events, }, }; } if (Time.realtimeSinceStartup < inFlight.NextAttemptAt) return; requestInProgress = true; var batch = inFlight; webrequest.Enqueue(config.ApiBaseUrl.TrimEnd('/') + "/collector/telemetry/batches", JsonConvert.SerializeObject(batch.Payload), (code, response) => { requestInProgress = false; if (code >= 200 && code < 300) { inFlight = null; return; } if (code == 0 || code == 429 || code >= 500) { batch.Attempts++; var delay = Mathf.Min(60f, Mathf.Pow(2f, batch.Attempts)) * UnityEngine.Random.Range(0.5f, 1.5f); batch.NextAttemptAt = Time.realtimeSinceStartup + delay; PrintWarning($"Telemetry send failed (HTTP {code}); retrying the same batch in {delay:F1}s."); return; } inFlight = null; PrintWarning($"Telemetry batch rejected (HTTP {code}): {ErrorCode(response)}"); }, this, RequestMethod.POST, Headers(), config.RequestTimeoutSeconds); } private static string ErrorCode(string body) { try { return JObject.Parse(body ?? "{}")["error"]?["code"]?.ToString() ?? "unknown"; } catch (JsonException) { return "unparseable response"; } } private void SendHeartbeat() { var body = JsonConvert.SerializeObject(new Dictionary { ["collector_version"] = CollectorVersion, ["instance_id"] = instanceId, ["online_players"] = BasePlayer.activePlayerList.Count, ["queue_depth"] = queue.Count, ["dropped_events"] = droppedEvents, }); webrequest.Enqueue(config.ApiBaseUrl.TrimEnd('/') + "/collector/heartbeat", body, (code, response) => { if (code < 200 || code >= 300) PrintWarning($"Heartbeat failed (HTTP {code}): {ErrorCode(response)}"); }, this, RequestMethod.POST, Headers(), config.RequestTimeoutSeconds); } #endregion #region Observation private void OnPlayerConnected(BasePlayer player) { Enqueue("player.join", player.UserIDString, new Dictionary { ["display_name"] = player.displayName }); } private void OnPlayerDisconnected(BasePlayer player, string reason) { Enqueue("player.leave", player.UserIDString, new Dictionary { ["reason"] = (reason ?? "").Length > 120 ? reason.Substring(0, 120) : reason }); } private void OnPlayerRespawned(BasePlayer player) => exemptUntilNextSample[player.userID] = "respawn"; private void SampleAim() { var interval = 1000f / config.AimSampleHz; foreach (var player in BasePlayer.activePlayerList) { if (player == null || player.IsDead() || player.IsSleeping() || player.serverInput?.current == null) continue; // Server-received input angles: x = pitch (positive looks down), y = yaw. var angles = player.serverInput.current.aimAngles; var yaw = Mathf.Repeat(angles.y + 180f, 360f) - 180f; var pitch = Mathf.Clamp(-angles.x, -90f, 90f); Enqueue("aim.sample", player.UserIDString, new Dictionary { ["yaw_deg"] = Math.Round(yaw, 4), ["pitch_deg"] = Math.Round(pitch, 4), ["sample_interval_ms"] = Math.Round(interval, 3), }); } } private void SampleMovement() { foreach (var player in BasePlayer.activePlayerList) { if (player == null || player.IsDead() || player.IsSleeping()) continue; string state = null; if (exemptUntilNextSample.TryGetValue(player.userID, out var pending)) { state = pending; exemptUntilNextSample.Remove(player.userID); } else if (player.isMounted) state = "mounted"; else if (player.IsSwimming()) state = "swimming"; else if (player.modelState != null && player.modelState.onLadder) state = "ladder"; else if (player.IsFlying) state = "admin_noclip"; var position = player.transform.position; var data = new Dictionary { ["x"] = Math.Round(position.x, 3), ["y"] = Math.Round(position.y, 3), ["z"] = Math.Round(position.z, 3), ["grounded"] = player.IsOnGround(), ["vertical_velocity"] = Math.Round(player.GetWorldVelocity().y, 3), ["world_id"] = ConVar.Server.level, }; if (state != null) data["movement_state"] = state; Enqueue("movement.sample", player.UserIDString, data); } } private void OnWeaponFired(BaseProjectile projectile, BasePlayer player, ItemModProjectile mod, ProtoBuf.ProjectileShoot projectiles) { if (player == null || projectile == null) return; var weapon = projectile.GetItem()?.info?.shortname ?? projectile.ShortPrefabName; var key = player.UserIDString + "|" + weapon; var now = Time.realtimeSinceStartup; var data = new Dictionary { ["action_type"] = projectile.automatic ? "auto_fire" : "semi_auto_fire", ["weapon_id"] = weapon, }; if (lastShotAt.TryGetValue(key, out var last) && now - last < 600f) data["interval_ms"] = Math.Round((now - last) * 1000.0, 3); lastShotAt[key] = now; Enqueue("combat.action", player.UserIDString, data); } // Drop -> pickup by a different player is recorded as a transfer of the same item instance. private object OnItemAction(Item item, string action, BasePlayer player) { if (player == null || item == null) return null; if (IsFrozen(player.userID) && (action == "drop" || action == "upgrade_item" || action == "crush")) { player.ChatMessage("Your inventory is temporarily frozen by server moderation."); return false; } if (action == "drop") drops[item.uid.Value] = new PendingDrop { DropperId = player.userID, At = Time.realtimeSinceStartup }; return null; } private void OnItemPickup(Item item, BasePlayer player) { if (item == null || player == null) return; if (!drops.TryGetValue(item.uid.Value, out var drop)) return; drops.Remove(item.uid.Value); if (drop.DropperId == player.userID || Time.realtimeSinceStartup - drop.At > config.TransferPickupWindowSeconds) return; Enqueue("economy.transfer", null, new Dictionary { ["from_player_id"] = drop.DropperId.ToString(), ["to_player_id"] = player.UserIDString, ["item_type"] = item.info.shortname, ["quantity"] = item.amount.ToString(), ["item_instance_id"] = item.uid.Value.ToString(), ["transfer_context"] = "drop_pickup", }); } private void OnDispenserGather(ResourceDispenser dispenser, BasePlayer player, Item item) { if (player == null || item == null) return; Enqueue("economy.resource", player.UserIDString, new Dictionary { ["resource_type"] = item.info.shortname, ["quantity"] = item.amount.ToString(), ["origin_type"] = "harvested", }); } private void OnItemCraftFinished(ItemCraftTask task, Item item, ItemCrafter crafter) { var owner = crafter?.owner; if (owner == null || item == null) return; Enqueue("economy.crafting", owner.UserIDString, new Dictionary { ["resource_type"] = item.info.shortname, ["quantity"] = item.amount.ToString(), ["item_instance_id"] = item.uid.Value.ToString(), }); } #endregion #region Inventory freeze (blocks moving items out; never deletes items) private bool IsFrozen(ulong userId) => freezes != null && freezes.FrozenUntilUtc.TryGetValue(userId, out var until) && until > DateTime.UtcNow; private void ExpireFreezes() { if (freezes == null) return; foreach (var id in freezes.FrozenUntilUtc.Where(kv => kv.Value <= DateTime.UtcNow).Select(kv => kv.Key).ToList()) freezes.FrozenUntilUtc.Remove(id); } private object CanLootEntity(BasePlayer player, StorageContainer container) => IsFrozen(player.userID) ? (object)false : null; private object CanLootPlayer(BasePlayer target, BasePlayer looter) => IsFrozen(looter.userID) || IsFrozen(target.userID) ? (object)false : null; private object OnVendingTransaction(VendingMachine machine, BasePlayer buyer, int sellOrderId, int numberOfTransactions) => IsFrozen(buyer.userID) ? (object)false : null; private object OnItemRecycle(Item item, Recycler recycler) => item?.GetOwnerPlayer() != null && IsFrozen(item.GetOwnerPlayer().userID) ? (object)false : null; #endregion #region Commands private void PollCommands() { if (!running || pollInProgress) return; pollInProgress = true; webrequest.Enqueue(config.ApiBaseUrl.TrimEnd('/') + "/collector/commands", null, (code, response) => { pollInProgress = false; if (code < 200 || code >= 300) { if (code != 429) PrintWarning($"Command poll failed (HTTP {code}): {ErrorCode(response)}"); return; } JArray commands; try { commands = (JArray)(JObject.Parse(response)["commands"] ?? new JArray()); } catch (Exception ex) when (ex is JsonException || ex is InvalidCastException) { PrintWarning("Command poll returned an unparseable response."); return; } foreach (var command in commands.OfType()) HandleCommand(command); }, this, RequestMethod.GET, Headers(), config.RequestTimeoutSeconds); } private void HandleCommand(JObject command) { var id = command["command_id"]?.ToString(); if (string.IsNullOrEmpty(id)) return; if (ledger.Outcomes.TryGetValue(id, out var previous)) { // Redelivery after a lost response: report the stored outcome, never execute twice. ReportResult(id, previous, "Duplicate delivery; command was already executed.", null); return; } var url = config.ApiBaseUrl.TrimEnd('/') + "/collector/commands/" + id + "/ack"; webrequest.Enqueue(url, "{}", (code, response) => { if (code < 200 || code >= 300) { PrintWarning($"Command {id} acknowledgement refused (HTTP {code}): {ErrorCode(response)}"); return; } var status = JObject.Parse(response)["status"]?.ToString(); if (status != "executing") return; // expired or already finished on the server string error; var message = Execute(command, out error); var outcome = error == null ? "succeeded" : "failed"; ledger.Outcomes[id] = outcome; Interface.Oxide.DataFileSystem.WriteObject("AP1XSentinel_commands", ledger); ReportResult(id, outcome, message, error); }, this, RequestMethod.POST, Headers(), config.RequestTimeoutSeconds); } private string Execute(JObject command, out string errorCode) { errorCode = null; var type = command["command_type"]?.ToString(); var parameters = command["parameters"] as JObject ?? new JObject(); var reason = parameters["reason"]?.ToString(); if (string.IsNullOrEmpty(reason)) { errorCode = "INVALID_PARAMETERS"; return "Command has no reason."; } var expires = command["expires_at"]?.ToObject().ToUniversalTime(); if (expires.HasValue && expires.Value <= DateTime.UtcNow) { errorCode = "COMMAND_EXPIRED"; return "Command deadline passed before execution."; } ulong target = 0; var targetRaw = command["target"]?["player_id"]?.ToString(); if (type != "quarantine_trade_chain" && !ulong.TryParse(targetRaw, out target)) { errorCode = "INVALID_TARGET"; return "Target is not a SteamID64."; } switch (type) { case "kick": { var player = BasePlayer.FindByID(target); if (player == null || !player.IsConnected) { errorCode = "PLAYER_NOT_ONLINE"; return "Player is not connected to this server."; } player.Kick(reason); return "Player kicked."; } case "ban": { var permanent = parameters["permanent"]?.ToObject() ?? true; long expiry = -1; if (!permanent) { var seconds = parameters["duration_seconds"]?.ToObject() ?? 0; if (seconds < 60) { errorCode = "INVALID_PARAMETERS"; return "Temporary ban needs duration_seconds >= 60."; } expiry = DateTimeOffset.UtcNow.ToUnixTimeSeconds() + seconds; } var online = BasePlayer.FindByID(target) ?? BasePlayer.FindSleeping(target); ServerUsers.Set(target, ServerUsers.UserGroup.Banned, online?.displayName ?? targetRaw, reason, expiry); ServerUsers.Save(); var connected = BasePlayer.FindByID(target); if (connected != null && connected.IsConnected) connected.Kick("Banned: " + reason); return permanent ? "Permanent ban recorded in ServerUsers." : $"Temporary ban until {DateTimeOffset.FromUnixTimeSeconds(expiry):u}."; } case "unban": { var existing = ServerUsers.Get(target); if (existing == null || existing.group != ServerUsers.UserGroup.Banned) { errorCode = "NOT_BANNED"; return "Player is not banned on this server."; } ServerUsers.Remove(target); ServerUsers.Save(); return "Ban removed."; } case "freeze_inventory": return Freeze(new[] { target }, parameters, out errorCode); case "quarantine_trade_chain": { var ids = new List(); foreach (var raw in parameters["player_ids"] as JArray ?? new JArray()) if (ulong.TryParse(raw.ToString(), out var id)) ids.Add(id); if (ids.Count == 0) { errorCode = "INVALID_PARAMETERS"; return "No valid SteamID64 values in player_ids."; } return Freeze(ids, parameters, out errorCode); } default: errorCode = "COMMAND_UNSUPPORTED"; return $"Command type '{type}' is not supported by this collector."; } } private string Freeze(IEnumerable targets, JObject parameters, out string errorCode) { errorCode = null; var seconds = parameters["duration_seconds"]?.ToObject() ?? 3600; if (seconds < 60 || seconds > 604800) { errorCode = "INVALID_PARAMETERS"; return "duration_seconds must be between 60 and 604800."; } var until = DateTime.UtcNow.AddSeconds(seconds); var list = targets.ToList(); foreach (var id in list) freezes.FrozenUntilUtc[id] = until; Interface.Oxide.DataFileSystem.WriteObject("AP1XSentinel_freezes", freezes); return $"Inventory movement blocked for {list.Count} player(s) until {until:u}; no items were removed."; } private void ReportResult(string id, string status, string message, string errorCode) { var body = new Dictionary { ["status"] = status, ["executed_at"] = IsoNow(), ["result"] = new Dictionary { ["platform_action_id"] = null, ["message"] = message }, }; if (errorCode != null) { body["error_code"] = errorCode; body["error_message"] = message; } webrequest.Enqueue(config.ApiBaseUrl.TrimEnd('/') + "/collector/commands/" + id + "/result", JsonConvert.SerializeObject(body), (code, response) => { if (code < 200 || code >= 300) PrintWarning($"Result for command {id} not accepted (HTTP {code}): {ErrorCode(response)}"); }, this, RequestMethod.POST, Headers(), config.RequestTimeoutSeconds); } #endregion } }