mirror of
https://github.com/xoo0524tw/SynapseAnticheat.git
synced 2026-12-05 21:46:01 +02:00
Initial commit: SynapseAiAnticheat v3.2 source, Maven, and IDEA setup
This commit is contained in:
commit
a9337d2628
59 files changed
+9541
No files matched your search
+21
@@ -0,0 +1,21 @@
|
||||
# Build & Maven
|
||||
target/
|
||||
|
||||
# IDE (keep shared project configuration in .idea/, ignore local user/cache files)
|
||||
.idea/workspace.xml
|
||||
.idea/usage.statistics.xml
|
||||
.idea/shelf/
|
||||
.idea/httpRequests/
|
||||
.idea/markdown.xml
|
||||
.idea/caches/
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
|
||||
# Reverse engineering artifacts & local scratch files
|
||||
/analysis/
|
||||
/tools/
|
||||
/tests/
|
||||
/*.jar
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
.gravity_input_*.txt
|
||||
Generated
+7
@@ -0,0 +1,7 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Markdown personal settings
|
||||
/markdown.xml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
||||
Generated
+13
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="CompilerConfiguration">
|
||||
<annotationProcessing>
|
||||
<profile name="Maven default annotation processors profile" />
|
||||
</annotationProcessing>
|
||||
</component>
|
||||
<component name="JavacSettings">
|
||||
<option name="ADDITIONAL_OPTIONS_OVERRIDE">
|
||||
<module name="SynapseAiAnticheat" options="-Xpkginfo:always" />
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
||||
Generated
+8
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="Encoding" defaultCharsetForPropertiesFiles="UTF-8">
|
||||
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
|
||||
<file url="PROJECT" charset="UTF-8" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
+30
@@ -0,0 +1,30 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="RemoteRepositoriesConfiguration">
|
||||
<remote-repository>
|
||||
<option name="id" value="central" />
|
||||
<option name="name" value="Central Repository" />
|
||||
<option name="url" value="https://repo.maven.apache.org/maven2" />
|
||||
</remote-repository>
|
||||
<remote-repository>
|
||||
<option name="id" value="spigot-snapshots" />
|
||||
<option name="name" value="spigot-snapshots" />
|
||||
<option name="url" value="https://hub.spigotmc.org/nexus/content/repositories/snapshots/" />
|
||||
</remote-repository>
|
||||
<remote-repository>
|
||||
<option name="id" value="central" />
|
||||
<option name="name" value="Maven Central repository" />
|
||||
<option name="url" value="https://repo1.maven.org/maven2" />
|
||||
</remote-repository>
|
||||
<remote-repository>
|
||||
<option name="id" value="jboss.community" />
|
||||
<option name="name" value="JBoss Community repository" />
|
||||
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
|
||||
</remote-repository>
|
||||
<remote-repository>
|
||||
<option name="id" value="papermc" />
|
||||
<option name="name" value="papermc" />
|
||||
<option name="url" value="https://repo.papermc.io/repository/maven-public/" />
|
||||
</remote-repository>
|
||||
</component>
|
||||
</project>
|
||||
Generated
+12
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||
<component name="MavenProjectsManager">
|
||||
<option name="originalFiles">
|
||||
<list>
|
||||
<option value="$PROJECT_DIR$/pom.xml" />
|
||||
</list>
|
||||
</option>
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK" />
|
||||
</project>
|
||||
@@ -0,0 +1,67 @@
|
||||
# SynapseAiAnticheat (v3.2)
|
||||
|
||||
**SynapseAiAnticheat** is a hybrid Minecraft anticheat plugin for **Spigot, Paper, and Purpur** (`1.16.5 – 1.20.4+`) that combines deterministic kinematic/combat checks with an embedded **ONNX Runtime** neural network (`anticheat_model.onnx`) and a multi-signal Risk Engine.
|
||||
|
||||
> **Disclaimer:** This repository contains source code recovered through static & behavioral reverse engineering of `SynapseAiAnticheat-3.2.jar` for educational, security research, and interoperability analysis purposes.
|
||||
|
||||
---
|
||||
|
||||
## 1. Original Obfuscation & Reverse-Engineering Summary
|
||||
|
||||
### Obfuscation Profile
|
||||
- **Protection strength:** Light / un-obfuscated bytecode.
|
||||
- The distributed JAR (`SynapseAiAnticheat-3.2.jar`) retained original package structures (`net.synapselabs.anticheat.*`), class names, method/field names, debug line tables, and embedded resources (`plugin.yml`, `config.yml`, `messages_en.yml`, `messages_ru.yml`, `anticheat_model.onnx`).
|
||||
- `com.microsoft.onnxruntime:onnxruntime` (`1.17.1`) was shaded directly into the plugin JAR without relocation.
|
||||
|
||||
### Reverse-Engineering Workflow
|
||||
1. **Archive & Dependency Inspection:** Identified the Maven coordinates, Paper API (`1.20.1-R0.1-SNAPSHOT`) target, Java 17 bytecode level, and shaded ONNX Runtime dependency.
|
||||
2. **Decompilation & Reconstruction:** Extracted and reconstructed all 46 plugin classes under `net.synapselabs.anticheat.*` along with all YAML/ONNX resources into a clean Maven project (`pom.xml`).
|
||||
3. **Behavioral Equivalence Verification:** Cross-checked enum ordinals, `FeatureSchema` assembly/defaults, `RiskEngine` / `RiskAccumulator` scoring math, and `PlayerRecordCodec` serialization round-trips against the original JAR's runtime behavior.
|
||||
|
||||
---
|
||||
|
||||
## 2. Recovered Architecture & Features
|
||||
|
||||
### Core AI & Risk Engine (`net.synapselabs.anticheat.engine`)
|
||||
- **ONNX Neural Inference (`AiInferenceEngine`, `InferenceService`):** Loads `anticheat_model.onnx` into RAM via ONNX Runtime (`<0.3 ms` target inference latency) and performs asynchronous combat classification with Platt-style calibration.
|
||||
- **32-Feature Kinematic Schema (`FeatureSchema`, `FeatureVector`, `CombatTracker`, `KinematicHistory`):** Extracts 32 combat features (`combat.v3`) per hit, including reach distance, angle offset, 1t/2t/5t yaw & pitch deltas/acceleration/jerk, raycast hit/angle error, hitbox edge proximity, GCD sensitivity & snap detection, attack interval variance, strafe-rotation correlation, and knockback deviation.
|
||||
- **Multi-Signal Risk Engine (`RiskEngine`, `ContextEngine`, `RiskAccumulator`, `HardCombatChecks`, `LagCompensator`):** Combines weighted signals (`HARD_SNAP`, `HITBOX_MISS`, `REACH`, `AIM_CONSISTENCY`, `KINEMATIC_ROBOTIC`, `SILENT_ROTATION`, `UNNATURAL_JERK`, `PERFECT_COOLDOWN_SYNC`, `AI_MODEL`) with ping/TPS/context modifiers and exponential time-decay (`30s` half-life) into `LEGIT`, `SUSPICIOUS`, and `CHEAT` verdicts.
|
||||
|
||||
### Modular Gameplay Checks (`net.synapselabs.anticheat.checks`)
|
||||
- **`AutoClickerCheck`:** CPS ceiling and click-interval standard deviation check.
|
||||
- **`FastBreakCheck`:** Block-break speed multiplier check.
|
||||
- **`FastPlaceCheck`:** Block-placement rate (blocks/sec) check.
|
||||
- **`FastInteractCheck`:** Minimum eat and bow-draw tick validation.
|
||||
|
||||
### Administration, Integrations & Tooling
|
||||
- **GrimAC Hybrid Bridge (`GrimAcBridge`):** Reflection-based integration that ingests GrimAC flags into `ThreatState` and boosts suspicion.
|
||||
- **Punishment & Freeze System (`PunishmentManager`, `FreezeManager`):** Supports `AUTO` detection (LiteBans, AdvancedBan, LibertyBans, Essentials, Bukkit), custom commands, shadow mode, auto-kick/cancel thresholds, and player freeze/interrogation workflows.
|
||||
- **Staff UX (`AdminGuiManager`, `AlertManager`, `OverheadDisplayManager`, `LanguageManager`):** 54-slot chest dashboard & per-player inspection GUI, clickable alerts, overhead `TextDisplay` threat indicators, and English/Russian (`en` / `ru`) localization.
|
||||
- **Telemetry, Dataset & Notifications (`DatasetManager`, `DebugManager`, `VisualDebugRenderer`, `AuditLogManager`, `DiscordWebhookService`, `UpdateChecker`):** Combat dataset CSV recording/export, hitbox/raycast debug rendering, file logging, Discord webhook embeds, and GitHub release checks.
|
||||
|
||||
---
|
||||
|
||||
## 3. Build & Usage
|
||||
|
||||
### Prerequisites
|
||||
- **Java Development Kit (JDK) 17** or newer (compiled with `--release 17`)
|
||||
- **Apache Maven 3.8+** (or IntelliJ IDEA with its bundled Maven)
|
||||
|
||||
### Building with Maven
|
||||
```bash
|
||||
mvn clean package
|
||||
```
|
||||
The shaded plugin JAR will be generated at:
|
||||
```text
|
||||
target/SynapseAiAnticheat-3.2.jar
|
||||
```
|
||||
|
||||
### Opening in IntelliJ IDEA
|
||||
1. Open the project root directory in **IntelliJ IDEA**.
|
||||
2. IntelliJ will automatically recognize `pom.xml` and the shared `.idea/` project configuration (UTF-8 encoding, Java 17 language level, Paper & Spigot Maven repositories, and `-Xpkginfo:always` compiler flag).
|
||||
3. Select a **JDK 17** SDK in **File → Project Structure → Project SDK** if prompted, then run the **Maven `package`** lifecycle goal.
|
||||
|
||||
### Server Installation
|
||||
1. Place `target/SynapseAiAnticheat-3.2.jar` into your server's `plugins/` folder (Paper/Purpur/Spigot `1.16.5 – 1.20.4+`).
|
||||
2. Start the server and run `/aiac` in-game to complete the initial language selection (`setup_completed: true`).
|
||||
3. Configure thresholds, punishment mode, Discord webhook, and checks in `plugins/SynapseAiAnticheat/config.yml`.
|
||||
@@ -0,0 +1,91 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>net.synapselabs</groupId>
|
||||
<artifactId>SynapseAiAnticheat</artifactId>
|
||||
<version>3.2</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>SynapseAiAnticheat</name>
|
||||
<description>Next-Gen AI Machine Learning & Hybrid Anticheat for Spigot, Paper and Purpur</description>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.release>17</maven.compiler.release>
|
||||
</properties>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>spigot-snapshots</id>
|
||||
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>papermc</id>
|
||||
<url>https://repo.papermc.io/repository/maven-public/</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.papermc.paper</groupId>
|
||||
<artifactId>paper-api</artifactId>
|
||||
<version>1.20.1-R0.1-SNAPSHOT</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.microsoft.onnxruntime</groupId>
|
||||
<artifactId>onnxruntime</artifactId>
|
||||
<version>1.17.1</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>${project.artifactId}-${project.version}</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>false</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.11.0</version>
|
||||
<configuration>
|
||||
<release>17</release>
|
||||
<encoding>UTF-8</encoding>
|
||||
<proc>none</proc>
|
||||
<compilerArgs>
|
||||
<arg>-Xpkginfo:always</arg>
|
||||
</compilerArgs>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.5.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<createDependencyReducedPom>false</createDependencyReducedPom>
|
||||
<artifactSet>
|
||||
<includes>
|
||||
<include>com.microsoft.onnxruntime:onnxruntime</include>
|
||||
</includes>
|
||||
</artifactSet>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,845 @@
|
||||
package net.synapselabs.anticheat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import net.md_5.bungee.api.chat.ClickEvent;
|
||||
import net.md_5.bungee.api.chat.TextComponent;
|
||||
import net.md_5.bungee.api.chat.ClickEvent.Action;
|
||||
import net.synapselabs.anticheat.alert.AlertManager;
|
||||
import net.synapselabs.anticheat.bridge.GrimAcBridge;
|
||||
import net.synapselabs.anticheat.checks.block.FastBreakCheck;
|
||||
import net.synapselabs.anticheat.checks.block.FastPlaceCheck;
|
||||
import net.synapselabs.anticheat.checks.combat.AutoClickerCheck;
|
||||
import net.synapselabs.anticheat.checks.item.FastInteractCheck;
|
||||
import net.synapselabs.anticheat.compat.CompatUtils;
|
||||
import net.synapselabs.anticheat.data.PlayerDataManager;
|
||||
import net.synapselabs.anticheat.data.PlayerProfile;
|
||||
import net.synapselabs.anticheat.dataset.DatasetLabel;
|
||||
import net.synapselabs.anticheat.dataset.DatasetManager;
|
||||
import net.synapselabs.anticheat.dataset.DatasetManager.DatasetStats;
|
||||
import net.synapselabs.anticheat.debug.DebugManager;
|
||||
import net.synapselabs.anticheat.engine.AiInferenceEngine;
|
||||
import net.synapselabs.anticheat.engine.HardCombatChecks;
|
||||
import net.synapselabs.anticheat.engine.InferenceService;
|
||||
import net.synapselabs.anticheat.freeze.FreezeManager;
|
||||
import net.synapselabs.anticheat.gui.AdminGuiManager;
|
||||
import net.synapselabs.anticheat.gui.GuiListener;
|
||||
import net.synapselabs.anticheat.lang.LanguageManager;
|
||||
import net.synapselabs.anticheat.listener.CombatListener;
|
||||
import net.synapselabs.anticheat.logging.AuditLogManager;
|
||||
import net.synapselabs.anticheat.overlay.OverheadDisplayManager;
|
||||
import net.synapselabs.anticheat.punishment.PunishmentManager;
|
||||
import net.synapselabs.anticheat.update.UpdateChecker;
|
||||
import net.synapselabs.anticheat.update.UpdateChecker.Status;
|
||||
import net.synapselabs.anticheat.update.UpdateChecker.UpdateResult;
|
||||
import net.synapselabs.anticheat.webhook.DiscordWebhookService;
|
||||
import org.bukkit.Bukkit;
|
||||
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.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
public class AiAnticheatPlugin extends JavaPlugin implements CommandExecutor, TabCompleter {
|
||||
private LanguageManager languageManager;
|
||||
private AiInferenceEngine engine;
|
||||
private InferenceService inferenceService;
|
||||
private HardCombatChecks hardCombatChecks;
|
||||
private AlertManager alertManager;
|
||||
private OverheadDisplayManager overheadDisplayManager;
|
||||
private CombatListener combatListener;
|
||||
private PlayerDataManager dataManager;
|
||||
private AdminGuiManager guiManager;
|
||||
private GrimAcBridge grimAcBridge;
|
||||
private FreezeManager freezeManager;
|
||||
private DiscordWebhookService webhookService;
|
||||
private PunishmentManager punishmentManager;
|
||||
private UpdateChecker updateChecker;
|
||||
private DebugManager debugManager;
|
||||
private AuditLogManager auditLogManager;
|
||||
private DatasetManager datasetManager;
|
||||
|
||||
public void onEnable() {
|
||||
this.saveDefaultConfig();
|
||||
this.languageManager = new LanguageManager(this);
|
||||
this.sendStartupBanner();
|
||||
this.auditLogManager = new AuditLogManager(this);
|
||||
this.debugManager = new DebugManager(this);
|
||||
this.datasetManager = new DatasetManager(this);
|
||||
this.punishmentManager = new PunishmentManager(this);
|
||||
this.dataManager = new PlayerDataManager(this);
|
||||
this.engine = new AiInferenceEngine(this);
|
||||
this.inferenceService = new InferenceService(this, this.engine);
|
||||
this.hardCombatChecks = new HardCombatChecks(this);
|
||||
this.alertManager = new AlertManager(this);
|
||||
this.overheadDisplayManager = new OverheadDisplayManager(this);
|
||||
this.combatListener = new CombatListener(this, this.hardCombatChecks, this.inferenceService, this.alertManager, this.overheadDisplayManager);
|
||||
this.guiManager = new AdminGuiManager(this, this.dataManager);
|
||||
this.grimAcBridge = new GrimAcBridge(this);
|
||||
this.freezeManager = new FreezeManager(this);
|
||||
this.webhookService = new DiscordWebhookService(this);
|
||||
this.getServer().getPluginManager().registerEvents(this.combatListener, this);
|
||||
this.getServer().getPluginManager().registerEvents(new GuiListener(this), this);
|
||||
this.getServer().getPluginManager().registerEvents(this.freezeManager, this);
|
||||
this.getServer().getPluginManager().registerEvents(this.overheadDisplayManager, this);
|
||||
this.getServer().getPluginManager().registerEvents(new FastBreakCheck(this), this);
|
||||
this.getServer().getPluginManager().registerEvents(new FastPlaceCheck(this), this);
|
||||
this.getServer().getPluginManager().registerEvents(new AutoClickerCheck(this), this);
|
||||
this.getServer().getPluginManager().registerEvents(new FastInteractCheck(this), this);
|
||||
if (this.getCommand("aianticheat") != null) {
|
||||
this.getCommand("aianticheat").setExecutor(this);
|
||||
this.getCommand("aianticheat").setTabCompleter(this);
|
||||
}
|
||||
|
||||
Bukkit.getScheduler().runTaskTimer(this, () -> {
|
||||
if (this.combatListener != null) {
|
||||
this.combatListener.decayAll(0.04F);
|
||||
}
|
||||
}, 100L, 100L);
|
||||
Bukkit.getScheduler().runTaskTimer(this, () -> {
|
||||
if (this.dataManager != null) {
|
||||
this.dataManager.saveDatabase();
|
||||
}
|
||||
}, 2400L, 2400L);
|
||||
this.updateChecker = new UpdateChecker(
|
||||
this.getConfig().getString("updates.github_repo", "Smuzik/SynapseAiAnticheat"),
|
||||
this.getDescription().getVersion(),
|
||||
runnable -> Bukkit.getScheduler().runTaskAsynchronously(this, runnable),
|
||||
runnable -> Bukkit.getScheduler().runTask(this, runnable)
|
||||
);
|
||||
if (this.getConfig().getBoolean("updates.check_for_updates", true)) {
|
||||
this.updateChecker
|
||||
.checkForUpdates(
|
||||
result -> {
|
||||
if (result.isUpdateAvailable()) {
|
||||
this.getLogger().warning("==========================================================");
|
||||
this.getLogger()
|
||||
.warning(
|
||||
"[SynapseAI] \ud83d\ude80 NEW UPDATE AVAILABLE: " + result.getLatestVersion() + " (Current: v" + result.getCurrentVersion() + ")"
|
||||
);
|
||||
this.getLogger().warning("[SynapseAI] Release: " + result.getReleaseName());
|
||||
this.getLogger().warning("[SynapseAI] Download at: " + result.getReleaseUrl());
|
||||
this.getLogger().warning("==========================================================");
|
||||
} else if (result.getStatus() == Status.UP_TO_DATE) {
|
||||
this.getLogger().info("Synapse AI-AntiCheat is up to date (v" + result.getCurrentVersion() + ").");
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
if (!this.isSetupCompleted()) {
|
||||
this.getLogger().warning("==========================================================");
|
||||
this.getLogger().warning("[Synapse AI] FIRST RUN SETUP REQUIRED!");
|
||||
this.getLogger().warning("Type /aiac in-game to select your language and activate AI protection.");
|
||||
this.getLogger().warning("==========================================================");
|
||||
} else {
|
||||
this.getLogger().info("Synapse AI-AntiCheat v3.2 is ACTIVE and protecting the server!");
|
||||
}
|
||||
}
|
||||
|
||||
private void sendStartupBanner() {
|
||||
String discordUrl = this.getConfig().getString("discord.invite_url", "https://dsc.gg/synapselabs");
|
||||
this.getLogger().info("==========================================================");
|
||||
this.getLogger().info(" ____ _ _ ");
|
||||
this.getLogger().info(" / ___| _ _ _ __ __ _ _ __ ___ ___ | | | | ");
|
||||
this.getLogger().info(" \\___ \\| | | | '_ \\ / _` | '_ \\/ __|/ _ \\| | | | ");
|
||||
this.getLogger().info(" ___) | |_| | | | | (_| | |_) \\__ \\ __/| |___| |___ ");
|
||||
this.getLogger().info(" |____/ \\__, |_| |_|\\__,_| .__/|___/\\___||_____|_____|");
|
||||
this.getLogger().info(" |___/ |_| ");
|
||||
this.getLogger().info(" Synapse AI-AntiCheat v3.2 (Spigot / Paper / Purpur) ");
|
||||
this.getLogger().info(" Author: Synapse Labs Studio ");
|
||||
this.getLogger().info(" Discord: " + discordUrl);
|
||||
this.getLogger().info("==========================================================");
|
||||
}
|
||||
|
||||
public boolean isSetupCompleted() {
|
||||
return this.getConfig().getBoolean("setup_completed", false);
|
||||
}
|
||||
|
||||
public void setSetupCompleted(boolean completed) {
|
||||
this.getConfig().set("setup_completed", completed);
|
||||
this.saveConfig();
|
||||
}
|
||||
|
||||
public void onDisable() {
|
||||
if (this.overheadDisplayManager != null) {
|
||||
this.overheadDisplayManager.removeAll();
|
||||
}
|
||||
|
||||
if (this.datasetManager != null) {
|
||||
this.datasetManager.close();
|
||||
}
|
||||
|
||||
if (this.inferenceService != null) {
|
||||
this.inferenceService.close();
|
||||
}
|
||||
|
||||
if (this.languageManager != null) {
|
||||
this.languageManager.savePlayerLanguages();
|
||||
}
|
||||
|
||||
if (this.dataManager != null) {
|
||||
this.dataManager.saveDatabase();
|
||||
}
|
||||
|
||||
if (this.auditLogManager != null) {
|
||||
this.auditLogManager.close();
|
||||
}
|
||||
|
||||
if (this.engine != null) {
|
||||
this.engine.close();
|
||||
}
|
||||
|
||||
this.getLogger().info("Synapse AI-AntiCheat disabled.");
|
||||
}
|
||||
|
||||
public LanguageManager getLanguageManager() {
|
||||
return this.languageManager;
|
||||
}
|
||||
|
||||
public CombatListener getCombatListener() {
|
||||
return this.combatListener;
|
||||
}
|
||||
|
||||
public PlayerDataManager getDataManager() {
|
||||
return this.dataManager;
|
||||
}
|
||||
|
||||
public AdminGuiManager getGuiManager() {
|
||||
return this.guiManager;
|
||||
}
|
||||
|
||||
public OverheadDisplayManager getOverheadManager() {
|
||||
return this.overheadDisplayManager;
|
||||
}
|
||||
|
||||
public OverheadDisplayManager getOverheadDisplayManager() {
|
||||
return this.overheadDisplayManager;
|
||||
}
|
||||
|
||||
public FreezeManager getFreezeManager() {
|
||||
return this.freezeManager;
|
||||
}
|
||||
|
||||
public DiscordWebhookService getWebhookService() {
|
||||
return this.webhookService;
|
||||
}
|
||||
|
||||
public PunishmentManager getPunishmentManager() {
|
||||
return this.punishmentManager;
|
||||
}
|
||||
|
||||
public GrimAcBridge getGrimAcBridge() {
|
||||
return this.grimAcBridge;
|
||||
}
|
||||
|
||||
public UpdateChecker getUpdateChecker() {
|
||||
return this.updateChecker;
|
||||
}
|
||||
|
||||
public DebugManager getDebugManager() {
|
||||
return this.debugManager;
|
||||
}
|
||||
|
||||
public AuditLogManager getAuditLogManager() {
|
||||
return this.auditLogManager;
|
||||
}
|
||||
|
||||
public DatasetManager getDatasetManager() {
|
||||
return this.datasetManager;
|
||||
}
|
||||
|
||||
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
if (!sender.hasPermission("aianticheat.admin") && !sender.hasPermission("aianticheat.debug")) {
|
||||
sender.sendMessage(
|
||||
this.languageManager.getMessage("prefix", sender, new Object[0]) + this.languageManager.getMessage("commands.access_denied", sender, new Object[0])
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (this.isSetupCompleted() || args.length != 0 && (args[0].equalsIgnoreCase("lang") || args[0].equalsIgnoreCase("language"))) {
|
||||
if (args.length == 0 || args[0].equalsIgnoreCase("help") || args[0].equalsIgnoreCase("?")) {
|
||||
this.sendHelpMenu(sender);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!args[0].equalsIgnoreCase("lang") && !args[0].equalsIgnoreCase("language")) {
|
||||
if (!args[0].equalsIgnoreCase("menu") && !args[0].equalsIgnoreCase("gui")) {
|
||||
if (args[0].equalsIgnoreCase("about") || args[0].equalsIgnoreCase("info")) {
|
||||
String discordUrl = this.getConfig().getString("discord.invite_url", "https://dsc.gg/synapselabs");
|
||||
String lang = this.languageManager.getPlayerLanguage(sender);
|
||||
sender.sendMessage(this.languageManager.getMessage("about.header", lang, new Object[0]));
|
||||
sender.sendMessage(this.languageManager.getMessage("about.title", lang, new Object[]{"version", "3.0"}));
|
||||
sender.sendMessage(this.languageManager.getMessage("about.author", lang, new Object[0]));
|
||||
sender.sendMessage(this.languageManager.getMessage("about.studio", lang, new Object[0]));
|
||||
sender.sendMessage(this.languageManager.getMessage("about.discord", lang, new Object[]{"url", discordUrl}));
|
||||
sender.sendMessage(this.languageManager.getMessage("about.engine", lang, new Object[0]));
|
||||
sender.sendMessage(this.languageManager.getMessage("about.header", lang, new Object[0]));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (args[0].equalsIgnoreCase("ping") || args[0].equalsIgnoreCase("checkping")) {
|
||||
Player target = null;
|
||||
if (args.length > 1) {
|
||||
target = Bukkit.getPlayer(args[1]);
|
||||
} else if (sender instanceof Player p) {
|
||||
target = p;
|
||||
}
|
||||
|
||||
if (target == null) {
|
||||
sender.sendMessage(this.languageManager.getMessage("commands.ping_specify", sender, new Object[0]));
|
||||
return true;
|
||||
}
|
||||
|
||||
String lang = this.languageManager.getPlayerLanguage(sender);
|
||||
int ping = target.getPing();
|
||||
String pingRating;
|
||||
if (ping < 50) {
|
||||
pingRating = this.languageManager.getRaw("commands.ping_rating_excellent", lang);
|
||||
} else if (ping < 110) {
|
||||
pingRating = this.languageManager.getRaw("commands.ping_rating_normal", lang);
|
||||
} else if (ping < 180) {
|
||||
pingRating = this.languageManager.getRaw("commands.ping_rating_elevated", lang);
|
||||
} else {
|
||||
pingRating = this.languageManager.getRaw("commands.ping_rating_high", lang);
|
||||
}
|
||||
|
||||
String ip = target.getAddress() != null
|
||||
? target.getAddress().getAddress().getHostAddress()
|
||||
: this.languageManager.getRaw("commands.unknown", lang);
|
||||
String grimStatus = this.grimAcBridge.isGrimLoaded()
|
||||
? this.languageManager.getRaw("commands.grim_synced", lang)
|
||||
: this.languageManager.getRaw("commands.grim_standalone", lang);
|
||||
sender.sendMessage(this.languageManager.getMessage("commands.separator", lang, new Object[0]));
|
||||
sender.sendMessage(this.languageManager.getMessage("commands.ping_header", lang, new Object[]{"player", target.getName()}));
|
||||
sender.sendMessage(this.languageManager.getMessage("commands.ping_current", lang, new Object[]{"ping", ping, "rating", pingRating}));
|
||||
sender.sendMessage(this.languageManager.getMessage("commands.ping_ip", lang, new Object[]{"ip", ip}));
|
||||
sender.sendMessage(this.languageManager.getMessage("commands.ping_tps", lang, new Object[0]));
|
||||
sender.sendMessage(this.languageManager.getMessage("commands.ping_grim", lang, new Object[]{"status", grimStatus}));
|
||||
sender.sendMessage(this.languageManager.getMessage("commands.separator", lang, new Object[0]));
|
||||
return true;
|
||||
} else if (args[0].equalsIgnoreCase("setfreezeloc")) {
|
||||
if (sender instanceof Player player) {
|
||||
this.freezeManager.setCustomFreezeLocation(player.getLocation());
|
||||
sender.sendMessage(this.languageManager.getMessage("commands.freezeloc_set", sender, new Object[0]));
|
||||
} else {
|
||||
sender.sendMessage(this.languageManager.getMessage("commands.ingame_only", sender, new Object[0]));
|
||||
}
|
||||
|
||||
return true;
|
||||
} else if ((args[0].equalsIgnoreCase("chat") || args[0].equalsIgnoreCase("msg")) && args.length > 1) {
|
||||
if (sender instanceof Player player) {
|
||||
if (!this.freezeManager.isModeratorChecking(player.getUniqueId())) {
|
||||
sender.sendMessage(this.languageManager.getMessage("commands.chat_not_inspecting", sender, new Object[0]));
|
||||
return true;
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
for (int i = 1; i < args.length; i++) {
|
||||
sb.append(args[i]).append(" ");
|
||||
}
|
||||
|
||||
this.freezeManager.sendInterrogationMessage(player, sb.toString().trim(), true);
|
||||
} else {
|
||||
sender.sendMessage(this.languageManager.getMessage("commands.ingame_only", sender, new Object[0]));
|
||||
}
|
||||
|
||||
return true;
|
||||
} else if (args[0].equalsIgnoreCase("inspect") && args.length > 1) {
|
||||
if (sender instanceof Player player) {
|
||||
Player target = Bukkit.getPlayer(args[1]);
|
||||
if (target == null) {
|
||||
player.sendMessage(this.languageManager.getMessage("commands.player_not_found_online", player, new Object[0]));
|
||||
return true;
|
||||
}
|
||||
|
||||
this.guiManager.openInspectMenu(player, target);
|
||||
} else {
|
||||
sender.sendMessage(this.languageManager.getMessage("commands.ingame_only", sender, new Object[0]));
|
||||
}
|
||||
|
||||
return true;
|
||||
} else if (args[0].equalsIgnoreCase("freeze") && args.length > 1) {
|
||||
Player target = Bukkit.getPlayer(args[1]);
|
||||
if (target == null) {
|
||||
sender.sendMessage(this.languageManager.getMessage("commands.player_not_found", sender, new Object[0]));
|
||||
return true;
|
||||
}
|
||||
|
||||
Player moderator = sender instanceof Player p ? p : null;
|
||||
String defaultReason = this.languageManager.getMessage("gui.freeze_reason", sender, new Object[0]);
|
||||
if (this.freezeManager.freeze(target, defaultReason, moderator)) {
|
||||
sender.sendMessage(this.languageManager.getMessage("freeze.frozen_staff", sender, new Object[]{"player", target.getName()}));
|
||||
} else {
|
||||
sender.sendMessage(
|
||||
this.languageManager
|
||||
.getMessage(
|
||||
"freeze.cooldown_wait", sender, new Object[]{"seconds", this.freezeManager.getRemainingCooldownSeconds(target.getUniqueId())}
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
} else if (args[0].equalsIgnoreCase("unfreeze") && args.length > 1) {
|
||||
Player target = Bukkit.getPlayer(args[1]);
|
||||
if (target == null) {
|
||||
sender.sendMessage(this.languageManager.getMessage("commands.player_not_found", sender, new Object[0]));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (this.freezeManager.unfreeze(target)) {
|
||||
sender.sendMessage(this.languageManager.getMessage("freeze.unfrozen_staff", sender, new Object[]{"player", target.getName()}));
|
||||
} else {
|
||||
sender.sendMessage(
|
||||
this.languageManager
|
||||
.getMessage(
|
||||
"freeze.cooldown_wait", sender, new Object[]{"seconds", this.freezeManager.getRemainingCooldownSeconds(target.getUniqueId())}
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
} else if (args[0].equalsIgnoreCase("status")) {
|
||||
String lang = this.languageManager.getPlayerLanguage(sender);
|
||||
boolean active = this.engine != null && this.engine.isInitialized();
|
||||
String discordUrl = this.getConfig().getString("discord.invite_url", "https://dsc.gg/synapselabs");
|
||||
sender.sendMessage(
|
||||
this.languageManager
|
||||
.getMessage(
|
||||
"commands.status_model",
|
||||
lang,
|
||||
new Object[]{"status", this.languageManager.getRaw(active ? "commands.status_model_active" : "commands.status_model_error", lang)}
|
||||
)
|
||||
);
|
||||
sender.sendMessage(
|
||||
this.languageManager
|
||||
.getMessage(
|
||||
"commands.status_bridge",
|
||||
lang,
|
||||
new Object[]{
|
||||
"status",
|
||||
this.languageManager
|
||||
.getRaw(this.grimAcBridge.isGrimLoaded() ? "commands.status_bridge_connected" : "commands.status_bridge_standalone", lang)
|
||||
}
|
||||
)
|
||||
);
|
||||
sender.sendMessage(
|
||||
this.languageManager
|
||||
.getMessage("commands.status_ban", lang, new Object[]{"system", this.punishmentManager.getActivePlugin().getDisplay()})
|
||||
);
|
||||
sender.sendMessage(this.languageManager.getMessage("commands.status_overhead", lang, new Object[0]));
|
||||
sender.sendMessage(this.languageManager.getMessage("commands.status_discord", lang, new Object[]{"url", discordUrl}));
|
||||
sender.sendMessage(
|
||||
this.languageManager
|
||||
.getMessage(
|
||||
"commands.status_webhook",
|
||||
lang,
|
||||
new Object[]{
|
||||
"status",
|
||||
this.languageManager
|
||||
.getRaw(
|
||||
this.getConfig().getBoolean("discord.webhook.enabled", false) ? "commands.status_enabled" : "commands.status_disabled",
|
||||
lang
|
||||
)
|
||||
}
|
||||
)
|
||||
);
|
||||
UpdateResult updateRes = this.updateChecker != null ? this.updateChecker.getLastResult() : null;
|
||||
String updateDisplay;
|
||||
if (updateRes != null && updateRes.isUpdateAvailable()) {
|
||||
updateDisplay = this.languageManager
|
||||
.getMessage("commands.status_update_available", lang, new Object[]{"latest", updateRes.getLatestVersion()});
|
||||
} else {
|
||||
updateDisplay = this.languageManager
|
||||
.getMessage("commands.status_up_to_date", lang, new Object[]{"version", this.getDescription().getVersion()});
|
||||
}
|
||||
|
||||
sender.sendMessage(this.languageManager.getMessage("commands.status_update", lang, new Object[]{"status", updateDisplay}));
|
||||
return true;
|
||||
} else if (args[0].equalsIgnoreCase("update") || args[0].equalsIgnoreCase("checkupdate")) {
|
||||
String lang = this.languageManager.getPlayerLanguage(sender);
|
||||
sender.sendMessage(this.languageManager.getMessage("updates.checking", lang, new Object[0]));
|
||||
if (this.updateChecker != null) {
|
||||
this.updateChecker
|
||||
.checkForUpdates(
|
||||
result -> {
|
||||
if (result.getStatus() == Status.UPDATE_AVAILABLE) {
|
||||
sender.sendMessage(
|
||||
this.languageManager
|
||||
.getMessage(
|
||||
"updates.available", lang, new Object[]{"latest", result.getLatestVersion(), "current", result.getCurrentVersion()}
|
||||
)
|
||||
);
|
||||
sender.sendMessage(
|
||||
this.languageManager.getMessage("updates.release_name", lang, new Object[]{"title", result.getReleaseName()})
|
||||
);
|
||||
sender.sendMessage(this.languageManager.getMessage("updates.release_url", lang, new Object[]{"url", result.getReleaseUrl()}));
|
||||
if (sender instanceof Player p) {
|
||||
TextComponent btn = CompatUtils.createGrimButton(
|
||||
this.languageManager.getRaw("updates.btn_github", lang),
|
||||
"�d2ff",
|
||||
this.languageManager.getMessage("updates.btn_github_hover", lang, new Object[]{"url", result.getReleaseUrl()}),
|
||||
null
|
||||
);
|
||||
btn.setClickEvent(new ClickEvent(Action.OPEN_URL, result.getReleaseUrl()));
|
||||
CompatUtils.sendComponent(p, btn);
|
||||
}
|
||||
} else if (result.getStatus() == Status.ERROR) {
|
||||
sender.sendMessage(this.languageManager.getMessage("updates.error", lang, new Object[]{"error", result.getErrorMessage()}));
|
||||
} else {
|
||||
sender.sendMessage(
|
||||
this.languageManager.getMessage("updates.up_to_date", lang, new Object[]{"version", result.getCurrentVersion()})
|
||||
);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
} else if (args[0].equalsIgnoreCase("check") && args.length > 1) {
|
||||
Player target = Bukkit.getPlayer(args[1]);
|
||||
if (target == null) {
|
||||
sender.sendMessage(this.languageManager.getMessage("commands.player_not_found_online", sender, new Object[0]));
|
||||
return true;
|
||||
} else {
|
||||
String lang = this.languageManager.getPlayerLanguage(sender);
|
||||
PlayerProfile profile = this.dataManager.getOrCreate(target);
|
||||
int kScore = Math.round(profile.getKillauraConfidence() * 100.0F);
|
||||
int aScore = Math.round(profile.getAimConfidence() * 100.0F);
|
||||
int susp = Math.round(profile.getSuspicion() * 100.0F);
|
||||
sender.sendMessage(this.languageManager.getMessage("commands.check_header", lang, new Object[]{"player", target.getName()}));
|
||||
sender.sendMessage(
|
||||
this.languageManager
|
||||
.getMessage(
|
||||
"commands.check_threat", lang, new Object[]{"state", this.languageManager.getRaw(profile.getThreatState().messageKey(), lang)}
|
||||
)
|
||||
);
|
||||
sender.sendMessage(
|
||||
this.languageManager
|
||||
.getMessage(
|
||||
"commands.check_killaura",
|
||||
lang,
|
||||
new Object[]{"bar", AdminGuiManager.renderBar(kScore, 10, "&#ff2244", "&#ffaa00", "�ff88"), "score", kScore}
|
||||
)
|
||||
);
|
||||
sender.sendMessage(
|
||||
this.languageManager
|
||||
.getMessage(
|
||||
"commands.check_aim",
|
||||
lang,
|
||||
new Object[]{"bar", AdminGuiManager.renderBar(aScore, 10, "&#ff2244", "&#ffaa00", "�ff88"), "score", aScore}
|
||||
)
|
||||
);
|
||||
sender.sendMessage(
|
||||
this.languageManager
|
||||
.getMessage(
|
||||
"commands.check_suspicion",
|
||||
lang,
|
||||
new Object[]{"bar", AdminGuiManager.renderBar(susp, 10, "&#ff2244", "&#ffaa00", "�ff88"), "score", susp}
|
||||
)
|
||||
);
|
||||
sender.sendMessage(
|
||||
this.languageManager
|
||||
.getMessage(
|
||||
"commands.check_flags",
|
||||
lang,
|
||||
new Object[]{
|
||||
"total",
|
||||
profile.getTotalFlags(),
|
||||
"hard",
|
||||
profile.getHardFlags(),
|
||||
"ai",
|
||||
profile.getAiFlags(),
|
||||
"grim",
|
||||
profile.getGrimFlagsCount()
|
||||
}
|
||||
)
|
||||
);
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
if (args[0].equalsIgnoreCase("testwebhook") || args[0].equalsIgnoreCase("webhook")) {
|
||||
this.webhookService.testWebhook(sender);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (args[0].equalsIgnoreCase("dataset") || args[0].equalsIgnoreCase("ds") || args[0].equalsIgnoreCase("data")) {
|
||||
String lang = this.languageManager.getPlayerLanguage(sender);
|
||||
if (!this.datasetManager.isEnabled()) {
|
||||
sender.sendMessage(this.languageManager.getMessage("dataset.disabled", lang, new Object[0]));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (args.length < 2) {
|
||||
sender.sendMessage(this.languageManager.getMessage("dataset.usage", lang, new Object[0]));
|
||||
return true;
|
||||
}
|
||||
|
||||
String action = args[1].toLowerCase();
|
||||
if (action.equals("start")) {
|
||||
if (args.length < 4) {
|
||||
sender.sendMessage(this.languageManager.getMessage("dataset.usage_start", lang, new Object[0]));
|
||||
return true;
|
||||
} else {
|
||||
Player target = Bukkit.getPlayer(args[2]);
|
||||
if (target == null) {
|
||||
sender.sendMessage(this.languageManager.getMessage("commands.player_not_found_online", lang, new Object[0]));
|
||||
return true;
|
||||
} else {
|
||||
DatasetLabel dLabel = DatasetLabel.fromString(args[3]);
|
||||
if (dLabel == null) {
|
||||
sender.sendMessage(this.languageManager.getMessage("dataset.invalid_label", lang, new Object[0]));
|
||||
return true;
|
||||
} else {
|
||||
this.datasetManager.startRecording(target.getUniqueId(), target.getName(), dLabel);
|
||||
sender.sendMessage(
|
||||
this.languageManager.getMessage("dataset.started", lang, new Object[]{"player", target.getName(), "label", dLabel.name()})
|
||||
);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (!action.equals("stop")) {
|
||||
if (action.equals("stats") || action.equals("status")) {
|
||||
DatasetStats stats = this.datasetManager.getStats();
|
||||
sender.sendMessage(this.languageManager.getMessage("dataset.stats_header", lang, new Object[0]));
|
||||
sender.sendMessage(this.languageManager.getMessage("dataset.stats_active", lang, new Object[]{"count", stats.activeSessionsCount()}));
|
||||
sender.sendMessage(this.languageManager.getMessage("dataset.stats_memory", lang, new Object[]{"count", stats.inMemoryCount()}));
|
||||
sender.sendMessage(this.languageManager.getMessage("dataset.stats_legit", lang, new Object[]{"count", stats.totalLegitCount()}));
|
||||
sender.sendMessage(this.languageManager.getMessage("dataset.stats_cheat", lang, new Object[]{"count", stats.totalCheatCount()}));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (action.equals("export") || action.equals("save")) {
|
||||
String customName = args.length > 2 ? args[2] : null;
|
||||
String exported = this.datasetManager.exportToCsv(customName);
|
||||
if (exported != null) {
|
||||
sender.sendMessage(this.languageManager.getMessage("dataset.exported", lang, new Object[]{"file", exported}));
|
||||
} else {
|
||||
sender.sendMessage(this.languageManager.getMessage("dataset.export_empty", lang, new Object[0]));
|
||||
}
|
||||
|
||||
return true;
|
||||
} else if (!action.equals("clear") && !action.equals("reset")) {
|
||||
sender.sendMessage(this.languageManager.getMessage("dataset.usage", lang, new Object[0]));
|
||||
return true;
|
||||
} else {
|
||||
this.datasetManager.clear();
|
||||
sender.sendMessage(this.languageManager.getMessage("dataset.cleared", lang, new Object[0]));
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
if (args.length >= 3 && !args[2].equalsIgnoreCase("all")) {
|
||||
Player target = Bukkit.getPlayer(args[2]);
|
||||
UUID targetId = target != null ? target.getUniqueId() : null;
|
||||
if (targetId != null && this.datasetManager.stopRecording(targetId)) {
|
||||
sender.sendMessage(this.languageManager.getMessage("dataset.stopped_player", lang, new Object[]{"player", target.getName()}));
|
||||
} else {
|
||||
sender.sendMessage(this.languageManager.getMessage("dataset.not_recording", lang, new Object[0]));
|
||||
}
|
||||
} else {
|
||||
int stopped = this.datasetManager.stopAll();
|
||||
sender.sendMessage(this.languageManager.getMessage("dataset.stopped_all", lang, new Object[]{"count", stopped}));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
} else if (args[0].equalsIgnoreCase("reload")) {
|
||||
this.reloadConfig();
|
||||
this.languageManager.reload();
|
||||
sender.sendMessage(this.languageManager.getMessage("punishment.reloaded", sender, new Object[0]));
|
||||
return true;
|
||||
} else {
|
||||
this.sendHelpMenu(sender);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (sender instanceof Player player) {
|
||||
this.guiManager.openMainMenu(player);
|
||||
} else {
|
||||
sender.sendMessage(this.languageManager.getMessage("commands.players_only_gui", sender, new Object[0]));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
if (args.length > 1) {
|
||||
String chosenLang = args[1].toLowerCase();
|
||||
if (!chosenLang.equals("en") && !chosenLang.equals("ru")) {
|
||||
sender.sendMessage(this.languageManager.getMessage("commands.lang_usage", sender, new Object[0]));
|
||||
} else {
|
||||
this.languageManager.setDefaultLanguage(chosenLang);
|
||||
if (sender instanceof Player p) {
|
||||
this.languageManager.setPlayerLanguage(p.getUniqueId(), chosenLang);
|
||||
}
|
||||
|
||||
if (!this.isSetupCompleted()) {
|
||||
this.setSetupCompleted(true);
|
||||
|
||||
for (Player staff : Bukkit.getOnlinePlayers()) {
|
||||
if (staff.hasPermission("aianticheat.admin")) {
|
||||
staff.sendMessage(this.languageManager.getMessage("setup.completed", chosenLang, new Object[]{"lang", chosenLang.toUpperCase()}));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
sender.sendMessage(this.languageManager.getMessage("lang_selector.changed", chosenLang, new Object[]{"lang", chosenLang.toUpperCase()}));
|
||||
}
|
||||
}
|
||||
} else if (sender instanceof Player player) {
|
||||
this.languageManager.sendLanguageSelectorPrompt(player);
|
||||
} else {
|
||||
sender.sendMessage(
|
||||
this.languageManager.getMessage("commands.lang_current_default", sender, new Object[]{"lang", this.getConfig().getString("language", "en")})
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
if (sender instanceof Player player) {
|
||||
this.languageManager.sendLanguageSelectorPrompt(player);
|
||||
} else {
|
||||
sender.sendMessage(CompatUtils.color("&c[SynapseAI] Please configure language first: /aiac lang <en|ru>"));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private void sendHelpMenu(CommandSender sender) {
|
||||
String lang = this.languageManager.getPlayerLanguage(sender);
|
||||
String discordUrl = this.getConfig().getString("discord.invite_url", "https://dsc.gg/synapselabs");
|
||||
sender.sendMessage(CompatUtils.color("&b================================================="));
|
||||
sender.sendMessage(this.languageManager.getMessage("help.header", lang, new Object[]{"version", this.getDescription().getVersion()}));
|
||||
sender.sendMessage(this.languageManager.getMessage("help.author", lang, new Object[0]));
|
||||
sender.sendMessage(CompatUtils.color("&b-------------------------------------------------"));
|
||||
sender.sendMessage(this.languageManager.getMessage("help.menu", lang, new Object[0]));
|
||||
sender.sendMessage(this.languageManager.getMessage("help.inspect", lang, new Object[0]));
|
||||
sender.sendMessage(this.languageManager.getMessage("help.freeze", lang, new Object[0]));
|
||||
sender.sendMessage(this.languageManager.getMessage("help.unfreeze", lang, new Object[0]));
|
||||
sender.sendMessage(this.languageManager.getMessage("help.dataset", lang, new Object[0]));
|
||||
sender.sendMessage(this.languageManager.getMessage("help.lang", lang, new Object[0]));
|
||||
sender.sendMessage(this.languageManager.getMessage("help.update", lang, new Object[0]));
|
||||
sender.sendMessage(this.languageManager.getMessage("help.reload", lang, new Object[0]));
|
||||
sender.sendMessage(this.languageManager.getMessage("help.discord", lang, new Object[]{"url", discordUrl}));
|
||||
if (sender instanceof Player p && !this.languageManager.hasExplicitLanguage(p)) {
|
||||
this.languageManager.sendLanguageSelectorPrompt(p);
|
||||
} else {
|
||||
sender.sendMessage(CompatUtils.color("&b================================================="));
|
||||
}
|
||||
}
|
||||
|
||||
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
|
||||
if (!sender.hasPermission("aianticheat.admin") && !sender.hasPermission("aianticheat.alerts")) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
List<String> completions = new ArrayList<>();
|
||||
if (args.length == 1) {
|
||||
List<String> subcommands = List.of(
|
||||
"menu", "gui", "inspect", "freeze", "unfreeze", "dataset", "ds", "ping", "check", "status", "update", "reload", "about", "lang", "webhook"
|
||||
);
|
||||
String input = args[0].toLowerCase();
|
||||
|
||||
for (String sub : subcommands) {
|
||||
if (sub.startsWith(input)) {
|
||||
completions.add(sub);
|
||||
}
|
||||
}
|
||||
|
||||
return completions;
|
||||
} else {
|
||||
if (args.length == 2) {
|
||||
String sub = args[0].toLowerCase();
|
||||
String input = args[1].toLowerCase();
|
||||
if (sub.equals("dataset") || sub.equals("ds") || sub.equals("data")) {
|
||||
for (String opt : List.of("start", "stop", "stats", "export", "clear")) {
|
||||
if (opt.startsWith(input)) {
|
||||
completions.add(opt);
|
||||
}
|
||||
}
|
||||
|
||||
return completions;
|
||||
}
|
||||
|
||||
if (sub.equals("inspect") || sub.equals("freeze") || sub.equals("unfreeze") || sub.equals("ping") || sub.equals("check")) {
|
||||
for (Player p : Bukkit.getOnlinePlayers()) {
|
||||
if (p.getName().toLowerCase().startsWith(input)) {
|
||||
completions.add(p.getName());
|
||||
}
|
||||
}
|
||||
|
||||
return completions;
|
||||
}
|
||||
|
||||
if (sub.equals("lang") || sub.equals("language")) {
|
||||
for (String l : List.of("en", "ru")) {
|
||||
if (l.startsWith(input)) {
|
||||
completions.add(l);
|
||||
}
|
||||
}
|
||||
|
||||
return completions;
|
||||
}
|
||||
}
|
||||
|
||||
if (args.length == 3) {
|
||||
String sub = args[0].toLowerCase();
|
||||
String sub2 = args[1].toLowerCase();
|
||||
String input = args[2].toLowerCase();
|
||||
if (sub.equals("dataset") || sub.equals("ds") || sub.equals("data")) {
|
||||
if (sub2.equals("start")) {
|
||||
for (Player p : Bukkit.getOnlinePlayers()) {
|
||||
if (p.getName().toLowerCase().startsWith(input)) {
|
||||
completions.add(p.getName());
|
||||
}
|
||||
}
|
||||
|
||||
return completions;
|
||||
}
|
||||
|
||||
if (sub2.equals("stop")) {
|
||||
List<String> stopOpts = new ArrayList<>(List.of("all"));
|
||||
|
||||
for (UUID uuid : this.datasetManager.getActiveSessions().keySet()) {
|
||||
Player p = Bukkit.getPlayer(uuid);
|
||||
if (p != null) {
|
||||
stopOpts.add(p.getName());
|
||||
}
|
||||
}
|
||||
|
||||
for (String opt : stopOpts) {
|
||||
if (opt.toLowerCase().startsWith(input)) {
|
||||
completions.add(opt);
|
||||
}
|
||||
}
|
||||
|
||||
return completions;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (args.length == 4) {
|
||||
String sub = args[0].toLowerCase();
|
||||
String sub2 = args[1].toLowerCase();
|
||||
String input = args[3].toLowerCase();
|
||||
if ((sub.equals("dataset") || sub.equals("ds") || sub.equals("data")) && sub2.equals("start")) {
|
||||
for (String label : List.of("legit", "cheat")) {
|
||||
if (label.startsWith(input)) {
|
||||
completions.add(label);
|
||||
}
|
||||
}
|
||||
|
||||
return completions;
|
||||
}
|
||||
}
|
||||
|
||||
return Collections.emptyList();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package net.synapselabs.anticheat.alert;
|
||||
|
||||
import net.md_5.bungee.api.chat.TextComponent;
|
||||
import net.synapselabs.anticheat.AiAnticheatPlugin;
|
||||
import net.synapselabs.anticheat.compat.CompatUtils;
|
||||
import net.synapselabs.anticheat.data.PlayerProfile;
|
||||
import net.synapselabs.anticheat.engine.DetectionSnapshot;
|
||||
import net.synapselabs.anticheat.lang.LanguageManager;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class AlertManager {
|
||||
private final AiAnticheatPlugin plugin;
|
||||
|
||||
public AlertManager(AiAnticheatPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
public void dispatchAlert(DetectionSnapshot snapshot) {
|
||||
if (snapshot.isFlagged()) {
|
||||
Player player = Bukkit.getPlayer(snapshot.playerId());
|
||||
if (player != null && player.isOnline()) {
|
||||
PlayerProfile profile = this.plugin.getDataManager().getOrCreate(player);
|
||||
this.broadcastAlert(snapshot, profile);
|
||||
if (this.plugin.getConfig().getBoolean("logging.console.enabled", true)) {
|
||||
String checkType = snapshot.hasHardViolations() ? "[Hard-Check]" : "[AI-Check]";
|
||||
this.plugin
|
||||
.getLogger()
|
||||
.info(
|
||||
String.format(
|
||||
"%s Player '%s' flagged for '%s' | Confidence: %d%% | State: %s | Ping: %dms | Flags: %d (Hard: %d, AI: %d, Grim: %d)",
|
||||
checkType,
|
||||
snapshot.playerName(),
|
||||
snapshot.getPrimaryViolation(),
|
||||
snapshot.getConfidencePercent(),
|
||||
snapshot.threatState().name(),
|
||||
player.getPing(),
|
||||
profile.getTotalFlags(),
|
||||
profile.getHardFlags(),
|
||||
profile.getAiFlags(),
|
||||
profile.getGrimFlagsCount()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
double reach = snapshot.featureVector() != null
|
||||
? snapshot.featureVector().namedFeatures().getOrDefault("raycast_distance", 3.0F).floatValue()
|
||||
: 3.0;
|
||||
float angle = snapshot.featureVector() != null ? snapshot.featureVector().namedFeatures().getOrDefault("angle_offset_deg", 0.0F) : 0.0F;
|
||||
this.plugin
|
||||
.getWebhookService()
|
||||
.sendFlagAlert(
|
||||
snapshot.playerName(),
|
||||
snapshot.getPrimaryViolation(),
|
||||
snapshot.getConfidencePercent(),
|
||||
profile.getTotalFlags(),
|
||||
player.getPing(),
|
||||
reach,
|
||||
angle
|
||||
);
|
||||
if (this.plugin.getAuditLogManager() != null) {
|
||||
this.plugin.getAuditLogManager().logDetection(snapshot, profile, "ALERT");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void broadcastAlert(DetectionSnapshot snapshot, PlayerProfile profile) {
|
||||
String soundName = this.plugin.getConfig().getString("detection.sound_alert.sound", "ENTITY_EXPERIENCE_ORB_PICKUP");
|
||||
boolean soundEnabled = this.plugin.getConfig().getBoolean("detection.sound_alert.enabled", true);
|
||||
boolean isHardCheck = snapshot.hasHardViolations();
|
||||
LanguageManager langMgr = this.plugin.getLanguageManager();
|
||||
|
||||
for (Player staff : Bukkit.getOnlinePlayers()) {
|
||||
if (staff.hasPermission("aianticheat.alerts") || staff.hasPermission("aianticheat.admin")) {
|
||||
String lang = langMgr != null ? langMgr.getPlayerLanguage(staff) : "en";
|
||||
TextComponent alertComp;
|
||||
if (isHardCheck) {
|
||||
String formatted = langMgr != null
|
||||
? langMgr.getMessage(
|
||||
"alerts.hard",
|
||||
lang,
|
||||
new Object[]{"player", snapshot.playerName(), "check", snapshot.getPrimaryViolation(), "flags", profile.getHardFlags()}
|
||||
)
|
||||
: "§b[Hard] " + snapshot.playerName() + " failed " + snapshot.getPrimaryViolation();
|
||||
alertComp = new TextComponent(formatted + " ");
|
||||
} else {
|
||||
String formatted = langMgr != null
|
||||
? langMgr.getMessage(
|
||||
"alerts.ai",
|
||||
lang,
|
||||
new Object[]{
|
||||
"player",
|
||||
snapshot.playerName(),
|
||||
"check",
|
||||
snapshot.getPrimaryViolation(),
|
||||
"confidence",
|
||||
snapshot.getConfidencePercent(),
|
||||
"state",
|
||||
langMgr.getRaw(snapshot.threatState().messageKey(), lang),
|
||||
"flags",
|
||||
profile.getAiFlags()
|
||||
}
|
||||
)
|
||||
: "§6[AI] " + snapshot.playerName() + " flagged " + snapshot.getPrimaryViolation();
|
||||
alertComp = new TextComponent(formatted + " ");
|
||||
}
|
||||
|
||||
this.appendButtons(alertComp, snapshot.playerName(), lang);
|
||||
CompatUtils.sendComponent(staff, alertComp);
|
||||
if (soundEnabled) {
|
||||
float pitch = isHardCheck ? 0.8F : 1.4F;
|
||||
CompatUtils.playSound(staff, soundName, 1.0F, pitch);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void appendButtons(TextComponent message, String playerName, String lang) {
|
||||
LanguageManager langMgr = this.plugin.getLanguageManager();
|
||||
String txtDossier = langMgr != null ? langMgr.getRaw("alerts.btn_dossier", lang) : "Dossier";
|
||||
String txtSpectate = langMgr != null ? langMgr.getRaw("alerts.btn_spectate", lang) : "Spectate";
|
||||
String txtFreeze = langMgr != null ? langMgr.getRaw("alerts.btn_freeze", lang) : "Freeze";
|
||||
String txtKick = langMgr != null ? langMgr.getRaw("alerts.btn_kick", lang) : "Kick";
|
||||
String hoverDossier = langMgr != null ? langMgr.getRaw("alerts.btn_dossier_hover", lang) : "Open dossier";
|
||||
String hoverSpectate = langMgr != null ? langMgr.getRaw("alerts.btn_spectate_hover", lang) : "Spectate player";
|
||||
String hoverFreeze = langMgr != null ? langMgr.getRaw("alerts.btn_freeze_hover", lang) : "Freeze player";
|
||||
String hoverKick = langMgr != null ? langMgr.getRaw("alerts.btn_kick_hover", lang) : "Kick player";
|
||||
String kickReason = langMgr != null ? langMgr.getRaw("alerts.kick_reason", lang) : "Unfair Advantage [SynapseAI]";
|
||||
message.addExtra(CompatUtils.createGrimButton(txtDossier, "�d2ff", hoverDossier, "/aiac inspect " + playerName));
|
||||
message.addExtra(new TextComponent(" "));
|
||||
message.addExtra(CompatUtils.createGrimButton(txtSpectate, "&#a855f7", hoverSpectate, "/aiac inspect " + playerName));
|
||||
message.addExtra(new TextComponent(" "));
|
||||
message.addExtra(CompatUtils.createGrimButton(txtFreeze, "b6d4", hoverFreeze, "/aiac freeze " + playerName));
|
||||
message.addExtra(new TextComponent(" "));
|
||||
message.addExtra(CompatUtils.createGrimButton(txtKick, "&#ef4444", hoverKick, "/kick " + playerName + " " + kickReason));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package net.synapselabs.anticheat.bridge;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import net.synapselabs.anticheat.AiAnticheatPlugin;
|
||||
import net.synapselabs.anticheat.data.PlayerProfile;
|
||||
import net.synapselabs.anticheat.tracker.CombatTracker;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
public class GrimAcBridge implements Listener {
|
||||
private final AiAnticheatPlugin plugin;
|
||||
private boolean grimLoaded = false;
|
||||
|
||||
public GrimAcBridge(AiAnticheatPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
this.hookGrim();
|
||||
}
|
||||
|
||||
private void hookGrim() {
|
||||
if (this.plugin.getConfig().getBoolean("detection.grimac_bridge.enabled", true)) {
|
||||
Plugin grim = Bukkit.getPluginManager().getPlugin("GrimAC");
|
||||
if (grim != null && grim.isEnabled()) {
|
||||
this.grimLoaded = true;
|
||||
this.plugin.getLogger().info("GrimAC engine successfully connected to Synapse AI Pipeline!");
|
||||
this.registerGrimEvents();
|
||||
} else {
|
||||
this.plugin.getLogger().info("GrimAC not detected (standalone Synapse AI mode active).");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void registerGrimEvents() {
|
||||
String[] possibleEventNames = new String[]{
|
||||
"ac.grim.grimac.api.events.FlagEvent", "ac.grim.grimac.api.event.events.FlagEvent", "ac.grim.grimac.api.events.GrimFlagEvent"
|
||||
};
|
||||
|
||||
for (String className : possibleEventNames) {
|
||||
try {
|
||||
Class<?> eventClass = Class.forName(className);
|
||||
if (Event.class.isAssignableFrom(eventClass)) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Class<? extends Event> typedEventClass = (Class<? extends Event>)eventClass;
|
||||
Bukkit.getPluginManager()
|
||||
.registerEvent(typedEventClass, this, EventPriority.MONITOR, (listener, event) -> this.handleGrimFlag(event), this.plugin, false);
|
||||
this.plugin.getLogger().info("GrimAC Flag Listener registered (" + className + ")!");
|
||||
return;
|
||||
}
|
||||
} catch (ClassNotFoundException var7) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void handleGrimFlag(Event event) {
|
||||
try {
|
||||
Player player = null;
|
||||
String checkName = "Unknown";
|
||||
double vl = 1.0;
|
||||
|
||||
try {
|
||||
Method getUserMethod = event.getClass().getMethod("getUser");
|
||||
Object userObj = getUserMethod.invoke(event);
|
||||
if (userObj != null) {
|
||||
Method getPlayerMethod = userObj.getClass().getMethod("getPlayer");
|
||||
player = (Player)getPlayerMethod.invoke(userObj);
|
||||
}
|
||||
} catch (Throwable var13) {
|
||||
}
|
||||
|
||||
if (player == null) {
|
||||
try {
|
||||
Method getPlayerMethod = event.getClass().getMethod("getPlayer");
|
||||
player = (Player)getPlayerMethod.invoke(event);
|
||||
} catch (Throwable var12) {
|
||||
}
|
||||
}
|
||||
|
||||
if (player == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Method getCheckMethod = event.getClass().getMethod("getCheck");
|
||||
Object checkObj = getCheckMethod.invoke(event);
|
||||
if (checkObj != null) {
|
||||
Method getNameMethod = checkObj.getClass().getMethod("getCheckName");
|
||||
checkName = (String)getNameMethod.invoke(checkObj);
|
||||
}
|
||||
} catch (Throwable ignored) {
|
||||
try {
|
||||
Method getNameMethod = event.getClass().getMethod("getCheckName");
|
||||
checkName = (String)getNameMethod.invoke(event);
|
||||
} catch (Throwable var10) {
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
Method getVlMethod = event.getClass().getMethod("getViolations");
|
||||
if (getVlMethod.invoke(event) instanceof Number num) {
|
||||
vl = num.doubleValue();
|
||||
}
|
||||
} catch (Throwable var9) {
|
||||
}
|
||||
|
||||
PlayerProfile profile = this.plugin.getDataManager().getOrCreate(player);
|
||||
profile.incrementGrimFlags(checkName, vl);
|
||||
CombatTracker tracker = this.plugin.getCombatListener() != null ? this.plugin.getCombatListener().getTracker(player.getUniqueId()) : null;
|
||||
if (tracker != null) {
|
||||
tracker.registerGrimViolation(checkName, vl);
|
||||
String checkLower = checkName.toLowerCase();
|
||||
if (checkLower.contains("reach") || checkLower.contains("hitbox") || checkLower.contains("killaura") || checkLower.contains("aim")) {
|
||||
tracker.getRiskAccumulator().observe(35.0, System.currentTimeMillis(), true);
|
||||
}
|
||||
|
||||
if (this.plugin.getOverheadManager() != null) {
|
||||
this.plugin
|
||||
.getOverheadManager()
|
||||
.updateDisplay(
|
||||
player.getUniqueId(),
|
||||
Math.round(tracker.getKillauraConfidence() * 100.0F),
|
||||
Math.round(tracker.getAimConfidence() * 100.0F),
|
||||
tracker.getThreatState()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (this.plugin.getConfig().getBoolean("logging.console.enabled", true)) {
|
||||
this.plugin
|
||||
.getLogger()
|
||||
.info(
|
||||
String.format(
|
||||
"[GrimAC-Bridge] Ingested flag for %s: %s (VL: %.1f) -> Updated SynapseAI State: %s",
|
||||
player.getName(),
|
||||
checkName,
|
||||
vl,
|
||||
tracker != null ? tracker.getThreatState().name() : "CLEAN"
|
||||
)
|
||||
);
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
this.plugin.getLogger().warning("Error handling GrimAC flag event: " + t.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isGrimLoaded() {
|
||||
return this.grimLoaded;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package net.synapselabs.anticheat.checks.block;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import net.synapselabs.anticheat.AiAnticheatPlugin;
|
||||
import net.synapselabs.anticheat.data.PlayerProfile;
|
||||
import org.bukkit.GameMode;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.block.BlockBreakEvent;
|
||||
import org.bukkit.event.block.BlockDamageEvent;
|
||||
import org.bukkit.potion.PotionEffectType;
|
||||
|
||||
public class FastBreakCheck implements Listener {
|
||||
private final AiAnticheatPlugin plugin;
|
||||
private final Map<UUID, Long> startDamageTime = new ConcurrentHashMap<>();
|
||||
|
||||
public FastBreakCheck(AiAnticheatPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onDamage(BlockDamageEvent event) {
|
||||
if (event.getPlayer().getGameMode() != GameMode.CREATIVE) {
|
||||
this.startDamageTime.put(event.getPlayer().getUniqueId(), System.currentTimeMillis());
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
|
||||
public void onBreak(BlockBreakEvent event) {
|
||||
if (this.plugin.isSetupCompleted()) {
|
||||
if (this.plugin.getConfig().getBoolean("detection.extra_checks.fastbreak.enabled", true)) {
|
||||
Player player = event.getPlayer();
|
||||
if (player.getGameMode() != GameMode.CREATIVE) {
|
||||
Block block = event.getBlock();
|
||||
Material type = block.getType();
|
||||
float hardness = type.getHardness();
|
||||
if (!(hardness <= 0.05F)) {
|
||||
UUID uuid = player.getUniqueId();
|
||||
Long startTime = this.startDamageTime.remove(uuid);
|
||||
long now = System.currentTimeMillis();
|
||||
if (startTime == null) {
|
||||
if (hardness > 0.8F && !player.hasPotionEffect(PotionEffectType.FAST_DIGGING)) {
|
||||
event.setCancelled(true);
|
||||
this.flag(player, "FastBreak (Instant: No Damage Packet)");
|
||||
}
|
||||
} else {
|
||||
long elapsedMs = now - startTime;
|
||||
long minExpectedMs = Math.round(hardness * 200.0);
|
||||
if (player.hasPotionEffect(PotionEffectType.FAST_DIGGING)) {
|
||||
minExpectedMs /= 2L;
|
||||
}
|
||||
|
||||
if (elapsedMs < minExpectedMs * 0.45 && minExpectedMs > 150L) {
|
||||
event.setCancelled(true);
|
||||
this.flag(player, String.format("FastBreak (%dms < %dms)", elapsedMs, minExpectedMs));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void flag(Player player, String reason) {
|
||||
PlayerProfile profile = this.plugin.getDataManager().getOrCreate(player);
|
||||
profile.incrementHardFlags(reason);
|
||||
if (this.plugin.getConfig().getBoolean("logging.console.enabled", true)) {
|
||||
this.plugin
|
||||
.getLogger()
|
||||
.info(String.format("[Extra-Check] Player '%s' flagged for '%s' | Hard Flags: %d", player.getName(), reason, profile.getHardFlags()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package net.synapselabs.anticheat.checks.block;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import net.synapselabs.anticheat.AiAnticheatPlugin;
|
||||
import net.synapselabs.anticheat.data.PlayerProfile;
|
||||
import org.bukkit.GameMode;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.block.BlockPlaceEvent;
|
||||
|
||||
public class FastPlaceCheck implements Listener {
|
||||
private final AiAnticheatPlugin plugin;
|
||||
private final Map<UUID, Deque<Long>> placeTimestamps = new ConcurrentHashMap<>();
|
||||
|
||||
public FastPlaceCheck(AiAnticheatPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
|
||||
public void onPlace(BlockPlaceEvent event) {
|
||||
if (this.plugin.isSetupCompleted()) {
|
||||
if (this.plugin.getConfig().getBoolean("detection.extra_checks.fastplace.enabled", true)) {
|
||||
Player player = event.getPlayer();
|
||||
if (player.getGameMode() != GameMode.CREATIVE) {
|
||||
UUID uuid = player.getUniqueId();
|
||||
long now = System.currentTimeMillis();
|
||||
Deque<Long> queue = this.placeTimestamps.computeIfAbsent(uuid, k -> new ArrayDeque<>());
|
||||
queue.addFirst(now);
|
||||
|
||||
while (!queue.isEmpty() && now - queue.peekLast() > 1000L) {
|
||||
queue.removeLast();
|
||||
}
|
||||
|
||||
int maxPerSec = this.plugin.getConfig().getInt("detection.extra_checks.fastplace.max_blocks_per_second", 20);
|
||||
if (queue.size() > maxPerSec) {
|
||||
event.setCancelled(true);
|
||||
this.flag(player, String.format("FastPlace (%d blocks/sec > %d)", queue.size(), maxPerSec));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void flag(Player player, String reason) {
|
||||
PlayerProfile profile = this.plugin.getDataManager().getOrCreate(player);
|
||||
profile.incrementHardFlags(reason);
|
||||
if (this.plugin.getConfig().getBoolean("logging.console.enabled", true)) {
|
||||
this.plugin
|
||||
.getLogger()
|
||||
.info(String.format("[Extra-Check] Player '%s' flagged for '%s' | Hard Flags: %d", player.getName(), reason, profile.getHardFlags()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package net.synapselabs.anticheat.checks.combat;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import net.synapselabs.anticheat.AiAnticheatPlugin;
|
||||
import net.synapselabs.anticheat.data.PlayerProfile;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.block.Action;
|
||||
import org.bukkit.event.block.BlockBreakEvent;
|
||||
import org.bukkit.event.block.BlockDamageEvent;
|
||||
import org.bukkit.event.player.PlayerAnimationEvent;
|
||||
import org.bukkit.event.player.PlayerAnimationType;
|
||||
import org.bukkit.event.player.PlayerInteractEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
|
||||
public class AutoClickerCheck implements Listener {
|
||||
private final AiAnticheatPlugin plugin;
|
||||
private final Map<UUID, Deque<Long>> swingTimestamps = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, Long> lastDiggingTimestamps = new ConcurrentHashMap<>();
|
||||
private static final long DIGGING_GRACE_MS = 500L;
|
||||
|
||||
public AutoClickerCheck(AiAnticheatPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onBlockDamage(BlockDamageEvent event) {
|
||||
this.lastDiggingTimestamps.put(event.getPlayer().getUniqueId(), System.currentTimeMillis());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onPlayerInteract(PlayerInteractEvent event) {
|
||||
if (event.getAction() == Action.LEFT_CLICK_BLOCK) {
|
||||
this.lastDiggingTimestamps.put(event.getPlayer().getUniqueId(), System.currentTimeMillis());
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onBlockBreak(BlockBreakEvent event) {
|
||||
this.lastDiggingTimestamps.put(event.getPlayer().getUniqueId(), System.currentTimeMillis());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onQuit(PlayerQuitEvent event) {
|
||||
UUID uuid = event.getPlayer().getUniqueId();
|
||||
this.swingTimestamps.remove(uuid);
|
||||
this.lastDiggingTimestamps.remove(uuid);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onArmSwing(PlayerAnimationEvent event) {
|
||||
if (this.plugin.isSetupCompleted()) {
|
||||
if (event.getAnimationType() == PlayerAnimationType.ARM_SWING) {
|
||||
if (this.plugin.getConfig().getBoolean("detection.extra_checks.autoclicker.enabled", true)) {
|
||||
Player player = event.getPlayer();
|
||||
UUID uuid = player.getUniqueId();
|
||||
long now = System.currentTimeMillis();
|
||||
Long lastDig = this.lastDiggingTimestamps.get(uuid);
|
||||
if (lastDig == null || now - lastDig >= 500L) {
|
||||
Deque<Long> queue = this.swingTimestamps.computeIfAbsent(uuid, k -> new ArrayDeque<>());
|
||||
queue.addFirst(now);
|
||||
|
||||
while (!queue.isEmpty() && now - queue.peekLast() > 1000L) {
|
||||
queue.removeLast();
|
||||
}
|
||||
|
||||
int maxCps = this.plugin.getConfig().getInt("detection.extra_checks.autoclicker.max_cps", 22);
|
||||
int cps = queue.size();
|
||||
if (cps > maxCps) {
|
||||
this.flag(player, String.format("AutoClicker (High CPS: %d > %d)", cps, maxCps));
|
||||
} else {
|
||||
if (queue.size() >= 15) {
|
||||
Long[] arr = queue.toArray(new Long[0]);
|
||||
double sum = 0.0;
|
||||
int count = arr.length - 1;
|
||||
|
||||
for (int i = 0; i < count; i++) {
|
||||
sum += arr[i] - arr[i + 1];
|
||||
}
|
||||
|
||||
double mean = sum / count;
|
||||
double sumSq = 0.0;
|
||||
|
||||
for (int i = 0; i < count; i++) {
|
||||
double diff = arr[i] - arr[i + 1] - mean;
|
||||
sumSq += diff * diff;
|
||||
}
|
||||
|
||||
double stdDevTicks = Math.sqrt(sumSq / count) / 50.0;
|
||||
double minStdDev = this.plugin.getConfig().getDouble("detection.extra_checks.autoclicker.min_stddev", 0.08);
|
||||
if (stdDevTicks < minStdDev && cps >= 16) {
|
||||
this.flag(player, String.format("AutoClicker (Macro Consistency: %.3f stddev)", stdDevTicks));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void flag(Player player, String reason) {
|
||||
PlayerProfile profile = this.plugin.getDataManager().getOrCreate(player);
|
||||
profile.incrementHardFlags(reason);
|
||||
if (this.plugin.getConfig().getBoolean("logging.console.enabled", true)) {
|
||||
this.plugin
|
||||
.getLogger()
|
||||
.info(String.format("[Extra-Check] Player '%s' flagged for '%s' | Hard Flags: %d", player.getName(), reason, profile.getHardFlags()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package net.synapselabs.anticheat.checks.item;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import net.synapselabs.anticheat.AiAnticheatPlugin;
|
||||
import net.synapselabs.anticheat.data.PlayerProfile;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.block.Action;
|
||||
import org.bukkit.event.entity.EntityShootBowEvent;
|
||||
import org.bukkit.event.player.PlayerInteractEvent;
|
||||
import org.bukkit.event.player.PlayerItemConsumeEvent;
|
||||
|
||||
public class FastInteractCheck implements Listener {
|
||||
private final AiAnticheatPlugin plugin;
|
||||
private final Map<UUID, Long> startEatTime = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, Long> startBowTime = new ConcurrentHashMap<>();
|
||||
|
||||
public FastInteractCheck(AiAnticheatPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onInteract(PlayerInteractEvent event) {
|
||||
if (this.plugin.isSetupCompleted()) {
|
||||
if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) {
|
||||
if (event.hasItem()) {
|
||||
Player player = event.getPlayer();
|
||||
UUID uuid = player.getUniqueId();
|
||||
Material type = event.getItem().getType();
|
||||
if (type.isEdible() || type == Material.POTION || type == Material.MILK_BUCKET) {
|
||||
this.startEatTime.put(uuid, System.currentTimeMillis());
|
||||
} else if (type == Material.BOW || type == Material.CROSSBOW) {
|
||||
this.startBowTime.put(uuid, System.currentTimeMillis());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
|
||||
public void onConsume(PlayerItemConsumeEvent event) {
|
||||
if (this.plugin.getConfig().getBoolean("detection.extra_checks.fastinteract.enabled", true)) {
|
||||
Player player = event.getPlayer();
|
||||
UUID uuid = player.getUniqueId();
|
||||
Long startTime = this.startEatTime.remove(uuid);
|
||||
if (startTime != null) {
|
||||
long elapsedTicks = (System.currentTimeMillis() - startTime) / 50L;
|
||||
int minEatTicks = this.plugin.getConfig().getInt("detection.extra_checks.fastinteract.min_eat_ticks", 25);
|
||||
if (elapsedTicks < minEatTicks) {
|
||||
event.setCancelled(true);
|
||||
this.flag(player, String.format("FastEat (%d ticks < %d ticks)", elapsedTicks, minEatTicks));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
|
||||
public void onShootBow(EntityShootBowEvent event) {
|
||||
if (event.getEntity() instanceof Player player) {
|
||||
if (this.plugin.getConfig().getBoolean("detection.extra_checks.fastinteract.enabled", true)) {
|
||||
UUID uuid = player.getUniqueId();
|
||||
Long startTime = this.startBowTime.remove(uuid);
|
||||
if (startTime != null) {
|
||||
long elapsedTicks = (System.currentTimeMillis() - startTime) / 50L;
|
||||
int minBowTicks = this.plugin.getConfig().getInt("detection.extra_checks.fastinteract.min_bow_ticks", 15);
|
||||
if (elapsedTicks < minBowTicks && event.getForce() >= 0.8F) {
|
||||
event.setCancelled(true);
|
||||
this.flag(player, String.format("FastBow (%d ticks < %d ticks)", elapsedTicks, minBowTicks));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void flag(Player player, String reason) {
|
||||
PlayerProfile profile = this.plugin.getDataManager().getOrCreate(player);
|
||||
profile.incrementHardFlags(reason);
|
||||
if (this.plugin.getConfig().getBoolean("logging.console.enabled", true)) {
|
||||
this.plugin
|
||||
.getLogger()
|
||||
.info(String.format("[Extra-Check] Player '%s' flagged for '%s' | Hard Flags: %d", player.getName(), reason, profile.getHardFlags()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package net.synapselabs.anticheat.compat;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import net.md_5.bungee.api.ChatColor;
|
||||
import net.md_5.bungee.api.ChatMessageType;
|
||||
import net.md_5.bungee.api.chat.ClickEvent;
|
||||
import net.md_5.bungee.api.chat.ComponentBuilder;
|
||||
import net.md_5.bungee.api.chat.HoverEvent;
|
||||
import net.md_5.bungee.api.chat.TextComponent;
|
||||
import net.md_5.bungee.api.chat.HoverEvent.Action;
|
||||
import org.bukkit.Sound;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class CompatUtils {
|
||||
private static final Pattern HEX_AMP_PATTERN = Pattern.compile("&#([A-Fa-f0-9]{6})");
|
||||
private static final Pattern HEX_HASH_PATTERN = Pattern.compile("#([A-Fa-f0-9]{6})");
|
||||
|
||||
public static String color(String msg) {
|
||||
if (msg == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
Matcher matcherAmp = HEX_AMP_PATTERN.matcher(msg);
|
||||
StringBuffer buffer = new StringBuffer();
|
||||
|
||||
while (matcherAmp.find()) {
|
||||
String hex = matcherAmp.group(1);
|
||||
matcherAmp.appendReplacement(buffer, ChatColor.of("#" + hex).toString());
|
||||
}
|
||||
|
||||
matcherAmp.appendTail(buffer);
|
||||
String step1 = buffer.toString();
|
||||
return org.bukkit.ChatColor.translateAlternateColorCodes('&', step1);
|
||||
}
|
||||
|
||||
public static String rgbGradient(String text, String hexFrom, String hexTo) {
|
||||
if (text != null && !text.isEmpty()) {
|
||||
try {
|
||||
Color color1 = Color.decode(hexFrom.startsWith("#") ? hexFrom : "#" + hexFrom);
|
||||
Color color2 = Color.decode(hexTo.startsWith("#") ? hexTo : "#" + hexTo);
|
||||
StringBuilder builder = new StringBuilder();
|
||||
int length = text.length();
|
||||
|
||||
for (int i = 0; i < length; i++) {
|
||||
float ratio = (float)i / Math.max(1, length - 1);
|
||||
int red = (int)(color1.getRed() * (1.0F - ratio) + color2.getRed() * ratio);
|
||||
int green = (int)(color1.getGreen() * (1.0F - ratio) + color2.getGreen() * ratio);
|
||||
int blue = (int)(color1.getBlue() * (1.0F - ratio) + color2.getBlue() * ratio);
|
||||
String hex = String.format("#%02x%02x%02x", red, green, blue);
|
||||
builder.append(ChatColor.of(hex)).append(text.charAt(i));
|
||||
}
|
||||
|
||||
return builder.toString();
|
||||
} catch (Exception e) {
|
||||
return color(text);
|
||||
}
|
||||
} else {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
public static TextComponent createGrimButton(String label, String hexColor, String hoverText, String command) {
|
||||
TextComponent btn = new TextComponent(color("&8[" + hexColor + label + "&8]"));
|
||||
btn.setHoverEvent(new HoverEvent(Action.SHOW_TEXT, new ComponentBuilder(color(hoverText)).create()));
|
||||
btn.setClickEvent(new ClickEvent(net.md_5.bungee.api.chat.ClickEvent.Action.RUN_COMMAND, command));
|
||||
return btn;
|
||||
}
|
||||
|
||||
public static void sendMessage(Player player, String message) {
|
||||
if (player != null && player.isOnline()) {
|
||||
player.sendMessage(color(message));
|
||||
}
|
||||
}
|
||||
|
||||
public static void sendComponent(Player player, TextComponent component) {
|
||||
if (player != null && player.isOnline()) {
|
||||
player.spigot().sendMessage(component);
|
||||
}
|
||||
}
|
||||
|
||||
public static void sendActionBar(Player player, String message) {
|
||||
if (player != null && player.isOnline()) {
|
||||
try {
|
||||
player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(color(message)));
|
||||
} catch (Throwable ignored) {
|
||||
player.sendMessage(color(message));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void sendTitle(Player player, String title, String subtitle, int fadeIn, int stay, int fadeOut) {
|
||||
if (player != null && player.isOnline()) {
|
||||
try {
|
||||
player.sendTitle(color(title), color(subtitle), fadeIn, stay, fadeOut);
|
||||
} catch (Throwable var7) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void playSound(Player player, String soundName, float volume, float pitch) {
|
||||
if (player != null && player.isOnline()) {
|
||||
try {
|
||||
Sound sound = Sound.valueOf(soundName.toUpperCase());
|
||||
player.playSound(player.getLocation(), sound, volume, pitch);
|
||||
} catch (Throwable var5) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package net.synapselabs.anticheat.data;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import net.synapselabs.anticheat.AiAnticheatPlugin;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class PlayerDataManager {
|
||||
private final AiAnticheatPlugin plugin;
|
||||
private final Map<UUID, PlayerProfile> profiles = new ConcurrentHashMap<>();
|
||||
private final Map<String, Set<UUID>> ipIndex = new ConcurrentHashMap<>();
|
||||
|
||||
public PlayerDataManager(AiAnticheatPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
this.loadDatabase();
|
||||
}
|
||||
|
||||
public PlayerProfile getOrCreate(Player player) {
|
||||
String ip = player.getAddress() != null ? player.getAddress().getAddress().getHostAddress() : "127.0.0.1";
|
||||
PlayerProfile profile = this.profiles.computeIfAbsent(player.getUniqueId(), k -> new PlayerProfile(player.getUniqueId(), player.getName(), ip));
|
||||
profile.setName(player.getName());
|
||||
profile.updateLastJoin(ip);
|
||||
this.indexIp(ip, player.getUniqueId());
|
||||
return profile;
|
||||
}
|
||||
|
||||
public PlayerProfile getProfile(UUID uuid) {
|
||||
return this.profiles.get(uuid);
|
||||
}
|
||||
|
||||
public PlayerProfile getProfileByName(String name) {
|
||||
for (PlayerProfile p : this.profiles.values()) {
|
||||
if (p.getName().equalsIgnoreCase(name)) {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private void indexIp(String ip, UUID uuid) {
|
||||
if (ip != null && !ip.isBlank()) {
|
||||
this.ipIndex.computeIfAbsent(ip, k -> ConcurrentHashMap.newKeySet()).add(uuid);
|
||||
}
|
||||
}
|
||||
|
||||
public List<PlayerProfile> getAccountsOnIp(String ip) {
|
||||
if (ip == null) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
Set<UUID> uuids = this.ipIndex.get(ip);
|
||||
if (uuids == null) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
List<PlayerProfile> list = new ArrayList<>();
|
||||
|
||||
for (UUID u : uuids) {
|
||||
PlayerProfile p = this.profiles.get(u);
|
||||
if (p != null) {
|
||||
list.add(p);
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
public boolean hasBannedAccountsOnIp(String ip) {
|
||||
for (PlayerProfile p : this.getAccountsOnIp(ip)) {
|
||||
if (p.isBanned()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (this.plugin.getPunishmentManager() != null && this.plugin.getPunishmentManager().isPlayerBanned(p.getName(), ip)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public int getAltCount(String ip) {
|
||||
Set<UUID> set = this.ipIndex.get(ip);
|
||||
return set != null ? set.size() : 1;
|
||||
}
|
||||
|
||||
public Collection<PlayerProfile> getAllProfiles() {
|
||||
return this.profiles.values();
|
||||
}
|
||||
|
||||
public void saveDatabase() {
|
||||
File file = new File(this.plugin.getDataFolder(), "player_database.txt");
|
||||
|
||||
try {
|
||||
if (!this.plugin.getDataFolder().exists()) {
|
||||
this.plugin.getDataFolder().mkdirs();
|
||||
}
|
||||
|
||||
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8))) {
|
||||
for (PlayerProfile p : this.profiles.values()) {
|
||||
writer.write(PlayerRecordCodec.encode(p));
|
||||
writer.write("\n");
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
this.plugin.getLogger().warning("Failed to save player database: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void loadDatabase() {
|
||||
File file = new File(this.plugin.getDataFolder(), "player_database.txt");
|
||||
if (file.exists()) {
|
||||
String line;
|
||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) {
|
||||
while ((line = reader.readLine()) != null) {
|
||||
if (!line.isBlank()) {
|
||||
PlayerProfile p = PlayerRecordCodec.decode(line);
|
||||
if (p != null) {
|
||||
this.profiles.put(p.getUuid(), p);
|
||||
this.indexIp(p.getLastIp(), p.getUuid());
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
this.plugin.getLogger().warning("Failed to load player database: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
package net.synapselabs.anticheat.data;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import net.synapselabs.anticheat.engine.DetectionSnapshot;
|
||||
|
||||
public class PlayerProfile {
|
||||
private final UUID uuid;
|
||||
private String name;
|
||||
private long firstJoin;
|
||||
private long lastJoin;
|
||||
private String lastIp;
|
||||
private final Set<String> knownIps = new HashSet<>();
|
||||
private int totalFlags = 0;
|
||||
private int hardFlags = 0;
|
||||
private int aiFlags = 0;
|
||||
private int grimFlagsCount = 0;
|
||||
private float killauraConfidence = 0.0F;
|
||||
private float aimConfidence = 0.0F;
|
||||
private float suspicion = 0.0F;
|
||||
private ThreatState threatState = ThreatState.CLEAN;
|
||||
private boolean banned = false;
|
||||
private String lastFlagReason = "None";
|
||||
private float lastFlagConfidence = 0.0F;
|
||||
private long lastFlagTimestamp = 0L;
|
||||
|
||||
public PlayerProfile(UUID uuid, String name, String ip) {
|
||||
this.uuid = uuid;
|
||||
this.name = name;
|
||||
this.firstJoin = System.currentTimeMillis();
|
||||
this.lastJoin = System.currentTimeMillis();
|
||||
this.lastIp = ip;
|
||||
if (ip != null) {
|
||||
this.knownIps.add(ip);
|
||||
}
|
||||
}
|
||||
|
||||
public UUID getUuid() {
|
||||
return this.uuid;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public long getFirstJoin() {
|
||||
return this.firstJoin;
|
||||
}
|
||||
|
||||
public void setFirstJoin(long firstJoin) {
|
||||
this.firstJoin = firstJoin;
|
||||
}
|
||||
|
||||
public long getLastJoin() {
|
||||
return this.lastJoin;
|
||||
}
|
||||
|
||||
public void updateLastJoin(String ip) {
|
||||
this.lastJoin = System.currentTimeMillis();
|
||||
this.lastIp = ip;
|
||||
if (ip != null) {
|
||||
this.knownIps.add(ip);
|
||||
}
|
||||
}
|
||||
|
||||
public void setLastJoin(long lastJoin) {
|
||||
this.lastJoin = lastJoin;
|
||||
}
|
||||
|
||||
public String getLastIp() {
|
||||
return this.lastIp;
|
||||
}
|
||||
|
||||
public Set<String> getKnownIps() {
|
||||
return this.knownIps;
|
||||
}
|
||||
|
||||
public int getTotalFlags() {
|
||||
return this.totalFlags;
|
||||
}
|
||||
|
||||
public int getHardFlags() {
|
||||
return this.hardFlags;
|
||||
}
|
||||
|
||||
public int getAiFlags() {
|
||||
return this.aiFlags;
|
||||
}
|
||||
|
||||
public void setTotalFlags(int totalFlags) {
|
||||
this.totalFlags = totalFlags;
|
||||
}
|
||||
|
||||
public void setHardFlags(int hardFlags) {
|
||||
this.hardFlags = hardFlags;
|
||||
}
|
||||
|
||||
public void setAiFlags(int aiFlags) {
|
||||
this.aiFlags = aiFlags;
|
||||
}
|
||||
|
||||
public void incrementHardFlags(String reason) {
|
||||
this.totalFlags++;
|
||||
this.hardFlags++;
|
||||
this.lastFlagReason = reason;
|
||||
this.lastFlagConfidence = 1.0F;
|
||||
this.lastFlagTimestamp = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public void incrementAiFlags(String reason, float confidence) {
|
||||
this.totalFlags++;
|
||||
this.aiFlags++;
|
||||
this.lastFlagReason = reason;
|
||||
this.lastFlagConfidence = confidence;
|
||||
this.lastFlagTimestamp = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public void resetFlags() {
|
||||
this.totalFlags = 0;
|
||||
this.hardFlags = 0;
|
||||
this.aiFlags = 0;
|
||||
this.killauraConfidence = 0.0F;
|
||||
this.aimConfidence = 0.0F;
|
||||
this.suspicion = 0.0F;
|
||||
this.threatState = ThreatState.CLEAN;
|
||||
}
|
||||
|
||||
public void applySnapshot(DetectionSnapshot snapshot) {
|
||||
this.killauraConfidence = snapshot.killauraConfidence();
|
||||
this.aimConfidence = snapshot.aimConfidence();
|
||||
this.suspicion = snapshot.suspicion();
|
||||
this.threatState = snapshot.threatState();
|
||||
if (snapshot.hasHardViolations()) {
|
||||
this.incrementHardFlags(snapshot.getPrimaryViolation());
|
||||
} else if (snapshot.hasAiViolations()) {
|
||||
this.incrementAiFlags(snapshot.getPrimaryViolation(), snapshot.confidence());
|
||||
}
|
||||
}
|
||||
|
||||
public float getKillauraConfidence() {
|
||||
return this.killauraConfidence;
|
||||
}
|
||||
|
||||
public void setKillauraConfidence(float killauraConfidence) {
|
||||
this.killauraConfidence = killauraConfidence;
|
||||
}
|
||||
|
||||
public float getAimConfidence() {
|
||||
return this.aimConfidence;
|
||||
}
|
||||
|
||||
public void setAimConfidence(float aimConfidence) {
|
||||
this.aimConfidence = aimConfidence;
|
||||
}
|
||||
|
||||
public float getSuspicion() {
|
||||
return this.suspicion;
|
||||
}
|
||||
|
||||
public void setSuspicion(float suspicion) {
|
||||
this.suspicion = suspicion;
|
||||
}
|
||||
|
||||
public ThreatState getThreatState() {
|
||||
return this.threatState;
|
||||
}
|
||||
|
||||
public void setThreatState(ThreatState threatState) {
|
||||
this.threatState = threatState;
|
||||
}
|
||||
|
||||
public int getGrimFlagsCount() {
|
||||
return this.grimFlagsCount;
|
||||
}
|
||||
|
||||
public int getGrimFlags() {
|
||||
return this.grimFlagsCount;
|
||||
}
|
||||
|
||||
public void setGrimFlagsCount(int grimFlagsCount) {
|
||||
this.grimFlagsCount = grimFlagsCount;
|
||||
}
|
||||
|
||||
public void incrementGrimFlags() {
|
||||
this.grimFlagsCount++;
|
||||
this.totalFlags++;
|
||||
}
|
||||
|
||||
public void incrementGrimFlags(String check, double vl) {
|
||||
this.grimFlagsCount++;
|
||||
this.totalFlags++;
|
||||
this.lastFlagReason = "GrimAC: " + check + " (x" + (int)vl + ")";
|
||||
this.lastFlagTimestamp = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public boolean isBanned() {
|
||||
return this.banned;
|
||||
}
|
||||
|
||||
public void setBanned(boolean banned) {
|
||||
this.banned = banned;
|
||||
}
|
||||
|
||||
public String getLastFlagReason() {
|
||||
return this.lastFlagReason;
|
||||
}
|
||||
|
||||
public float getLastFlagConfidence() {
|
||||
return this.lastFlagConfidence;
|
||||
}
|
||||
|
||||
public long getLastFlagTimestamp() {
|
||||
return this.lastFlagTimestamp;
|
||||
}
|
||||
|
||||
public void setLastFlagReason(String lastFlagReason) {
|
||||
this.lastFlagReason = lastFlagReason;
|
||||
}
|
||||
|
||||
public void setLastFlagConfidence(float lastFlagConfidence) {
|
||||
this.lastFlagConfidence = lastFlagConfidence;
|
||||
}
|
||||
|
||||
public void setLastFlagTimestamp(long lastFlagTimestamp) {
|
||||
this.lastFlagTimestamp = lastFlagTimestamp;
|
||||
}
|
||||
|
||||
public String getFormattedFirstJoin() {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
|
||||
return sdf.format(new Date(this.firstJoin));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package net.synapselabs.anticheat.data;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class PlayerRecordCodec {
|
||||
static final int FIELDS_V2 = 17;
|
||||
|
||||
private PlayerRecordCodec() {
|
||||
}
|
||||
|
||||
public static String encode(PlayerProfile p) {
|
||||
return String.format(
|
||||
Locale.ROOT,
|
||||
"%s;%s;%d;%d;%s;%d;%d;%b;%s;%.4f;%d;%d;%s;%.4f;%.4f;%.4f;%d",
|
||||
p.getUuid(),
|
||||
sanitize(p.getName()),
|
||||
p.getFirstJoin(),
|
||||
p.getLastJoin(),
|
||||
p.getLastIp(),
|
||||
p.getAiFlags(),
|
||||
p.getGrimFlagsCount(),
|
||||
p.isBanned(),
|
||||
sanitize(p.getLastFlagReason()),
|
||||
p.getLastFlagConfidence(),
|
||||
p.getHardFlags(),
|
||||
p.getTotalFlags(),
|
||||
p.getThreatState().name(),
|
||||
p.getKillauraConfidence(),
|
||||
p.getAimConfidence(),
|
||||
p.getSuspicion(),
|
||||
p.getLastFlagTimestamp()
|
||||
);
|
||||
}
|
||||
|
||||
public static PlayerProfile decode(String line) {
|
||||
if (line == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String trimmed = line.trim();
|
||||
if (trimmed.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String[] parts = trimmed.split(";", -1);
|
||||
if (parts.length < 8) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
UUID uuid = UUID.fromString(parts[0].trim());
|
||||
String name = parts[1];
|
||||
long firstJoin = Long.parseLong(parts[2].trim());
|
||||
long lastJoin = Long.parseLong(parts[3].trim());
|
||||
String ip = parts[4];
|
||||
int aiFlags = Integer.parseInt(parts[5].trim());
|
||||
int grimFlags = Integer.parseInt(parts[6].trim());
|
||||
boolean banned = Boolean.parseBoolean(parts[7].trim());
|
||||
PlayerProfile p = new PlayerProfile(uuid, name, ip);
|
||||
p.setFirstJoin(firstJoin);
|
||||
p.setLastJoin(lastJoin);
|
||||
p.setBanned(banned);
|
||||
p.setAiFlags(aiFlags);
|
||||
p.setGrimFlagsCount(grimFlags);
|
||||
if (parts.length >= 10) {
|
||||
p.setLastFlagReason(parts[8]);
|
||||
p.setLastFlagConfidence(parseFloat(parts[9], 0.0F));
|
||||
}
|
||||
|
||||
if (parts.length >= 17) {
|
||||
int hardFlags = parseInt(parts[10], 0);
|
||||
p.setHardFlags(hardFlags);
|
||||
p.setTotalFlags(parseInt(parts[11], hardFlags + aiFlags + grimFlags));
|
||||
p.setThreatState(parseThreat(parts[12]));
|
||||
p.setKillauraConfidence(parseFloat(parts[13], 0.0F));
|
||||
p.setAimConfidence(parseFloat(parts[14], 0.0F));
|
||||
p.setSuspicion(parseFloat(parts[15], 0.0F));
|
||||
p.setLastFlagTimestamp(parseLong(parts[16], 0L));
|
||||
} else {
|
||||
p.setTotalFlags(aiFlags + grimFlags);
|
||||
}
|
||||
|
||||
return p;
|
||||
} catch (RuntimeException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static String sanitize(String s) {
|
||||
return s == null ? "" : s.replace(';', ',').replace('\n', ' ').replace('\r', ' ');
|
||||
}
|
||||
|
||||
private static ThreatState parseThreat(String s) {
|
||||
try {
|
||||
return ThreatState.valueOf(s.trim());
|
||||
} catch (RuntimeException e) {
|
||||
return ThreatState.CLEAN;
|
||||
}
|
||||
}
|
||||
|
||||
private static int parseInt(String s, int fallback) {
|
||||
try {
|
||||
return Integer.parseInt(s.trim());
|
||||
} catch (RuntimeException e) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
private static long parseLong(String s, long fallback) {
|
||||
try {
|
||||
return Long.parseLong(s.trim());
|
||||
} catch (RuntimeException e) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
private static float parseFloat(String s, float fallback) {
|
||||
try {
|
||||
return Float.parseFloat(s.trim());
|
||||
} catch (RuntimeException e) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package net.synapselabs.anticheat.data;
|
||||
|
||||
import net.synapselabs.anticheat.compat.CompatUtils;
|
||||
|
||||
public enum ThreatState {
|
||||
CLEAN("�ff88✔ &aЧИСТ", "&a✔ CLEAN", "�ff88", 0.0F, 0.39F),
|
||||
SUSPICIOUS("&#ffaa00⚠ &#ffcc00ПОДОЗРЕНИЕ", "&e⚠ SUSPICIOUS", "&#ffaa00", 0.4F, 0.69F),
|
||||
HIGH_CONFIDENCE("&#ff7700⚠ &#ffa500ВЫСОКИЙ РИСК", "&6⚠ HIGH CONFIDENCE", "&#ff7700", 0.7F, 0.89F),
|
||||
CONFIRMED("&#ff2244⚡ &#ff0055ПОДТВЕРЖДЕН (ЧИТ)", "&c⚡ CONFIRMED", "&#ff2244", 0.9F, 1.0F);
|
||||
|
||||
private final String displayTag;
|
||||
private final String plainTag;
|
||||
private final String hexColor;
|
||||
private final float minConfidence;
|
||||
private final float maxConfidence;
|
||||
|
||||
ThreatState(String displayTag, String plainTag, String hexColor, float minConfidence, float maxConfidence) {
|
||||
this.displayTag = displayTag;
|
||||
this.plainTag = plainTag;
|
||||
this.hexColor = hexColor;
|
||||
this.minConfidence = minConfidence;
|
||||
this.maxConfidence = maxConfidence;
|
||||
}
|
||||
|
||||
public String getDisplayTag() {
|
||||
return CompatUtils.color(this.displayTag);
|
||||
}
|
||||
|
||||
public String getPlainTag() {
|
||||
return this.plainTag;
|
||||
}
|
||||
|
||||
public String messageKey() {
|
||||
return switch (this) {
|
||||
case CLEAN -> "threat_state.clean";
|
||||
case SUSPICIOUS -> "threat_state.suspicious";
|
||||
case HIGH_CONFIDENCE -> "threat_state.high_confidence";
|
||||
case CONFIRMED -> "threat_state.confirmed";
|
||||
};
|
||||
}
|
||||
|
||||
public String getHexColor() {
|
||||
return this.hexColor;
|
||||
}
|
||||
|
||||
public float getMinConfidence() {
|
||||
return this.minConfidence;
|
||||
}
|
||||
|
||||
public float getMaxConfidence() {
|
||||
return this.maxConfidence;
|
||||
}
|
||||
|
||||
public static ThreatState fromConfidence(float confidence) {
|
||||
float clamped = Math.max(0.0F, Math.min(1.0F, confidence));
|
||||
if (clamped >= 0.9F) {
|
||||
return CONFIRMED;
|
||||
} else if (clamped >= 0.7F) {
|
||||
return HIGH_CONFIDENCE;
|
||||
} else {
|
||||
return clamped >= 0.4F ? SUSPICIOUS : CLEAN;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package net.synapselabs.anticheat.dataset;
|
||||
|
||||
public enum DatasetLabel {
|
||||
LEGIT(0),
|
||||
CHEAT(1);
|
||||
|
||||
private final int value;
|
||||
|
||||
DatasetLabel(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public int getValue() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
public static DatasetLabel fromString(String str) {
|
||||
if (str == null) {
|
||||
return null;
|
||||
} else {
|
||||
String lower = str.trim().toLowerCase();
|
||||
if (lower.equals("legit") || lower.equals("0") || lower.equals("clean")) {
|
||||
return LEGIT;
|
||||
} else {
|
||||
return !lower.equals("cheat") && !lower.equals("1") && !lower.equals("cheater") && !lower.equals("killaura") ? null : CHEAT;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
package net.synapselabs.anticheat.dataset;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.PrintWriter;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.Deque;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import net.synapselabs.anticheat.AiAnticheatPlugin;
|
||||
import net.synapselabs.anticheat.engine.FeatureVector;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class DatasetManager implements AutoCloseable {
|
||||
private final AiAnticheatPlugin plugin;
|
||||
private final Map<UUID, DatasetManager.DatasetSession> activeSessions = new ConcurrentHashMap<>();
|
||||
private final ConcurrentLinkedQueue<DatasetRecord> inMemoryQueue = new ConcurrentLinkedQueue<>();
|
||||
private final Map<UUID, Deque<DatasetRecord>> playerRecentHistory = new ConcurrentHashMap<>();
|
||||
private static final int PLAYER_RECENT_MAX = 100;
|
||||
private final AtomicLong totalLegitSamples = new AtomicLong(0L);
|
||||
private final AtomicLong totalCheatSamples = new AtomicLong(0L);
|
||||
private final ScheduledExecutorService flusherExecutor;
|
||||
private final File datasetFolder;
|
||||
|
||||
public DatasetManager(AiAnticheatPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
String dirName = plugin.getConfig().getString("dataset.directory", "datasets");
|
||||
this.datasetFolder = new File(plugin.getDataFolder(), dirName);
|
||||
if (!this.datasetFolder.exists()) {
|
||||
this.datasetFolder.mkdirs();
|
||||
}
|
||||
|
||||
this.flusherExecutor = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
Thread t = new Thread(r, "SynapseAI-DatasetFlusher");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
int flushInterval = plugin.getConfig().getInt("dataset.auto_flush_interval_seconds", 15);
|
||||
if (flushInterval > 0) {
|
||||
this.flusherExecutor.scheduleWithFixedDelay(this::flushAutoSave, flushInterval, flushInterval, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
return this.plugin.getConfig().getBoolean("dataset.enabled", false);
|
||||
}
|
||||
|
||||
public boolean isRecording(UUID playerId) {
|
||||
return this.isEnabled() && this.activeSessions.containsKey(playerId);
|
||||
}
|
||||
|
||||
public boolean startRecording(UUID playerId, String playerName, DatasetLabel label) {
|
||||
if (this.isEnabled() && playerId != null && label != null) {
|
||||
this.activeSessions.put(playerId, new DatasetManager.DatasetSession(playerId, playerName, label, System.currentTimeMillis()));
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean stopRecording(UUID playerId) {
|
||||
return this.activeSessions.remove(playerId) != null;
|
||||
}
|
||||
|
||||
public int stopAll() {
|
||||
int count = this.activeSessions.size();
|
||||
this.activeSessions.clear();
|
||||
return count;
|
||||
}
|
||||
|
||||
public void recordAttack(Player player, FeatureVector vector, int ping) {
|
||||
if (player != null && vector != null) {
|
||||
UUID uuid = player.getUniqueId();
|
||||
long now = System.currentTimeMillis();
|
||||
DatasetManager.DatasetSession session = this.activeSessions.get(uuid);
|
||||
int labelVal = session != null ? session.label().getValue() : 0;
|
||||
DatasetRecord record = new DatasetRecord(now, uuid, player.getName(), ping, vector.rawValues(), labelVal);
|
||||
Deque<DatasetRecord> history = this.playerRecentHistory.computeIfAbsent(uuid, k -> new ArrayDeque<>());
|
||||
synchronized (history) {
|
||||
history.addFirst(record);
|
||||
|
||||
while (history.size() > 100) {
|
||||
history.removeLast();
|
||||
}
|
||||
}
|
||||
|
||||
if (session != null) {
|
||||
this.inMemoryQueue.add(record);
|
||||
if (session.label() == DatasetLabel.LEGIT) {
|
||||
this.totalLegitSamples.incrementAndGet();
|
||||
} else {
|
||||
this.totalCheatSamples.incrementAndGet();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int logConfirmedFalsePositive(UUID playerId, long windowMs) {
|
||||
Deque<DatasetRecord> history = this.playerRecentHistory.get(playerId);
|
||||
if (history == null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
List<DatasetRecord> fpRecords = new ArrayList<>();
|
||||
long cutoff = System.currentTimeMillis() - windowMs;
|
||||
synchronized (history) {
|
||||
for (DatasetRecord rec : history) {
|
||||
if (rec.timestamp() >= cutoff) {
|
||||
fpRecords.add(new DatasetRecord(rec.timestamp(), rec.playerId(), rec.playerName(), rec.ping(), rec.features(), DatasetLabel.LEGIT.getValue()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (fpRecords.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
this.flusherExecutor.submit(() -> {
|
||||
File fpFile = new File(this.datasetFolder, "confirmed_legit_fp.csv");
|
||||
boolean needsHeader = !fpFile.exists() || fpFile.length() == 0L;
|
||||
|
||||
try (PrintWriter out = new PrintWriter(new FileWriter(fpFile, true))) {
|
||||
if (needsHeader) {
|
||||
out.println(DatasetRecord.getCsvHeader());
|
||||
}
|
||||
|
||||
for (DatasetRecord recx : fpRecords) {
|
||||
out.println(recx.toCsvRow());
|
||||
}
|
||||
|
||||
this.plugin.getLogger().info("[DatasetManager] Logged " + fpRecords.size() + " confirmed False Positive samples to " + fpFile.getName());
|
||||
} catch (Exception e) {
|
||||
this.plugin.getLogger().warning("[DatasetManager] Failed to write confirmed FP dataset: " + e.getMessage());
|
||||
}
|
||||
});
|
||||
return fpRecords.size();
|
||||
}
|
||||
|
||||
public String exportToCsv(String customFileName) {
|
||||
if (this.inMemoryQueue.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String fileName = customFileName != null && !customFileName.isBlank()
|
||||
? (customFileName.endsWith(".csv") ? customFileName : customFileName + ".csv")
|
||||
: "dataset_" + new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date()) + ".csv";
|
||||
File targetFile = new File(this.datasetFolder, fileName);
|
||||
boolean needsHeader = !targetFile.exists() || targetFile.length() == 0L;
|
||||
List<DatasetRecord> toWrite = new ArrayList<>();
|
||||
|
||||
DatasetRecord r;
|
||||
while ((r = this.inMemoryQueue.poll()) != null) {
|
||||
toWrite.add(r);
|
||||
}
|
||||
|
||||
try (PrintWriter out = new PrintWriter(new FileWriter(targetFile, true))) {
|
||||
if (needsHeader) {
|
||||
out.println(DatasetRecord.getCsvHeader());
|
||||
}
|
||||
|
||||
for (DatasetRecord rec : toWrite) {
|
||||
out.println(rec.toCsvRow());
|
||||
}
|
||||
|
||||
return targetFile.getName();
|
||||
} catch (Exception e) {
|
||||
this.plugin.getLogger().warning("[DatasetManager] Export failed: " + e.getMessage());
|
||||
this.inMemoryQueue.addAll(toWrite);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void flushAutoSave() {
|
||||
if (!this.inMemoryQueue.isEmpty()) {
|
||||
String autoName = "dataset_autosave_" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + ".csv";
|
||||
this.exportToCsv(autoName);
|
||||
}
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
this.inMemoryQueue.clear();
|
||||
}
|
||||
|
||||
public DatasetManager.DatasetStats getStats() {
|
||||
return new DatasetManager.DatasetStats(this.activeSessions.size(), this.inMemoryQueue.size(), this.totalLegitSamples.get(), this.totalCheatSamples.get());
|
||||
}
|
||||
|
||||
public Map<UUID, DatasetManager.DatasetSession> getActiveSessions() {
|
||||
return Collections.unmodifiableMap(this.activeSessions);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
try {
|
||||
this.flushAutoSave();
|
||||
this.flusherExecutor.shutdown();
|
||||
if (!this.flusherExecutor.awaitTermination(2L, TimeUnit.SECONDS)) {
|
||||
this.flusherExecutor.shutdownNow();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
this.flusherExecutor.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
public record DatasetSession(UUID playerId, String playerName, DatasetLabel label, long startedAt) {
|
||||
}
|
||||
|
||||
public record DatasetStats(int activeSessionsCount, int inMemoryCount, long totalLegitCount, long totalCheatCount) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package net.synapselabs.anticheat.dataset;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.UUID;
|
||||
import net.synapselabs.anticheat.engine.FeatureSchema;
|
||||
|
||||
public record DatasetRecord(long timestamp, UUID playerId, String playerName, int ping, float[] features, int label) {
|
||||
public String toCsvRow() {
|
||||
StringBuilder sb = new StringBuilder(256);
|
||||
sb.append(this.timestamp).append(',');
|
||||
sb.append(this.playerId != null ? this.playerId.toString() : "unknown").append(',');
|
||||
sb.append(this.playerName != null ? this.playerName.replace(',', '_') : "unknown").append(',');
|
||||
sb.append(this.ping).append(',');
|
||||
float[] feats = this.features != null && this.features.length == 32 ? this.features : new float[32];
|
||||
|
||||
for (float f : feats) {
|
||||
sb.append(String.format(Locale.US, "%.5f", f)).append(',');
|
||||
}
|
||||
|
||||
sb.append(this.label);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static String getCsvHeader() {
|
||||
StringBuilder sb = new StringBuilder(256);
|
||||
sb.append("timestamp,player_id,player_name,ping,");
|
||||
|
||||
for (String name : FeatureSchema.NAMES) {
|
||||
sb.append(name).append(',');
|
||||
}
|
||||
|
||||
sb.append("label");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,523 @@
|
||||
package net.synapselabs.anticheat.debug;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import net.synapselabs.anticheat.AiAnticheatPlugin;
|
||||
import net.synapselabs.anticheat.compat.CompatUtils;
|
||||
import net.synapselabs.anticheat.engine.CombatContext;
|
||||
import net.synapselabs.anticheat.engine.FeatureVector;
|
||||
import net.synapselabs.anticheat.engine.RiskAssessment;
|
||||
import net.synapselabs.anticheat.engine.Signal;
|
||||
import net.synapselabs.anticheat.engine.SignalType;
|
||||
import net.synapselabs.anticheat.engine.HardCombatChecks.HardCheckResult;
|
||||
import net.synapselabs.anticheat.engine.RiskAssessment.Contribution;
|
||||
import net.synapselabs.anticheat.lang.LanguageManager;
|
||||
import net.synapselabs.anticheat.tracker.CombatTracker;
|
||||
import net.synapselabs.anticheat.tracker.KinematicHistory;
|
||||
import net.synapselabs.anticheat.tracker.KinematicHistory.RaycastHitResult;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.block.BlockFace;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.ConsoleCommandSender;
|
||||
import org.bukkit.entity.LivingEntity;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class DebugManager {
|
||||
private final AiAnticheatPlugin plugin;
|
||||
private final Map<UUID, DebugManager.DebugSession> activeSessions = new ConcurrentHashMap<>();
|
||||
private boolean consoleDebug = false;
|
||||
|
||||
public DebugManager(AiAnticheatPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
public boolean hasActiveSessions() {
|
||||
return !this.activeSessions.isEmpty() || this.consoleDebug;
|
||||
}
|
||||
|
||||
public boolean isDebugging(UUID viewerId) {
|
||||
return this.activeSessions.containsKey(viewerId);
|
||||
}
|
||||
|
||||
public boolean isConsoleDebugging() {
|
||||
return this.consoleDebug;
|
||||
}
|
||||
|
||||
public void setConsoleDebugging(boolean consoleDebug) {
|
||||
this.consoleDebug = consoleDebug;
|
||||
}
|
||||
|
||||
public void toggleSession(CommandSender sender, Player targetFilter) {
|
||||
LanguageManager langMgr = this.plugin.getLanguageManager();
|
||||
String lang = langMgr.getPlayerLanguage(sender);
|
||||
if (sender instanceof ConsoleCommandSender) {
|
||||
this.consoleDebug = !this.consoleDebug;
|
||||
if (this.consoleDebug) {
|
||||
sender.sendMessage(CompatUtils.color(langMgr.getMessage("commands.debug_enabled_all", lang, new Object[0])));
|
||||
} else {
|
||||
sender.sendMessage(CompatUtils.color(langMgr.getMessage("commands.debug_disabled", lang, new Object[0])));
|
||||
}
|
||||
} else if (sender instanceof Player player) {
|
||||
UUID uuid = player.getUniqueId();
|
||||
DebugManager.DebugSession current = this.activeSessions.get(uuid);
|
||||
if (targetFilter != null) {
|
||||
UUID targetId = targetFilter.getUniqueId();
|
||||
if (current != null && targetId.equals(current.getTargetFilter())) {
|
||||
current.setTargetFilter(null);
|
||||
player.sendMessage(CompatUtils.color(langMgr.getMessage("commands.debug_enabled_all", lang, new Object[0])));
|
||||
} else {
|
||||
this.activeSessions.put(uuid, new DebugManager.DebugSession(uuid, targetId, true));
|
||||
player.sendMessage(CompatUtils.color(langMgr.getMessage("commands.debug_enabled_player", lang, new Object[]{"player", targetFilter.getName()})));
|
||||
}
|
||||
} else if (current != null) {
|
||||
this.activeSessions.remove(uuid);
|
||||
player.sendMessage(CompatUtils.color(langMgr.getMessage("commands.debug_disabled", lang, new Object[0])));
|
||||
} else {
|
||||
this.activeSessions.put(uuid, new DebugManager.DebugSession(uuid, null, true));
|
||||
player.sendMessage(CompatUtils.color(langMgr.getMessage("commands.debug_enabled_all", lang, new Object[0])));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void toggleVisual(CommandSender sender) {
|
||||
LanguageManager langMgr = this.plugin.getLanguageManager();
|
||||
String lang = langMgr.getPlayerLanguage(sender);
|
||||
if (sender instanceof Player player) {
|
||||
UUID uuid = player.getUniqueId();
|
||||
DebugManager.DebugSession session = this.activeSessions.computeIfAbsent(uuid, k -> new DebugManager.DebugSession(uuid, null, true));
|
||||
session.setVisualParticles(!session.isVisualParticles());
|
||||
if (session.isVisualParticles()) {
|
||||
player.sendMessage(CompatUtils.color(langMgr.getMessage("commands.debug_visual_on", lang, new Object[0])));
|
||||
} else {
|
||||
player.sendMessage(CompatUtils.color(langMgr.getMessage("commands.debug_visual_off", lang, new Object[0])));
|
||||
}
|
||||
} else {
|
||||
sender.sendMessage(CompatUtils.color(langMgr.getMessage("commands.ingame_only", lang, new Object[0])));
|
||||
}
|
||||
}
|
||||
|
||||
public void disableSession(CommandSender sender) {
|
||||
LanguageManager langMgr = this.plugin.getLanguageManager();
|
||||
String lang = langMgr.getPlayerLanguage(sender);
|
||||
if (sender instanceof ConsoleCommandSender) {
|
||||
this.consoleDebug = false;
|
||||
sender.sendMessage(CompatUtils.color(langMgr.getMessage("commands.debug_disabled", lang, new Object[0])));
|
||||
} else {
|
||||
if (sender instanceof Player player) {
|
||||
this.activeSessions.remove(player.getUniqueId());
|
||||
player.sendMessage(CompatUtils.color(langMgr.getMessage("commands.debug_disabled", lang, new Object[0])));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void clearAllSessions(CommandSender sender) {
|
||||
this.activeSessions.clear();
|
||||
this.consoleDebug = false;
|
||||
LanguageManager langMgr = this.plugin.getLanguageManager();
|
||||
String lang = langMgr.getPlayerLanguage(sender);
|
||||
sender.sendMessage(CompatUtils.color(langMgr.getMessage("commands.debug_cleared", lang, new Object[0])));
|
||||
}
|
||||
|
||||
public DebugManager.AttackDebugRecord captureAttack(
|
||||
Player attacker,
|
||||
LivingEntity victim,
|
||||
Location eyeLoc,
|
||||
RaycastHitResult raycast,
|
||||
double rawReach,
|
||||
double compensatedReach,
|
||||
double latencyMargin,
|
||||
HardCheckResult hardResult,
|
||||
FeatureVector vector,
|
||||
CombatTracker tracker
|
||||
) {
|
||||
KinematicHistory history = tracker.getHistory();
|
||||
CombatContext ctx = hardResult.context();
|
||||
int attackerPing = attacker.getPing();
|
||||
int victimPing = victim instanceof Player vp ? vp.getPing() : 0;
|
||||
float yaw1t = history.getYawDelta(1);
|
||||
float yaw5t = history.getYawDelta(5);
|
||||
float pitch1t = history.getPitchDelta(1);
|
||||
float pitch5t = history.getPitchDelta(5);
|
||||
float yawAccel = history.getYawAcceleration();
|
||||
float yawJerk = history.getYawJerk();
|
||||
float pitchAccel = history.getPitchAcceleration();
|
||||
float pitchJerk = history.getPitchJerk();
|
||||
float rotVel = history.getAngularVelocity();
|
||||
float rotVar = history.getRotationVariance10t();
|
||||
long rotAge = history.getTimeSinceLastRotation();
|
||||
float cooldown = 1.0F;
|
||||
|
||||
try {
|
||||
cooldown = attacker.getAttackCooldown();
|
||||
} catch (Throwable var32) {
|
||||
}
|
||||
|
||||
float attackIntervalTicks = history.getAttackIntervalTicks();
|
||||
return new DebugManager.AttackDebugRecord(
|
||||
attacker.getUniqueId(),
|
||||
attacker.getName(),
|
||||
attackerPing,
|
||||
victim.getUniqueId(),
|
||||
victim.getName(),
|
||||
victimPing,
|
||||
victim.getLocation(),
|
||||
eyeLoc,
|
||||
raycast.angleOffsetDeg(),
|
||||
raycast.hit(),
|
||||
raycast.distance(),
|
||||
raycast.hitboxEdgeProximity(),
|
||||
rawReach,
|
||||
compensatedReach,
|
||||
latencyMargin,
|
||||
ctx.inCorner(),
|
||||
countSolidSides(victim.getLocation()),
|
||||
ctx.nearWall(),
|
||||
ctx.inWater(),
|
||||
ctx.isCrit(),
|
||||
ctx.victimKnockback(),
|
||||
yaw1t,
|
||||
yaw5t,
|
||||
pitch1t,
|
||||
pitch5t,
|
||||
yawAccel,
|
||||
yawJerk,
|
||||
pitchAccel,
|
||||
pitchJerk,
|
||||
rotVel,
|
||||
rotVar,
|
||||
rotAge,
|
||||
cooldown,
|
||||
attackIntervalTicks,
|
||||
hardResult.cancelDamage(),
|
||||
hardResult.signals()
|
||||
);
|
||||
}
|
||||
|
||||
public void renderVisuals(Player attacker, LivingEntity victim, Location eyeLoc, RaycastHitResult raycast, CombatContext context, double latencyMargin) {
|
||||
if (!this.activeSessions.isEmpty()) {
|
||||
List<Player> viewers = new ArrayList<>();
|
||||
UUID attackerId = attacker.getUniqueId();
|
||||
|
||||
for (DebugManager.DebugSession session : this.activeSessions.values()) {
|
||||
if (session.isVisualParticles() && (session.getTargetFilter() == null || session.getTargetFilter().equals(attackerId))) {
|
||||
Player viewer = Bukkit.getPlayer(session.getViewerId());
|
||||
if (viewer != null && viewer.isOnline()) {
|
||||
viewers.add(viewer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!viewers.isEmpty()) {
|
||||
VisualDebugRenderer.renderTraces(attacker, victim, eyeLoc, raycast, context, latencyMargin, viewers);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void dispatchReport(DebugManager.AttackDebugRecord record, float modelP, RiskAssessment assessment) {
|
||||
if (this.plugin.getAuditLogManager() != null) {
|
||||
this.plugin.getAuditLogManager().logCombatDebug(record, modelP, assessment);
|
||||
}
|
||||
|
||||
if (this.hasActiveSessions()) {
|
||||
LanguageManager langMgr = this.plugin.getLanguageManager();
|
||||
List<CommandSender> targets = new ArrayList<>();
|
||||
if (this.consoleDebug) {
|
||||
targets.add(Bukkit.getConsoleSender());
|
||||
}
|
||||
|
||||
for (DebugManager.DebugSession session : this.activeSessions.values()) {
|
||||
if (session.getTargetFilter() == null || session.getTargetFilter().equals(record.attackerId())) {
|
||||
Player viewer = Bukkit.getPlayer(session.getViewerId());
|
||||
if (viewer != null && viewer.isOnline()) {
|
||||
targets.add(viewer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!targets.isEmpty()) {
|
||||
for (CommandSender recipient : targets) {
|
||||
String lang = langMgr.getPlayerLanguage(recipient);
|
||||
this.sendDebugCard(recipient, record, modelP, assessment, lang);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void sendDebugCard(CommandSender recipient, DebugManager.AttackDebugRecord r, float modelP, RiskAssessment assessment, String lang) {
|
||||
LanguageManager lm = this.plugin.getLanguageManager();
|
||||
String rayHitStr = r.rayHit() ? "�ff88✔ YES" : "&#ff2244✖ NO";
|
||||
String cornerStr = r.inCorner() ? "&#ff2244✔ YES (" + r.solidSides() + " sides)" : (r.solidSides() > 0 ? "&7NO (" + r.solidSides() + " sides)" : "&7NO");
|
||||
String wallStr = r.nearWall() ? "�ff88YES" : "&7NO";
|
||||
String critStr = r.isCrit() ? "�ff88YES" : "&7NO";
|
||||
String kbStr = r.victimKnockback() ? "&#ffaa00YES" : "&7NO";
|
||||
int modelPct = Math.round(modelP * 100.0F);
|
||||
int cooldownPct = Math.round(r.cooldown() * 100.0F);
|
||||
float cps = r.attackIntervalTicks() > 0.0F ? 20.0F / r.attackIntervalTicks() : 0.0F;
|
||||
|
||||
String verdictDisplay = switch (assessment.verdict()) {
|
||||
case CHEAT -> "&#ff2244&l[CHEAT]";
|
||||
case SUSPICIOUS -> "&#ffaa00&l[SUSPICIOUS]";
|
||||
case LEGIT -> "�ff88&l[LEGIT]";
|
||||
default -> throw new IncompatibleClassChangeError();
|
||||
};
|
||||
String aggRiskDisplay = assessment.risk() >= 60.0
|
||||
? "&#ff2244" + String.format("%.1f", assessment.risk())
|
||||
: (assessment.risk() >= 20.0 ? "&#ffaa00" + String.format("%.1f", assessment.risk()) : "�ff88" + String.format("%.1f", assessment.risk()));
|
||||
List<String> signalStrs = new ArrayList<>();
|
||||
|
||||
for (Signal s : r.hardSignals()) {
|
||||
String name = formatSignalName(s.type());
|
||||
signalStrs.add(name + " (" + String.format("%.1f", s.value()) + ")");
|
||||
}
|
||||
|
||||
String signalsFormatted = signalStrs.isEmpty() ? "&7None" : String.join("&8, &f", signalStrs);
|
||||
List<String> contribStrs = new ArrayList<>();
|
||||
|
||||
for (Contribution c : assessment.contributions()) {
|
||||
if (c.contribution() >= 0.5) {
|
||||
String name = formatSignalName(c.signal());
|
||||
contribStrs.add(name + " &e" + String.format("%.1f", c.contribution()));
|
||||
}
|
||||
}
|
||||
|
||||
String contribsFormatted = contribStrs.isEmpty() ? "&7Clean" : String.join("&8, &f", contribStrs);
|
||||
recipient.sendMessage(
|
||||
CompatUtils.color(
|
||||
lm.getMessage(
|
||||
"commands.debug_card_header",
|
||||
lang,
|
||||
new Object[]{"attacker", r.attackerName(), "attacker_ping", r.attackerPing(), "victim", r.victimName(), "victim_ping", r.victimPing()}
|
||||
)
|
||||
)
|
||||
);
|
||||
recipient.sendMessage(
|
||||
CompatUtils.color(
|
||||
lm.getMessage(
|
||||
"commands.debug_card_geometry",
|
||||
lang,
|
||||
new Object[]{
|
||||
"angle",
|
||||
String.format("%.2f", r.angleOffsetDeg()),
|
||||
"reach",
|
||||
String.format("%.2f", r.raycastDistance()),
|
||||
"comp_reach",
|
||||
String.format("%.2f", r.compensatedReach()),
|
||||
"raw_reach",
|
||||
String.format("%.2f", r.rawReach())
|
||||
}
|
||||
)
|
||||
)
|
||||
);
|
||||
recipient.sendMessage(
|
||||
CompatUtils.color(
|
||||
lm.getMessage(
|
||||
"commands.debug_card_hitbox",
|
||||
lang,
|
||||
new Object[]{
|
||||
"ray_hit",
|
||||
rayHitStr,
|
||||
"edge_prox",
|
||||
String.format("%.2f", r.hitboxEdgeProximity()),
|
||||
"margin",
|
||||
String.format("%.2f", r.latencyMargin()),
|
||||
"corner",
|
||||
cornerStr,
|
||||
"wall",
|
||||
wallStr
|
||||
}
|
||||
)
|
||||
)
|
||||
);
|
||||
recipient.sendMessage(
|
||||
CompatUtils.color(
|
||||
lm.getMessage(
|
||||
"commands.debug_card_kinematics",
|
||||
lang,
|
||||
new Object[]{
|
||||
"yaw_1t",
|
||||
String.format("%+.2f", r.yaw1t()),
|
||||
"yaw_5t",
|
||||
String.format("%+.2f", r.yaw5t()),
|
||||
"pitch_1t",
|
||||
String.format("%+.2f", r.pitch1t()),
|
||||
"pitch_5t",
|
||||
String.format("%+.2f", r.pitch5t())
|
||||
}
|
||||
)
|
||||
)
|
||||
);
|
||||
recipient.sendMessage(
|
||||
CompatUtils.color(
|
||||
lm.getMessage(
|
||||
"commands.debug_card_dynamics",
|
||||
lang,
|
||||
new Object[]{
|
||||
"rot_vel",
|
||||
String.format("%.1f", r.rotVel()),
|
||||
"yaw_accel",
|
||||
String.format("%+.1f", r.yawAccel()),
|
||||
"yaw_jerk",
|
||||
String.format("%+.1f", r.yawJerk()),
|
||||
"rot_var",
|
||||
String.format("%.2f", r.rotVar()),
|
||||
"rot_age",
|
||||
r.rotAge()
|
||||
}
|
||||
)
|
||||
)
|
||||
);
|
||||
recipient.sendMessage(
|
||||
CompatUtils.color(
|
||||
lm.getMessage(
|
||||
"commands.debug_card_combat",
|
||||
lang,
|
||||
new Object[]{
|
||||
"cooldown",
|
||||
cooldownPct,
|
||||
"interval",
|
||||
String.format("%.1f", r.attackIntervalTicks()),
|
||||
"cps",
|
||||
String.format("%.1f", cps),
|
||||
"crit",
|
||||
critStr,
|
||||
"kb",
|
||||
kbStr
|
||||
}
|
||||
)
|
||||
)
|
||||
);
|
||||
recipient.sendMessage(
|
||||
CompatUtils.color(
|
||||
lm.getMessage(
|
||||
"commands.debug_card_ai",
|
||||
lang,
|
||||
new Object[]{
|
||||
"model_p",
|
||||
String.format("%.3f", modelP),
|
||||
"model_pct",
|
||||
modelPct,
|
||||
"event_risk",
|
||||
String.format("%.1f", assessment.eventRisk()),
|
||||
"agg_risk",
|
||||
aggRiskDisplay,
|
||||
"verdict",
|
||||
verdictDisplay
|
||||
}
|
||||
)
|
||||
)
|
||||
);
|
||||
recipient.sendMessage(CompatUtils.color(lm.getMessage("commands.debug_card_signals", lang, new Object[]{"signals", signalsFormatted})));
|
||||
recipient.sendMessage(CompatUtils.color(lm.getMessage("commands.debug_card_contribs", lang, new Object[]{"contribs", contribsFormatted})));
|
||||
}
|
||||
|
||||
private static String formatSignalName(SignalType type) {
|
||||
if (type == null) {
|
||||
return "Unknown";
|
||||
}
|
||||
|
||||
return switch (type) {
|
||||
case HARD_SNAP -> "Aim snap";
|
||||
case HITBOX_MISS -> "Hitbox miss";
|
||||
case REACH -> "Reach";
|
||||
case AIM_CONSISTENCY -> "Superhuman aim";
|
||||
case KINEMATIC_ROBOTIC -> "Robotic rotation";
|
||||
case SILENT_ROTATION -> "Silent rotation";
|
||||
case UNNATURAL_JERK -> "Unnatural jerk";
|
||||
case PERFECT_COOLDOWN_SYNC -> "Cooldown lock";
|
||||
case AI_MODEL -> "KillAura (AI)";
|
||||
default -> throw new IncompatibleClassChangeError();
|
||||
};
|
||||
}
|
||||
|
||||
private static int countSolidSides(Location feet) {
|
||||
Location torso = feet.clone().add(0.0, 1.0, 0.0);
|
||||
int count = 0;
|
||||
|
||||
for (BlockFace face : new BlockFace[]{BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST}) {
|
||||
try {
|
||||
if (torso.getBlock().getRelative(face).getType().isSolid()) {
|
||||
count++;
|
||||
}
|
||||
} catch (Throwable var8) {
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
public record AttackDebugRecord(
|
||||
UUID attackerId,
|
||||
String attackerName,
|
||||
int attackerPing,
|
||||
UUID victimId,
|
||||
String victimName,
|
||||
int victimPing,
|
||||
Location victimLoc,
|
||||
Location attackerEyeLoc,
|
||||
float angleOffsetDeg,
|
||||
boolean rayHit,
|
||||
float raycastDistance,
|
||||
float hitboxEdgeProximity,
|
||||
double rawReach,
|
||||
double compensatedReach,
|
||||
double latencyMargin,
|
||||
boolean inCorner,
|
||||
int solidSides,
|
||||
boolean nearWall,
|
||||
boolean inWater,
|
||||
boolean isCrit,
|
||||
boolean victimKnockback,
|
||||
float yaw1t,
|
||||
float yaw5t,
|
||||
float pitch1t,
|
||||
float pitch5t,
|
||||
float yawAccel,
|
||||
float yawJerk,
|
||||
float pitchAccel,
|
||||
float pitchJerk,
|
||||
float rotVel,
|
||||
float rotVar,
|
||||
long rotAge,
|
||||
float cooldown,
|
||||
float attackIntervalTicks,
|
||||
boolean cancelDamage,
|
||||
List<Signal> hardSignals
|
||||
) {
|
||||
}
|
||||
|
||||
public static class DebugSession {
|
||||
private final UUID viewerId;
|
||||
private UUID targetFilter;
|
||||
private boolean visualParticles;
|
||||
|
||||
public DebugSession(UUID viewerId, UUID targetFilter, boolean visualParticles) {
|
||||
this.viewerId = viewerId;
|
||||
this.targetFilter = targetFilter;
|
||||
this.visualParticles = visualParticles;
|
||||
}
|
||||
|
||||
public UUID getViewerId() {
|
||||
return this.viewerId;
|
||||
}
|
||||
|
||||
public UUID getTargetFilter() {
|
||||
return this.targetFilter;
|
||||
}
|
||||
|
||||
public void setTargetFilter(UUID targetFilter) {
|
||||
this.targetFilter = targetFilter;
|
||||
}
|
||||
|
||||
public boolean isVisualParticles() {
|
||||
return this.visualParticles;
|
||||
}
|
||||
|
||||
public void setVisualParticles(boolean visualParticles) {
|
||||
this.visualParticles = visualParticles;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package net.synapselabs.anticheat.debug;
|
||||
|
||||
import java.util.Collection;
|
||||
import net.synapselabs.anticheat.engine.CombatContext;
|
||||
import net.synapselabs.anticheat.tracker.KinematicHistory.RaycastHitResult;
|
||||
import org.bukkit.Color;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Particle;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.Particle.DustOptions;
|
||||
import org.bukkit.entity.LivingEntity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.util.BoundingBox;
|
||||
import org.bukkit.util.Vector;
|
||||
|
||||
public class VisualDebugRenderer {
|
||||
private static final double STEP_SIZE = 0.25;
|
||||
|
||||
public static void renderTraces(
|
||||
Player attacker, LivingEntity victim, Location eyeLoc, RaycastHitResult raycast, CombatContext context, double latencyMargin, Collection<Player> viewers
|
||||
) {
|
||||
if (viewers != null && !viewers.isEmpty()) {
|
||||
World world = eyeLoc.getWorld();
|
||||
if (world != null) {
|
||||
Vector origin = eyeLoc.toVector();
|
||||
Vector direction = eyeLoc.getDirection().normalize();
|
||||
double maxDist = Math.min(6.0, Math.max(1.5, raycast.distance() + 0.5));
|
||||
|
||||
for (double d = 0.3; d <= maxDist; d += 0.25) {
|
||||
Vector point = origin.clone().add(direction.clone().multiply(d));
|
||||
|
||||
for (Player viewer : viewers) {
|
||||
if (viewer.getWorld().equals(world)) {
|
||||
spawnTraceParticle(viewer, point.getX(), point.getY(), point.getZ(), raycast.hit());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Vector impactPos = origin.clone().add(direction.clone().multiply(raycast.distance()));
|
||||
|
||||
for (Player viewer : viewers) {
|
||||
if (viewer.getWorld().equals(world)) {
|
||||
spawnImpactParticle(viewer, impactPos.getX(), impactPos.getY(), impactPos.getZ(), raycast.hit());
|
||||
}
|
||||
}
|
||||
|
||||
BoundingBox box = victim.getBoundingBox().clone().expand(latencyMargin);
|
||||
renderBoundingBox(box, world, viewers, raycast.hit());
|
||||
if (context.inCorner() || context.nearWall()) {
|
||||
Location victimLoc = victim.getLocation();
|
||||
renderCornerHighlight(victimLoc, world, viewers, context.inCorner());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void spawnTraceParticle(Player viewer, double x, double y, double z, boolean hit) {
|
||||
try {
|
||||
Color color = hit ? Color.fromRGB(0, 210, 255) : Color.fromRGB(255, 140, 0);
|
||||
DustOptions dust = new DustOptions(color, 0.7F);
|
||||
viewer.spawnParticle(Particle.REDSTONE, x, y, z, 1, 0.0, 0.0, 0.0, 0.0, dust);
|
||||
} catch (Throwable t) {
|
||||
try {
|
||||
viewer.spawnParticle(Particle.CRIT, x, y, z, 1, 0.0, 0.0, 0.0, 0.0);
|
||||
} catch (Throwable var10) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void spawnImpactParticle(Player viewer, double x, double y, double z, boolean hit) {
|
||||
try {
|
||||
Color color = hit ? Color.fromRGB(0, 255, 100) : Color.fromRGB(255, 30, 30);
|
||||
DustOptions dust = new DustOptions(color, 1.4F);
|
||||
viewer.spawnParticle(Particle.REDSTONE, x, y, z, 3, 0.05, 0.05, 0.05, 0.0, dust);
|
||||
} catch (Throwable t) {
|
||||
try {
|
||||
Particle p = hit ? Particle.VILLAGER_HAPPY : Particle.FLAME;
|
||||
viewer.spawnParticle(p, x, y, z, 3, 0.05, 0.05, 0.05, 0.0);
|
||||
} catch (Throwable var10) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void renderBoundingBox(BoundingBox box, World world, Collection<Player> viewers, boolean hit) {
|
||||
double minX = box.getMinX();
|
||||
double minY = box.getMinY();
|
||||
double minZ = box.getMinZ();
|
||||
double maxX = box.getMaxX();
|
||||
double maxY = box.getMaxY();
|
||||
double maxZ = box.getMaxZ();
|
||||
double[][] corners = new double[][]{
|
||||
{minX, minY, minZ},
|
||||
{maxX, minY, minZ},
|
||||
{maxX, minY, maxZ},
|
||||
{minX, minY, maxZ},
|
||||
{minX, maxY, minZ},
|
||||
{maxX, maxY, minZ},
|
||||
{maxX, maxY, maxZ},
|
||||
{minX, maxY, maxZ}
|
||||
};
|
||||
Color boxColor = hit ? Color.fromRGB(50, 255, 120) : Color.fromRGB(255, 80, 80);
|
||||
DustOptions dust = new DustOptions(boxColor, 0.85F);
|
||||
|
||||
for (double[] corner : corners) {
|
||||
for (Player viewer : viewers) {
|
||||
if (viewer.getWorld().equals(world)) {
|
||||
try {
|
||||
viewer.spawnParticle(Particle.REDSTONE, corner[0], corner[1], corner[2], 1, 0.0, 0.0, 0.0, 0.0, dust);
|
||||
} catch (Throwable t) {
|
||||
try {
|
||||
viewer.spawnParticle(Particle.SPELL_MOB, corner[0], corner[1], corner[2], 0, 0.2, 0.9, 0.4, 1.0);
|
||||
} catch (Throwable var27) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void renderCornerHighlight(Location center, World world, Collection<Player> viewers, boolean inCorner) {
|
||||
double y = center.getY() + 0.9;
|
||||
Color color = inCorner ? Color.fromRGB(168, 85, 247) : Color.fromRGB(14, 165, 233);
|
||||
DustOptions dust = new DustOptions(color, 1.0F);
|
||||
|
||||
for (Player viewer : viewers) {
|
||||
if (viewer.getWorld().equals(world)) {
|
||||
try {
|
||||
viewer.spawnParticle(Particle.REDSTONE, center.getX(), y, center.getZ(), 2, 0.2, 0.2, 0.2, 0.0, dust);
|
||||
} catch (Throwable var11) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package net.synapselabs.anticheat.engine;
|
||||
|
||||
import ai.onnxruntime.NodeInfo;
|
||||
import ai.onnxruntime.OnnxTensor;
|
||||
import ai.onnxruntime.OrtEnvironment;
|
||||
import ai.onnxruntime.OrtSession;
|
||||
import ai.onnxruntime.TensorInfo;
|
||||
import ai.onnxruntime.OrtSession.Result;
|
||||
import ai.onnxruntime.OrtSession.SessionOptions;
|
||||
import ai.onnxruntime.OrtSession.SessionOptions.OptLevel;
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.logging.Level;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
public class AiInferenceEngine implements AutoCloseable {
|
||||
private final JavaPlugin plugin;
|
||||
private OrtEnvironment env;
|
||||
private OrtSession session;
|
||||
private boolean initialized = false;
|
||||
private int expectedInputDim = 32;
|
||||
|
||||
public AiInferenceEngine(JavaPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
this.initEngine();
|
||||
}
|
||||
|
||||
private void initEngine() {
|
||||
try {
|
||||
this.env = OrtEnvironment.getEnvironment();
|
||||
File modelFile = new File(this.plugin.getDataFolder(), "anticheat_model.onnx");
|
||||
this.plugin.getDataFolder().mkdirs();
|
||||
|
||||
try (InputStream in = this.plugin.getResource("anticheat_model.onnx")) {
|
||||
if (in != null) {
|
||||
byte[] embeddedBytes = in.readAllBytes();
|
||||
boolean needsUpdate = !modelFile.exists() || modelFile.length() != embeddedBytes.length;
|
||||
if (needsUpdate) {
|
||||
Files.write(modelFile.toPath(), embeddedBytes);
|
||||
this.plugin.getLogger().info("Synchronized anticheat_model.onnx from JAR resources (" + embeddedBytes.length + " bytes).");
|
||||
}
|
||||
} else if (!modelFile.exists()) {
|
||||
this.plugin.getLogger().severe("Embedded anticheat_model.onnx resource not found!");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
SessionOptions opts = new SessionOptions();
|
||||
opts.setOptimizationLevel(OptLevel.ALL_OPT);
|
||||
opts.setIntraOpNumThreads(2);
|
||||
this.session = this.env.createSession(modelFile.getAbsolutePath(), opts);
|
||||
this.initialized = true;
|
||||
|
||||
try {
|
||||
for (Entry<String, NodeInfo> entry : this.session.getInputInfo().entrySet()) {
|
||||
TensorInfo info = (TensorInfo)entry.getValue().getInfo();
|
||||
long[] shape = info.getShape();
|
||||
if (shape.length >= 2 && shape[1] > 0L) {
|
||||
this.expectedInputDim = (int)shape[1];
|
||||
this.plugin.getLogger().info("ONNX Model input dimension: " + this.expectedInputDim + " features.");
|
||||
}
|
||||
}
|
||||
} catch (Throwable var8) {
|
||||
}
|
||||
|
||||
this.plugin.getLogger().info("Synapse AI ONNX Model successfully loaded into RAM (<0.3ms latency)!");
|
||||
} catch (Exception e) {
|
||||
this.plugin.getLogger().log(Level.SEVERE, "Failed to initialize ONNX Runtime Engine", e);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isInitialized() {
|
||||
return this.initialized;
|
||||
}
|
||||
|
||||
public synchronized AiInferenceEngine.PredictionResult predict(float[] features) {
|
||||
if (!this.initialized || this.session == null) {
|
||||
return new AiInferenceEngine.PredictionResult(0, 0.0F);
|
||||
}
|
||||
|
||||
if (features == null) {
|
||||
return new AiInferenceEngine.PredictionResult(0, 0.0F);
|
||||
}
|
||||
|
||||
float[] adaptedInput;
|
||||
if (this.expectedInputDim <= 0 || features.length == this.expectedInputDim) {
|
||||
adaptedInput = features;
|
||||
} else if (features.length > this.expectedInputDim) {
|
||||
adaptedInput = Arrays.copyOf(features, this.expectedInputDim);
|
||||
} else {
|
||||
adaptedInput = Arrays.copyOf(features, this.expectedInputDim);
|
||||
|
||||
for (int i = features.length; i < this.expectedInputDim; i++) {
|
||||
adaptedInput[i] = FeatureSchema.neutralDefault(i);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
float[][] inputData = new float[][]{adaptedInput};
|
||||
OnnxTensor inputTensor = OnnxTensor.createTensor(this.env, inputData);
|
||||
String inputName = (String)this.session.getInputNames().iterator().next();
|
||||
Result results = this.session.run(Collections.singletonMap(inputName, inputTensor));
|
||||
|
||||
AiInferenceEngine.PredictionResult var29;
|
||||
try {
|
||||
float cheatProb = 0.0F;
|
||||
int predictedLabel = 0;
|
||||
Object firstOut = results.get(0).getValue();
|
||||
if (firstOut instanceof float[][] fArr && fArr.length > 0) {
|
||||
if (fArr[0].length == 1) {
|
||||
cheatProb = fArr[0][0];
|
||||
predictedLabel = cheatProb >= 0.5F ? 1 : 0;
|
||||
} else if (fArr[0].length >= 2) {
|
||||
cheatProb = fArr[0][1];
|
||||
predictedLabel = cheatProb >= 0.5F ? 1 : 0;
|
||||
}
|
||||
} else if (firstOut instanceof long[] labels && labels.length > 0) {
|
||||
predictedLabel = (int)labels[0];
|
||||
cheatProb = predictedLabel == 1 ? 0.95F : 0.05F;
|
||||
if (results.size() > 1) {
|
||||
Object probObj = results.get(1).getValue();
|
||||
if (probObj instanceof List<?> list && !list.isEmpty()) {
|
||||
if (list.get(0) instanceof Map<?, ?> map) {
|
||||
for (Entry<?, ?> entry : map.entrySet()) {
|
||||
if (entry.getKey().toString().equals("1") && entry.getValue() instanceof Number n) {
|
||||
cheatProb = n.floatValue();
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (probObj instanceof float[][] probArr && probArr.length > 0 && probArr[0].length > 1) {
|
||||
cheatProb = probArr[0][1];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inputTensor.close();
|
||||
float calibratedProb = this.applyCalibration(cheatProb);
|
||||
var29 = new AiInferenceEngine.PredictionResult(calibratedProb >= 0.5F ? 1 : 0, calibratedProb);
|
||||
} catch (Throwable var22) {
|
||||
if (results != null) {
|
||||
try {
|
||||
results.close();
|
||||
} catch (Throwable var21) {
|
||||
var22.addSuppressed(var21);
|
||||
}
|
||||
}
|
||||
|
||||
throw var22;
|
||||
}
|
||||
|
||||
if (results != null) {
|
||||
results.close();
|
||||
}
|
||||
|
||||
return var29;
|
||||
} catch (Exception e) {
|
||||
this.plugin.getLogger().log(Level.WARNING, "Error during AI model inference", e);
|
||||
return new AiInferenceEngine.PredictionResult(0, 0.0F);
|
||||
}
|
||||
}
|
||||
|
||||
private float applyCalibration(float rawProb) {
|
||||
double a = this.plugin.getConfig().getDouble("detection.calibration.platt_a", 1.0);
|
||||
double b = this.plugin.getConfig().getDouble("detection.calibration.platt_b", 0.0);
|
||||
if (Math.abs(a - 1.0) < 1.0E-4 && Math.abs(b) < 1.0E-4) {
|
||||
return rawProb;
|
||||
}
|
||||
|
||||
double p = Math.max(1.0E-5, Math.min(0.99999, rawProb));
|
||||
double logit = Math.log(p / (1.0 - p));
|
||||
double calibrated = 1.0 / (1.0 + Math.exp(-(a * logit + b)));
|
||||
return (float)Math.max(0.0, Math.min(1.0, calibrated));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
try {
|
||||
if (this.session != null) {
|
||||
this.session.close();
|
||||
}
|
||||
|
||||
if (this.env != null) {
|
||||
this.env.close();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
this.plugin.getLogger().log(Level.WARNING, "Error closing ONNX environment", e);
|
||||
}
|
||||
}
|
||||
|
||||
public record PredictionResult(int predictedClass, float cheatProbability) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package net.synapselabs.anticheat.engine;
|
||||
|
||||
public record CombatContext(
|
||||
boolean inCorner,
|
||||
boolean nearWall,
|
||||
boolean victimKnockback,
|
||||
int pingMs,
|
||||
boolean isCrit,
|
||||
boolean targetSwitch,
|
||||
boolean repeatedPattern,
|
||||
boolean inWater,
|
||||
double yawAccel,
|
||||
boolean tpsDip,
|
||||
boolean recentTeleportOrRespawn,
|
||||
boolean inSpecialBlock,
|
||||
boolean microFlick
|
||||
) {
|
||||
public static CombatContext.Builder builder() {
|
||||
return new CombatContext.Builder();
|
||||
}
|
||||
|
||||
public static final class Builder {
|
||||
private boolean inCorner;
|
||||
private boolean nearWall;
|
||||
private boolean victimKnockback;
|
||||
private boolean isCrit;
|
||||
private boolean targetSwitch;
|
||||
private boolean repeatedPattern;
|
||||
private boolean inWater;
|
||||
private int pingMs;
|
||||
private double yawAccel;
|
||||
private boolean tpsDip;
|
||||
private boolean recentTeleportOrRespawn;
|
||||
private boolean inSpecialBlock;
|
||||
private boolean microFlick;
|
||||
|
||||
public CombatContext.Builder inCorner(boolean v) {
|
||||
this.inCorner = v;
|
||||
return this;
|
||||
}
|
||||
|
||||
public CombatContext.Builder nearWall(boolean v) {
|
||||
this.nearWall = v;
|
||||
return this;
|
||||
}
|
||||
|
||||
public CombatContext.Builder victimKnockback(boolean v) {
|
||||
this.victimKnockback = v;
|
||||
return this;
|
||||
}
|
||||
|
||||
public CombatContext.Builder pingMs(int v) {
|
||||
this.pingMs = v;
|
||||
return this;
|
||||
}
|
||||
|
||||
public CombatContext.Builder isCrit(boolean v) {
|
||||
this.isCrit = v;
|
||||
return this;
|
||||
}
|
||||
|
||||
public CombatContext.Builder targetSwitch(boolean v) {
|
||||
this.targetSwitch = v;
|
||||
return this;
|
||||
}
|
||||
|
||||
public CombatContext.Builder repeatedPattern(boolean v) {
|
||||
this.repeatedPattern = v;
|
||||
return this;
|
||||
}
|
||||
|
||||
public CombatContext.Builder inWater(boolean v) {
|
||||
this.inWater = v;
|
||||
return this;
|
||||
}
|
||||
|
||||
public CombatContext.Builder yawAccel(double v) {
|
||||
this.yawAccel = v;
|
||||
return this;
|
||||
}
|
||||
|
||||
public CombatContext.Builder tpsDip(boolean v) {
|
||||
this.tpsDip = v;
|
||||
return this;
|
||||
}
|
||||
|
||||
public CombatContext.Builder recentTeleportOrRespawn(boolean v) {
|
||||
this.recentTeleportOrRespawn = v;
|
||||
return this;
|
||||
}
|
||||
|
||||
public CombatContext.Builder inSpecialBlock(boolean v) {
|
||||
this.inSpecialBlock = v;
|
||||
return this;
|
||||
}
|
||||
|
||||
public CombatContext.Builder microFlick(boolean v) {
|
||||
this.microFlick = v;
|
||||
return this;
|
||||
}
|
||||
|
||||
public CombatContext build() {
|
||||
return new CombatContext(
|
||||
this.inCorner,
|
||||
this.nearWall,
|
||||
this.victimKnockback,
|
||||
this.pingMs,
|
||||
this.isCrit,
|
||||
this.targetSwitch,
|
||||
this.repeatedPattern,
|
||||
this.inWater,
|
||||
this.yawAccel,
|
||||
this.tpsDip,
|
||||
this.recentTeleportOrRespawn,
|
||||
this.inSpecialBlock,
|
||||
this.microFlick
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package net.synapselabs.anticheat.engine;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public final class ContextEngine {
|
||||
public static final double M_CORNER = 0.25;
|
||||
public static final double M_NEAR_WALL = 0.5;
|
||||
public static final double M_KNOCKBACK = 0.4;
|
||||
public static final double M_HIGH_PING = 0.7;
|
||||
public static final double M_CRIT = 0.55;
|
||||
public static final double M_IN_WATER = 0.4;
|
||||
public static final double M_TARGET_SWITCH = 0.5;
|
||||
public static final double M_HUMAN_DECEL = 0.5;
|
||||
public static final double M_REPEATED = 1.5;
|
||||
public static final double M_TPS_DIP = 0.4;
|
||||
public static final double M_RECENT_TELEPORT = 0.2;
|
||||
public static final double M_SPECIAL_BLOCK = 0.4;
|
||||
public static final double M_UNCONFIRMED = 0.35;
|
||||
public static final double M_MICRO_FLICK = 0.4;
|
||||
public static final int HIGH_PING_MS = 100;
|
||||
public static final double DECEL_THRESHOLD = -2.0;
|
||||
public static final double BASE_REACH = 3.0;
|
||||
public static final double KB_SPEED = 6.0;
|
||||
public static final double PING_JITTER = 1.0;
|
||||
public static final double WATER_ALLOWANCE = 0.15;
|
||||
|
||||
private ContextEngine() {
|
||||
}
|
||||
|
||||
public static double lagCompensatedReachExcess(double value, CombatContext ctx) {
|
||||
double pingSec = ctx.pingMs() / 1000.0;
|
||||
double allowance = 3.0;
|
||||
if (ctx.victimKnockback()) {
|
||||
allowance += 6.0 * pingSec;
|
||||
}
|
||||
|
||||
if (ctx.inWater()) {
|
||||
allowance += 0.15;
|
||||
}
|
||||
|
||||
allowance += 1.0 * pingSec;
|
||||
return Math.max(0.0, value - allowance);
|
||||
}
|
||||
|
||||
public static double reachConfidence(double value, CombatContext ctx) {
|
||||
double excess = lagCompensatedReachExcess(value, ctx);
|
||||
return excess <= 0.0 ? 0.05 : Math.min(1.0, 0.2 + excess);
|
||||
}
|
||||
|
||||
public static Map<String, Double> modifiersFor(SignalType type, CombatContext ctx) {
|
||||
Map<String, Double> mods = new LinkedHashMap<>();
|
||||
boolean isAi = type == SignalType.AI_MODEL;
|
||||
boolean snapLike = type == SignalType.HARD_SNAP || type == SignalType.HITBOX_MISS;
|
||||
boolean reachLike = snapLike || type == SignalType.REACH;
|
||||
if ((snapLike || isAi) && ctx.inCorner()) {
|
||||
mods.put("corner", 0.25);
|
||||
} else if ((snapLike || isAi) && ctx.nearWall()) {
|
||||
mods.put("near_wall", 0.5);
|
||||
}
|
||||
|
||||
if ((reachLike || isAi) && ctx.victimKnockback()) {
|
||||
mods.put("knockback", 0.4);
|
||||
}
|
||||
|
||||
if ((reachLike || isAi) && ctx.pingMs() > 100) {
|
||||
mods.put("high_ping", 0.7);
|
||||
}
|
||||
|
||||
if ((type == SignalType.HARD_SNAP || type == SignalType.KINEMATIC_ROBOTIC) && ctx.isCrit()) {
|
||||
mods.put("crit", 0.55);
|
||||
}
|
||||
|
||||
if (isAi && ctx.isCrit() && ctx.yawAccel() < -2.0) {
|
||||
mods.put("crit_decel", 0.55);
|
||||
}
|
||||
|
||||
if (ctx.inWater()
|
||||
&& (
|
||||
snapLike
|
||||
|| type == SignalType.AIM_CONSISTENCY
|
||||
|| type == SignalType.KINEMATIC_ROBOTIC
|
||||
|| type == SignalType.UNNATURAL_JERK
|
||||
|| type == SignalType.SILENT_ROTATION
|
||||
|| isAi
|
||||
)) {
|
||||
mods.put("in_water", 0.4);
|
||||
}
|
||||
|
||||
if (snapLike && ctx.targetSwitch()) {
|
||||
mods.put("target_switch", 0.5);
|
||||
}
|
||||
|
||||
if ((type == SignalType.HARD_SNAP || type == SignalType.KINEMATIC_ROBOTIC || isAi) && ctx.yawAccel() < -2.0) {
|
||||
mods.put("human_decel", 0.5);
|
||||
}
|
||||
|
||||
if ((snapLike || type == SignalType.SILENT_ROTATION || isAi) && ctx.microFlick() && !ctx.repeatedPattern()) {
|
||||
mods.put("micro_flick", 0.4);
|
||||
}
|
||||
|
||||
if (ctx.tpsDip()) {
|
||||
mods.put("tps_dip", 0.4);
|
||||
}
|
||||
|
||||
if (ctx.recentTeleportOrRespawn()) {
|
||||
mods.put("recent_teleport", 0.2);
|
||||
}
|
||||
|
||||
if (ctx.inSpecialBlock()) {
|
||||
mods.put("special_block", 0.4);
|
||||
}
|
||||
|
||||
boolean patternSignal = type == SignalType.AIM_CONSISTENCY || type == SignalType.KINEMATIC_ROBOTIC;
|
||||
if (patternSignal && !ctx.repeatedPattern()) {
|
||||
mods.put("unconfirmed_pattern", 0.35);
|
||||
}
|
||||
|
||||
if (ctx.repeatedPattern()) {
|
||||
mods.put("repeated_pattern", 1.5);
|
||||
}
|
||||
|
||||
return mods;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package net.synapselabs.anticheat.engine;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import net.synapselabs.anticheat.data.ThreatState;
|
||||
|
||||
public record DetectionSnapshot(
|
||||
UUID playerId,
|
||||
String playerName,
|
||||
long timestamp,
|
||||
float rawScore,
|
||||
float confidence,
|
||||
float suspicion,
|
||||
float killauraConfidence,
|
||||
float aimConfidence,
|
||||
ThreatState threatState,
|
||||
List<String> hardViolations,
|
||||
List<String> aiViolations,
|
||||
FeatureVector featureVector,
|
||||
Map<String, Object> metadata,
|
||||
String verdict,
|
||||
float riskScore,
|
||||
List<String> reasons
|
||||
) {
|
||||
public boolean hasHardViolations() {
|
||||
return this.hardViolations != null && !this.hardViolations.isEmpty();
|
||||
}
|
||||
|
||||
public boolean hasAiViolations() {
|
||||
return this.aiViolations != null && !this.aiViolations.isEmpty();
|
||||
}
|
||||
|
||||
public boolean isFlagged() {
|
||||
return "CHEAT".equals(this.verdict) || this.hasHardViolations() || this.hasAiViolations();
|
||||
}
|
||||
|
||||
public boolean isActionable() {
|
||||
return "CHEAT".equals(this.verdict);
|
||||
}
|
||||
|
||||
public String getPrimaryViolation() {
|
||||
if (this.hasHardViolations()) {
|
||||
return this.hardViolations.get(0);
|
||||
} else if (this.hasAiViolations()) {
|
||||
return this.aiViolations.get(0);
|
||||
} else if (this.reasons != null && !this.reasons.isEmpty()) {
|
||||
String firstReason = this.reasons.get(0);
|
||||
int lastSpace = firstReason.lastIndexOf(32);
|
||||
return lastSpace > 0 && firstReason.endsWith("%") ? firstReason.substring(0, lastSpace) : firstReason;
|
||||
} else {
|
||||
return "Clean";
|
||||
}
|
||||
}
|
||||
|
||||
public int getRiskPercent() {
|
||||
return Math.round(Math.max(0.0F, Math.min(1.0F, this.riskScore)) * 100.0F);
|
||||
}
|
||||
|
||||
public int getConfidencePercent() {
|
||||
return Math.round(this.confidence * 100.0F);
|
||||
}
|
||||
|
||||
public int getSuspicionPercent() {
|
||||
return Math.round(this.suspicion * 100.0F);
|
||||
}
|
||||
|
||||
public int getKillauraPercent() {
|
||||
return Math.round(this.killauraConfidence * 100.0F);
|
||||
}
|
||||
|
||||
public int getAimPercent() {
|
||||
return Math.round(this.aimConfidence * 100.0F);
|
||||
}
|
||||
|
||||
public static DetectionSnapshot.Builder builder(UUID playerId, String playerName) {
|
||||
return new DetectionSnapshot.Builder(playerId, playerName);
|
||||
}
|
||||
|
||||
public static class Builder {
|
||||
private final UUID playerId;
|
||||
private final String playerName;
|
||||
private long timestamp = System.currentTimeMillis();
|
||||
private float rawScore = 0.0F;
|
||||
private float confidence = 0.0F;
|
||||
private float suspicion = 0.0F;
|
||||
private float killauraConfidence = 0.0F;
|
||||
private float aimConfidence = 0.0F;
|
||||
private ThreatState threatState = ThreatState.CLEAN;
|
||||
private List<String> hardViolations = Collections.emptyList();
|
||||
private List<String> aiViolations = Collections.emptyList();
|
||||
private FeatureVector featureVector = null;
|
||||
private Map<String, Object> metadata = Collections.emptyMap();
|
||||
private String verdict = "LEGIT";
|
||||
private float riskScore = 0.0F;
|
||||
private List<String> reasons = Collections.emptyList();
|
||||
|
||||
public Builder(UUID playerId, String playerName) {
|
||||
this.playerId = playerId;
|
||||
this.playerName = playerName;
|
||||
}
|
||||
|
||||
public DetectionSnapshot.Builder timestamp(long timestamp) {
|
||||
this.timestamp = timestamp;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DetectionSnapshot.Builder rawScore(float rawScore) {
|
||||
this.rawScore = rawScore;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DetectionSnapshot.Builder confidence(float confidence) {
|
||||
this.confidence = confidence;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DetectionSnapshot.Builder suspicion(float suspicion) {
|
||||
this.suspicion = suspicion;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DetectionSnapshot.Builder killauraConfidence(float killauraConfidence) {
|
||||
this.killauraConfidence = killauraConfidence;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DetectionSnapshot.Builder aimConfidence(float aimConfidence) {
|
||||
this.aimConfidence = aimConfidence;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DetectionSnapshot.Builder threatState(ThreatState threatState) {
|
||||
this.threatState = threatState;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DetectionSnapshot.Builder hardViolations(List<String> hardViolations) {
|
||||
this.hardViolations = hardViolations;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DetectionSnapshot.Builder aiViolations(List<String> aiViolations) {
|
||||
this.aiViolations = aiViolations;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DetectionSnapshot.Builder featureVector(FeatureVector featureVector) {
|
||||
this.featureVector = featureVector;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DetectionSnapshot.Builder metadata(Map<String, Object> metadata) {
|
||||
this.metadata = metadata;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DetectionSnapshot.Builder verdict(String verdict) {
|
||||
this.verdict = verdict;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DetectionSnapshot.Builder riskScore(float riskScore) {
|
||||
this.riskScore = riskScore;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DetectionSnapshot.Builder reasons(List<String> reasons) {
|
||||
this.reasons = reasons;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DetectionSnapshot build() {
|
||||
return new DetectionSnapshot(
|
||||
this.playerId,
|
||||
this.playerName,
|
||||
this.timestamp,
|
||||
this.rawScore,
|
||||
this.confidence,
|
||||
this.suspicion,
|
||||
this.killauraConfidence,
|
||||
this.aimConfidence,
|
||||
this.threatState,
|
||||
this.hardViolations,
|
||||
this.aiViolations,
|
||||
this.featureVector,
|
||||
this.metadata,
|
||||
this.verdict,
|
||||
this.riskScore,
|
||||
this.reasons
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package net.synapselabs.anticheat.engine;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public final class FeatureSchema {
|
||||
public static final String VERSION = "combat.v3";
|
||||
public static final int FEATURE_COUNT = 32;
|
||||
public static final int I_DISTANCE = 0;
|
||||
public static final int I_ANGLE_OFFSET_DEG = 1;
|
||||
public static final int I_YAW_DELTA_1T = 2;
|
||||
public static final int I_YAW_DELTA_2T = 3;
|
||||
public static final int I_YAW_DELTA_5T = 4;
|
||||
public static final int I_YAW_ACCEL = 5;
|
||||
public static final int I_YAW_JERK = 6;
|
||||
public static final int I_PITCH_DELTA_1T = 7;
|
||||
public static final int I_PITCH_DELTA_2T = 8;
|
||||
public static final int I_PITCH_DELTA_5T = 9;
|
||||
public static final int I_PITCH_ACCEL = 10;
|
||||
public static final int I_PITCH_JERK = 11;
|
||||
public static final int I_RAYCAST_HIT = 12;
|
||||
public static final int I_RAYCAST_DISTANCE = 13;
|
||||
public static final int I_RAYCAST_ANGLE_ERROR = 14;
|
||||
public static final int I_HITBOX_EDGE_PROXIMITY = 15;
|
||||
public static final int I_IS_FALLING = 16;
|
||||
public static final int I_IS_SPRINTING = 17;
|
||||
public static final int I_ATTACK_COOLDOWN = 18;
|
||||
public static final int I_ROTATION_VARIANCE_10T = 19;
|
||||
public static final int I_ATTACK_INTERVAL_TICKS = 20;
|
||||
public static final int I_TARGET_SWITCH_TICKS = 21;
|
||||
public static final int I_ATTACKER_VELOCITY_SQ = 22;
|
||||
public static final int I_VICTIM_VELOCITY_SQ = 23;
|
||||
public static final int I_GCD_ERROR_RATE = 24;
|
||||
public static final int I_DETECTED_SENSITIVITY = 25;
|
||||
public static final int I_GCD_SNAP_FLAG = 26;
|
||||
public static final int I_ATTACK_INTERVAL_VARIANCE_10T = 27;
|
||||
public static final int I_STRAFE_ROTATION_CORRELATION = 28;
|
||||
public static final int I_PRE_POST_ANGULAR_VELOCITY_DELTA = 29;
|
||||
public static final int I_MULTI_TARGET_SWITCH_RATE = 30;
|
||||
public static final int I_VELOCITY_KNOCKBACK_DEVIATION = 31;
|
||||
public static final String[] NAMES = new String[]{
|
||||
"distance",
|
||||
"angle_offset_deg",
|
||||
"yaw_delta_1t",
|
||||
"yaw_delta_2t",
|
||||
"yaw_delta_5t",
|
||||
"yaw_accel",
|
||||
"yaw_jerk",
|
||||
"pitch_delta_1t",
|
||||
"pitch_delta_2t",
|
||||
"pitch_delta_5t",
|
||||
"pitch_accel",
|
||||
"pitch_jerk",
|
||||
"raycast_hit",
|
||||
"raycast_distance",
|
||||
"raycast_angle_error",
|
||||
"hitbox_edge_proximity",
|
||||
"is_falling",
|
||||
"is_sprinting",
|
||||
"attack_cooldown_progress",
|
||||
"rotation_variance_10t",
|
||||
"attack_interval_ticks",
|
||||
"target_switch_ticks",
|
||||
"attacker_velocity_sq",
|
||||
"victim_velocity_sq",
|
||||
"gcd_error_rate",
|
||||
"detected_sensitivity",
|
||||
"gcd_snap_flag",
|
||||
"attack_interval_variance_10t",
|
||||
"strafe_rotation_correlation",
|
||||
"pre_post_angular_velocity_delta",
|
||||
"multi_target_switch_rate",
|
||||
"velocity_knockback_deviation"
|
||||
};
|
||||
|
||||
private FeatureSchema() {
|
||||
}
|
||||
|
||||
public static float[] assemble(Map<String, Float> canonicalValues) {
|
||||
float[] out = new float[32];
|
||||
|
||||
for (int i = 0; i < 32; i++) {
|
||||
Float v = canonicalValues.get(NAMES[i]);
|
||||
out[i] = v != null && !v.isNaN() && !v.isInfinite() ? v : neutralDefault(i);
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
public static float neutralDefault(int index) {
|
||||
return switch (index) {
|
||||
case 0, 13 -> 3.0F;
|
||||
case 1, 14 -> 10.0F;
|
||||
default -> 0.0F;
|
||||
case 12, 18 -> 1.0F;
|
||||
case 15 -> 0.0F;
|
||||
case 19 -> 5.0F;
|
||||
case 20 -> 10.0F;
|
||||
case 21 -> 100.0F;
|
||||
case 25 -> 0.5F;
|
||||
case 27 -> 1.0F;
|
||||
case 28 -> 0.5F;
|
||||
};
|
||||
}
|
||||
|
||||
public static String validate(float[] v) {
|
||||
if (v == null) {
|
||||
return "vector is null";
|
||||
}
|
||||
|
||||
if (v.length != 32) {
|
||||
return "expected 32 features, got " + v.length;
|
||||
}
|
||||
|
||||
for (int i = 0; i < v.length; i++) {
|
||||
if (Float.isNaN(v[i]) || Float.isInfinite(v[i])) {
|
||||
return "non-finite value at " + NAMES[i];
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
package net.synapselabs.anticheat.engine;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public record FeatureVector(String version, float[] rawValues, float[] normalizedValues, Map<String, Float> namedFeatures) {
|
||||
public static final String CURRENT_VERSION = "combat.v3";
|
||||
|
||||
public static FeatureVector createV1(
|
||||
float distance,
|
||||
float angleOffsetDeg,
|
||||
float yawDelta1t,
|
||||
float yawDelta2t,
|
||||
float yawDelta5t,
|
||||
float yawAccel,
|
||||
float pitchDelta1t,
|
||||
float pitchDelta2t,
|
||||
float pitchDelta5t,
|
||||
float pitchAccel,
|
||||
boolean raycastHit,
|
||||
float raycastDistance,
|
||||
float raycastAngleError,
|
||||
boolean isFalling,
|
||||
boolean isSprinting,
|
||||
float attackCooldownProgress
|
||||
) {
|
||||
return createV2(
|
||||
distance,
|
||||
angleOffsetDeg,
|
||||
yawDelta1t,
|
||||
yawDelta2t,
|
||||
yawDelta5t,
|
||||
yawAccel,
|
||||
0.0F,
|
||||
pitchDelta1t,
|
||||
pitchDelta2t,
|
||||
pitchDelta5t,
|
||||
pitchAccel,
|
||||
0.0F,
|
||||
raycastHit,
|
||||
raycastDistance,
|
||||
raycastAngleError,
|
||||
0.0F,
|
||||
isFalling,
|
||||
isSprinting,
|
||||
attackCooldownProgress,
|
||||
5.0F,
|
||||
10.0F,
|
||||
100.0F,
|
||||
0.0F,
|
||||
0.0F
|
||||
);
|
||||
}
|
||||
|
||||
public static FeatureVector createV2(
|
||||
float distance,
|
||||
float angleOffsetDeg,
|
||||
float yawDelta1t,
|
||||
float yawDelta2t,
|
||||
float yawDelta5t,
|
||||
float yawAccel,
|
||||
float yawJerk,
|
||||
float pitchDelta1t,
|
||||
float pitchDelta2t,
|
||||
float pitchDelta5t,
|
||||
float pitchAccel,
|
||||
float pitchJerk,
|
||||
boolean raycastHit,
|
||||
float raycastDistance,
|
||||
float raycastAngleError,
|
||||
float hitboxEdgeProximity,
|
||||
boolean isFalling,
|
||||
boolean isSprinting,
|
||||
float attackCooldownProgress,
|
||||
float rotationVariance10t,
|
||||
float attackIntervalTicks,
|
||||
float targetSwitchTicks,
|
||||
float attackerVelocitySq,
|
||||
float victimVelocitySq
|
||||
) {
|
||||
return createV3(
|
||||
distance,
|
||||
angleOffsetDeg,
|
||||
yawDelta1t,
|
||||
yawDelta2t,
|
||||
yawDelta5t,
|
||||
yawAccel,
|
||||
yawJerk,
|
||||
pitchDelta1t,
|
||||
pitchDelta2t,
|
||||
pitchDelta5t,
|
||||
pitchAccel,
|
||||
pitchJerk,
|
||||
raycastHit,
|
||||
raycastDistance,
|
||||
raycastAngleError,
|
||||
hitboxEdgeProximity,
|
||||
isFalling,
|
||||
isSprinting,
|
||||
attackCooldownProgress,
|
||||
rotationVariance10t,
|
||||
attackIntervalTicks,
|
||||
targetSwitchTicks,
|
||||
attackerVelocitySq,
|
||||
victimVelocitySq,
|
||||
0.0F,
|
||||
0.5F,
|
||||
0.0F,
|
||||
1.0F,
|
||||
0.5F,
|
||||
0.0F,
|
||||
0.0F,
|
||||
0.0F
|
||||
);
|
||||
}
|
||||
|
||||
public static FeatureVector createV3(
|
||||
float distance,
|
||||
float angleOffsetDeg,
|
||||
float yawDelta1t,
|
||||
float yawDelta2t,
|
||||
float yawDelta5t,
|
||||
float yawAccel,
|
||||
float yawJerk,
|
||||
float pitchDelta1t,
|
||||
float pitchDelta2t,
|
||||
float pitchDelta5t,
|
||||
float pitchAccel,
|
||||
float pitchJerk,
|
||||
boolean raycastHit,
|
||||
float raycastDistance,
|
||||
float raycastAngleError,
|
||||
float hitboxEdgeProximity,
|
||||
boolean isFalling,
|
||||
boolean isSprinting,
|
||||
float attackCooldownProgress,
|
||||
float rotationVariance10t,
|
||||
float attackIntervalTicks,
|
||||
float targetSwitchTicks,
|
||||
float attackerVelocitySq,
|
||||
float victimVelocitySq,
|
||||
float gcdErrorRate,
|
||||
float detectedSensitivity,
|
||||
float gcdSnapFlag,
|
||||
float attackIntervalVariance10t,
|
||||
float strafeRotationCorrelation,
|
||||
float prePostAngularVelocityDelta,
|
||||
float multiTargetSwitchRate,
|
||||
float velocityKnockbackDeviation
|
||||
) {
|
||||
Map<String, Float> named = new LinkedHashMap<>();
|
||||
named.put(FeatureSchema.NAMES[0], distance);
|
||||
named.put(FeatureSchema.NAMES[1], angleOffsetDeg);
|
||||
named.put(FeatureSchema.NAMES[2], yawDelta1t);
|
||||
named.put(FeatureSchema.NAMES[3], yawDelta2t);
|
||||
named.put(FeatureSchema.NAMES[4], yawDelta5t);
|
||||
named.put(FeatureSchema.NAMES[5], yawAccel);
|
||||
named.put(FeatureSchema.NAMES[6], yawJerk);
|
||||
named.put(FeatureSchema.NAMES[7], pitchDelta1t);
|
||||
named.put(FeatureSchema.NAMES[8], pitchDelta2t);
|
||||
named.put(FeatureSchema.NAMES[9], pitchDelta5t);
|
||||
named.put(FeatureSchema.NAMES[10], pitchAccel);
|
||||
named.put(FeatureSchema.NAMES[11], pitchJerk);
|
||||
named.put(FeatureSchema.NAMES[12], raycastHit ? 1.0F : 0.0F);
|
||||
named.put(FeatureSchema.NAMES[13], raycastDistance);
|
||||
named.put(FeatureSchema.NAMES[14], raycastAngleError);
|
||||
named.put(FeatureSchema.NAMES[15], hitboxEdgeProximity);
|
||||
named.put(FeatureSchema.NAMES[16], isFalling ? 1.0F : 0.0F);
|
||||
named.put(FeatureSchema.NAMES[17], isSprinting ? 1.0F : 0.0F);
|
||||
named.put(FeatureSchema.NAMES[18], attackCooldownProgress);
|
||||
named.put(FeatureSchema.NAMES[19], rotationVariance10t);
|
||||
named.put(FeatureSchema.NAMES[20], attackIntervalTicks);
|
||||
named.put(FeatureSchema.NAMES[21], targetSwitchTicks);
|
||||
named.put(FeatureSchema.NAMES[22], attackerVelocitySq);
|
||||
named.put(FeatureSchema.NAMES[23], victimVelocitySq);
|
||||
named.put(FeatureSchema.NAMES[24], gcdErrorRate);
|
||||
named.put(FeatureSchema.NAMES[25], detectedSensitivity);
|
||||
named.put(FeatureSchema.NAMES[26], gcdSnapFlag);
|
||||
named.put(FeatureSchema.NAMES[27], attackIntervalVariance10t);
|
||||
named.put(FeatureSchema.NAMES[28], strafeRotationCorrelation);
|
||||
named.put(FeatureSchema.NAMES[29], prePostAngularVelocityDelta);
|
||||
named.put(FeatureSchema.NAMES[30], multiTargetSwitchRate);
|
||||
named.put(FeatureSchema.NAMES[31], velocityKnockbackDeviation);
|
||||
float[] canonical = FeatureSchema.assemble(named);
|
||||
return new FeatureVector("combat.v3", canonical, (float[])canonical.clone(), Collections.unmodifiableMap(named));
|
||||
}
|
||||
|
||||
public float[] getInferenceInput16() {
|
||||
return FeatureSchema.assemble(this.namedFeatures);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package net.synapselabs.anticheat.engine;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import net.synapselabs.anticheat.AiAnticheatPlugin;
|
||||
import net.synapselabs.anticheat.tracker.CombatTracker;
|
||||
import net.synapselabs.anticheat.tracker.KinematicHistory;
|
||||
import net.synapselabs.anticheat.tracker.CombatTracker.PatternContext;
|
||||
import net.synapselabs.anticheat.tracker.KinematicHistory.RaycastHitResult;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.BlockFace;
|
||||
import org.bukkit.entity.LivingEntity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.util.Vector;
|
||||
|
||||
public class HardCombatChecks {
|
||||
private final AiAnticheatPlugin plugin;
|
||||
|
||||
public HardCombatChecks(AiAnticheatPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
public HardCombatChecks.HardCheckResult evaluate(
|
||||
Player attacker, LivingEntity victim, CombatTracker tracker, RaycastHitResult raycast, double compensatedReach
|
||||
) {
|
||||
KinematicHistory history = tracker.getHistory();
|
||||
double maxReachConfig = this.plugin.getConfig().getDouble("detection.hard_checks.max_reach", 3.25);
|
||||
double reachHardFlag = this.plugin.getConfig().getDouble("detection.hard_checks.reach_hard_flag", 3.65);
|
||||
double fovOuterGate = this.plugin.getConfig().getDouble("detection.hard_checks.fov_outer_deg", 70.0);
|
||||
float angleOffset = raycast.angleOffsetDeg();
|
||||
boolean rayHit = raycast.hit();
|
||||
float yawDelta5t = history.getYawDelta(5);
|
||||
float yawAccelSigned = history.getYawAcceleration();
|
||||
float angularVel = history.getAngularVelocity();
|
||||
float yawSpeedChange = history.getYawSpeedChange();
|
||||
long timeSinceRot = history.getTimeSinceLastRotation();
|
||||
float rotVar = history.getRotationVariance10t();
|
||||
boolean roboticCandidate = Math.abs(yawDelta5t) > 35.0F && yawSpeedChange > 12.0F && angleOffset < 6.0F && rotVar < 2.0F;
|
||||
PatternContext pat = tracker.updatePattern(victim.getUniqueId(), roboticCandidate);
|
||||
if (!roboticCandidate && (!(Math.abs(yawDelta5t) > 35.0F) || !(yawSpeedChange > 12.0F) || !(angleOffset < 6.0F) || !pat.repeatedPattern())) {
|
||||
boolean roboticSnap = false;
|
||||
} else {
|
||||
boolean roboticSnap = true;
|
||||
}
|
||||
|
||||
int solidSides = countSolidSides(victim.getLocation());
|
||||
boolean nearWall = solidSides >= 1;
|
||||
boolean inCorner = solidSides >= 2;
|
||||
boolean inWater = isEntityInWater(attacker) || isEntityInWater(victim);
|
||||
boolean isCrit = isCritical(attacker, history);
|
||||
boolean victimKnockback = isBeingKnockedBack(victim);
|
||||
int ping = safePing(attacker);
|
||||
boolean tpsDip = isTpsDip();
|
||||
boolean inSpecialBlock = isInSpecialBlock(attacker);
|
||||
boolean microFlick = (Math.abs(history.getYawDelta(1)) > 8.0F || Math.abs(yawDelta5t) > 16.0F)
|
||||
&& angleOffset < 20.0F
|
||||
&& (yawAccelSigned < -1.0F || history.getPrePostAngularVelocityDelta() > 2.0F);
|
||||
boolean hardSnap = !microFlick
|
||||
&& (
|
||||
angularVel > 45.0F && yawSpeedChange > 18.0F && angleOffset < 5.0F && (rotVar < 2.5F || pat.repeatedPattern())
|
||||
|| Math.abs(yawDelta5t) > 60.0F && angleOffset > 35.0F && !rayHit && !inCorner && !nearWall
|
||||
|| angularVel > 35.0F && pat.repeatedPattern() && timeSinceRot <= 50L
|
||||
);
|
||||
CombatContext context = CombatContext.builder()
|
||||
.inCorner(inCorner)
|
||||
.nearWall(nearWall)
|
||||
.victimKnockback(victimKnockback)
|
||||
.pingMs(ping)
|
||||
.isCrit(isCrit)
|
||||
.targetSwitch(pat.targetSwitch())
|
||||
.repeatedPattern(pat.repeatedPattern())
|
||||
.inWater(inWater)
|
||||
.yawAccel(yawAccelSigned)
|
||||
.tpsDip(tpsDip)
|
||||
.inSpecialBlock(inSpecialBlock)
|
||||
.microFlick(microFlick)
|
||||
.build();
|
||||
double excess = ContextEngine.lagCompensatedReachExcess(compensatedReach, context);
|
||||
boolean cancelDamage = compensatedReach >= reachHardFlag && excess > 0.0;
|
||||
List<Signal> signals = new ArrayList<>();
|
||||
if (compensatedReach > maxReachConfig && excess > 0.01) {
|
||||
signals.add(
|
||||
Signal.of(SignalType.REACH, SignalType.REACH.defaultConfidence(), compensatedReach, String.format("reach %.2fm (lag-comp)", compensatedReach))
|
||||
);
|
||||
}
|
||||
|
||||
boolean silentRot = !rayHit
|
||||
&& !microFlick
|
||||
&& (
|
||||
angularVel < 0.2F && timeSinceRot > 150L && (raycast.distance() >= 2.0 && angleOffset > 30.0F || raycast.distance() < 2.0 && angleOffset > 60.0F)
|
||||
|| tracker.getConsecutiveSilentHits() >= 2 && angleOffset > 20.0F && raycast.distance() >= 1.8 && angularVel < 0.5F
|
||||
);
|
||||
if (silentRot && !inWater && !inCorner && !nearWall) {
|
||||
signals.add(
|
||||
Signal.of(
|
||||
SignalType.SILENT_ROTATION,
|
||||
SignalType.SILENT_ROTATION.defaultConfidence(),
|
||||
angleOffset,
|
||||
String.format("silent packet rotation (0° rot, %.1f° angle)", angleOffset)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
boolean wideMiss = !microFlick && angleOffset > 35.0F && !inWater && !inCorner && !nearWall;
|
||||
boolean distanceMiss = !rayHit && !microFlick && angleOffset > 20.0F && raycast.distance() >= 2.2 && !inWater && !inCorner && !nearWall;
|
||||
if (wideMiss || distanceMiss) {
|
||||
signals.add(
|
||||
Signal.of(
|
||||
SignalType.HITBOX_MISS,
|
||||
SignalType.HITBOX_MISS.defaultConfidence(),
|
||||
angleOffset,
|
||||
String.format("ray miss @ %.1f° (dist %.1fm)", angleOffset, raycast.distance())
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (hardSnap) {
|
||||
signals.add(
|
||||
Signal.of(
|
||||
SignalType.HARD_SNAP, SignalType.HARD_SNAP.defaultConfidence(), angularVel, String.format("snap %.0f°/t accel %.0f", angularVel, yawSpeedChange)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
boolean smoothAimbot = rotVar < 2.0F
|
||||
&& angleOffset < 6.0F
|
||||
&& raycast.distance() >= 1.8
|
||||
&& Math.abs(yawDelta5t) > 3.0F
|
||||
&& !inWater
|
||||
&& !inCorner
|
||||
&& !nearWall;
|
||||
if (smoothAimbot) {
|
||||
signals.add(
|
||||
Signal.of(SignalType.AIM_CONSISTENCY, SignalType.AIM_CONSISTENCY.defaultConfidence(), rotVar, String.format("aimbot lock (var %.2f)", rotVar))
|
||||
);
|
||||
}
|
||||
|
||||
float raycastAngleError = rayHit ? 0.0F : angleOffset;
|
||||
RiskEngine.addDerivedSignals(signals, angleOffset, raycastAngleError, yawDelta5t, yawSpeedChange, compensatedReach);
|
||||
return new HardCombatChecks.HardCheckResult(signals, context, cancelDamage, compensatedReach, angleOffset, rayHit);
|
||||
}
|
||||
|
||||
private static int countSolidSides(Location feet) {
|
||||
Location torso = feet.clone().add(0.0, 1.0, 0.0);
|
||||
int count = 0;
|
||||
|
||||
for (BlockFace face : new BlockFace[]{BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST}) {
|
||||
try {
|
||||
if (torso.getBlock().getRelative(face).getType().isSolid()) {
|
||||
count++;
|
||||
}
|
||||
} catch (Throwable var8) {
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
private static boolean isEntityInWater(LivingEntity entity) {
|
||||
try {
|
||||
if (entity.isInWater()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
Location loc = entity.getLocation();
|
||||
return loc.getBlock().isLiquid() || loc.clone().add(0.0, 0.5, 0.0).getBlock().isLiquid();
|
||||
} catch (Throwable ignored) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isCritical(Player attacker, KinematicHistory history) {
|
||||
try {
|
||||
boolean airborne = !attacker.isOnGround();
|
||||
boolean falling = attacker.getFallDistance() > 0.0F || history != null && history.isMovingDownwards();
|
||||
boolean fullCharge = attacker.getAttackCooldown() > 0.7F;
|
||||
boolean grounded = attacker.isInsideVehicle() || attacker.isClimbing();
|
||||
return (airborne || falling) && fullCharge && !grounded;
|
||||
} catch (Throwable ignored) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isBeingKnockedBack(LivingEntity victim) {
|
||||
try {
|
||||
Vector v = victim.getVelocity();
|
||||
double horiz = Math.sqrt(v.getX() * v.getX() + v.getZ() * v.getZ());
|
||||
return horiz > 0.35 || victim.getNoDamageTicks() > 10 && horiz > 0.15;
|
||||
} catch (Throwable ignored) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static int safePing(Player attacker) {
|
||||
try {
|
||||
return attacker.getPing();
|
||||
} catch (Throwable ignored) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isTpsDip() {
|
||||
try {
|
||||
double[] tps = Bukkit.getTPS();
|
||||
return tps.length > 0 && tps[0] < 18.5;
|
||||
} catch (Throwable ignored) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isInSpecialBlock(Player player) {
|
||||
try {
|
||||
if (player.isInsideVehicle()) {
|
||||
return true;
|
||||
} else {
|
||||
Location loc = player.getLocation();
|
||||
Material type = loc.getBlock().getType();
|
||||
if (type != Material.COBWEB && !type.name().contains("ICE")) {
|
||||
Material below = loc.clone().subtract(0.0, 0.5, 0.0).getBlock().getType();
|
||||
return below.name().contains("ICE") || below == Material.SLIME_BLOCK || below == Material.HONEY_BLOCK;
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch (Throwable ignored) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public record HardCheckResult(
|
||||
List<Signal> signals, CombatContext context, boolean cancelDamage, double calculatedReach, float angleOffsetDeg, boolean rayHit
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
package net.synapselabs.anticheat.engine;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Consumer;
|
||||
import net.synapselabs.anticheat.AiAnticheatPlugin;
|
||||
import net.synapselabs.anticheat.data.PlayerProfile;
|
||||
import net.synapselabs.anticheat.data.ThreatState;
|
||||
import net.synapselabs.anticheat.debug.DebugManager.AttackDebugRecord;
|
||||
import net.synapselabs.anticheat.engine.AiInferenceEngine.PredictionResult;
|
||||
import net.synapselabs.anticheat.engine.RiskAssessment.Contribution;
|
||||
import net.synapselabs.anticheat.engine.RiskAssessment.Verdict;
|
||||
import net.synapselabs.anticheat.tracker.CombatTracker;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class InferenceService implements AutoCloseable {
|
||||
private final AiAnticheatPlugin plugin;
|
||||
private final AiInferenceEngine engine;
|
||||
private final RiskEngine riskEngine;
|
||||
private final ExecutorService executor;
|
||||
private final List<Consumer<DetectionSnapshot>> subscribers = new ArrayList<>();
|
||||
|
||||
public InferenceService(AiAnticheatPlugin plugin, AiInferenceEngine engine) {
|
||||
this.plugin = plugin;
|
||||
this.engine = engine;
|
||||
double suspicious = plugin.getConfig().getDouble("detection.calibration.suspicious_threshold", 20.0);
|
||||
double cheat = plugin.getConfig().getDouble("detection.calibration.cheat_threshold", 60.0);
|
||||
this.riskEngine = new RiskEngine(suspicious, cheat);
|
||||
this.executor = Executors.newFixedThreadPool(2, r -> {
|
||||
Thread t = new Thread(r, "SynapseAI-InferenceWorker");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
}
|
||||
|
||||
public void subscribe(Consumer<DetectionSnapshot> listener) {
|
||||
this.subscribers.add(listener);
|
||||
}
|
||||
|
||||
public void submitAnalysis(Player player, FeatureVector vector, CombatTracker tracker, List<Signal> signals, CombatContext context) {
|
||||
this.submitAnalysis(player, vector, tracker, signals, context, null);
|
||||
}
|
||||
|
||||
public void submitAnalysis(
|
||||
Player player, FeatureVector vector, CombatTracker tracker, List<Signal> signals, CombatContext context, AttackDebugRecord debugRecord
|
||||
) {
|
||||
if (player != null && player.isOnline()) {
|
||||
UUID playerId = player.getUniqueId();
|
||||
String playerName = player.getName();
|
||||
this.executor
|
||||
.submit(
|
||||
() -> {
|
||||
try {
|
||||
float modelP = 0.0F;
|
||||
|
||||
try {
|
||||
float[] input = vector.getInferenceInput16();
|
||||
PredictionResult result = this.engine.predict(input);
|
||||
modelP = result.cheatProbability();
|
||||
} catch (Throwable t) {
|
||||
this.plugin.getLogger().warning("[AI Inference] Model execution failed: " + t.getClass().getSimpleName() + ": " + t.getMessage());
|
||||
}
|
||||
|
||||
List<Contribution> contribs = this.riskEngine.contributions(signals, context, modelP);
|
||||
double eventRisk = this.riskEngine.eventRisk(contribs);
|
||||
long now = System.currentTimeMillis();
|
||||
double aiFactor = 1.0;
|
||||
|
||||
for (Contribution c : contribs) {
|
||||
if (c.signal() == SignalType.AI_MODEL) {
|
||||
for (double f : c.modifiers().values()) {
|
||||
aiFactor *= f;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
boolean hasStructuralSignals = signals.stream()
|
||||
.anyMatch(
|
||||
s -> s.type() == SignalType.HARD_SNAP
|
||||
|| s.type() == SignalType.REACH
|
||||
|| s.type() == SignalType.HITBOX_MISS
|
||||
|| s.type() == SignalType.KINEMATIC_ROBOTIC
|
||||
|| s.type() == SignalType.AIM_CONSISTENCY
|
||||
|| s.type() == SignalType.SILENT_ROTATION
|
||||
)
|
||||
|| context.repeatedPattern() && !signals.isEmpty()
|
||||
|| modelP >= 0.85F;
|
||||
double aggregated = tracker.getRiskAccumulator().observe(eventRisk, now, hasStructuralSignals);
|
||||
RiskAssessment assessment = this.riskEngine.assess(signals, context, modelP, aggregated);
|
||||
tracker.setLastAssessment(assessment);
|
||||
tracker.recordModelInference(modelP);
|
||||
int requiredHits = this.plugin.getConfig().getInt("detection.multi_hit.required_hits", 5);
|
||||
double hitConfidenceThreshold = this.plugin.getConfig().getDouble("detection.multi_hit.confidence_threshold", 0.75);
|
||||
boolean multiHitConfirmed = tracker.hasMultiHitConfirmation(requiredHits, (float)hitConfidenceThreshold);
|
||||
Verdict finalVerdict = assessment.verdict();
|
||||
if (finalVerdict == Verdict.CHEAT && !multiHitConfirmed) {
|
||||
finalVerdict = Verdict.SUSPICIOUS;
|
||||
}
|
||||
|
||||
String verdict = finalVerdict.name();
|
||||
float riskScore01 = (float)(assessment.risk() / 100.0);
|
||||
ThreatState state = threatStateFor(finalVerdict);
|
||||
tracker.applyRisk(riskScore01, state);
|
||||
List<String> reasons = buildReasons(assessment);
|
||||
List<String> hardViolations = List.of();
|
||||
List<String> aiViolations = List.of();
|
||||
if (finalVerdict == Verdict.CHEAT) {
|
||||
Contribution dominant = dominantSignal(assessment);
|
||||
String label = dominant != null ? label(dominant.signal()) : "KillAura (AI Confirmed)";
|
||||
if (dominant == null
|
||||
|| dominant.signal() != SignalType.REACH
|
||||
&& dominant.signal() != SignalType.HARD_SNAP
|
||||
&& dominant.signal() != SignalType.HITBOX_MISS
|
||||
&& dominant.signal() != SignalType.SILENT_ROTATION) {
|
||||
aiViolations = List.of(label);
|
||||
} else {
|
||||
hardViolations = List.of(label);
|
||||
}
|
||||
} else if (finalVerdict == Verdict.SUSPICIOUS && eventRisk >= 10.0 && hasStructuralSignals) {
|
||||
Contribution dominant = dominantSignal(assessment);
|
||||
String label = dominant != null ? label(dominant.signal()) : "KillAura (AI)";
|
||||
if (dominant == null
|
||||
|| dominant.signal() != SignalType.REACH
|
||||
&& dominant.signal() != SignalType.HARD_SNAP
|
||||
&& dominant.signal() != SignalType.HITBOX_MISS
|
||||
&& dominant.signal() != SignalType.SILENT_ROTATION) {
|
||||
aiViolations = List.of(label);
|
||||
} else {
|
||||
hardViolations = List.of(label);
|
||||
}
|
||||
}
|
||||
|
||||
if (this.plugin.getConfig().getBoolean("logging.console.verbose", false)) {
|
||||
this.plugin
|
||||
.getLogger()
|
||||
.info(
|
||||
String.format(
|
||||
"[Risk] %s | model=%.2f | event=%.2f | risk=%.1f | %s | %s",
|
||||
playerName,
|
||||
modelP,
|
||||
eventRisk,
|
||||
assessment.risk(),
|
||||
verdict,
|
||||
reasons
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, Object> metadata = new LinkedHashMap<>();
|
||||
metadata.put("verdict", verdict);
|
||||
metadata.put("risk", assessment.risk());
|
||||
metadata.put("event_risk", eventRisk);
|
||||
metadata.put("model_p", (double)modelP);
|
||||
metadata.put("schema", "combat.v3");
|
||||
DetectionSnapshot snapshot = DetectionSnapshot.builder(playerId, playerName)
|
||||
.rawScore(modelP)
|
||||
.confidence(riskScore01)
|
||||
.suspicion(tracker.getSuspicion())
|
||||
.killauraConfidence(riskScore01)
|
||||
.aimConfidence(riskScore01)
|
||||
.threatState(state)
|
||||
.hardViolations(hardViolations)
|
||||
.aiViolations(aiViolations)
|
||||
.featureVector(vector)
|
||||
.metadata(metadata)
|
||||
.verdict(verdict)
|
||||
.riskScore(riskScore01)
|
||||
.reasons(reasons)
|
||||
.build();
|
||||
float finalModelP = modelP;
|
||||
Bukkit.getScheduler().runTask(this.plugin, () -> {
|
||||
Player p = Bukkit.getPlayer(playerId);
|
||||
if (p != null && p.isOnline()) {
|
||||
PlayerProfile profile = this.plugin.getDataManager().getOrCreate(p);
|
||||
profile.applySnapshot(snapshot);
|
||||
|
||||
for (Consumer<DetectionSnapshot> sub : this.subscribers) {
|
||||
try {
|
||||
sub.accept(snapshot);
|
||||
} catch (Throwable t) {
|
||||
this.plugin.getLogger().warning("Error in detection snapshot subscriber: " + t.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (debugRecord != null && this.plugin.getDebugManager() != null) {
|
||||
try {
|
||||
this.plugin.getDebugManager().dispatchReport(debugRecord, finalModelP, assessment);
|
||||
} catch (Throwable t) {
|
||||
this.plugin.getLogger().warning("Error dispatching debug report: " + t.getMessage());
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (Throwable t) {
|
||||
this.plugin.getLogger().warning("Failed during async inference analysis: " + t.getMessage());
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private static ThreatState threatStateFor(Verdict verdict) {
|
||||
return switch (verdict) {
|
||||
case CHEAT -> ThreatState.CONFIRMED;
|
||||
case SUSPICIOUS -> ThreatState.SUSPICIOUS;
|
||||
case LEGIT -> ThreatState.CLEAN;
|
||||
default -> throw new IncompatibleClassChangeError();
|
||||
};
|
||||
}
|
||||
|
||||
private static Contribution dominantSignal(RiskAssessment assessment) {
|
||||
Contribution nonAi = assessment.contributions()
|
||||
.stream()
|
||||
.filter(c -> c.signal() != SignalType.AI_MODEL)
|
||||
.max(Comparator.comparingDouble(Contribution::contribution))
|
||||
.orElse(null);
|
||||
return nonAi != null && nonAi.contribution() >= 1.0
|
||||
? nonAi
|
||||
: assessment.contributions().stream().filter(c -> c.signal() == SignalType.AI_MODEL).findFirst().orElse(nonAi);
|
||||
}
|
||||
|
||||
private static List<String> buildReasons(RiskAssessment assessment) {
|
||||
if (assessment.verdict() == Verdict.LEGIT && assessment.risk() < 15.0) {
|
||||
return List.of("Clean");
|
||||
}
|
||||
|
||||
double total = 0.0;
|
||||
|
||||
for (Contribution c : assessment.contributions()) {
|
||||
total += Math.max(0.0, c.contribution());
|
||||
}
|
||||
|
||||
double denom = total <= 0.0 ? 1.0 : total;
|
||||
List<Contribution> sorted = new ArrayList<>(assessment.contributions());
|
||||
sorted.sort(Comparator.comparingDouble(Contribution::contribution).reversed());
|
||||
List<String> reasons = new ArrayList<>();
|
||||
|
||||
for (Contribution c : sorted) {
|
||||
if (!(c.contribution() < 1.0)) {
|
||||
int share = (int)Math.round(c.contribution() / denom * 100.0);
|
||||
reasons.add(label(c.signal()) + " " + share + "%");
|
||||
if (reasons.size() >= 3) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (reasons.isEmpty()) {
|
||||
reasons.add("Clean");
|
||||
}
|
||||
|
||||
return reasons;
|
||||
}
|
||||
|
||||
private static String label(SignalType type) {
|
||||
return switch (type) {
|
||||
case HARD_SNAP -> "Aim snap";
|
||||
case HITBOX_MISS -> "Hitbox miss";
|
||||
case REACH -> "Reach";
|
||||
case AIM_CONSISTENCY -> "Superhuman aim";
|
||||
case KINEMATIC_ROBOTIC -> "Robotic rotation";
|
||||
case SILENT_ROTATION -> "Silent rotation";
|
||||
case UNNATURAL_JERK -> "Unnatural jerk";
|
||||
case PERFECT_COOLDOWN_SYNC -> "Cooldown lock";
|
||||
case AI_MODEL -> "KillAura (AI)";
|
||||
default -> throw new IncompatibleClassChangeError();
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
this.executor.shutdown();
|
||||
|
||||
try {
|
||||
if (!this.executor.awaitTermination(1000L, TimeUnit.MILLISECONDS)) {
|
||||
this.executor.shutdownNow();
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
this.executor.shutdownNow();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package net.synapselabs.anticheat.engine;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.util.BoundingBox;
|
||||
import org.bukkit.util.Vector;
|
||||
|
||||
public final class LagCompensator {
|
||||
private static final int MAX_SAMPLES = 60;
|
||||
private static final long MAX_AGE_MS = 3000L;
|
||||
private final Map<UUID, Deque<LagCompensator.Pose>> history = new ConcurrentHashMap<>();
|
||||
|
||||
public void record(Entity entity) {
|
||||
if (entity != null) {
|
||||
BoundingBox box = entity.getBoundingBox();
|
||||
LagCompensator.Pose pose = new LagCompensator.Pose(
|
||||
box.getCenterX(),
|
||||
box.getCenterY(),
|
||||
box.getCenterZ(),
|
||||
box.getWidthX() / 2.0,
|
||||
box.getHeight() / 2.0,
|
||||
box.getWidthZ() / 2.0,
|
||||
System.currentTimeMillis()
|
||||
);
|
||||
Deque<LagCompensator.Pose> q = this.history.computeIfAbsent(entity.getUniqueId(), k -> new ArrayDeque<>());
|
||||
synchronized (q) {
|
||||
q.addFirst(pose);
|
||||
|
||||
while (q.size() > 60) {
|
||||
q.removeLast();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void forget(UUID id) {
|
||||
this.history.remove(id);
|
||||
}
|
||||
|
||||
public double compensatedReach(Location eyeLoc, UUID victimId, int pingMs, double naiveReach) {
|
||||
Deque<LagCompensator.Pose> q = this.history.get(victimId);
|
||||
if (q == null) {
|
||||
return naiveReach;
|
||||
}
|
||||
|
||||
long now = System.currentTimeMillis();
|
||||
long targetAge = Math.max(0L, pingMs);
|
||||
long jitter = Math.max(60L, (long)(pingMs * 0.3));
|
||||
Vector eye = eyeLoc.toVector();
|
||||
double best = naiveReach;
|
||||
boolean matched = false;
|
||||
LagCompensator.Pose[] snapshot;
|
||||
synchronized (q) {
|
||||
snapshot = q.toArray(new LagCompensator.Pose[0]);
|
||||
}
|
||||
|
||||
for (LagCompensator.Pose p : snapshot) {
|
||||
long age = now - p.time();
|
||||
if (age > 3000L) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (Math.abs(age - targetAge) <= jitter) {
|
||||
double d = distanceToBox(eye, p);
|
||||
if (!matched || d < best) {
|
||||
best = d;
|
||||
matched = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return matched ? Math.min(best, naiveReach) : naiveReach;
|
||||
}
|
||||
|
||||
private static double distanceToBox(Vector eye, LagCompensator.Pose p) {
|
||||
double dx = Math.max(0.0, Math.abs(eye.getX() - p.cx()) - p.hx());
|
||||
double dy = Math.max(0.0, Math.abs(eye.getY() - p.cy()) - p.hy());
|
||||
double dz = Math.max(0.0, Math.abs(eye.getZ() - p.cz()) - p.hz());
|
||||
return Math.sqrt(dx * dx + dy * dy + dz * dz);
|
||||
}
|
||||
|
||||
public record Pose(double cx, double cy, double cz, double hx, double hy, double hz, long time) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package net.synapselabs.anticheat.engine;
|
||||
|
||||
public final class RiskAccumulator {
|
||||
public static final long DEFAULT_HALF_LIFE_MILLIS = 30000L;
|
||||
private final long halfLifeMillis;
|
||||
private double risk;
|
||||
private long lastUpdate;
|
||||
|
||||
public RiskAccumulator() {
|
||||
this(30000L);
|
||||
}
|
||||
|
||||
public RiskAccumulator(long halfLifeMillis) {
|
||||
if (halfLifeMillis <= 0L) {
|
||||
throw new IllegalArgumentException("halfLifeMillis must be > 0");
|
||||
}
|
||||
|
||||
this.halfLifeMillis = halfLifeMillis;
|
||||
}
|
||||
|
||||
public synchronized double observe(double eventRisk, long nowMillis) {
|
||||
return this.observe(eventRisk, nowMillis, eventRisk >= 12.0);
|
||||
}
|
||||
|
||||
public synchronized double observe(double eventRisk, long nowMillis, boolean isSuspiciousEvent) {
|
||||
this.decayTo(nowMillis);
|
||||
if (isSuspiciousEvent && eventRisk >= 12.0) {
|
||||
this.risk = RiskEngine.clamp(this.risk + eventRisk);
|
||||
} else {
|
||||
this.risk = Math.max(0.0, this.risk * 0.85);
|
||||
this.risk = Math.max(this.risk, eventRisk);
|
||||
}
|
||||
|
||||
this.lastUpdate = nowMillis;
|
||||
return this.risk;
|
||||
}
|
||||
|
||||
public synchronized double current(long nowMillis) {
|
||||
this.decayTo(nowMillis);
|
||||
return this.risk;
|
||||
}
|
||||
|
||||
public synchronized void reset() {
|
||||
this.risk = 0.0;
|
||||
this.lastUpdate = 0L;
|
||||
}
|
||||
|
||||
private void decayTo(long nowMillis) {
|
||||
if (this.lastUpdate == 0L) {
|
||||
this.lastUpdate = nowMillis;
|
||||
} else {
|
||||
long dt = nowMillis - this.lastUpdate;
|
||||
if (dt > 0L) {
|
||||
double factor = Math.pow(0.5, (double)dt / this.halfLifeMillis);
|
||||
this.risk *= factor;
|
||||
this.lastUpdate = nowMillis;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package net.synapselabs.anticheat.engine;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public record RiskAssessment(RiskAssessment.Verdict verdict, double risk, double eventRisk, List<RiskAssessment.Contribution> contributions) {
|
||||
public boolean isActionable() {
|
||||
return this.verdict == RiskAssessment.Verdict.CHEAT;
|
||||
}
|
||||
|
||||
public int riskPercent() {
|
||||
return (int)Math.round(Math.max(0.0, Math.min(100.0, this.risk)));
|
||||
}
|
||||
|
||||
public record Contribution(SignalType signal, double base, double confidence, Map<String, Double> modifiers, double contribution) {
|
||||
}
|
||||
|
||||
public enum Verdict {
|
||||
LEGIT,
|
||||
SUSPICIOUS,
|
||||
CHEAT;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package net.synapselabs.anticheat.engine;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import net.synapselabs.anticheat.engine.RiskAssessment.Contribution;
|
||||
import net.synapselabs.anticheat.engine.RiskAssessment.Verdict;
|
||||
|
||||
public final class RiskEngine {
|
||||
public static final double MODEL_TRUST = 0.5;
|
||||
public static final double MODEL_SCALE = 30.0;
|
||||
public static final double RISK_CLAMP = 100.0;
|
||||
public static final double DEFAULT_SUSPICIOUS = 20.0;
|
||||
public static final double DEFAULT_CHEAT = 60.0;
|
||||
public static final double DECAY = 0.85;
|
||||
private static final int REPEATED_REPLAY = 6;
|
||||
private final double suspiciousThreshold;
|
||||
private final double cheatThreshold;
|
||||
|
||||
public RiskEngine() {
|
||||
this(20.0, 60.0);
|
||||
}
|
||||
|
||||
public RiskEngine(double suspiciousThreshold, double cheatThreshold) {
|
||||
this.suspiciousThreshold = suspiciousThreshold;
|
||||
this.cheatThreshold = cheatThreshold;
|
||||
}
|
||||
|
||||
public List<Contribution> contributions(List<Signal> signals, CombatContext ctx, double modelPCheat) {
|
||||
List<Contribution> out = new ArrayList<>();
|
||||
|
||||
for (Signal s : signals) {
|
||||
if (s.type() != SignalType.AI_MODEL) {
|
||||
double base = s.baseWeight();
|
||||
double conf = s.type() == SignalType.REACH ? ContextEngine.reachConfidence(s.value(), ctx) : s.confidence();
|
||||
Map<String, Double> mods = ContextEngine.modifiersFor(s.type(), ctx);
|
||||
double factor = 1.0;
|
||||
|
||||
for (double f : mods.values()) {
|
||||
factor *= f;
|
||||
}
|
||||
|
||||
out.add(new Contribution(s.type(), base, conf, mods, base * conf * factor));
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, Double> aiMods = ContextEngine.modifiersFor(SignalType.AI_MODEL, ctx);
|
||||
double aiFactor = 1.0;
|
||||
|
||||
for (double f : aiMods.values()) {
|
||||
aiFactor *= f;
|
||||
}
|
||||
|
||||
double aiBase = modelPCheat * 30.0;
|
||||
out.add(new Contribution(SignalType.AI_MODEL, aiBase, 0.5, aiMods, aiBase * 0.5 * aiFactor));
|
||||
return out;
|
||||
}
|
||||
|
||||
public double eventRisk(List<Contribution> contributions) {
|
||||
double sum = 0.0;
|
||||
|
||||
for (Contribution c : contributions) {
|
||||
sum += c.contribution();
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
public Verdict verdictFor(double risk) {
|
||||
if (risk >= this.cheatThreshold) {
|
||||
return Verdict.CHEAT;
|
||||
} else {
|
||||
return risk >= this.suspiciousThreshold ? Verdict.SUSPICIOUS : Verdict.LEGIT;
|
||||
}
|
||||
}
|
||||
|
||||
public RiskAssessment assess(List<Signal> signals, CombatContext ctx, double modelPCheat, double aggregatedRisk) {
|
||||
List<Contribution> contribs = this.contributions(signals, ctx, modelPCheat);
|
||||
double ev = this.eventRisk(contribs);
|
||||
double risk = clamp(aggregatedRisk);
|
||||
Verdict verdict = this.verdictFor(risk);
|
||||
return new RiskAssessment(verdict, risk, ev, contribs);
|
||||
}
|
||||
|
||||
public RiskAssessment scoreScenario(List<Signal> signals, CombatContext ctx, double modelPCheat) {
|
||||
List<Contribution> contribs = this.contributions(signals, ctx, modelPCheat);
|
||||
double ev = this.eventRisk(contribs);
|
||||
double risk = ctx.repeatedPattern() ? aggregateRepeated(ev) : ev;
|
||||
risk = clamp(risk);
|
||||
return new RiskAssessment(this.verdictFor(risk), risk, ev, contribs);
|
||||
}
|
||||
|
||||
public static double aggregateRepeated(double eventRisk) {
|
||||
double acc = 0.0;
|
||||
|
||||
for (int i = 0; i < 6; i++) {
|
||||
acc = acc * 0.85 + eventRisk;
|
||||
}
|
||||
|
||||
return acc;
|
||||
}
|
||||
|
||||
public static double clamp(double risk) {
|
||||
return Math.max(0.0, Math.min(100.0, risk));
|
||||
}
|
||||
|
||||
public static void addDerivedSignals(List<Signal> signals, float angleOffsetDeg, float raycastAngleError, float yawDelta5t, float yawAccel, double distance) {
|
||||
if (angleOffsetDeg < 1.0F && raycastAngleError < 2.0F && distance >= 2.0 && Math.abs(yawDelta5t) > 20.0F) {
|
||||
signals.add(
|
||||
Signal.of(SignalType.AIM_CONSISTENCY, SignalType.AIM_CONSISTENCY.defaultConfidence(), angleOffsetDeg, "aim offset " + angleOffsetDeg + "°")
|
||||
);
|
||||
}
|
||||
|
||||
if (angleOffsetDeg < 8.0F && raycastAngleError < 6.0F && Math.abs(yawDelta5t) > 60.0F && yawAccel > 15.0F) {
|
||||
signals.add(
|
||||
Signal.of(
|
||||
SignalType.KINEMATIC_ROBOTIC, SignalType.KINEMATIC_ROBOTIC.defaultConfidence(), yawAccel, "no deceleration onto target (accel " + yawAccel + ")"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package net.synapselabs.anticheat.engine;
|
||||
|
||||
public final class SchemaVersions {
|
||||
public static final String FEATURE_SCHEMA_VERSION = "combat.v3";
|
||||
public static final String MODEL_VERSION_DEFAULT = "rf.calibrated.v2";
|
||||
public static final String DATASET_VERSION = "3.0";
|
||||
|
||||
private SchemaVersions() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package net.synapselabs.anticheat.engine;
|
||||
|
||||
public record Signal(SignalType type, double baseWeight, double confidence, double value, String detail) {
|
||||
public static Signal of(SignalType type) {
|
||||
return new Signal(type, type.baseWeight(), type.defaultConfidence(), Double.NaN, null);
|
||||
}
|
||||
|
||||
public static Signal of(SignalType type, double confidence, double value, String detail) {
|
||||
return new Signal(type, type.baseWeight(), confidence, value, detail);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package net.synapselabs.anticheat.engine;
|
||||
|
||||
public enum SignalType {
|
||||
HARD_SNAP(15.0, 0.9),
|
||||
HITBOX_MISS(8.0, 0.85),
|
||||
REACH(20.0, 1.0),
|
||||
AIM_CONSISTENCY(12.0, 0.8),
|
||||
KINEMATIC_ROBOTIC(10.0, 0.7),
|
||||
SILENT_ROTATION(14.0, 0.85),
|
||||
UNNATURAL_JERK(8.0, 0.75),
|
||||
PERFECT_COOLDOWN_SYNC(6.0, 0.65),
|
||||
AI_MODEL(0.0, 0.5);
|
||||
|
||||
private final double baseWeight;
|
||||
private final double defaultConfidence;
|
||||
|
||||
SignalType(double baseWeight, double defaultConfidence) {
|
||||
this.baseWeight = baseWeight;
|
||||
this.defaultConfidence = defaultConfidence;
|
||||
}
|
||||
|
||||
public double baseWeight() {
|
||||
return this.baseWeight;
|
||||
}
|
||||
|
||||
public double defaultConfidence() {
|
||||
return this.defaultConfidence;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
package net.synapselabs.anticheat.freeze;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import net.synapselabs.anticheat.AiAnticheatPlugin;
|
||||
import net.synapselabs.anticheat.compat.CompatUtils;
|
||||
import net.synapselabs.anticheat.lang.LanguageManager;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.block.BlockBreakEvent;
|
||||
import org.bukkit.event.block.BlockPlaceEvent;
|
||||
import org.bukkit.event.entity.EntityDamageByEntityEvent;
|
||||
import org.bukkit.event.player.AsyncPlayerChatEvent;
|
||||
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
|
||||
import org.bukkit.event.player.PlayerMoveEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
|
||||
public class FreezeManager implements Listener {
|
||||
private final AiAnticheatPlugin plugin;
|
||||
private final Map<UUID, Location> frozenLocations = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, Location> previousLocations = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, Long> cooldowns = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, UUID> suspectToModerator = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, UUID> moderatorToSuspect = new ConcurrentHashMap<>();
|
||||
|
||||
public FreezeManager(AiAnticheatPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
this.startWarningTask();
|
||||
}
|
||||
|
||||
public boolean isFrozen(UUID uuid) {
|
||||
return this.frozenLocations.containsKey(uuid);
|
||||
}
|
||||
|
||||
public boolean isModeratorChecking(UUID moderatorUuid) {
|
||||
return this.moderatorToSuspect.containsKey(moderatorUuid);
|
||||
}
|
||||
|
||||
public UUID getSuspectForModerator(UUID moderatorUuid) {
|
||||
return this.moderatorToSuspect.get(moderatorUuid);
|
||||
}
|
||||
|
||||
public String getDiscordUrl() {
|
||||
return this.plugin.getConfig().getString("discord.invite_url", "https://dsc.gg/synapselabs");
|
||||
}
|
||||
|
||||
public boolean hasCooldown(UUID targetUuid) {
|
||||
Long exp = this.cooldowns.get(targetUuid);
|
||||
return exp != null && System.currentTimeMillis() < exp;
|
||||
}
|
||||
|
||||
public long getRemainingCooldownSeconds(UUID targetUuid) {
|
||||
Long exp = this.cooldowns.get(targetUuid);
|
||||
if (exp == null) {
|
||||
return 0L;
|
||||
}
|
||||
|
||||
long diff = exp - System.currentTimeMillis();
|
||||
return Math.max(0L, (diff + 999L) / 1000L);
|
||||
}
|
||||
|
||||
public void applyCooldown(UUID targetUuid) {
|
||||
int cdSec = this.plugin.getConfig().getInt("freeze.cooldown_seconds", 3);
|
||||
this.cooldowns.put(targetUuid, System.currentTimeMillis() + cdSec * 1000L);
|
||||
}
|
||||
|
||||
public void setCustomFreezeLocation(Location loc) {
|
||||
this.plugin.getConfig().set("freeze.teleport.enabled", true);
|
||||
this.plugin.getConfig().set("freeze.teleport.use_custom_location", true);
|
||||
this.plugin.getConfig().set("freeze.teleport.custom_location.world", loc.getWorld().getName());
|
||||
this.plugin.getConfig().set("freeze.teleport.custom_location.x", loc.getX());
|
||||
this.plugin.getConfig().set("freeze.teleport.custom_location.y", loc.getY());
|
||||
this.plugin.getConfig().set("freeze.teleport.custom_location.z", loc.getZ());
|
||||
this.plugin.getConfig().set("freeze.teleport.custom_location.yaw", (double)loc.getYaw());
|
||||
this.plugin.getConfig().set("freeze.teleport.custom_location.pitch", (double)loc.getPitch());
|
||||
this.plugin.saveConfig();
|
||||
}
|
||||
|
||||
private Location getTargetFreezeLocation(Player player) {
|
||||
if (!this.plugin.getConfig().getBoolean("freeze.teleport.enabled", true)) {
|
||||
return player.getLocation();
|
||||
}
|
||||
|
||||
boolean useCustom = this.plugin.getConfig().getBoolean("freeze.teleport.use_custom_location", false);
|
||||
if (useCustom) {
|
||||
String worldName = this.plugin.getConfig().getString("freeze.teleport.custom_location.world", "world");
|
||||
World world = Bukkit.getWorld(worldName);
|
||||
if (world != null) {
|
||||
double x = this.plugin.getConfig().getDouble("freeze.teleport.custom_location.x", 0.5);
|
||||
double y = this.plugin.getConfig().getDouble("freeze.teleport.custom_location.y", 100.0);
|
||||
double z = this.plugin.getConfig().getDouble("freeze.teleport.custom_location.z", 0.5);
|
||||
float yaw = (float)this.plugin.getConfig().getDouble("freeze.teleport.custom_location.yaw", 0.0);
|
||||
float pitch = (float)this.plugin.getConfig().getDouble("freeze.teleport.custom_location.pitch", 0.0);
|
||||
return new Location(world, x, y, z, yaw, pitch);
|
||||
}
|
||||
}
|
||||
|
||||
return player.getWorld().getSpawnLocation().add(0.5, 0.0, 0.5);
|
||||
}
|
||||
|
||||
public boolean freeze(Player player, String reason, Player moderator) {
|
||||
UUID suspectId = player.getUniqueId();
|
||||
LanguageManager lang = this.plugin.getLanguageManager();
|
||||
if (this.hasCooldown(suspectId)) {
|
||||
if (moderator != null) {
|
||||
CompatUtils.sendMessage(
|
||||
moderator, lang.getMessage("freeze.cooldown_wait", moderator, new Object[]{"seconds", this.getRemainingCooldownSeconds(suspectId)})
|
||||
);
|
||||
}
|
||||
|
||||
return false;
|
||||
} else {
|
||||
this.applyCooldown(suspectId);
|
||||
this.previousLocations.put(suspectId, player.getLocation());
|
||||
Location targetLoc = this.getTargetFreezeLocation(player);
|
||||
player.teleport(targetLoc);
|
||||
this.frozenLocations.put(suspectId, targetLoc);
|
||||
if (moderator != null) {
|
||||
UUID modId = moderator.getUniqueId();
|
||||
this.suspectToModerator.put(suspectId, modId);
|
||||
this.moderatorToSuspect.put(modId, suspectId);
|
||||
CompatUtils.sendMessage(moderator, lang.getMessage("freeze.staff_start", moderator, new Object[]{"player", player.getName()}));
|
||||
}
|
||||
|
||||
String discordUrl = this.getDiscordUrl();
|
||||
String targetLang = lang.getPlayerLanguage(player);
|
||||
String displayReason = reason != null && !reason.isBlank() && !reason.equals("Inspection by Staff") && !reason.equals("Inspection by Admin")
|
||||
? reason
|
||||
: lang.getMessage("gui.freeze_reason", targetLang, new Object[0]);
|
||||
CompatUtils.playSound(player, "ENTITY_ELDER_GUARDIAN_CURSE", 1.0F, 1.0F);
|
||||
CompatUtils.sendTitle(
|
||||
player,
|
||||
lang.getMessage("freeze.title_frozen", targetLang, new Object[0]),
|
||||
lang.getMessage("freeze.subtitle_discord", targetLang, new Object[]{"discord_url", discordUrl}),
|
||||
10,
|
||||
80,
|
||||
20
|
||||
);
|
||||
CompatUtils.sendMessage(player, lang.getMessage("freeze.frozen_target", targetLang, new Object[]{"reason", displayReason, "discord_url", discordUrl}));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean unfreeze(Player player) {
|
||||
UUID suspectId = player.getUniqueId();
|
||||
LanguageManager lang = this.plugin.getLanguageManager();
|
||||
if (this.hasCooldown(suspectId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.applyCooldown(suspectId);
|
||||
this.frozenLocations.remove(suspectId);
|
||||
UUID modId = this.suspectToModerator.remove(suspectId);
|
||||
if (modId != null) {
|
||||
this.moderatorToSuspect.remove(modId);
|
||||
Player mod = Bukkit.getPlayer(modId);
|
||||
if (mod != null && mod.isOnline()) {
|
||||
CompatUtils.sendMessage(mod, lang.getMessage("freeze.staff_passed", mod, new Object[]{"player", player.getName()}));
|
||||
}
|
||||
}
|
||||
|
||||
boolean toSpawn = this.plugin.getConfig().getBoolean("freeze.teleport_to_spawn_on_pass", true);
|
||||
if (toSpawn) {
|
||||
Location spawnLoc = player.getWorld().getSpawnLocation().add(0.5, 0.0, 0.5);
|
||||
player.teleport(spawnLoc);
|
||||
} else {
|
||||
Location prev = this.previousLocations.remove(suspectId);
|
||||
if (prev != null) {
|
||||
player.teleport(prev);
|
||||
}
|
||||
}
|
||||
|
||||
this.previousLocations.remove(suspectId);
|
||||
String targetLang = lang.getPlayerLanguage(player);
|
||||
CompatUtils.playSound(player, "ENTITY_PLAYER_LEVELUP", 1.0F, 1.2F);
|
||||
CompatUtils.sendTitle(
|
||||
player,
|
||||
lang.getMessage("freeze.title_passed", targetLang, new Object[0]),
|
||||
lang.getMessage("freeze.subtitle_passed", targetLang, new Object[0]),
|
||||
10,
|
||||
60,
|
||||
15
|
||||
);
|
||||
CompatUtils.sendMessage(player, lang.getMessage("freeze.unfrozen_target", targetLang, new Object[0]));
|
||||
if (this.plugin.getDatasetManager() != null) {
|
||||
this.plugin.getDatasetManager().logConfirmedFalsePositive(suspectId, 180000L);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public void sendInterrogationMessage(Player sender, String message, boolean isModerator) {
|
||||
LanguageManager lang = this.plugin.getLanguageManager();
|
||||
UUID suspectId = isModerator ? this.moderatorToSuspect.get(sender.getUniqueId()) : sender.getUniqueId();
|
||||
UUID moderatorId = isModerator ? sender.getUniqueId() : this.suspectToModerator.get(sender.getUniqueId());
|
||||
Player suspect = suspectId != null ? Bukkit.getPlayer(suspectId) : null;
|
||||
Player moderator = moderatorId != null ? Bukkit.getPlayer(moderatorId) : null;
|
||||
if (suspect != null && suspect.isOnline()) {
|
||||
String suspectLang = lang.getPlayerLanguage(suspect);
|
||||
String roleTag = lang.getRaw(isModerator ? "freeze.role_moderator" : "freeze.role_suspect", suspectLang);
|
||||
String formatted = lang.getMessage(
|
||||
"freeze.interrogation_format", suspectLang, new Object[]{"role", roleTag, "sender", sender.getName(), "message", message}
|
||||
);
|
||||
suspect.sendMessage(formatted);
|
||||
CompatUtils.playSound(suspect, "ENTITY_EXPERIENCE_ORB_PICKUP", 0.8F, 1.2F);
|
||||
}
|
||||
|
||||
if (moderator != null && moderator.isOnline()) {
|
||||
String modLang = lang.getPlayerLanguage(moderator);
|
||||
String roleTag = lang.getRaw(isModerator ? "freeze.role_moderator" : "freeze.role_suspect", modLang);
|
||||
String formatted = lang.getMessage(
|
||||
"freeze.interrogation_format", modLang, new Object[]{"role", roleTag, "sender", sender.getName(), "message", message}
|
||||
);
|
||||
moderator.sendMessage(formatted);
|
||||
CompatUtils.playSound(moderator, "ENTITY_EXPERIENCE_ORB_PICKUP", 0.8F, 1.5F);
|
||||
}
|
||||
|
||||
for (Player staff : Bukkit.getOnlinePlayers()) {
|
||||
if (staff.hasPermission("aianticheat.admin") && staff != suspect && staff != moderator) {
|
||||
String staffLang = lang.getPlayerLanguage(staff);
|
||||
String roleTag = lang.getRaw(isModerator ? "freeze.role_moderator" : "freeze.role_suspect", staffLang);
|
||||
String formatted = lang.getMessage(
|
||||
"freeze.interrogation_format", staffLang, new Object[]{"role", roleTag, "sender", sender.getName(), "message", message}
|
||||
);
|
||||
staff.sendMessage(formatted);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
public void onChat(AsyncPlayerChatEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
UUID uuid = player.getUniqueId();
|
||||
if (this.isFrozen(uuid)) {
|
||||
event.setCancelled(true);
|
||||
this.sendInterrogationMessage(player, event.getMessage(), false);
|
||||
} else {
|
||||
if (this.isModeratorChecking(uuid)) {
|
||||
String msg = event.getMessage();
|
||||
if (msg.startsWith("!") || msg.startsWith("@")) {
|
||||
event.setCancelled(true);
|
||||
String cleanMsg = msg.substring(1).trim();
|
||||
if (!cleanMsg.isEmpty()) {
|
||||
this.sendInterrogationMessage(player, cleanMsg, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void startWarningTask() {
|
||||
Bukkit.getScheduler()
|
||||
.runTaskTimer(
|
||||
this.plugin,
|
||||
() -> {
|
||||
LanguageManager lang = this.plugin.getLanguageManager();
|
||||
String discordUrl = this.getDiscordUrl();
|
||||
|
||||
for (UUID id : this.frozenLocations.keySet()) {
|
||||
Player p = Bukkit.getPlayer(id);
|
||||
if (p != null && p.isOnline()) {
|
||||
CompatUtils.sendTitle(
|
||||
p,
|
||||
lang.getMessage("freeze.title_warning", p, new Object[0]),
|
||||
lang.getMessage("freeze.subtitle_discord", p, new Object[]{"discord_url", discordUrl}),
|
||||
0,
|
||||
40,
|
||||
10
|
||||
);
|
||||
CompatUtils.sendActionBar(p, lang.getMessage("freeze.actionbar_warning", p, new Object[0]));
|
||||
}
|
||||
}
|
||||
},
|
||||
30L,
|
||||
30L
|
||||
);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onMove(PlayerMoveEvent event) {
|
||||
UUID id = event.getPlayer().getUniqueId();
|
||||
if (this.frozenLocations.containsKey(id)) {
|
||||
Location from = event.getFrom();
|
||||
Location to = event.getTo();
|
||||
if (to != null && (from.getX() != to.getX() || from.getY() != to.getY() || from.getZ() != to.getZ())) {
|
||||
event.setTo(from.setDirection(to.getDirection()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
public void onDamage(EntityDamageByEntityEvent event) {
|
||||
if (event.getDamager() instanceof Player p && this.frozenLocations.containsKey(p.getUniqueId())) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
public void onBreak(BlockBreakEvent event) {
|
||||
if (this.frozenLocations.containsKey(event.getPlayer().getUniqueId())) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
public void onPlace(BlockPlaceEvent event) {
|
||||
if (this.frozenLocations.containsKey(event.getPlayer().getUniqueId())) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
public void onCommand(PlayerCommandPreprocessEvent event) {
|
||||
if (this.frozenLocations.containsKey(event.getPlayer().getUniqueId())) {
|
||||
String msg = event.getMessage().toLowerCase();
|
||||
if (!msg.startsWith("/msg") && !msg.startsWith("/r") && !msg.startsWith("/w")) {
|
||||
event.setCancelled(true);
|
||||
CompatUtils.sendMessage(event.getPlayer(), this.plugin.getLanguageManager().getMessage("freeze.command_blocked", event.getPlayer(), new Object[0]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onQuit(PlayerQuitEvent event) {
|
||||
UUID id = event.getPlayer().getUniqueId();
|
||||
if (this.frozenLocations.remove(id) != null) {
|
||||
this.previousLocations.remove(id);
|
||||
UUID modId = this.suspectToModerator.remove(id);
|
||||
if (modId != null) {
|
||||
this.moderatorToSuspect.remove(modId);
|
||||
}
|
||||
|
||||
String ip = event.getPlayer().getAddress() != null ? event.getPlayer().getAddress().getAddress().getHostAddress() : "127.0.0.1";
|
||||
this.plugin.getPunishmentManager().banForRefusingCheck(event.getPlayer().getName(), ip);
|
||||
LanguageManager lang = this.plugin.getLanguageManager();
|
||||
String defLang = lang.getPlayerLanguage(Bukkit.getConsoleSender());
|
||||
Bukkit.broadcastMessage(lang.getMessage("freeze.quit_ban_broadcast", defLang, new Object[]{"player", event.getPlayer().getName()}));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
package net.synapselabs.anticheat.gui;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import net.synapselabs.anticheat.AiAnticheatPlugin;
|
||||
import net.synapselabs.anticheat.compat.CompatUtils;
|
||||
import net.synapselabs.anticheat.data.PlayerDataManager;
|
||||
import net.synapselabs.anticheat.data.PlayerProfile;
|
||||
import net.synapselabs.anticheat.data.ThreatState;
|
||||
import net.synapselabs.anticheat.lang.LanguageManager;
|
||||
import net.synapselabs.anticheat.update.UpdateChecker.UpdateResult;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.inventory.meta.SkullMeta;
|
||||
|
||||
public class AdminGuiManager {
|
||||
private final AiAnticheatPlugin plugin;
|
||||
private final PlayerDataManager dataManager;
|
||||
|
||||
public AdminGuiManager(AiAnticheatPlugin plugin, PlayerDataManager dataManager) {
|
||||
this.plugin = plugin;
|
||||
this.dataManager = dataManager;
|
||||
}
|
||||
|
||||
public void openMainMenu(Player admin) {
|
||||
LanguageManager langMgr = this.plugin.getLanguageManager();
|
||||
String lang = langMgr != null ? langMgr.getPlayerLanguage(admin) : "en";
|
||||
String title = langMgr != null ? langMgr.getMessage("gui.main_title", lang, new Object[0]) : "Admin Dashboard | Synapse AI";
|
||||
Inventory inv = Bukkit.createInventory(null, 54, title);
|
||||
ItemStack border = createItem(Material.BLACK_STAINED_GLASS_PANE, " ");
|
||||
ItemStack cyanBorder = createItem(Material.CYAN_STAINED_GLASS_PANE, " ");
|
||||
ItemStack blueBorder = createItem(Material.BLUE_STAINED_GLASS_PANE, " ");
|
||||
|
||||
for (int i = 0; i < 9; i++) {
|
||||
inv.setItem(i, cyanBorder);
|
||||
inv.setItem(45 + i, blueBorder);
|
||||
}
|
||||
|
||||
for (int i = 0; i < 54; i += 9) {
|
||||
inv.setItem(i, border);
|
||||
inv.setItem(i + 8, border);
|
||||
}
|
||||
|
||||
String discordUrl = this.plugin.getConfig().getString("discord.invite_url", "https://dsc.gg/synapselabs");
|
||||
String grimStatus = this.plugin.getGrimAcBridge().isGrimLoaded()
|
||||
? (langMgr != null ? langMgr.getRaw("gui.grim_connected", lang) : "CONNECTED (HYBRID)")
|
||||
: (langMgr != null ? langMgr.getRaw("gui.grim_standalone", lang) : "STANDALONE");
|
||||
String topTitle = langMgr != null ? langMgr.getRaw("gui.top_title", lang) : "�d2ff&l\ud83e\udde0 Synapse AI-AntiCheat v3.0";
|
||||
String engineStr = langMgr != null ? langMgr.getRaw("gui.engine", lang) : "&fEngine: �d2ffONNX Runtime Machine Learning";
|
||||
String speedStr = langMgr != null ? langMgr.getRaw("gui.inference_speed", lang) : "&fInference latency: �ff88< 0.3 ms (RAM ThreadPool)";
|
||||
String grimStr = langMgr != null ? langMgr.getMessage("gui.grim_status", lang, new Object[]{"status", grimStatus}) : "&fGrimAC: " + grimStatus;
|
||||
String discStr = langMgr != null ? langMgr.getMessage("gui.discord", lang, new Object[]{"url", discordUrl}) : "&fDiscord: " + discordUrl;
|
||||
UpdateResult updateRes = this.plugin.getUpdateChecker() != null ? this.plugin.getUpdateChecker().getLastResult() : null;
|
||||
String updateStatusStr;
|
||||
if (updateRes != null && updateRes.isUpdateAvailable()) {
|
||||
updateStatusStr = langMgr != null
|
||||
? langMgr.getMessage("gui.update_status_available", lang, new Object[]{"latest", updateRes.getLatestVersion()})
|
||||
: "&#ffaa00v" + updateRes.getLatestVersion() + " AVAILABLE";
|
||||
} else {
|
||||
String ver = this.plugin.getDescription().getVersion();
|
||||
updateStatusStr = langMgr != null
|
||||
? langMgr.getMessage("gui.update_status_latest", lang, new Object[]{"version", ver})
|
||||
: "�ff88v" + ver + " (LATEST)";
|
||||
}
|
||||
|
||||
String updateLine = langMgr != null
|
||||
? langMgr.getMessage("gui.update_status", lang, new Object[]{"status", updateStatusStr})
|
||||
: "&fUpdates: " + updateStatusStr;
|
||||
String activeStr = langMgr != null ? langMgr.getRaw("gui.system_active", lang) : "�ff88✔ SYSTEM ACTIVE & PROTECTING SERVER";
|
||||
inv.setItem(
|
||||
4,
|
||||
createItem(
|
||||
Material.NETHER_STAR,
|
||||
topTitle,
|
||||
"&7&m----------------------------------------",
|
||||
engineStr,
|
||||
speedStr,
|
||||
grimStr,
|
||||
discStr,
|
||||
updateLine,
|
||||
"&7&m----------------------------------------",
|
||||
activeStr
|
||||
)
|
||||
);
|
||||
String threatTitle = langMgr != null ? langMgr.getRaw("gui.threat_info_title", lang) : "&#ffa500&l⚡ AI Architecture & Threat Levels";
|
||||
String cleanDesc = langMgr != null ? langMgr.getRaw("gui.threat_clean", lang) : "�ff88✔ CLEAN (0-24%)";
|
||||
String suspDesc = langMgr != null ? langMgr.getRaw("gui.threat_suspicious", lang) : "&#ffaa00⚠ SUSPICIOUS (25-59%)";
|
||||
String cheatDesc = langMgr != null ? langMgr.getRaw("gui.threat_cheat", lang) : "&#ff2244⚡ CHEAT (60-100%)";
|
||||
inv.setItem(
|
||||
49,
|
||||
createItem(
|
||||
Material.COMPASS,
|
||||
threatTitle,
|
||||
"&7&m----------------------------------------",
|
||||
cleanDesc,
|
||||
suspDesc,
|
||||
cheatDesc,
|
||||
"&7&m----------------------------------------"
|
||||
)
|
||||
);
|
||||
int slot = 10;
|
||||
|
||||
for (Player p : Bukkit.getOnlinePlayers()) {
|
||||
if (slot >= 44) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (slot % 9 == 8) {
|
||||
slot += 2;
|
||||
}
|
||||
|
||||
PlayerProfile profile = this.dataManager.getOrCreate(p);
|
||||
int kScore = Math.round(profile.getKillauraConfidence() * 100.0F);
|
||||
int aScore = Math.round(profile.getAimConfidence() * 100.0F);
|
||||
ThreatState state = profile.getThreatState();
|
||||
int alts = this.dataManager.getAltCount(profile.getLastIp());
|
||||
boolean hasBanned = this.dataManager.hasBannedAccountsOnIp(profile.getLastIp());
|
||||
int ping = p.getPing();
|
||||
String pingColor = ping < 60 ? "�ff88" : (ping < 130 ? "&#ffaa00" : "&#ff2244");
|
||||
String bannedStatus = hasBanned
|
||||
? (langMgr != null ? langMgr.getRaw("gui.banned_yes", lang) : "&#ff2244&lYES")
|
||||
: (langMgr != null ? langMgr.getRaw("gui.banned_no", lang) : "�ff88NO");
|
||||
String threatTag = langMgr != null ? langMgr.getRaw(state.messageKey(), lang) : state.getDisplayTag();
|
||||
ItemStack skull = new ItemStack(Material.PLAYER_HEAD);
|
||||
SkullMeta meta = (SkullMeta)skull.getItemMeta();
|
||||
if (meta != null) {
|
||||
meta.setOwningPlayer(p);
|
||||
meta.setDisplayName(CompatUtils.color("&#ffa500&l" + p.getName()));
|
||||
List<String> lore = new ArrayList<>();
|
||||
lore.add(CompatUtils.color("&7&m----------------------------------------"));
|
||||
lore.add(
|
||||
CompatUtils.color(langMgr != null ? langMgr.getMessage("gui.player_threat", lang, new Object[]{"state", threatTag}) : "&7• Status: " + threatTag)
|
||||
);
|
||||
lore.add(
|
||||
CompatUtils.color(
|
||||
langMgr != null
|
||||
? langMgr.getMessage(
|
||||
"gui.player_killaura", lang, new Object[]{"bar", renderBar(kScore, 10, "&#ff2244", "&#ffaa00", "�ff88"), "score", kScore}
|
||||
)
|
||||
: "&7• Killaura: " + kScore + "%"
|
||||
)
|
||||
);
|
||||
lore.add(
|
||||
CompatUtils.color(
|
||||
langMgr != null
|
||||
? langMgr.getMessage(
|
||||
"gui.player_aim", lang, new Object[]{"bar", renderBar(aScore, 10, "&#ff2244", "&#ffaa00", "�ff88"), "score", aScore}
|
||||
)
|
||||
: "&7• Aim Assist: " + aScore + "%"
|
||||
)
|
||||
);
|
||||
lore.add(
|
||||
CompatUtils.color(
|
||||
langMgr != null ? langMgr.getMessage("gui.player_ping", lang, new Object[]{"color", pingColor, "ping", ping}) : "&7• Ping: " + ping + "ms"
|
||||
)
|
||||
);
|
||||
lore.add(
|
||||
CompatUtils.color(
|
||||
langMgr != null ? langMgr.getMessage("gui.player_ip", lang, new Object[]{"ip", profile.getLastIp()}) : "&7• IP: " + profile.getLastIp()
|
||||
)
|
||||
);
|
||||
lore.add(
|
||||
CompatUtils.color(
|
||||
langMgr != null
|
||||
? langMgr.getMessage("gui.player_alts", lang, new Object[]{"color", alts > 1 ? "&#ffaa00" : "�ff88", "alts", alts})
|
||||
: "&7• Alts: " + alts
|
||||
)
|
||||
);
|
||||
lore.add(
|
||||
CompatUtils.color(
|
||||
langMgr != null
|
||||
? langMgr.getMessage("gui.player_banned_on_ip", lang, new Object[]{"status", bannedStatus})
|
||||
: "&7• Banned on IP: " + bannedStatus
|
||||
)
|
||||
);
|
||||
lore.add(
|
||||
CompatUtils.color(
|
||||
langMgr != null
|
||||
? langMgr.getMessage(
|
||||
"gui.player_flags", lang, new Object[]{"total", profile.getTotalFlags(), "hard", profile.getHardFlags(), "ai", profile.getAiFlags()}
|
||||
)
|
||||
: "&7• Total flags: " + profile.getTotalFlags()
|
||||
)
|
||||
);
|
||||
lore.add(
|
||||
CompatUtils.color(
|
||||
langMgr != null
|
||||
? langMgr.getMessage("gui.player_last_flag", lang, new Object[]{"reason", profile.getLastFlagReason()})
|
||||
: "&7• Last flag: " + profile.getLastFlagReason()
|
||||
)
|
||||
);
|
||||
lore.add(" ");
|
||||
lore.add(CompatUtils.color(langMgr != null ? langMgr.getRaw("gui.player_click_inspect", lang) : "�ff88▶ Click to open player dossier"));
|
||||
lore.add(CompatUtils.color("&7&m----------------------------------------"));
|
||||
meta.setLore(lore);
|
||||
skull.setItemMeta(meta);
|
||||
}
|
||||
|
||||
inv.setItem(slot++, skull);
|
||||
}
|
||||
|
||||
admin.openInventory(inv);
|
||||
}
|
||||
|
||||
public void openInspectMenu(Player admin, Player target) {
|
||||
LanguageManager langMgr = this.plugin.getLanguageManager();
|
||||
String lang = langMgr != null ? langMgr.getPlayerLanguage(admin) : "en";
|
||||
PlayerProfile profile = this.dataManager.getOrCreate(target);
|
||||
int ping = target.getPing();
|
||||
String pingColor = ping < 60 ? "�ff88" : (ping < 130 ? "&#ffaa00" : "&#ff2244");
|
||||
boolean isFrozen = this.plugin.getFreezeManager().isFrozen(target.getUniqueId());
|
||||
int kScore = Math.round(profile.getKillauraConfidence() * 100.0F);
|
||||
int aScore = Math.round(profile.getAimConfidence() * 100.0F);
|
||||
int suspScore = Math.round(profile.getSuspicion() * 100.0F);
|
||||
ThreatState state = profile.getThreatState();
|
||||
String threatTag = langMgr != null ? langMgr.getRaw(state.messageKey(), lang) : state.getDisplayTag();
|
||||
String freezeStatus = isFrozen
|
||||
? (langMgr != null ? langMgr.getRaw("gui.freeze_frozen", lang) : "&#ff2244&lFROZEN")
|
||||
: (langMgr != null ? langMgr.getRaw("gui.freeze_free", lang) : "�ff88FREE");
|
||||
String title = langMgr != null
|
||||
? langMgr.getMessage("gui.inspect_title", lang, new Object[]{"player", target.getName()})
|
||||
: "�d2ff[Dossier] &#ffa500" + target.getName();
|
||||
Inventory inv = Bukkit.createInventory(null, 36, title);
|
||||
ItemStack border = createItem(Material.GRAY_STAINED_GLASS_PANE, " ");
|
||||
|
||||
for (int i = 0; i < 36; i++) {
|
||||
inv.setItem(i, border);
|
||||
}
|
||||
|
||||
ItemStack skull = new ItemStack(Material.PLAYER_HEAD);
|
||||
SkullMeta meta = (SkullMeta)skull.getItemMeta();
|
||||
if (meta != null) {
|
||||
meta.setOwningPlayer(target);
|
||||
meta.setDisplayName(CompatUtils.color("&#ffa500&l" + target.getName()));
|
||||
List<String> lore = new ArrayList<>();
|
||||
lore.add(
|
||||
CompatUtils.color(
|
||||
langMgr != null
|
||||
? langMgr.getMessage("gui.inspect_first_join", lang, new Object[]{"time", profile.getFormattedFirstJoin()})
|
||||
: "&7• First login: " + profile.getFormattedFirstJoin()
|
||||
)
|
||||
);
|
||||
lore.add(
|
||||
CompatUtils.color(
|
||||
langMgr != null ? langMgr.getMessage("gui.inspect_ip", lang, new Object[]{"ip", profile.getLastIp()}) : "&7• IP: " + profile.getLastIp()
|
||||
)
|
||||
);
|
||||
lore.add(
|
||||
CompatUtils.color(langMgr != null ? langMgr.getMessage("gui.inspect_status", lang, new Object[]{"state", threatTag}) : "&7• Status: " + threatTag)
|
||||
);
|
||||
lore.add(
|
||||
CompatUtils.color(
|
||||
langMgr != null ? langMgr.getMessage("gui.inspect_freeze_state", lang, new Object[]{"state", freezeStatus}) : "&7• Freeze: " + freezeStatus
|
||||
)
|
||||
);
|
||||
meta.setLore(lore);
|
||||
skull.setItemMeta(meta);
|
||||
}
|
||||
|
||||
inv.setItem(4, skull);
|
||||
List<PlayerProfile> alts = this.dataManager.getAccountsOnIp(profile.getLastIp());
|
||||
List<String> altLore = new ArrayList<>();
|
||||
altLore.add(
|
||||
langMgr != null
|
||||
? langMgr.getMessage("gui.inspect_alts_header", lang, new Object[]{"ip", profile.getLastIp()})
|
||||
: "&7All accounts on IP " + profile.getLastIp() + ":"
|
||||
);
|
||||
|
||||
for (PlayerProfile alt : alts) {
|
||||
String bStatus = alt.isBanned() ? (lang.equals("ru") ? "&c[ЗАБАНЕН]" : "&c[BANNED]") : (lang.equals("ru") ? "&a[ЧИСТЫЙ]" : "&a[CLEAN]");
|
||||
altLore.add("&7• &f" + alt.getName() + " " + bStatus + " &8(" + alt.getFormattedFirstJoin() + ")");
|
||||
}
|
||||
|
||||
String altsTitle = langMgr != null
|
||||
? langMgr.getMessage("gui.inspect_alts_title", lang, new Object[]{"count", alts.size()})
|
||||
: "&#ffa500&l\ud83c\udf10 Known Accounts (" + alts.size() + ")";
|
||||
inv.setItem(10, createItem(Material.BOOKSHELF, altsTitle, altLore.toArray(new String[0])));
|
||||
String diagTitle = langMgr != null ? langMgr.getRaw("gui.inspect_combat_diag", lang) : "�d2ff&l\ud83c\udfaf AI Combat Diagnostics";
|
||||
inv.setItem(
|
||||
12,
|
||||
createItem(
|
||||
Material.TARGET,
|
||||
diagTitle,
|
||||
langMgr != null
|
||||
? langMgr.getMessage(
|
||||
"gui.player_killaura", lang, new Object[]{"bar", renderBar(kScore, 10, "&#ff2244", "&#ffaa00", "�ff88"), "score", kScore}
|
||||
)
|
||||
: "&7• Killaura: " + kScore + "%",
|
||||
langMgr != null
|
||||
? langMgr.getMessage("gui.player_aim", lang, new Object[]{"bar", renderBar(aScore, 10, "&#ff2244", "&#ffaa00", "�ff88"), "score", aScore})
|
||||
: "&7• Aim Assist: " + aScore + "%",
|
||||
langMgr != null
|
||||
? langMgr.getMessage(
|
||||
"gui.player_risk", lang, new Object[]{"bar", renderBar(suspScore, 10, "&#ff2244", "&#ffaa00", "�ff88"), "score", suspScore}
|
||||
)
|
||||
: "&7• Risk: " + suspScore + "%",
|
||||
"&7• Hard: �d2ff" + profile.getHardFlags(),
|
||||
"&7• AI: &#ff7700" + profile.getAiFlags(),
|
||||
"&7• GrimAC: &bdf8" + profile.getGrimFlagsCount(),
|
||||
langMgr != null
|
||||
? langMgr.getMessage("gui.player_last_flag", lang, new Object[]{"reason", profile.getLastFlagReason()})
|
||||
: "&7• Last Flag: " + profile.getLastFlagReason()
|
||||
)
|
||||
);
|
||||
String quality = ping < 100
|
||||
? (langMgr != null ? langMgr.getRaw("gui.network_stable", lang) : "�ff88Stable")
|
||||
: (langMgr != null ? langMgr.getRaw("gui.network_lag", lang) : "&#ffaa00High Jitter / Lag");
|
||||
String netTitle = langMgr != null ? langMgr.getRaw("gui.inspect_network_diag", lang) : "�d2ff&l\ud83d\udcf6 Network Diagnostics";
|
||||
inv.setItem(
|
||||
14,
|
||||
createItem(
|
||||
Material.CLOCK,
|
||||
netTitle,
|
||||
langMgr != null ? langMgr.getMessage("gui.player_ping", lang, new Object[]{"color", pingColor, "ping", ping}) : "&7• Ping: " + ping + "ms",
|
||||
langMgr != null ? langMgr.getMessage("gui.inspect_network_quality", lang, new Object[]{"quality", quality}) : "&7• Quality: " + quality,
|
||||
"&7• TPS: �ff8820.0",
|
||||
"&7• GrimAC Sync: �ff88" + (this.plugin.getGrimAcBridge().isGrimLoaded() ? "OK" : "N/A")
|
||||
)
|
||||
);
|
||||
if (isFrozen) {
|
||||
String unfreezeBtn = langMgr != null ? langMgr.getRaw("gui.inspect_btn_unfreeze", lang) : "�ff88&l\ud83d\udd13 Unfreeze Player";
|
||||
String unfreezeLore = langMgr != null ? langMgr.getRaw("gui.inspect_btn_unfreeze_lore", lang) : "&7Finish inspection and send to spawn.";
|
||||
inv.setItem(16, createItem(Material.PACKED_ICE, unfreezeBtn, unfreezeLore));
|
||||
} else {
|
||||
String freezeBtn = langMgr != null ? langMgr.getRaw("gui.inspect_btn_freeze", lang) : "�d2ff&l❄️ Call for Inspection";
|
||||
String freezeLore = langMgr != null ? langMgr.getRaw("gui.inspect_btn_freeze_lore", lang) : "&7Teleport to inspection room and freeze movements.";
|
||||
inv.setItem(16, createItem(Material.ICE, freezeBtn, freezeLore));
|
||||
}
|
||||
|
||||
String resetBtn = langMgr != null ? langMgr.getRaw("gui.inspect_btn_reset", lang) : "�ff88&l⚡ Reset Flags";
|
||||
String resetLore = langMgr != null ? langMgr.getRaw("gui.inspect_btn_reset_lore", lang) : "&7Clear flags and suspicion.";
|
||||
inv.setItem(28, createItem(Material.GOLDEN_APPLE, resetBtn, resetLore));
|
||||
String spectateBtn = langMgr != null ? langMgr.getRaw("gui.inspect_btn_spectate", lang) : "&#a855f7&l\ud83d\udc41️ Spectate";
|
||||
String spectateLore = langMgr != null ? langMgr.getRaw("gui.inspect_btn_spectate_lore", lang) : "&7Watch player in first person mode.";
|
||||
inv.setItem(30, createItem(Material.ENDER_EYE, spectateBtn, spectateLore));
|
||||
String kickBtn = langMgr != null ? langMgr.getRaw("gui.inspect_btn_kick", lang) : "&#ffaa00&l\ud83d\udeab Kick Player";
|
||||
String kickLore = langMgr != null ? langMgr.getRaw("gui.inspect_btn_kick_lore", lang) : "&7Disconnect suspect from server.";
|
||||
inv.setItem(32, createItem(Material.BARRIER, kickBtn, kickLore));
|
||||
String banBtn = langMgr != null ? langMgr.getRaw("gui.inspect_btn_ban", lang) : "&#ff2244&l\ud83d\udd28 Ban Account";
|
||||
String banLore = langMgr != null ? langMgr.getRaw("gui.inspect_btn_ban_lore", lang) : "&7Issue ban via punishment system.";
|
||||
inv.setItem(34, createItem(Material.ANVIL, banBtn, banLore));
|
||||
String backBtn = langMgr != null ? langMgr.getRaw("gui.inspect_btn_back", lang) : "&#ffa500&l⬅️ Back to Menu";
|
||||
inv.setItem(35, createItem(Material.ARROW, backBtn));
|
||||
admin.openInventory(inv);
|
||||
}
|
||||
|
||||
public static String renderBar(int percent, int totalBars, String dangerColor, String warningColor, String safeColor) {
|
||||
int filled = (int)Math.round(percent / 100.0 * totalBars);
|
||||
String color = percent >= 70 ? dangerColor : (percent >= 40 ? warningColor : safeColor);
|
||||
StringBuilder sb = new StringBuilder("&8[");
|
||||
sb.append(color);
|
||||
|
||||
for (int i = 0; i < totalBars; i++) {
|
||||
if (i < filled) {
|
||||
sb.append("█");
|
||||
} else {
|
||||
sb.append("&7░");
|
||||
}
|
||||
}
|
||||
|
||||
sb.append("&8]");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static ItemStack createItem(Material mat, String name, String... lore) {
|
||||
ItemStack item = new ItemStack(mat);
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
if (meta != null) {
|
||||
meta.setDisplayName(CompatUtils.color(name));
|
||||
if (lore != null && lore.length > 0) {
|
||||
List<String> list = new ArrayList<>();
|
||||
|
||||
for (String s : lore) {
|
||||
if (s != null) {
|
||||
list.add(CompatUtils.color(s));
|
||||
}
|
||||
}
|
||||
|
||||
meta.setLore(list);
|
||||
}
|
||||
|
||||
item.setItemMeta(meta);
|
||||
}
|
||||
|
||||
return item;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package net.synapselabs.anticheat.gui;
|
||||
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
|
||||
public class AdminMainMenuHolder implements InventoryHolder {
|
||||
private Inventory inventory;
|
||||
|
||||
public void setInventory(Inventory inventory) {
|
||||
this.inventory = inventory;
|
||||
}
|
||||
|
||||
public Inventory getInventory() {
|
||||
return this.inventory;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package net.synapselabs.anticheat.gui;
|
||||
|
||||
import net.synapselabs.anticheat.AiAnticheatPlugin;
|
||||
import net.synapselabs.anticheat.compat.CompatUtils;
|
||||
import net.synapselabs.anticheat.data.PlayerProfile;
|
||||
import net.synapselabs.anticheat.data.ThreatState;
|
||||
import net.synapselabs.anticheat.lang.LanguageManager;
|
||||
import net.synapselabs.anticheat.tracker.CombatTracker;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.GameMode;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.SkullMeta;
|
||||
|
||||
public class GuiListener implements Listener {
|
||||
private final AiAnticheatPlugin plugin;
|
||||
|
||||
public GuiListener(AiAnticheatPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onInventoryClick(InventoryClickEvent event) {
|
||||
if (event.getWhoClicked() instanceof Player admin) {
|
||||
String rawTitle = event.getView().getTitle();
|
||||
String plainTitle = ChatColor.stripColor(rawTitle);
|
||||
boolean isMainMenu = plainTitle.contains("Панель Администратора") || plainTitle.contains("Admin Dashboard") || plainTitle.contains("Synapse AI");
|
||||
boolean isInspectMenu = plainTitle.contains("Досье")
|
||||
|| plainTitle.contains("Dossier")
|
||||
|| plainTitle.contains("[Досье]")
|
||||
|| plainTitle.contains("[Dossier]");
|
||||
LanguageManager langMgr = this.plugin.getLanguageManager();
|
||||
String lang = langMgr != null ? langMgr.getPlayerLanguage(admin) : "en";
|
||||
if (isMainMenu) {
|
||||
event.setCancelled(true);
|
||||
ItemStack clicked = event.getCurrentItem();
|
||||
if (clicked == null || clicked.getType() == Material.AIR) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (clicked.getType() == Material.PLAYER_HEAD && clicked.getItemMeta() instanceof SkullMeta meta) {
|
||||
if (meta.getOwningPlayer() != null && meta.getOwningPlayer().getPlayer() != null) {
|
||||
Player target = meta.getOwningPlayer().getPlayer();
|
||||
this.plugin.getGuiManager().openInspectMenu(admin, target);
|
||||
} else if (meta.hasDisplayName()) {
|
||||
String cleanName = ChatColor.stripColor(meta.getDisplayName()).trim();
|
||||
Player target = Bukkit.getPlayer(cleanName);
|
||||
if (target != null) {
|
||||
this.plugin.getGuiManager().openInspectMenu(admin, target);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (isInspectMenu) {
|
||||
event.setCancelled(true);
|
||||
ItemStack clicked = event.getCurrentItem();
|
||||
if (clicked == null || clicked.getType() == Material.AIR) {
|
||||
return;
|
||||
}
|
||||
|
||||
Player target = null;
|
||||
Inventory inv = event.getInventory();
|
||||
ItemStack headItem = inv.getItem(4);
|
||||
if (headItem != null && headItem.getItemMeta() instanceof SkullMeta meta && meta.getOwningPlayer() != null) {
|
||||
target = meta.getOwningPlayer().getPlayer();
|
||||
}
|
||||
|
||||
if (target == null) {
|
||||
String targetName = plainTitle.replace("[Досье]", "")
|
||||
.replace("[Dossier]", "")
|
||||
.replace("Досье", "")
|
||||
.replace("Dossier", "")
|
||||
.replace("|", "")
|
||||
.trim();
|
||||
target = Bukkit.getPlayerExact(targetName);
|
||||
if (target == null) {
|
||||
target = Bukkit.getPlayer(targetName);
|
||||
}
|
||||
}
|
||||
|
||||
if (target == null && clicked.getType() != Material.ARROW) {
|
||||
String offlineMsg = langMgr != null ? langMgr.getMessage("gui.target_offline", lang, new Object[0]) : "Target player is offline.";
|
||||
CompatUtils.sendMessage(admin, offlineMsg);
|
||||
admin.closeInventory();
|
||||
return;
|
||||
}
|
||||
|
||||
Material mat = clicked.getType();
|
||||
switch (mat) {
|
||||
case ARROW:
|
||||
this.plugin.getGuiManager().openMainMenu(admin);
|
||||
break;
|
||||
case GOLDEN_APPLE:
|
||||
if (target != null) {
|
||||
PlayerProfile profile = this.plugin.getDataManager().getOrCreate(target);
|
||||
profile.resetFlags();
|
||||
CombatTracker tracker = this.plugin.getCombatListener().getTracker(target.getUniqueId());
|
||||
if (tracker != null) {
|
||||
tracker.reset();
|
||||
}
|
||||
|
||||
this.plugin.getOverheadDisplayManager().updateDisplay(target.getUniqueId(), 0, 0, ThreatState.CLEAN);
|
||||
String resetMsg = langMgr != null
|
||||
? langMgr.getMessage("gui.flags_reset", lang, new Object[]{"player", target.getName()})
|
||||
: "Flags and suspicion reset for " + target.getName();
|
||||
CompatUtils.sendMessage(admin, resetMsg);
|
||||
this.plugin.getGuiManager().openInspectMenu(admin, target);
|
||||
}
|
||||
break;
|
||||
case ICE:
|
||||
case PACKED_ICE:
|
||||
if (target != null) {
|
||||
if (this.plugin.getFreezeManager().isFrozen(target.getUniqueId())) {
|
||||
if (this.plugin.getFreezeManager().unfreeze(target)) {
|
||||
String unfreezeStaff = langMgr != null
|
||||
? langMgr.getMessage("freeze.unfrozen_staff", lang, new Object[]{"player", target.getName()})
|
||||
: "Player " + target.getName() + " unfrozen.";
|
||||
CompatUtils.sendMessage(admin, unfreezeStaff);
|
||||
} else {
|
||||
String waitMsg = langMgr != null
|
||||
? langMgr.getMessage(
|
||||
"freeze.cooldown_wait",
|
||||
lang,
|
||||
new Object[]{"seconds", this.plugin.getFreezeManager().getRemainingCooldownSeconds(target.getUniqueId())}
|
||||
)
|
||||
: "Please wait before repeating this action.";
|
||||
CompatUtils.sendMessage(admin, waitMsg);
|
||||
}
|
||||
} else {
|
||||
String freezeReason = langMgr != null ? langMgr.getMessage("gui.freeze_reason", lang, new Object[0]) : "Inspection by Admin";
|
||||
if (this.plugin.getFreezeManager().freeze(target, freezeReason, admin)) {
|
||||
String frozenStaff = langMgr != null
|
||||
? langMgr.getMessage("freeze.frozen_staff", lang, new Object[]{"player", target.getName()})
|
||||
: "Player " + target.getName() + " frozen for inspection.";
|
||||
CompatUtils.sendMessage(admin, frozenStaff);
|
||||
} else {
|
||||
String waitMsg = langMgr != null
|
||||
? langMgr.getMessage(
|
||||
"freeze.cooldown_wait",
|
||||
lang,
|
||||
new Object[]{"seconds", this.plugin.getFreezeManager().getRemainingCooldownSeconds(target.getUniqueId())}
|
||||
)
|
||||
: "Please wait before repeating this action.";
|
||||
CompatUtils.sendMessage(admin, waitMsg);
|
||||
}
|
||||
}
|
||||
|
||||
this.plugin.getGuiManager().openInspectMenu(admin, target);
|
||||
}
|
||||
break;
|
||||
case ENDER_EYE:
|
||||
if (target != null) {
|
||||
admin.setGameMode(GameMode.SPECTATOR);
|
||||
admin.teleport(target.getLocation());
|
||||
String specMsg = langMgr != null
|
||||
? langMgr.getMessage("gui.spectate_msg", lang, new Object[]{"player", target.getName()})
|
||||
: "Spectating " + target.getName();
|
||||
CompatUtils.sendMessage(admin, specMsg);
|
||||
admin.closeInventory();
|
||||
}
|
||||
break;
|
||||
case BARRIER:
|
||||
if (target != null) {
|
||||
String kickClient = langMgr != null ? langMgr.getMessage("gui.kick_msg", lang, new Object[0]) : "Disconnected by admin.";
|
||||
target.kickPlayer(CompatUtils.color(kickClient));
|
||||
String kickAdmin = langMgr != null
|
||||
? langMgr.getMessage("gui.kick_admin", lang, new Object[]{"player", target.getName()})
|
||||
: "Player " + target.getName() + " kicked.";
|
||||
CompatUtils.sendMessage(admin, kickAdmin);
|
||||
this.plugin.getGuiManager().openMainMenu(admin);
|
||||
}
|
||||
break;
|
||||
case ANVIL:
|
||||
if (target != null) {
|
||||
PlayerProfile profile = this.plugin.getDataManager().getOrCreate(target);
|
||||
profile.setBanned(true);
|
||||
this.plugin.getDataManager().saveDatabase();
|
||||
String banReason = langMgr != null ? langMgr.getMessage("gui.ban_reason", lang, new Object[0]) : "Cheating";
|
||||
this.plugin.getPunishmentManager().banPlayer(target, banReason, admin.getName(), false);
|
||||
String banAdmin = langMgr != null
|
||||
? langMgr.getMessage(
|
||||
"gui.ban_admin",
|
||||
lang,
|
||||
new Object[]{"player", target.getName(), "system", this.plugin.getPunishmentManager().getActivePlugin().getDisplay()}
|
||||
)
|
||||
: "Player " + target.getName() + " banned.";
|
||||
CompatUtils.sendMessage(admin, banAdmin);
|
||||
this.plugin.getGuiManager().openMainMenu(admin);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package net.synapselabs.anticheat.gui;
|
||||
|
||||
import java.util.UUID;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
|
||||
public class InspectMenuHolder implements InventoryHolder {
|
||||
private final UUID targetId;
|
||||
private final String targetName;
|
||||
private Inventory inventory;
|
||||
|
||||
public InspectMenuHolder(UUID targetId, String targetName) {
|
||||
this.targetId = targetId;
|
||||
this.targetName = targetName;
|
||||
}
|
||||
|
||||
public UUID getTargetId() {
|
||||
return this.targetId;
|
||||
}
|
||||
|
||||
public String getTargetName() {
|
||||
return this.targetName;
|
||||
}
|
||||
|
||||
public void setInventory(Inventory inventory) {
|
||||
this.inventory = inventory;
|
||||
}
|
||||
|
||||
public Inventory getInventory() {
|
||||
return this.inventory;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package net.synapselabs.anticheat.lang;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import net.md_5.bungee.api.chat.TextComponent;
|
||||
import net.synapselabs.anticheat.AiAnticheatPlugin;
|
||||
import net.synapselabs.anticheat.compat.CompatUtils;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class LanguageManager {
|
||||
private static final String PLAYER_LANG_FILE = "player_languages.yml";
|
||||
private final AiAnticheatPlugin plugin;
|
||||
private final Map<String, YamlConfiguration> langConfigs = new HashMap<>();
|
||||
private final Map<UUID, String> playerLanguages = new ConcurrentHashMap<>();
|
||||
private String defaultLanguage = "en";
|
||||
|
||||
public LanguageManager(AiAnticheatPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
this.reload();
|
||||
}
|
||||
|
||||
public void reload() {
|
||||
this.langConfigs.clear();
|
||||
this.defaultLanguage = this.plugin.getConfig().getString("language", "en").toLowerCase();
|
||||
this.saveDefaultLangFile("messages_en.yml");
|
||||
this.saveDefaultLangFile("messages_ru.yml");
|
||||
this.loadLangFile("en", "messages_en.yml");
|
||||
this.loadLangFile("ru", "messages_ru.yml");
|
||||
this.loadPlayerLanguages();
|
||||
}
|
||||
|
||||
private void saveDefaultLangFile(String filename) {
|
||||
File file = new File(this.plugin.getDataFolder(), filename);
|
||||
if (!file.exists()) {
|
||||
this.plugin.saveResource(filename, false);
|
||||
}
|
||||
}
|
||||
|
||||
private void loadLangFile(String langCode, String filename) {
|
||||
File file = new File(this.plugin.getDataFolder(), filename);
|
||||
YamlConfiguration config;
|
||||
if (file.exists()) {
|
||||
config = YamlConfiguration.loadConfiguration(file);
|
||||
} else {
|
||||
InputStream stream = this.plugin.getResource(filename);
|
||||
if (stream != null) {
|
||||
config = YamlConfiguration.loadConfiguration(new InputStreamReader(stream, StandardCharsets.UTF_8));
|
||||
} else {
|
||||
config = new YamlConfiguration();
|
||||
}
|
||||
}
|
||||
|
||||
this.langConfigs.put(langCode.toLowerCase(), config);
|
||||
}
|
||||
|
||||
public String getPlayerLanguage(CommandSender sender) {
|
||||
return sender instanceof Player p ? this.playerLanguages.getOrDefault(p.getUniqueId(), this.defaultLanguage) : this.defaultLanguage;
|
||||
}
|
||||
|
||||
public String getDefaultLanguage() {
|
||||
return this.defaultLanguage;
|
||||
}
|
||||
|
||||
public void setDefaultLanguage(String lang) {
|
||||
this.defaultLanguage = lang.toLowerCase();
|
||||
this.plugin.getConfig().set("language", this.defaultLanguage);
|
||||
this.plugin.saveConfig();
|
||||
}
|
||||
|
||||
public boolean hasExplicitLanguage(CommandSender sender) {
|
||||
return sender instanceof Player p && this.playerLanguages.containsKey(p.getUniqueId());
|
||||
}
|
||||
|
||||
public void setPlayerLanguage(UUID uuid, String lang) {
|
||||
this.playerLanguages.put(uuid, lang.toLowerCase());
|
||||
this.savePlayerLanguages();
|
||||
}
|
||||
|
||||
private void loadPlayerLanguages() {
|
||||
this.playerLanguages.clear();
|
||||
File file = new File(this.plugin.getDataFolder(), "player_languages.yml");
|
||||
if (file.exists()) {
|
||||
YamlConfiguration cfg = YamlConfiguration.loadConfiguration(file);
|
||||
ConfigurationSection section = cfg.getConfigurationSection("players");
|
||||
if (section != null) {
|
||||
for (String key : section.getKeys(false)) {
|
||||
try {
|
||||
UUID id = UUID.fromString(key);
|
||||
String lang = section.getString(key);
|
||||
if (lang != null && !lang.isBlank()) {
|
||||
this.playerLanguages.put(id, lang.toLowerCase());
|
||||
}
|
||||
} catch (IllegalArgumentException var8) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void savePlayerLanguages() {
|
||||
File file = new File(this.plugin.getDataFolder(), "player_languages.yml");
|
||||
YamlConfiguration cfg = new YamlConfiguration();
|
||||
|
||||
for (Entry<UUID, String> entry : this.playerLanguages.entrySet()) {
|
||||
cfg.set("players." + entry.getKey(), entry.getValue());
|
||||
}
|
||||
|
||||
try {
|
||||
cfg.save(file);
|
||||
} catch (IOException e) {
|
||||
this.plugin.getLogger().warning("Failed to save player_languages.yml: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public String getRaw(String key, String lang) {
|
||||
YamlConfiguration config = this.langConfigs.get(lang.toLowerCase());
|
||||
if (config == null || !config.contains(key)) {
|
||||
config = this.langConfigs.get(this.defaultLanguage);
|
||||
}
|
||||
|
||||
if (config == null || !config.contains(key)) {
|
||||
config = this.langConfigs.get("en");
|
||||
}
|
||||
|
||||
return config != null ? config.getString(key, key) : key;
|
||||
}
|
||||
|
||||
public String getMessage(String key, CommandSender sender, Object... replacements) {
|
||||
String lang = this.getPlayerLanguage(sender);
|
||||
return this.getMessage(key, lang, replacements);
|
||||
}
|
||||
|
||||
public String getMessage(String key, String lang, Object... replacements) {
|
||||
String template = this.getRaw(key, lang);
|
||||
if (replacements != null && replacements.length > 0) {
|
||||
for (int i = 0; i < replacements.length - 1; i += 2) {
|
||||
String placeholder = "{" + replacements[i] + "}";
|
||||
String val = String.valueOf(replacements[i + 1]);
|
||||
template = template.replace(placeholder, val);
|
||||
}
|
||||
}
|
||||
|
||||
return CompatUtils.color(template);
|
||||
}
|
||||
|
||||
public void sendLanguageSelectorPrompt(Player player) {
|
||||
String currentLang = this.getPlayerLanguage(player);
|
||||
CompatUtils.sendMessage(player, this.getMessage("lang_selector.header", currentLang));
|
||||
CompatUtils.sendMessage(player, this.getMessage("lang_selector.prompt", currentLang));
|
||||
CompatUtils.sendMessage(player, this.getMessage("lang_selector.current", currentLang, "current", currentLang.toUpperCase()));
|
||||
TextComponent options = new TextComponent(" ");
|
||||
options.addExtra(
|
||||
CompatUtils.createGrimButton(
|
||||
this.getRaw("lang_selector.btn_en", currentLang), "�d2ff", this.getRaw("lang_selector.btn_en_hover", currentLang), "/aiac lang en"
|
||||
)
|
||||
);
|
||||
options.addExtra(new TextComponent(" "));
|
||||
options.addExtra(
|
||||
CompatUtils.createGrimButton(
|
||||
this.getRaw("lang_selector.btn_ru", currentLang), "�ff88", this.getRaw("lang_selector.btn_ru_hover", currentLang), "/aiac lang ru"
|
||||
)
|
||||
);
|
||||
CompatUtils.sendComponent(player, options);
|
||||
CompatUtils.sendMessage(player, this.getMessage("lang_selector.header", currentLang));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
package net.synapselabs.anticheat.listener;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import net.md_5.bungee.api.chat.ClickEvent;
|
||||
import net.md_5.bungee.api.chat.TextComponent;
|
||||
import net.md_5.bungee.api.chat.ClickEvent.Action;
|
||||
import net.synapselabs.anticheat.AiAnticheatPlugin;
|
||||
import net.synapselabs.anticheat.alert.AlertManager;
|
||||
import net.synapselabs.anticheat.compat.CompatUtils;
|
||||
import net.synapselabs.anticheat.data.PlayerProfile;
|
||||
import net.synapselabs.anticheat.debug.DebugManager.AttackDebugRecord;
|
||||
import net.synapselabs.anticheat.engine.DetectionSnapshot;
|
||||
import net.synapselabs.anticheat.engine.FeatureVector;
|
||||
import net.synapselabs.anticheat.engine.HardCombatChecks;
|
||||
import net.synapselabs.anticheat.engine.InferenceService;
|
||||
import net.synapselabs.anticheat.engine.LagCompensator;
|
||||
import net.synapselabs.anticheat.engine.HardCombatChecks.HardCheckResult;
|
||||
import net.synapselabs.anticheat.overlay.OverheadDisplayManager;
|
||||
import net.synapselabs.anticheat.tracker.CombatTracker;
|
||||
import net.synapselabs.anticheat.tracker.KinematicHistory;
|
||||
import net.synapselabs.anticheat.tracker.KinematicHistory.RaycastHitResult;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.LivingEntity;
|
||||
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.EntityDamageByEntityEvent;
|
||||
import org.bukkit.event.entity.PlayerDeathEvent;
|
||||
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
|
||||
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;
|
||||
|
||||
public class CombatListener implements Listener {
|
||||
private final AiAnticheatPlugin plugin;
|
||||
private final HardCombatChecks hardChecks;
|
||||
private final InferenceService inferenceService;
|
||||
private final AlertManager alertManager;
|
||||
private final OverheadDisplayManager overheadManager;
|
||||
private final LagCompensator lagCompensator = new LagCompensator();
|
||||
private final Map<UUID, CombatTracker> trackers = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, Long> lastTeleportOrRespawn = new ConcurrentHashMap<>();
|
||||
private static final long MIN_GRACE_MS = 300L;
|
||||
|
||||
public CombatListener(
|
||||
AiAnticheatPlugin plugin,
|
||||
HardCombatChecks hardChecks,
|
||||
InferenceService inferenceService,
|
||||
AlertManager alertManager,
|
||||
OverheadDisplayManager overheadManager
|
||||
) {
|
||||
this.plugin = plugin;
|
||||
this.hardChecks = hardChecks;
|
||||
this.inferenceService = inferenceService;
|
||||
this.alertManager = alertManager;
|
||||
this.overheadManager = overheadManager;
|
||||
this.inferenceService.subscribe(this::handleAsyncSnapshot);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onJoin(PlayerJoinEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
PlayerProfile profile = this.plugin.getDataManager().getOrCreate(player);
|
||||
if (!this.plugin.isSetupCompleted() && (player.isOp() || player.hasPermission("aianticheat.admin"))) {
|
||||
Bukkit.getScheduler().runTaskLater(this.plugin, () -> {
|
||||
if (player.isOnline() && !this.plugin.isSetupCompleted()) {
|
||||
this.plugin.getLanguageManager().sendLanguageSelectorPrompt(player);
|
||||
}
|
||||
}, 20L);
|
||||
}
|
||||
|
||||
if (this.plugin.getDataManager().hasBannedAccountsOnIp(profile.getLastIp())) {
|
||||
for (Player staff : Bukkit.getOnlinePlayers()) {
|
||||
if (staff.hasPermission("aianticheat.admin") || staff.hasPermission("aianticheat.alerts")) {
|
||||
String lang = this.plugin.getLanguageManager().getPlayerLanguage(staff);
|
||||
CompatUtils.sendMessage(
|
||||
staff,
|
||||
this.plugin
|
||||
.getLanguageManager()
|
||||
.getMessage("alerts.banned_ip_join", lang, new Object[]{"player", player.getName(), "ip", profile.getLastIp()})
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this.plugin.getConfig().getBoolean("updates.notify_admins_on_join", true)
|
||||
&& (
|
||||
player.isOp()
|
||||
|| player.hasPermission("aianticheat.admin")
|
||||
|| player.hasPermission("aianticheat.update")
|
||||
|| player.hasPermission("aianticheat.alerts")
|
||||
)
|
||||
&& this.plugin.getUpdateChecker() != null) {
|
||||
this.plugin
|
||||
.getUpdateChecker()
|
||||
.checkForUpdates(
|
||||
result -> {
|
||||
if (result != null && result.isUpdateAvailable() && player.isOnline()) {
|
||||
String langx = this.plugin.getLanguageManager().getPlayerLanguage(player);
|
||||
CompatUtils.sendMessage(
|
||||
player,
|
||||
this.plugin
|
||||
.getLanguageManager()
|
||||
.getMessage("updates.available", langx, new Object[]{"latest", result.getLatestVersion(), "current", result.getCurrentVersion()})
|
||||
);
|
||||
CompatUtils.sendMessage(
|
||||
player, this.plugin.getLanguageManager().getMessage("updates.release_name", langx, new Object[]{"title", result.getReleaseName()})
|
||||
);
|
||||
TextComponent btn = CompatUtils.createGrimButton(
|
||||
this.plugin.getLanguageManager().getRaw("updates.btn_github", langx),
|
||||
"�d2ff",
|
||||
this.plugin.getLanguageManager().getMessage("updates.btn_github_hover", langx, new Object[]{"url", result.getReleaseUrl()}),
|
||||
null
|
||||
);
|
||||
btn.setClickEvent(new ClickEvent(Action.OPEN_URL, result.getReleaseUrl()));
|
||||
CompatUtils.sendComponent(player, btn);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onMove(PlayerMoveEvent event) {
|
||||
if (this.plugin.isSetupCompleted()) {
|
||||
Player player = event.getPlayer();
|
||||
CombatTracker tracker = this.trackers.computeIfAbsent(player.getUniqueId(), k -> new CombatTracker());
|
||||
tracker.getHistory().push(event.getTo());
|
||||
this.lagCompensator.record(player);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOW)
|
||||
public void onDamage(EntityDamageByEntityEvent event) {
|
||||
if (this.plugin.isSetupCompleted()) {
|
||||
if (this.plugin.isSetupCompleted()) {
|
||||
if (event.getDamager() instanceof Player attacker && event.getEntity() instanceof LivingEntity victim) {
|
||||
try {
|
||||
if (event.getCause() == DamageCause.ENTITY_SWEEP_ATTACK) {
|
||||
return;
|
||||
}
|
||||
} catch (Throwable var24) {
|
||||
}
|
||||
|
||||
boolean pvpOnly = this.plugin.getConfig().getBoolean("detection.pvp_only", true);
|
||||
if (!pvpOnly || victim instanceof Player) {
|
||||
if (this.plugin.getConfig().getBoolean("detection.tps_protection.enabled", true)) {
|
||||
try {
|
||||
double[] tps = Bukkit.getTPS();
|
||||
double minTps = this.plugin.getConfig().getDouble("detection.tps_protection.min_tps", 17.5);
|
||||
if (tps.length > 0 && tps[0] < minTps) {
|
||||
return;
|
||||
}
|
||||
} catch (Throwable var23) {
|
||||
}
|
||||
}
|
||||
|
||||
UUID attackerId = attacker.getUniqueId();
|
||||
int ping = safePing(attacker);
|
||||
Long lastGrace = this.lastTeleportOrRespawn.get(attackerId);
|
||||
if (lastGrace != null) {
|
||||
long gracePeriod = Math.max(300L, ping * 2L);
|
||||
if (System.currentTimeMillis() - lastGrace < gracePeriod) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (victim instanceof Player victimPlayer) {
|
||||
Long victimGrace = this.lastTeleportOrRespawn.get(victimPlayer.getUniqueId());
|
||||
if (victimGrace != null) {
|
||||
long gracePeriod = Math.max(300L, safePing(victimPlayer) * 2L);
|
||||
if (System.currentTimeMillis() - victimGrace < gracePeriod) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CombatTracker tracker = this.trackers.computeIfAbsent(attackerId, k -> new CombatTracker());
|
||||
KinematicHistory history = tracker.getHistory();
|
||||
history.push(attacker.getLocation());
|
||||
Location eyeLoc = attacker.getEyeLocation();
|
||||
double distance = eyeLoc.distance(victim.getEyeLocation());
|
||||
history.registerAttack(distance);
|
||||
this.lagCompensator.record(victim);
|
||||
double latencyMargin = latencyMarginFor(ping);
|
||||
RaycastHitResult raycast = KinematicHistory.raycastTargetHitbox(eyeLoc, victim, latencyMargin, 6.0);
|
||||
double compensatedReach = this.lagCompensator.compensatedReach(eyeLoc, victim.getUniqueId(), ping, raycast.distance());
|
||||
if (!(compensatedReach < 0.5) || !(raycast.distance() < 0.3F)) {
|
||||
HardCheckResult hardResult = this.hardChecks.evaluate(attacker, victim, tracker, raycast, compensatedReach);
|
||||
if (hardResult.cancelDamage()) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
|
||||
FeatureVector vector = tracker.createFeatureVector(attacker, eyeLoc, victim.getEyeLocation(), raycast);
|
||||
if (this.plugin.getDatasetManager() != null) {
|
||||
this.plugin.getDatasetManager().recordAttack(attacker, vector, ping);
|
||||
}
|
||||
|
||||
AttackDebugRecord debugRecord = null;
|
||||
boolean debugActive = this.plugin.getDebugManager() != null && this.plugin.getDebugManager().hasActiveSessions();
|
||||
boolean fileLogActive = this.plugin.getConfig().getBoolean("logging.files.combat_debug", true);
|
||||
if (this.plugin.getDebugManager() != null && (debugActive || fileLogActive)) {
|
||||
debugRecord = this.plugin
|
||||
.getDebugManager()
|
||||
.captureAttack(attacker, victim, eyeLoc, raycast, distance, compensatedReach, latencyMargin, hardResult, vector, tracker);
|
||||
if (debugActive) {
|
||||
this.plugin.getDebugManager().renderVisuals(attacker, victim, eyeLoc, raycast, hardResult.context(), latencyMargin);
|
||||
}
|
||||
}
|
||||
|
||||
this.inferenceService.submitAnalysis(attacker, vector, tracker, hardResult.signals(), hardResult.context(), debugRecord);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onTeleport(PlayerTeleportEvent event) {
|
||||
this.lastTeleportOrRespawn.put(event.getPlayer().getUniqueId(), System.currentTimeMillis());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onRespawn(PlayerRespawnEvent event) {
|
||||
this.lastTeleportOrRespawn.put(event.getPlayer().getUniqueId(), System.currentTimeMillis());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onDeath(PlayerDeathEvent event) {
|
||||
this.lastTeleportOrRespawn.put(event.getEntity().getUniqueId(), System.currentTimeMillis());
|
||||
}
|
||||
|
||||
private void handleAsyncSnapshot(DetectionSnapshot snapshot) {
|
||||
this.overheadManager.updateDisplay(snapshot.playerId(), snapshot.getKillauraPercent(), snapshot.getAimPercent(), snapshot.threatState());
|
||||
if (snapshot.isFlagged()) {
|
||||
this.alertManager.dispatchAlert(snapshot);
|
||||
}
|
||||
|
||||
if (snapshot.isActionable()) {
|
||||
this.plugin.getPunishmentManager().evaluateSnapshot(snapshot);
|
||||
}
|
||||
}
|
||||
|
||||
private static double latencyMarginFor(int pingMs) {
|
||||
return Math.max(0.1, Math.min(0.4, 0.1 + pingMs * 0.001));
|
||||
}
|
||||
|
||||
private static int safePing(Player player) {
|
||||
try {
|
||||
return player.getPing();
|
||||
} catch (Throwable ignored) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onQuit(PlayerQuitEvent event) {
|
||||
UUID uuid = event.getPlayer().getUniqueId();
|
||||
this.trackers.remove(uuid);
|
||||
this.lagCompensator.forget(uuid);
|
||||
this.lastTeleportOrRespawn.remove(uuid);
|
||||
}
|
||||
|
||||
public void decayAll(float amount) {
|
||||
for (Entry<UUID, CombatTracker> entry : this.trackers.entrySet()) {
|
||||
UUID uuid = entry.getKey();
|
||||
CombatTracker tracker = entry.getValue();
|
||||
tracker.decay(amount);
|
||||
Player p = Bukkit.getPlayer(uuid);
|
||||
if (p != null && p.isOnline()) {
|
||||
PlayerProfile profile = this.plugin.getDataManager().getOrCreate(p);
|
||||
profile.setKillauraConfidence(tracker.getKillauraConfidence());
|
||||
profile.setAimConfidence(tracker.getAimConfidence());
|
||||
profile.setSuspicion(tracker.getSuspicion());
|
||||
profile.setThreatState(tracker.getThreatState());
|
||||
this.overheadManager
|
||||
.updateDisplay(
|
||||
uuid, Math.round(tracker.getKillauraConfidence() * 100.0F), Math.round(tracker.getAimConfidence() * 100.0F), tracker.getThreatState()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public CombatTracker getTracker(UUID uuid) {
|
||||
return this.trackers.get(uuid);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
package net.synapselabs.anticheat.logging;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import net.synapselabs.anticheat.AiAnticheatPlugin;
|
||||
import net.synapselabs.anticheat.data.PlayerProfile;
|
||||
import net.synapselabs.anticheat.debug.DebugManager.AttackDebugRecord;
|
||||
import net.synapselabs.anticheat.engine.DetectionSnapshot;
|
||||
import net.synapselabs.anticheat.engine.RiskAssessment;
|
||||
import net.synapselabs.anticheat.engine.Signal;
|
||||
import net.synapselabs.anticheat.engine.RiskAssessment.Contribution;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class AuditLogManager implements AutoCloseable {
|
||||
private static final DateTimeFormatter TIMESTAMP_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
private final AiAnticheatPlugin plugin;
|
||||
private final File logsDir;
|
||||
private final File detectionsFile;
|
||||
private final File combatDebugFile;
|
||||
private final ExecutorService logExecutor;
|
||||
|
||||
public AuditLogManager(AiAnticheatPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
this.logsDir = new File(plugin.getDataFolder(), "logs");
|
||||
this.detectionsFile = new File(this.logsDir, "detections.log");
|
||||
this.combatDebugFile = new File(this.logsDir, "combat_debug.log");
|
||||
if (!this.logsDir.exists()) {
|
||||
this.logsDir.mkdirs();
|
||||
}
|
||||
|
||||
this.logExecutor = Executors.newSingleThreadExecutor(r -> {
|
||||
Thread t = new Thread(r, "SynapseAI-LogWriter");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
}
|
||||
|
||||
public File getDetectionsFile() {
|
||||
return this.detectionsFile;
|
||||
}
|
||||
|
||||
public File getCombatDebugFile() {
|
||||
return this.combatDebugFile;
|
||||
}
|
||||
|
||||
public void logDetection(DetectionSnapshot snapshot, PlayerProfile profile, String action) {
|
||||
if (this.plugin.getConfig().getBoolean("logging.files.detections", true)) {
|
||||
this.logExecutor
|
||||
.submit(
|
||||
() -> {
|
||||
try {
|
||||
String timestamp = LocalDateTime.now().format(TIMESTAMP_FORMAT);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String checkType = snapshot.hasHardViolations() ? "HARD-CHECK" : "AI-COMBAT";
|
||||
String reasonList = snapshot.reasons() != null && !snapshot.reasons().isEmpty() ? String.join(", ", snapshot.reasons()) : "Clean";
|
||||
sb.append(
|
||||
String.format(
|
||||
"[%s] [%s] [%s] Player: %s (UUID: %s, IP: %s)\n",
|
||||
timestamp,
|
||||
action,
|
||||
checkType,
|
||||
snapshot.playerName(),
|
||||
snapshot.playerId(),
|
||||
profile != null ? profile.getLastIp() : "Unknown"
|
||||
)
|
||||
);
|
||||
sb.append(
|
||||
String.format(
|
||||
" • Primary Violation: %s | Threat: %s | AI Confidence: %d%%\n",
|
||||
snapshot.getPrimaryViolation(),
|
||||
snapshot.threatState().name(),
|
||||
snapshot.getConfidencePercent()
|
||||
)
|
||||
);
|
||||
sb.append(
|
||||
String.format(
|
||||
" • Risk Score: %.1f/100 | Event Risk: %.1f | Model P: %.3f | Verdict: %s\n",
|
||||
snapshot.riskScore() * 100.0F,
|
||||
snapshot.metadata() != null && snapshot.metadata().get("event_risk") instanceof Double er ? er : 0.0,
|
||||
snapshot.rawScore(),
|
||||
snapshot.verdict() != null ? snapshot.verdict() : "UNKNOWN"
|
||||
)
|
||||
);
|
||||
sb.append(
|
||||
String.format(
|
||||
" • Flags Count: Total=%d (Hard=%d, AI=%d, Grim=%d)\n",
|
||||
profile != null ? profile.getTotalFlags() : 0,
|
||||
profile != null ? profile.getHardFlags() : 0,
|
||||
profile != null ? profile.getAiFlags() : 0,
|
||||
profile != null ? profile.getGrimFlagsCount() : 0
|
||||
)
|
||||
);
|
||||
sb.append(String.format(" • Risk Contributors: [%s]\n", reasonList));
|
||||
if (snapshot.featureVector() != null && snapshot.featureVector().namedFeatures() != null) {
|
||||
Map<String, Float> f = snapshot.featureVector().namedFeatures();
|
||||
sb.append(
|
||||
String.format(
|
||||
" • Kinematics: Distance=%.2fm, Angle=%.2f°, RayHit=%.0f, RayDist=%.2fm, YawΔ1t=%.2f°, PitchΔ1t=%.2f°\n",
|
||||
f.getOrDefault("distance", 0.0F),
|
||||
f.getOrDefault("angle_offset_deg", 0.0F),
|
||||
f.getOrDefault("raycast_hit", 0.0F),
|
||||
f.getOrDefault("raycast_distance", 0.0F),
|
||||
f.getOrDefault("yaw_delta_1t", 0.0F),
|
||||
f.getOrDefault("pitch_delta_1t", 0.0F)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
sb.append("\n");
|
||||
this.appendToFile(this.detectionsFile, sb.toString());
|
||||
} catch (Throwable t) {
|
||||
this.plugin.getLogger().warning("Failed to write to detections.log: " + t.getMessage());
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public void logPunishment(Player target, String reason, String punishmentType, boolean isHardCheck) {
|
||||
if (this.plugin.getConfig().getBoolean("logging.files.detections", true)) {
|
||||
this.logExecutor
|
||||
.submit(
|
||||
() -> {
|
||||
try {
|
||||
String timestamp = LocalDateTime.now().format(TIMESTAMP_FORMAT);
|
||||
String ip = target != null && target.getAddress() != null ? target.getAddress().getAddress().getHostAddress() : "Unknown";
|
||||
String entry = String.format(
|
||||
"[%s] [PUNISHMENT] [%s] Player: %s (UUID: %s, IP: %s) | Reason: %s | HardCheck: %s\n\n",
|
||||
timestamp,
|
||||
punishmentType.toUpperCase(),
|
||||
target != null ? target.getName() : "Unknown",
|
||||
target != null ? target.getUniqueId() : "Unknown",
|
||||
ip,
|
||||
reason,
|
||||
isHardCheck
|
||||
);
|
||||
this.appendToFile(this.detectionsFile, entry);
|
||||
} catch (Throwable t) {
|
||||
this.plugin.getLogger().warning("Failed to write punishment to detections.log: " + t.getMessage());
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public void logCombatDebug(AttackDebugRecord r, float modelP, RiskAssessment assessment) {
|
||||
if (this.plugin.getConfig().getBoolean("logging.files.combat_debug", true)) {
|
||||
this.logExecutor
|
||||
.submit(
|
||||
() -> {
|
||||
try {
|
||||
String timestamp = LocalDateTime.now().format(TIMESTAMP_FORMAT);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int modelPct = Math.round(modelP * 100.0F);
|
||||
int cooldownPct = Math.round(r.cooldown() * 100.0F);
|
||||
float cps = r.attackIntervalTicks() > 0.0F ? 20.0F / r.attackIntervalTicks() : 0.0F;
|
||||
String cornerStr = r.inCorner() ? "YES (" + r.solidSides() + " sides)" : "NO";
|
||||
List<String> signalStrs = new ArrayList<>();
|
||||
|
||||
for (Signal s : r.hardSignals()) {
|
||||
signalStrs.add(s.type().name() + " (" + String.format("%.1f", s.value()) + ")");
|
||||
}
|
||||
|
||||
String signalsFormatted = signalStrs.isEmpty() ? "None" : String.join(", ", signalStrs);
|
||||
List<String> contribStrs = new ArrayList<>();
|
||||
|
||||
for (Contribution c : assessment.contributions()) {
|
||||
if (c.contribution() >= 0.5) {
|
||||
contribStrs.add(c.signal().name() + " " + String.format("%.1f", c.contribution()));
|
||||
}
|
||||
}
|
||||
|
||||
String contribsFormatted = contribStrs.isEmpty() ? "Clean" : String.join(", ", contribStrs);
|
||||
sb.append(
|
||||
String.format(
|
||||
"[%s] [COMBAT-DEBUG] %s (Ping: %dms) ⚔ %s (Ping: %dms)\n",
|
||||
timestamp,
|
||||
r.attackerName(),
|
||||
r.attackerPing(),
|
||||
r.victimName(),
|
||||
r.victimPing()
|
||||
)
|
||||
);
|
||||
sb.append(
|
||||
String.format(
|
||||
" • Geometry: Angle=%.2f°, Reach=%.2fm (Comp=%.2fm, Raw=%.2fm), Margin=+%.2fm\n",
|
||||
r.angleOffsetDeg(),
|
||||
r.raycastDistance(),
|
||||
r.compensatedReach(),
|
||||
r.rawReach(),
|
||||
r.latencyMargin()
|
||||
)
|
||||
);
|
||||
sb.append(
|
||||
String.format(
|
||||
" • Hitbox: RayHit=%s, EdgeProx=%.2f, Corner=%s, Wall=%s, Water=%s, KB=%s\n",
|
||||
r.rayHit() ? "YES" : "NO",
|
||||
r.hitboxEdgeProximity(),
|
||||
cornerStr,
|
||||
r.nearWall() ? "YES" : "NO",
|
||||
r.inWater() ? "YES" : "NO",
|
||||
r.victimKnockback() ? "YES" : "NO"
|
||||
)
|
||||
);
|
||||
sb.append(
|
||||
String.format(
|
||||
" • Kinematics: YawΔ[1t=%+.2f°, 5t=%+.2f°], PitchΔ[1t=%+.2f°, 5t=%+.2f°], RotVel=%.1f°/t, YawAccel=%+.1f, Jerk=%+.1f, Var10t=%.2f, RotAge=%dms\n",
|
||||
r.yaw1t(),
|
||||
r.yaw5t(),
|
||||
r.pitch1t(),
|
||||
r.pitch5t(),
|
||||
r.rotVel(),
|
||||
r.yawAccel(),
|
||||
r.yawJerk(),
|
||||
r.rotVar(),
|
||||
r.rotAge()
|
||||
)
|
||||
);
|
||||
sb.append(
|
||||
String.format(
|
||||
" • Combat: Cooldown=%d%%, Interval=%.1ft (~%.1f CPS), Crit=%s, DamageCanceled=%s\n",
|
||||
cooldownPct,
|
||||
r.attackIntervalTicks(),
|
||||
cps,
|
||||
r.isCrit() ? "YES" : "NO",
|
||||
r.cancelDamage() ? "YES" : "NO"
|
||||
)
|
||||
);
|
||||
sb.append(
|
||||
String.format(
|
||||
" • AI & Risk: ModelP=%.3f (%d%%), EventRisk=%.1f, AggRisk=%.1f/100, Verdict=%s\n",
|
||||
modelP,
|
||||
modelPct,
|
||||
assessment.eventRisk(),
|
||||
assessment.risk(),
|
||||
assessment.verdict().name()
|
||||
)
|
||||
);
|
||||
sb.append(String.format(" • Hard Signals: [%s]\n", signalsFormatted));
|
||||
sb.append(String.format(" • Risk Contributors: [%s]\n\n", contribsFormatted));
|
||||
this.appendToFile(this.combatDebugFile, sb.toString());
|
||||
} catch (Throwable t) {
|
||||
this.plugin.getLogger().warning("Failed to write to combat_debug.log: " + t.getMessage());
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void appendToFile(File file, String text) throws IOException {
|
||||
if (!this.logsDir.exists()) {
|
||||
this.logsDir.mkdirs();
|
||||
}
|
||||
|
||||
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), StandardCharsets.UTF_8))) {
|
||||
writer.write(text);
|
||||
writer.flush();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
this.logExecutor.shutdown();
|
||||
|
||||
try {
|
||||
if (!this.logExecutor.awaitTermination(2000L, TimeUnit.MILLISECONDS)) {
|
||||
this.logExecutor.shutdownNow();
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
this.logExecutor.shutdownNow();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
package net.synapselabs.anticheat.overlay;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import net.synapselabs.anticheat.AiAnticheatPlugin;
|
||||
import net.synapselabs.anticheat.compat.CompatUtils;
|
||||
import net.synapselabs.anticheat.data.PlayerProfile;
|
||||
import net.synapselabs.anticheat.data.ThreatState;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.ArmorStand;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.EntityType;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerChangedWorldEvent;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.event.world.WorldLoadEvent;
|
||||
import org.bukkit.event.world.WorldUnloadEvent;
|
||||
|
||||
public class OverheadDisplayManager implements Listener {
|
||||
public static final String OVERHEAD_TAG = "synapse_overhead";
|
||||
private final AiAnticheatPlugin plugin;
|
||||
private final Map<UUID, OverheadDisplayManager.OverheadEntry> displays = new ConcurrentHashMap<>();
|
||||
|
||||
public OverheadDisplayManager(AiAnticheatPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
this.purgeOrphanedDisplays();
|
||||
this.startPositionTask();
|
||||
this.startPermissionSyncTask();
|
||||
}
|
||||
|
||||
public void purgeOrphanedDisplays() {
|
||||
for (World world : Bukkit.getWorlds()) {
|
||||
for (Entity entity : world.getEntities()) {
|
||||
if (entity.getScoreboardTags().contains("synapse_overhead")) {
|
||||
try {
|
||||
entity.remove();
|
||||
} catch (Throwable var6) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void createDisplay(Player target) {
|
||||
if (this.plugin.getConfig().getBoolean("detection.overhead_display.enabled", true)) {
|
||||
if (target != null && target.isOnline()) {
|
||||
UUID uuid = target.getUniqueId();
|
||||
this.removeDisplay(uuid);
|
||||
|
||||
try {
|
||||
Location loc = target.getLocation().add(0.0, 2.0, 0.0);
|
||||
ArmorStand display = (ArmorStand)target.getWorld().spawnEntity(loc, EntityType.ARMOR_STAND);
|
||||
display.setVisible(false);
|
||||
display.setMarker(true);
|
||||
display.setSmall(true);
|
||||
display.setGravity(false);
|
||||
display.setCustomNameVisible(true);
|
||||
display.setPersistent(false);
|
||||
display.addScoreboardTag("synapse_overhead");
|
||||
PlayerProfile profile = this.plugin.getDataManager().getOrCreate(target);
|
||||
int kScore = Math.round(profile.getKillauraConfidence() * 100.0F);
|
||||
int aScore = Math.round(profile.getAimConfidence() * 100.0F);
|
||||
ThreatState state = profile.getThreatState();
|
||||
String defaultLang = this.plugin.getLanguageManager().getPlayerLanguage(target);
|
||||
String text = this.formatDisplayText(kScore, aScore, state, defaultLang);
|
||||
display.setCustomName(text);
|
||||
OverheadDisplayManager.OverheadEntry entry = new OverheadDisplayManager.OverheadEntry(display);
|
||||
entry.lastKillauraScore = kScore;
|
||||
entry.lastAimScore = aScore;
|
||||
entry.lastState = state;
|
||||
entry.lastUpdate = System.currentTimeMillis();
|
||||
this.displays.put(uuid, entry);
|
||||
this.applyInitialVisibility(display);
|
||||
} catch (Throwable t) {
|
||||
this.plugin.getLogger().warning("Could not spawn overhead indicator: " + t.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void updateDisplay(UUID targetUuid, int killauraScore, int aimScore, ThreatState state) {
|
||||
OverheadDisplayManager.OverheadEntry entry = this.displays.get(targetUuid);
|
||||
if (entry == null || entry.entity == null || !entry.entity.isValid()) {
|
||||
Player target = Bukkit.getPlayer(targetUuid);
|
||||
if (target != null && target.isOnline()) {
|
||||
this.createDisplay(target);
|
||||
}
|
||||
} else if (entry.lastKillauraScore != killauraScore || entry.lastAimScore != aimScore || entry.lastState != state) {
|
||||
Player target = Bukkit.getPlayer(targetUuid);
|
||||
String lang = target != null ? this.plugin.getLanguageManager().getPlayerLanguage(target) : "en";
|
||||
String text = this.formatDisplayText(killauraScore, aimScore, state, lang);
|
||||
entry.entity.setCustomName(text);
|
||||
entry.lastKillauraScore = killauraScore;
|
||||
entry.lastAimScore = aimScore;
|
||||
entry.lastState = state;
|
||||
entry.lastUpdate = System.currentTimeMillis();
|
||||
}
|
||||
}
|
||||
|
||||
public void updateVisibility(Player viewer) {
|
||||
if (viewer != null && viewer.isOnline()) {
|
||||
boolean isStaff = this.hasOverheadPermission(viewer);
|
||||
|
||||
for (OverheadDisplayManager.OverheadEntry entry : this.displays.values()) {
|
||||
if (entry.entity != null && entry.entity.isValid()) {
|
||||
try {
|
||||
if (isStaff) {
|
||||
viewer.showEntity(this.plugin, entry.entity);
|
||||
} else {
|
||||
viewer.hideEntity(this.plugin, entry.entity);
|
||||
}
|
||||
} catch (Throwable var6) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void applyInitialVisibility(ArmorStand display) {
|
||||
for (Player p : Bukkit.getOnlinePlayers()) {
|
||||
try {
|
||||
if (this.hasOverheadPermission(p)) {
|
||||
p.showEntity(this.plugin, display);
|
||||
} else {
|
||||
p.hideEntity(this.plugin, display);
|
||||
}
|
||||
} catch (Throwable var5) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean hasOverheadPermission(Player player) {
|
||||
String perm = this.plugin.getConfig().getString("detection.overhead_display.required_permission", "aianticheat.overhead");
|
||||
return player.hasPermission(perm) || player.hasPermission("aianticheat.admin");
|
||||
}
|
||||
|
||||
private String formatDisplayText(int killauraScore, int aimScore, ThreatState state, String lang) {
|
||||
String kColor = killauraScore >= 70 ? "&#ff2244" : (killauraScore >= 40 ? "&#ffaa00" : "�ff88");
|
||||
String aColor = aimScore >= 70 ? "&#ff2244" : (aimScore >= 40 ? "&#ffaa00" : "�ff88");
|
||||
String stateTag = this.plugin.getLanguageManager().getMessage(state.messageKey(), lang, new Object[0]);
|
||||
return CompatUtils.color(
|
||||
String.format("%s 󙀸[򽸱Killaura: %s%d%% 󙀸| 򽸱Aim: %s%d%%󙀸]", stateTag, kColor, killauraScore, aColor, aimScore)
|
||||
);
|
||||
}
|
||||
|
||||
public void removeDisplay(UUID targetUuid) {
|
||||
OverheadDisplayManager.OverheadEntry entry = this.displays.remove(targetUuid);
|
||||
if (entry != null && entry.entity != null && entry.entity.isValid()) {
|
||||
try {
|
||||
entry.entity.remove();
|
||||
} catch (Throwable var4) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void removeAll() {
|
||||
for (OverheadDisplayManager.OverheadEntry entry : this.displays.values()) {
|
||||
if (entry.entity != null && entry.entity.isValid()) {
|
||||
try {
|
||||
entry.entity.remove();
|
||||
} catch (Throwable var4) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.displays.clear();
|
||||
this.purgeOrphanedDisplays();
|
||||
}
|
||||
|
||||
private void startPositionTask() {
|
||||
Bukkit.getScheduler().runTaskTimer(this.plugin, () -> {
|
||||
double heightOffset = this.plugin.getConfig().getDouble("detection.overhead_display.height_offset", 2.0);
|
||||
|
||||
for (Entry<UUID, OverheadDisplayManager.OverheadEntry> entry : this.displays.entrySet()) {
|
||||
Player player = Bukkit.getPlayer(entry.getKey());
|
||||
ArmorStand display = entry.getValue().entity;
|
||||
if (player != null && player.isOnline() && display != null && display.isValid() && player.getWorld().equals(display.getWorld())) {
|
||||
display.teleport(player.getLocation().add(0.0, heightOffset, 0.0));
|
||||
}
|
||||
}
|
||||
}, 20L, 4L);
|
||||
}
|
||||
|
||||
private void startPermissionSyncTask() {
|
||||
Bukkit.getScheduler().runTaskTimer(this.plugin, () -> {
|
||||
if (this.plugin.isSetupCompleted()) {
|
||||
for (Player player : Bukkit.getOnlinePlayers()) {
|
||||
this.updateVisibility(player);
|
||||
}
|
||||
}
|
||||
}, 60L, 60L);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onJoin(PlayerJoinEvent event) {
|
||||
if (this.plugin.isSetupCompleted()) {
|
||||
Player player = event.getPlayer();
|
||||
Bukkit.getScheduler().runTaskLater(this.plugin, () -> {
|
||||
if (player.isOnline()) {
|
||||
this.createDisplay(player);
|
||||
this.updateVisibility(player);
|
||||
}
|
||||
}, 10L);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onQuit(PlayerQuitEvent event) {
|
||||
this.removeDisplay(event.getPlayer().getUniqueId());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onWorldChange(PlayerChangedWorldEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
Bukkit.getScheduler().runTaskLater(this.plugin, () -> {
|
||||
if (player.isOnline()) {
|
||||
this.createDisplay(player);
|
||||
this.updateVisibility(player);
|
||||
}
|
||||
}, 5L);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onWorldLoad(WorldLoadEvent event) {
|
||||
this.purgeOrphanedDisplays();
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onWorldUnload(WorldUnloadEvent event) {
|
||||
this.purgeOrphanedDisplays();
|
||||
}
|
||||
|
||||
private static class OverheadEntry {
|
||||
final ArmorStand entity;
|
||||
int lastKillauraScore = -1;
|
||||
int lastAimScore = -1;
|
||||
ThreatState lastState = null;
|
||||
long lastUpdate = 0L;
|
||||
|
||||
OverheadEntry(ArmorStand entity) {
|
||||
this.entity = entity;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
package net.synapselabs.anticheat.punishment;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import net.synapselabs.anticheat.AiAnticheatPlugin;
|
||||
import net.synapselabs.anticheat.data.PlayerProfile;
|
||||
import net.synapselabs.anticheat.data.ThreatState;
|
||||
import net.synapselabs.anticheat.engine.DetectionSnapshot;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.BanList.Type;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class PunishmentManager {
|
||||
private final AiAnticheatPlugin plugin;
|
||||
private PunishmentManager.DetectedBanPlugin activePlugin = PunishmentManager.DetectedBanPlugin.BUKKIT;
|
||||
private final Map<UUID, Long> hardCooldowns = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, Long> aiCooldowns = new ConcurrentHashMap<>();
|
||||
|
||||
public PunishmentManager(AiAnticheatPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
this.detectBanPlugin();
|
||||
}
|
||||
|
||||
public void detectBanPlugin() {
|
||||
if (Bukkit.getPluginManager().isPluginEnabled("LiteBans")) {
|
||||
this.activePlugin = PunishmentManager.DetectedBanPlugin.LITEBANS;
|
||||
} else if (Bukkit.getPluginManager().isPluginEnabled("AdvancedBan")) {
|
||||
this.activePlugin = PunishmentManager.DetectedBanPlugin.ADVANCED_BAN;
|
||||
} else if (Bukkit.getPluginManager().isPluginEnabled("LibertyBans")) {
|
||||
this.activePlugin = PunishmentManager.DetectedBanPlugin.LIBERTY_BANS;
|
||||
} else if (Bukkit.getPluginManager().isPluginEnabled("Essentials")) {
|
||||
this.activePlugin = PunishmentManager.DetectedBanPlugin.ESSENTIALS;
|
||||
} else if (Bukkit.getPluginManager().isPluginEnabled("MaxBans")) {
|
||||
this.activePlugin = PunishmentManager.DetectedBanPlugin.MAX_BANS;
|
||||
} else {
|
||||
this.activePlugin = PunishmentManager.DetectedBanPlugin.BUKKIT;
|
||||
}
|
||||
|
||||
this.plugin.getLogger().info("Detected Ban System: " + this.activePlugin.getDisplay());
|
||||
}
|
||||
|
||||
public PunishmentManager.DetectedBanPlugin getActivePlugin() {
|
||||
return this.activePlugin;
|
||||
}
|
||||
|
||||
public boolean isPlayerBanned(String playerName, String ip) {
|
||||
try {
|
||||
if (Bukkit.getBanList(Type.NAME).isBanned(playerName)) {
|
||||
return true;
|
||||
}
|
||||
} catch (Throwable var10) {
|
||||
}
|
||||
|
||||
try {
|
||||
if (ip != null && Bukkit.getBanList(Type.IP).isBanned(ip)) {
|
||||
return true;
|
||||
}
|
||||
} catch (Throwable var9) {
|
||||
}
|
||||
|
||||
if (this.activePlugin == PunishmentManager.DetectedBanPlugin.LITEBANS) {
|
||||
try {
|
||||
Class<?> dbClass = Class.forName("litebans.api.Database");
|
||||
Object dbInstance = dbClass.getMethod("get").invoke(null);
|
||||
if (dbInstance != null) {
|
||||
Player p = Bukkit.getPlayer(playerName);
|
||||
if (p != null) {
|
||||
Boolean banned = (Boolean)dbClass.getMethod("isPlayerBanned", UUID.class, String.class).invoke(dbInstance, p.getUniqueId(), ip);
|
||||
if (banned != null && banned) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Throwable var8) {
|
||||
}
|
||||
}
|
||||
|
||||
if (this.activePlugin == PunishmentManager.DetectedBanPlugin.ADVANCED_BAN) {
|
||||
try {
|
||||
Class<?> pmClass = Class.forName("me.leoko.advancedban.manager.PunishmentManager");
|
||||
Object pmInstance = pmClass.getMethod("get").invoke(null);
|
||||
if (pmInstance != null) {
|
||||
Boolean banned = (Boolean)pmClass.getMethod("isBanned", String.class).invoke(pmInstance, playerName);
|
||||
if (banned != null && banned) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch (Throwable var7) {
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isPunishmentEnabled() {
|
||||
return this.plugin.getConfig().getBoolean("detection.punishments.enabled", true) && this.plugin.getConfig().getBoolean("punishment.enabled", true);
|
||||
}
|
||||
|
||||
public boolean isAutoKickEnabled() {
|
||||
if (!this.isPunishmentEnabled()) {
|
||||
return false;
|
||||
} else if (!this.plugin.getConfig().getBoolean("punishment.auto_kick", true)) {
|
||||
return false;
|
||||
} else {
|
||||
return !this.plugin.getConfig().getBoolean("detection.punishments.auto_kick", true) ? false : this.plugin.getConfig().getBoolean("auto_kick", true);
|
||||
}
|
||||
}
|
||||
|
||||
public void evaluateSnapshot(DetectionSnapshot snapshot) {
|
||||
if (this.isPunishmentEnabled()) {
|
||||
Player player = Bukkit.getPlayer(snapshot.playerId());
|
||||
if (player != null && player.isOnline()) {
|
||||
PlayerProfile profile = this.plugin.getDataManager().getOrCreate(player);
|
||||
long now = System.currentTimeMillis();
|
||||
if (snapshot.hasHardViolations()) {
|
||||
boolean hardAutoKick = this.isAutoKickEnabled() && this.plugin.getConfig().getBoolean("detection.punishments.hard.auto_kick", true);
|
||||
int hardKickThreshold = this.plugin.getConfig().getInt("detection.punishments.hard.flags_to_kick", 2);
|
||||
int hardCooldownSec = this.plugin.getConfig().getInt("detection.punishments.hard.cooldown_seconds", 10);
|
||||
Long lastHard = this.hardCooldowns.get(player.getUniqueId());
|
||||
if ((lastHard == null || now - lastHard > hardCooldownSec * 1000L)
|
||||
&& hardAutoKick
|
||||
&& hardKickThreshold > 0
|
||||
&& profile.getHardFlags() >= hardKickThreshold) {
|
||||
this.hardCooldowns.put(player.getUniqueId(), now);
|
||||
this.kickPlayer(player, snapshot.getPrimaryViolation(), true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (snapshot.hasAiViolations()) {
|
||||
boolean aiAutoKick = this.isAutoKickEnabled() && this.plugin.getConfig().getBoolean("detection.punishments.ai.auto_kick", true);
|
||||
int aiKickThreshold = this.plugin.getConfig().getInt("detection.punishments.ai.flags_to_kick", 4);
|
||||
int aiCooldownSec = this.plugin.getConfig().getInt("detection.punishments.ai.cooldown_seconds", 15);
|
||||
boolean shouldKick = snapshot.threatState() == ThreatState.CONFIRMED || aiKickThreshold > 0 && profile.getAiFlags() >= aiKickThreshold;
|
||||
Long lastAi = this.aiCooldowns.get(player.getUniqueId());
|
||||
if ((lastAi == null || now - lastAi > aiCooldownSec * 1000L) && aiAutoKick && shouldKick) {
|
||||
this.aiCooldowns.put(player.getUniqueId(), now);
|
||||
this.kickPlayer(player, snapshot.getPrimaryViolation() + " (" + snapshot.getConfidencePercent() + "% conf)", false);
|
||||
}
|
||||
}
|
||||
|
||||
if (profile.getGrimFlags() >= 4 && this.isAutoKickEnabled()) {
|
||||
Long lastGrim = this.hardCooldowns.get(player.getUniqueId());
|
||||
if (lastGrim == null || now - lastGrim > 15000L) {
|
||||
this.hardCooldowns.put(player.getUniqueId(), now);
|
||||
this.kickPlayer(player, "Unfair Advantage (GrimAC Detection)", true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void kickPlayer(Player target, String reason, boolean isHardCheck) {
|
||||
String mode = this.plugin.getConfig().getString("punishment.mode", "AUTO").toUpperCase();
|
||||
String discordUrl = this.plugin.getConfig().getString("discord.invite_url", "https://dsc.gg/synapselabs");
|
||||
if (mode.equals("CUSTOM_COMMAND")) {
|
||||
String template = this.plugin.getConfig().getString("punishment.commands.kick", "kick {player} {reason}");
|
||||
String commandToRun = template.replace("{player}", target.getName()).replace("{reason}", reason).replace("{discord_url}", discordUrl);
|
||||
Bukkit.getScheduler().runTask(this.plugin, () -> {
|
||||
if (target.isOnline()) {
|
||||
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), commandToRun);
|
||||
this.plugin.getLogger().info("Executed custom kick command for " + target.getName() + ": " + commandToRun);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
String kickMsg = this.plugin
|
||||
.getLanguageManager()
|
||||
.getMessage("punishment.kick_message", target, new Object[]{"player", target.getName(), "reason", reason, "discord_url", discordUrl});
|
||||
Bukkit.getScheduler().runTask(this.plugin, () -> {
|
||||
if (target.isOnline()) {
|
||||
target.kickPlayer(kickMsg);
|
||||
this.plugin.getLogger().info("Kicked player " + target.getName() + " for: " + reason + " (Hard: " + isHardCheck + ")");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (this.plugin.getAuditLogManager() != null) {
|
||||
this.plugin.getAuditLogManager().logPunishment(target, reason, "KICK", isHardCheck);
|
||||
}
|
||||
}
|
||||
|
||||
public void banPlayer(Player target, String reason, String adminName, boolean isAutoBan) {
|
||||
String mode = this.plugin.getConfig().getString("punishment.mode", "AUTO").toUpperCase();
|
||||
String discordUrl = this.plugin.getConfig().getString("discord.invite_url", "https://dsc.gg/synapselabs");
|
||||
String template;
|
||||
if (isAutoBan) {
|
||||
template = this.plugin.getConfig().getString("punishment.commands.auto_ban", "tempban {player} 14d Auto-Ban: Cheating [SynapseAI] -s");
|
||||
} else {
|
||||
template = this.plugin.getConfig().getString("punishment.commands.manual_ban", "ban {player} 30d Unfair Advantage [SynapseAI] -s");
|
||||
}
|
||||
|
||||
String commandToRun = template.replace("{player}", target.getName())
|
||||
.replace("{reason}", reason)
|
||||
.replace("{admin}", adminName)
|
||||
.replace("{discord_url}", discordUrl);
|
||||
if (!mode.equals("CUSTOM_COMMAND") && (mode.equals("BUKKIT") || this.activePlugin == PunishmentManager.DetectedBanPlugin.BUKKIT)) {
|
||||
Bukkit.getScheduler()
|
||||
.runTask(
|
||||
this.plugin,
|
||||
() -> {
|
||||
String fullReason = this.plugin
|
||||
.getLanguageManager()
|
||||
.getMessage("punishment.ban_reason", target, new Object[]{"reason", reason, "discord_url", discordUrl});
|
||||
Bukkit.getBanList(Type.NAME).addBan(target.getName(), fullReason, null, adminName);
|
||||
target.kickPlayer(fullReason);
|
||||
}
|
||||
);
|
||||
} else {
|
||||
Bukkit.getScheduler().runTask(this.plugin, () -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), commandToRun));
|
||||
}
|
||||
|
||||
if (this.plugin.getAuditLogManager() != null) {
|
||||
this.plugin.getAuditLogManager().logPunishment(target, reason, isAutoBan ? "AUTO-BAN" : "MANUAL-BAN", false);
|
||||
}
|
||||
}
|
||||
|
||||
public void banForRefusingCheck(String playerName, String ip) {
|
||||
String mode = this.plugin.getConfig().getString("punishment.mode", "AUTO").toUpperCase();
|
||||
String template = this.plugin
|
||||
.getConfig()
|
||||
.getString("punishment.commands.leave_on_freeze_ban", "tempban {player} 30d Refusal of Cheat Inspection [SynapseAI] -s");
|
||||
String discordUrl = this.plugin.getConfig().getString("discord.invite_url", "https://dsc.gg/synapselabs");
|
||||
String commandToRun = template.replace("{player}", playerName).replace("{discord_url}", discordUrl);
|
||||
Bukkit.getScheduler()
|
||||
.runTask(
|
||||
this.plugin,
|
||||
() -> {
|
||||
if (!mode.equals("CUSTOM_COMMAND") && this.activePlugin == PunishmentManager.DetectedBanPlugin.BUKKIT) {
|
||||
String fullReason = this.plugin
|
||||
.getLanguageManager()
|
||||
.getMessage("punishment.ban_reason_refusal", Bukkit.getConsoleSender(), new Object[]{"discord_url", discordUrl});
|
||||
Bukkit.getBanList(Type.NAME).addBan(playerName, fullReason, new Date(System.currentTimeMillis() + 2592000000L), "SynapseAI");
|
||||
} else {
|
||||
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), commandToRun);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
public enum DetectedBanPlugin {
|
||||
LITEBANS("LiteBans"),
|
||||
ADVANCED_BAN("AdvancedBan"),
|
||||
LIBERTY_BANS("LibertyBans"),
|
||||
ESSENTIALS("Essentials"),
|
||||
MAX_BANS("MaxBans"),
|
||||
BUKKIT("Bukkit/Vanilla");
|
||||
|
||||
private final String display;
|
||||
|
||||
DetectedBanPlugin(String display) {
|
||||
this.display = display;
|
||||
}
|
||||
|
||||
public String getDisplay() {
|
||||
return this.display;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
package net.synapselabs.anticheat.tracker;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.UUID;
|
||||
import net.synapselabs.anticheat.data.ThreatState;
|
||||
import net.synapselabs.anticheat.engine.FeatureVector;
|
||||
import net.synapselabs.anticheat.engine.RiskAccumulator;
|
||||
import net.synapselabs.anticheat.engine.RiskAssessment;
|
||||
import net.synapselabs.anticheat.tracker.KinematicHistory.RaycastHitResult;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class CombatTracker {
|
||||
private final KinematicHistory history = new KinematicHistory();
|
||||
private final RiskAccumulator riskAccumulator = new RiskAccumulator();
|
||||
private volatile RiskAssessment lastAssessment;
|
||||
private static final long TARGET_SWITCH_WINDOW_MS = 800L;
|
||||
private static final long ROBOTIC_STREAK_GAP_MS = 1500L;
|
||||
private static final int REPEATED_PATTERN_MIN = 4;
|
||||
private UUID lastVictimId;
|
||||
private long lastVictimTime;
|
||||
private int roboticStreak;
|
||||
private long lastRoboticTime;
|
||||
private float rawScore = 0.0F;
|
||||
private float confidence = 0.0F;
|
||||
private float killauraConfidence = 0.0F;
|
||||
private float aimConfidence = 0.0F;
|
||||
private float suspicion = 0.0F;
|
||||
private ThreatState threatState = ThreatState.CLEAN;
|
||||
private int suspiciousStreak = 0;
|
||||
private int consecutivePerfectHits = 0;
|
||||
private int consecutiveCrits = 0;
|
||||
private int consecutiveLowVarianceHits = 0;
|
||||
private int consecutiveSilentHits = 0;
|
||||
private long lastAnalysisTimestamp = 0L;
|
||||
private long lastDecayTimestamp = System.currentTimeMillis();
|
||||
private float lastModelProbability = 0.0F;
|
||||
private final Deque<Float> recentHitConfidences = new ArrayDeque<>();
|
||||
private static final int MULTI_HIT_WINDOW = 10;
|
||||
|
||||
public KinematicHistory getHistory() {
|
||||
return this.history;
|
||||
}
|
||||
|
||||
public RiskAccumulator getRiskAccumulator() {
|
||||
return this.riskAccumulator;
|
||||
}
|
||||
|
||||
public int getConsecutivePerfectHits() {
|
||||
return this.consecutivePerfectHits;
|
||||
}
|
||||
|
||||
public int getConsecutiveCrits() {
|
||||
return this.consecutiveCrits;
|
||||
}
|
||||
|
||||
public int getConsecutiveLowVarianceHits() {
|
||||
return this.consecutiveLowVarianceHits;
|
||||
}
|
||||
|
||||
public int getConsecutiveSilentHits() {
|
||||
return this.consecutiveSilentHits;
|
||||
}
|
||||
|
||||
public void setLastAssessment(RiskAssessment assessment) {
|
||||
this.lastAssessment = assessment;
|
||||
}
|
||||
|
||||
public RiskAssessment getLastAssessment() {
|
||||
return this.lastAssessment;
|
||||
}
|
||||
|
||||
public float getLastModelProbability() {
|
||||
return this.lastModelProbability;
|
||||
}
|
||||
|
||||
public synchronized CombatTracker.PatternContext updatePattern(UUID victimId, boolean roboticSnap) {
|
||||
long now = System.currentTimeMillis();
|
||||
boolean targetSwitch = this.lastVictimId != null && !this.lastVictimId.equals(victimId) && now - this.lastVictimTime < 800L;
|
||||
this.lastVictimId = victimId;
|
||||
this.lastVictimTime = now;
|
||||
if (roboticSnap) {
|
||||
this.roboticStreak = now - this.lastRoboticTime <= 1500L ? this.roboticStreak + 1 : 1;
|
||||
this.lastRoboticTime = now;
|
||||
} else if (now - this.lastRoboticTime > 1500L) {
|
||||
this.roboticStreak = 0;
|
||||
}
|
||||
|
||||
boolean repeatedPattern = this.roboticStreak >= 4;
|
||||
return new CombatTracker.PatternContext(targetSwitch, repeatedPattern);
|
||||
}
|
||||
|
||||
public synchronized void applyRisk(float riskScore01, ThreatState state) {
|
||||
float clamped = Math.max(0.0F, Math.min(1.0F, riskScore01));
|
||||
this.rawScore = clamped;
|
||||
this.confidence = clamped;
|
||||
this.killauraConfidence = clamped;
|
||||
this.aimConfidence = clamped;
|
||||
this.suspicion = Math.max(this.suspicion, clamped);
|
||||
this.threatState = state;
|
||||
this.lastAnalysisTimestamp = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public FeatureVector createFeatureVector(Player attacker, Location eyeLoc, Location victimLoc, RaycastHitResult raycast) {
|
||||
float distance = (float)eyeLoc.distance(victimLoc);
|
||||
float angleOffsetToEye = KinematicHistory.calculateAngleOffset(eyeLoc, victimLoc);
|
||||
boolean rayHit = raycast.hit();
|
||||
float raycastDistance = raycast.distance();
|
||||
float raycastAngleError = rayHit ? 0.0F : raycast.angleOffsetDeg();
|
||||
float hitboxEdgeProximity = raycast.hitboxEdgeProximity();
|
||||
float yawDelta1t = this.history.getYawDelta(1);
|
||||
float yawDelta2t = this.history.getYawDelta(2);
|
||||
float yawDelta5t = this.history.getYawDelta(5);
|
||||
float yawAccel = this.history.getYawAcceleration();
|
||||
float yawJerk = this.history.getYawJerk();
|
||||
float pitchDelta1t = this.history.getPitchDelta(1);
|
||||
float pitchDelta2t = this.history.getPitchDelta(2);
|
||||
float pitchDelta5t = this.history.getPitchDelta(5);
|
||||
float pitchAccel = this.history.getPitchAcceleration();
|
||||
float pitchJerk = this.history.getPitchJerk();
|
||||
boolean isFalling = attacker.getFallDistance() > 0.0F && !attacker.isOnGround() || attacker.isInWater() && attacker.getVelocity().getY() < -0.05;
|
||||
boolean isSprinting = attacker.isSprinting();
|
||||
float cooldown = 1.0F;
|
||||
|
||||
try {
|
||||
cooldown = attacker.getAttackCooldown();
|
||||
} catch (Throwable var40) {
|
||||
}
|
||||
|
||||
float attackIntervalTicks = this.history.getAttackIntervalTicks();
|
||||
float rotationVariance10t = this.history.getRotationVariance10t();
|
||||
float targetSwitchTicks = this.lastVictimTime > 0L ? Math.min(200.0F, (float)(System.currentTimeMillis() - this.lastVictimTime) / 50.0F) : 100.0F;
|
||||
float attackerVelocitySq = 0.0F;
|
||||
|
||||
try {
|
||||
attackerVelocitySq = (float)attacker.getVelocity().lengthSquared();
|
||||
} catch (Throwable var39) {
|
||||
}
|
||||
|
||||
float victimVelocitySq = 0.0F;
|
||||
if (cooldown >= 0.98F && attackIntervalTicks >= 10.0F && attackIntervalTicks <= 14.0F) {
|
||||
this.consecutivePerfectHits++;
|
||||
} else if (cooldown < 0.9F || attackIntervalTicks < 8.0F) {
|
||||
this.consecutivePerfectHits = 0;
|
||||
}
|
||||
|
||||
boolean isCritHit = isFalling && cooldown > 0.85F;
|
||||
if (isCritHit) {
|
||||
this.consecutiveCrits++;
|
||||
} else {
|
||||
this.consecutiveCrits = Math.max(0, this.consecutiveCrits - 1);
|
||||
}
|
||||
|
||||
if (rotationVariance10t < 5.0F && distance >= 1.5F && angleOffsetToEye < 25.0F) {
|
||||
this.consecutiveLowVarianceHits++;
|
||||
} else if (rotationVariance10t > 15.0F) {
|
||||
this.consecutiveLowVarianceHits = 0;
|
||||
}
|
||||
|
||||
float angularVel = this.history.getAngularVelocity();
|
||||
if (!rayHit && angularVel < 0.2F && angleOffsetToEye > 12.0F && distance >= 1.5F) {
|
||||
this.consecutiveSilentHits++;
|
||||
} else {
|
||||
this.consecutiveSilentHits = 0;
|
||||
}
|
||||
|
||||
float gcdErrorRate = this.history.getGcdErrorRate();
|
||||
float detectedSensitivity = this.history.getDetectedSensitivity();
|
||||
float gcdSnapFlag = this.history.getGcdSnapFlag(System.currentTimeMillis());
|
||||
float attackIntervalVariance10t = this.history.getAttackIntervalVariance10t();
|
||||
float strafeRotationCorrelation = this.history.getStrafeRotationCorrelation();
|
||||
float prePostAngularVelocityDelta = this.history.getPrePostAngularVelocityDelta();
|
||||
float multiTargetSwitchRate = 0.0F;
|
||||
if (targetSwitchTicks < 20.0F && angleOffsetToEye > 25.0F) {
|
||||
multiTargetSwitchRate = (float)Math.min(5.0, angleOffsetToEye / Math.max(1.0F, targetSwitchTicks));
|
||||
}
|
||||
|
||||
float velocityKnockbackDeviation = 0.0F;
|
||||
if (attacker.getVelocity().lengthSquared() > 0.01) {
|
||||
velocityKnockbackDeviation = (float)Math.abs(attacker.getVelocity().getY());
|
||||
}
|
||||
|
||||
return FeatureVector.createV3(
|
||||
distance,
|
||||
angleOffsetToEye,
|
||||
yawDelta1t,
|
||||
yawDelta2t,
|
||||
yawDelta5t,
|
||||
yawAccel,
|
||||
yawJerk,
|
||||
pitchDelta1t,
|
||||
pitchDelta2t,
|
||||
pitchDelta5t,
|
||||
pitchAccel,
|
||||
pitchJerk,
|
||||
rayHit,
|
||||
raycastDistance,
|
||||
raycastAngleError,
|
||||
hitboxEdgeProximity,
|
||||
isFalling,
|
||||
isSprinting,
|
||||
cooldown,
|
||||
rotationVariance10t,
|
||||
attackIntervalTicks,
|
||||
targetSwitchTicks,
|
||||
attackerVelocitySq,
|
||||
victimVelocitySq,
|
||||
gcdErrorRate,
|
||||
detectedSensitivity,
|
||||
gcdSnapFlag,
|
||||
attackIntervalVariance10t,
|
||||
strafeRotationCorrelation,
|
||||
prePostAngularVelocityDelta,
|
||||
multiTargetSwitchRate,
|
||||
velocityKnockbackDeviation
|
||||
);
|
||||
}
|
||||
|
||||
public synchronized void recordModelInference(float modelProbability) {
|
||||
this.lastModelProbability = modelProbability;
|
||||
this.recentHitConfidences.addFirst(modelProbability);
|
||||
|
||||
while (this.recentHitConfidences.size() > 10) {
|
||||
this.recentHitConfidences.removeLast();
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized boolean hasMultiHitConfirmation(int requiredHits, float threshold) {
|
||||
if (this.recentHitConfidences.size() < requiredHits) {
|
||||
return false;
|
||||
}
|
||||
|
||||
int highConfidenceCount = 0;
|
||||
|
||||
for (float conf : this.recentHitConfidences) {
|
||||
if (conf >= threshold) {
|
||||
highConfidenceCount++;
|
||||
}
|
||||
}
|
||||
|
||||
return highConfidenceCount >= requiredHits;
|
||||
}
|
||||
|
||||
public synchronized int getRecentHighConfidenceHits(float threshold) {
|
||||
int count = 0;
|
||||
|
||||
for (float conf : this.recentHitConfidences) {
|
||||
if (conf >= threshold) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
public synchronized void processAiInference(float aiProbability, float minConfidenceThreshold) {
|
||||
this.rawScore = aiProbability;
|
||||
this.lastAnalysisTimestamp = System.currentTimeMillis();
|
||||
if (aiProbability >= minConfidenceThreshold) {
|
||||
this.suspiciousStreak++;
|
||||
float alpha = 0.4F + Math.min(0.35F, this.suspiciousStreak * 0.1F);
|
||||
this.killauraConfidence = alpha * aiProbability + (1.0F - alpha) * this.killauraConfidence;
|
||||
this.aimConfidence = alpha * (aiProbability * 0.95F) + (1.0F - alpha) * this.aimConfidence;
|
||||
this.suspicion = Math.min(1.0F, this.suspicion + 0.15F);
|
||||
} else {
|
||||
if (this.suspiciousStreak > 0) {
|
||||
this.suspiciousStreak--;
|
||||
}
|
||||
|
||||
this.killauraConfidence = Math.max(0.0F, this.killauraConfidence * 0.96F);
|
||||
this.aimConfidence = Math.max(0.0F, this.aimConfidence * 0.96F);
|
||||
}
|
||||
|
||||
this.confidence = Math.max(this.killauraConfidence, this.aimConfidence);
|
||||
this.threatState = ThreatState.fromConfidence(this.confidence);
|
||||
}
|
||||
|
||||
public synchronized void registerHardViolation(String checkName) {
|
||||
this.rawScore = 1.0F;
|
||||
this.confidence = 0.98F;
|
||||
this.killauraConfidence = 0.98F;
|
||||
this.aimConfidence = 0.95F;
|
||||
this.suspicion = Math.min(1.0F, this.suspicion + 0.4F);
|
||||
this.threatState = ThreatState.CONFIRMED;
|
||||
this.suspiciousStreak += 3;
|
||||
}
|
||||
|
||||
public synchronized void registerGrimViolation(String checkName, double vl) {
|
||||
this.lastAnalysisTimestamp = System.currentTimeMillis();
|
||||
this.suspicion = Math.min(1.0F, this.suspicion + 0.25F);
|
||||
this.suspiciousStreak += 2;
|
||||
String checkLower = checkName.toLowerCase();
|
||||
if (!checkLower.contains("reach") && !checkLower.contains("hitbox") && !checkLower.contains("killaura") && !checkLower.contains("aim")) {
|
||||
this.confidence = Math.max(this.confidence, 0.6F);
|
||||
if (this.threatState == ThreatState.CLEAN) {
|
||||
this.threatState = ThreatState.SUSPICIOUS;
|
||||
}
|
||||
} else {
|
||||
this.killauraConfidence = Math.max(0.8F, this.killauraConfidence + 0.25F);
|
||||
this.aimConfidence = Math.max(0.75F, this.aimConfidence + 0.2F);
|
||||
this.confidence = Math.max(this.killauraConfidence, this.aimConfidence);
|
||||
this.threatState = ThreatState.fromConfidence(this.confidence);
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void decay(float amount) {
|
||||
long now = System.currentTimeMillis();
|
||||
if (now - this.lastAnalysisTimestamp > 6000L) {
|
||||
this.killauraConfidence = Math.max(0.0F, this.killauraConfidence - amount * 0.3F);
|
||||
this.aimConfidence = Math.max(0.0F, this.aimConfidence - amount * 0.3F);
|
||||
this.confidence = Math.max(this.killauraConfidence, this.aimConfidence);
|
||||
this.suspicion = Math.max(0.0F, this.suspicion - amount * 0.5F);
|
||||
this.threatState = ThreatState.fromConfidence(this.confidence);
|
||||
}
|
||||
|
||||
this.lastDecayTimestamp = now;
|
||||
}
|
||||
|
||||
public synchronized void reset() {
|
||||
this.rawScore = 0.0F;
|
||||
this.confidence = 0.0F;
|
||||
this.killauraConfidence = 0.0F;
|
||||
this.aimConfidence = 0.0F;
|
||||
this.suspicion = 0.0F;
|
||||
this.threatState = ThreatState.CLEAN;
|
||||
this.suspiciousStreak = 0;
|
||||
this.roboticStreak = 0;
|
||||
this.lastRoboticTime = 0L;
|
||||
this.lastVictimId = null;
|
||||
this.lastVictimTime = 0L;
|
||||
this.riskAccumulator.reset();
|
||||
this.lastAssessment = null;
|
||||
}
|
||||
|
||||
public float getRawScore() {
|
||||
return this.rawScore;
|
||||
}
|
||||
|
||||
public float getConfidence() {
|
||||
return this.confidence;
|
||||
}
|
||||
|
||||
public float getKillauraConfidence() {
|
||||
return this.killauraConfidence;
|
||||
}
|
||||
|
||||
public float getAimConfidence() {
|
||||
return this.aimConfidence;
|
||||
}
|
||||
|
||||
public float getSuspicion() {
|
||||
return this.suspicion;
|
||||
}
|
||||
|
||||
public ThreatState getThreatState() {
|
||||
return this.threatState;
|
||||
}
|
||||
|
||||
public int getSuspiciousStreak() {
|
||||
return this.suspiciousStreak;
|
||||
}
|
||||
|
||||
public record PatternContext(boolean targetSwitch, boolean repeatedPattern) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,532 @@
|
||||
package net.synapselabs.anticheat.tracker;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.LinkedList;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.LivingEntity;
|
||||
import org.bukkit.util.BoundingBox;
|
||||
import org.bukkit.util.RayTraceResult;
|
||||
import org.bukkit.util.Vector;
|
||||
|
||||
public class KinematicHistory {
|
||||
private final LinkedList<KinematicHistory.Snapshot> history = new LinkedList<>();
|
||||
private static final int MAX_HISTORY = 40;
|
||||
private final Deque<Long> attackTimestamps = new ArrayDeque<>();
|
||||
private final Deque<Double> distanceHistory = new ArrayDeque<>();
|
||||
private static final int STATS_WINDOW = 10;
|
||||
private final Deque<Float> yawDeltaWindow = new ArrayDeque<>();
|
||||
private final Deque<Float> pitchDeltaWindow = new ArrayDeque<>();
|
||||
private static final int GCD_WINDOW_SIZE = 25;
|
||||
private double personalBaselineGcdError = 0.05;
|
||||
private long baselineUpdateCount = 0L;
|
||||
private float rollingDetectedSensitivity = 0.5F;
|
||||
private double rollingGcdStep = 0.015;
|
||||
private long lastRotationTimestamp = 0L;
|
||||
private long lastAttackTimestamp = 0L;
|
||||
|
||||
public void push(Location loc) {
|
||||
if (loc != null) {
|
||||
long now = System.currentTimeMillis();
|
||||
if (!this.history.isEmpty()) {
|
||||
KinematicHistory.Snapshot last = this.history.peekFirst();
|
||||
if (last != null) {
|
||||
if (Math.abs(loc.getX() - last.x) < 1.0E-4
|
||||
&& Math.abs(loc.getY() - last.y) < 1.0E-4
|
||||
&& Math.abs(loc.getZ() - last.z) < 1.0E-4
|
||||
&& Math.abs(loc.getYaw() - last.yaw) < 0.01F
|
||||
&& Math.abs(loc.getPitch() - last.pitch) < 0.01F) {
|
||||
return;
|
||||
}
|
||||
|
||||
float dYaw = Math.abs(angleDelta(loc.getYaw(), last.yaw));
|
||||
float dPitch = Math.abs(angleDelta(loc.getPitch(), last.pitch));
|
||||
if (dYaw > 0.01F || dPitch > 0.01F) {
|
||||
this.lastRotationTimestamp = now;
|
||||
this.recordDelta(dYaw, dPitch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.history.addFirst(new KinematicHistory.Snapshot(loc.getYaw(), loc.getPitch(), loc.getX(), loc.getY(), loc.getZ(), now));
|
||||
|
||||
while (this.history.size() > 40) {
|
||||
this.history.removeLast();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void recordDelta(float dYaw, float dPitch) {
|
||||
if (dYaw > 0.005F && dYaw < 45.0F) {
|
||||
this.yawDeltaWindow.addFirst(dYaw);
|
||||
|
||||
while (this.yawDeltaWindow.size() > 25) {
|
||||
this.yawDeltaWindow.removeLast();
|
||||
}
|
||||
}
|
||||
|
||||
if (dPitch > 0.005F && dPitch < 45.0F) {
|
||||
this.pitchDeltaWindow.addFirst(dPitch);
|
||||
|
||||
while (this.pitchDeltaWindow.size() > 25) {
|
||||
this.pitchDeltaWindow.removeLast();
|
||||
}
|
||||
}
|
||||
|
||||
if (this.yawDeltaWindow.size() >= 5) {
|
||||
this.updateGcdAndSensitivity();
|
||||
}
|
||||
}
|
||||
|
||||
private void updateGcdAndSensitivity() {
|
||||
Float[] yaws = this.yawDeltaWindow.toArray(new Float[0]);
|
||||
Float[] pitches = this.pitchDeltaWindow.toArray(new Float[0]);
|
||||
if (yaws.length >= 3) {
|
||||
double currentGcd = 0.0;
|
||||
|
||||
for (int i = 0; i < yaws.length - 1; i++) {
|
||||
double pairGcd = computeFloatGcd(yaws[i].floatValue(), yaws[i + 1].floatValue());
|
||||
if (pairGcd > 0.001 && pairGcd < 3.0) {
|
||||
currentGcd = currentGcd == 0.0 ? pairGcd : computeFloatGcd(currentGcd, pairGcd);
|
||||
}
|
||||
}
|
||||
|
||||
if (pitches.length >= 2) {
|
||||
for (int i = 0; i < pitches.length - 1; i++) {
|
||||
double pairGcd = computeFloatGcd(pitches[i].floatValue(), pitches[i + 1].floatValue());
|
||||
if (pairGcd > 0.001 && pairGcd < 3.0) {
|
||||
currentGcd = currentGcd == 0.0 ? pairGcd : computeFloatGcd(currentGcd, pairGcd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (currentGcd >= 5.0E-4 && currentGcd <= 1.5) {
|
||||
this.rollingGcdStep = 0.85 * this.rollingGcdStep + 0.15 * currentGcd;
|
||||
double f = Math.cbrt(this.rollingGcdStep / 0.18);
|
||||
double sens = (f - 0.2) / 0.6;
|
||||
this.rollingDetectedSensitivity = (float)Math.max(0.0, Math.min(1.0, sens));
|
||||
double rawError = this.computeCurrentRawGcdError();
|
||||
if (this.baselineUpdateCount < 50L) {
|
||||
this.personalBaselineGcdError = (this.personalBaselineGcdError * this.baselineUpdateCount + rawError) / (this.baselineUpdateCount + 1L);
|
||||
this.baselineUpdateCount++;
|
||||
} else {
|
||||
this.personalBaselineGcdError = 0.995 * this.personalBaselineGcdError + 0.005 * rawError;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public double getPersonalBaselineGcdError() {
|
||||
return this.personalBaselineGcdError;
|
||||
}
|
||||
|
||||
public void updatePersonalBaseline(double error) {
|
||||
this.personalBaselineGcdError = error;
|
||||
}
|
||||
|
||||
public static double computeFloatGcd(double a, double b) {
|
||||
if (a < b) {
|
||||
double t = a;
|
||||
a = b;
|
||||
b = t;
|
||||
}
|
||||
|
||||
return Math.abs(b) < 0.001 ? a : computeFloatGcd(b, a - Math.floor(a / b) * b);
|
||||
}
|
||||
|
||||
private double computeCurrentRawGcdError() {
|
||||
if (!(this.rollingGcdStep < 1.0E-4) && !this.yawDeltaWindow.isEmpty()) {
|
||||
double sumError = 0.0;
|
||||
int count = 0;
|
||||
|
||||
for (Float d : this.yawDeltaWindow) {
|
||||
double multiple = Math.round(d.floatValue() / this.rollingGcdStep);
|
||||
double expected = multiple * this.rollingGcdStep;
|
||||
double error = Math.abs(d.floatValue() - expected) / (this.rollingGcdStep + 1.0E-5);
|
||||
sumError += Math.min(1.0, error);
|
||||
count++;
|
||||
}
|
||||
|
||||
return count > 0 ? sumError / count : 0.0;
|
||||
} else {
|
||||
return 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
public float getGcdErrorRate() {
|
||||
double rawError = this.computeCurrentRawGcdError();
|
||||
return this.personalBaselineGcdError > 1.0E-4
|
||||
? (float)Math.max(0.0, Math.min(5.0, rawError / this.personalBaselineGcdError))
|
||||
: (float)Math.max(0.0, Math.min(5.0, rawError));
|
||||
}
|
||||
|
||||
public float getDetectedSensitivity() {
|
||||
return this.rollingDetectedSensitivity;
|
||||
}
|
||||
|
||||
public float getGcdSnapFlag(long hitTimestamp) {
|
||||
if (this.history.size() < 4) {
|
||||
return 0.0F;
|
||||
}
|
||||
|
||||
int nearHitCount = 0;
|
||||
double nearHitError = 0.0;
|
||||
int outsideCount = 0;
|
||||
double outsideError = 0.0;
|
||||
|
||||
for (int i = 0; i < this.history.size() - 1; i++) {
|
||||
KinematicHistory.Snapshot curr = this.history.get(i);
|
||||
KinematicHistory.Snapshot prev = this.history.get(i + 1);
|
||||
float dYaw = Math.abs(angleDelta(curr.yaw, prev.yaw));
|
||||
if (!(dYaw < 0.01F)) {
|
||||
double multiple = Math.round(dYaw / (this.rollingGcdStep + 1.0E-5));
|
||||
double err = Math.abs(dYaw - multiple * this.rollingGcdStep) / (this.rollingGcdStep + 1.0E-5);
|
||||
long diff = Math.abs(curr.time - hitTimestamp);
|
||||
if (diff <= 250L) {
|
||||
nearHitError += err;
|
||||
nearHitCount++;
|
||||
} else if (diff <= 1000L) {
|
||||
outsideError += err;
|
||||
outsideCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (nearHitCount >= 2 && outsideCount >= 2) {
|
||||
double avgNear = nearHitError / nearHitCount;
|
||||
double avgOutside = outsideError / outsideCount;
|
||||
if (avgNear < 0.02 && avgOutside > 0.15) {
|
||||
return 1.0F;
|
||||
}
|
||||
}
|
||||
|
||||
return 0.0F;
|
||||
}
|
||||
|
||||
public float getAttackIntervalVariance10t() {
|
||||
if (this.attackTimestamps.size() < 3) {
|
||||
return 1.0F;
|
||||
}
|
||||
|
||||
Long[] arr = this.attackTimestamps.toArray(new Long[0]);
|
||||
int n = arr.length - 1;
|
||||
double[] intervals = new double[n];
|
||||
double sum = 0.0;
|
||||
|
||||
for (int i = 0; i < n; i++) {
|
||||
intervals[i] = (arr[i] - arr[i + 1]) / 50.0;
|
||||
sum += intervals[i];
|
||||
}
|
||||
|
||||
double mean = sum / n;
|
||||
double sumSq = 0.0;
|
||||
|
||||
for (int i = 0; i < n; i++) {
|
||||
sumSq += Math.pow(intervals[i] - mean, 2.0);
|
||||
}
|
||||
|
||||
return (float)(sumSq / n);
|
||||
}
|
||||
|
||||
public float getStrafeRotationCorrelation() {
|
||||
int window = Math.min(10, this.history.size() - 1);
|
||||
if (window < 4) {
|
||||
return 0.5F;
|
||||
}
|
||||
|
||||
double sumMoveAngle = 0.0;
|
||||
double sumYaw = 0.0;
|
||||
double[] moveAngles = new double[window];
|
||||
double[] yaws = new double[window];
|
||||
|
||||
for (int i = 0; i < window; i++) {
|
||||
KinematicHistory.Snapshot curr = this.history.get(i);
|
||||
KinematicHistory.Snapshot prev = this.history.get(i + 1);
|
||||
double dx = curr.x - prev.x;
|
||||
double dz = curr.z - prev.z;
|
||||
double moveAngle = Math.toDegrees(Math.atan2(dz, dx));
|
||||
moveAngles[i] = moveAngle;
|
||||
yaws[i] = curr.yaw;
|
||||
sumMoveAngle += moveAngle;
|
||||
sumYaw += curr.yaw;
|
||||
}
|
||||
|
||||
double meanMove = sumMoveAngle / window;
|
||||
double meanYaw = sumYaw / window;
|
||||
double num = 0.0;
|
||||
double den1 = 0.0;
|
||||
double den2 = 0.0;
|
||||
|
||||
for (int i = 0; i < window; i++) {
|
||||
double dMove = moveAngles[i] - meanMove;
|
||||
double dYaw = yaws[i] - meanYaw;
|
||||
num += dMove * dYaw;
|
||||
den1 += dMove * dMove;
|
||||
den2 += dYaw * dYaw;
|
||||
}
|
||||
|
||||
double denom = Math.sqrt(den1 * den2);
|
||||
return denom < 1.0E-5 ? 0.5F : (float)Math.max(-1.0, Math.min(1.0, num / denom));
|
||||
}
|
||||
|
||||
public float getPrePostAngularVelocityDelta() {
|
||||
if (this.history.size() < 4) {
|
||||
return 0.0F;
|
||||
}
|
||||
|
||||
long now = System.currentTimeMillis();
|
||||
double preSpeedSum = 0.0;
|
||||
int preCount = 0;
|
||||
double postSpeedSum = 0.0;
|
||||
int postCount = 0;
|
||||
|
||||
for (int i = 0; i < this.history.size() - 1; i++) {
|
||||
KinematicHistory.Snapshot curr = this.history.get(i);
|
||||
KinematicHistory.Snapshot prev = this.history.get(i + 1);
|
||||
float yd = Math.abs(angleDelta(curr.yaw, prev.yaw));
|
||||
float pd = Math.abs(angleDelta(curr.pitch, prev.pitch));
|
||||
double speed = Math.sqrt(yd * yd + pd * pd);
|
||||
long dt = curr.time - this.lastAttackTimestamp;
|
||||
if (dt >= -300L && dt <= 0L) {
|
||||
preSpeedSum += speed;
|
||||
preCount++;
|
||||
} else if (dt > 0L && dt <= 300L) {
|
||||
postSpeedSum += speed;
|
||||
postCount++;
|
||||
}
|
||||
}
|
||||
|
||||
double avgPre = preCount > 0 ? preSpeedSum / preCount : 0.0;
|
||||
double avgPost = postCount > 0 ? postSpeedSum / postCount : 0.0;
|
||||
return (float)(avgPre - avgPost);
|
||||
}
|
||||
|
||||
public boolean isMovingDownwards() {
|
||||
if (this.history.size() < 2) {
|
||||
return false;
|
||||
}
|
||||
|
||||
KinematicHistory.Snapshot curr = this.history.get(0);
|
||||
KinematicHistory.Snapshot prev = this.history.get(1);
|
||||
return curr.y < prev.y - 0.005;
|
||||
}
|
||||
|
||||
public void registerAttack(double distance) {
|
||||
long now = System.currentTimeMillis();
|
||||
this.lastAttackTimestamp = now;
|
||||
this.attackTimestamps.addFirst(now);
|
||||
|
||||
while (this.attackTimestamps.size() > 10) {
|
||||
this.attackTimestamps.removeLast();
|
||||
}
|
||||
|
||||
this.distanceHistory.addFirst(distance);
|
||||
|
||||
while (this.distanceHistory.size() > 10) {
|
||||
this.distanceHistory.removeLast();
|
||||
}
|
||||
}
|
||||
|
||||
public float getAttackIntervalTicks() {
|
||||
if (this.attackTimestamps.size() < 2) {
|
||||
return 10.0F;
|
||||
}
|
||||
|
||||
Long[] arr = this.attackTimestamps.toArray(new Long[0]);
|
||||
long deltaMs = arr[0] - arr[1];
|
||||
return Math.max(1.0F, (float)(deltaMs / 50.0));
|
||||
}
|
||||
|
||||
public double getMeanReach() {
|
||||
if (this.distanceHistory.isEmpty()) {
|
||||
return 3.0;
|
||||
}
|
||||
|
||||
double sum = 0.0;
|
||||
|
||||
for (double d : this.distanceHistory) {
|
||||
sum += d;
|
||||
}
|
||||
|
||||
return sum / this.distanceHistory.size();
|
||||
}
|
||||
|
||||
public double getReachVariance() {
|
||||
if (this.distanceHistory.size() < 2) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
double mean = this.getMeanReach();
|
||||
double sum = 0.0;
|
||||
|
||||
for (double d : this.distanceHistory) {
|
||||
sum += Math.pow(d - mean, 2.0);
|
||||
}
|
||||
|
||||
return sum / this.distanceHistory.size();
|
||||
}
|
||||
|
||||
public long getLastAttackTimestamp() {
|
||||
return this.lastAttackTimestamp;
|
||||
}
|
||||
|
||||
public long getLastRotationTimestamp() {
|
||||
return this.lastRotationTimestamp;
|
||||
}
|
||||
|
||||
public long getTimeSinceLastRotation() {
|
||||
return System.currentTimeMillis() - this.lastRotationTimestamp;
|
||||
}
|
||||
|
||||
public static float wrapDegrees(float f) {
|
||||
f %= 360.0F;
|
||||
if (f >= 180.0F) {
|
||||
f -= 360.0F;
|
||||
}
|
||||
|
||||
if (f < -180.0F) {
|
||||
f += 360.0F;
|
||||
}
|
||||
|
||||
return f;
|
||||
}
|
||||
|
||||
public static float angleDelta(float current, float prev) {
|
||||
return wrapDegrees(current - prev);
|
||||
}
|
||||
|
||||
public float getYawDelta(int ticksAgo) {
|
||||
return this.history.size() <= ticksAgo ? 0.0F : angleDelta(this.history.get(0).yaw, this.history.get(ticksAgo).yaw);
|
||||
}
|
||||
|
||||
public float getPitchDelta(int ticksAgo) {
|
||||
return this.history.size() <= ticksAgo ? 0.0F : angleDelta(this.history.get(0).pitch, this.history.get(ticksAgo).pitch);
|
||||
}
|
||||
|
||||
public float getYawAcceleration() {
|
||||
if (this.history.size() < 3) {
|
||||
return 0.0F;
|
||||
}
|
||||
|
||||
float d1 = this.getYawDelta(1);
|
||||
float dPrev = angleDelta(this.history.get(1).yaw, this.history.get(2).yaw);
|
||||
return d1 - dPrev;
|
||||
}
|
||||
|
||||
public float getYawSpeedChange() {
|
||||
if (this.history.size() < 3) {
|
||||
return 0.0F;
|
||||
}
|
||||
|
||||
float d1 = Math.abs(this.getYawDelta(1));
|
||||
float dPrev = Math.abs(angleDelta(this.history.get(1).yaw, this.history.get(2).yaw));
|
||||
return d1 - dPrev;
|
||||
}
|
||||
|
||||
public float getPitchAcceleration() {
|
||||
if (this.history.size() < 3) {
|
||||
return 0.0F;
|
||||
}
|
||||
|
||||
float d1 = this.getPitchDelta(1);
|
||||
float dPrev = angleDelta(this.history.get(1).pitch, this.history.get(2).pitch);
|
||||
return d1 - dPrev;
|
||||
}
|
||||
|
||||
public float getYawJerk() {
|
||||
if (this.history.size() < 4) {
|
||||
return 0.0F;
|
||||
}
|
||||
|
||||
float aCurrent = this.getYawAcceleration();
|
||||
float dPrev1 = angleDelta(this.history.get(1).yaw, this.history.get(2).yaw);
|
||||
float dPrev2 = angleDelta(this.history.get(2).yaw, this.history.get(3).yaw);
|
||||
float aPrev = dPrev1 - dPrev2;
|
||||
return aCurrent - aPrev;
|
||||
}
|
||||
|
||||
public float getPitchJerk() {
|
||||
if (this.history.size() < 4) {
|
||||
return 0.0F;
|
||||
}
|
||||
|
||||
float aCurrent = this.getPitchAcceleration();
|
||||
float dPrev1 = angleDelta(this.history.get(1).pitch, this.history.get(2).pitch);
|
||||
float dPrev2 = angleDelta(this.history.get(2).pitch, this.history.get(3).pitch);
|
||||
float aPrev = dPrev1 - dPrev2;
|
||||
return aCurrent - aPrev;
|
||||
}
|
||||
|
||||
public float getRotationVariance10t() {
|
||||
int window = Math.min(10, this.history.size() - 1);
|
||||
if (window < 3) {
|
||||
return 5.0F;
|
||||
}
|
||||
|
||||
float[] speeds = new float[window];
|
||||
float sum = 0.0F;
|
||||
|
||||
for (int i = 0; i < window; i++) {
|
||||
float yd = Math.abs(angleDelta(this.history.get(i).yaw, this.history.get(i + 1).yaw));
|
||||
float pd = Math.abs(angleDelta(this.history.get(i).pitch, this.history.get(i + 1).pitch));
|
||||
speeds[i] = (float)Math.sqrt(yd * yd + pd * pd);
|
||||
sum += speeds[i];
|
||||
}
|
||||
|
||||
float mean = sum / window;
|
||||
float sumSq = 0.0F;
|
||||
|
||||
for (int i = 0; i < window; i++) {
|
||||
float diff = speeds[i] - mean;
|
||||
sumSq += diff * diff;
|
||||
}
|
||||
|
||||
return (float)Math.sqrt(sumSq / window);
|
||||
}
|
||||
|
||||
public float getAngularVelocity() {
|
||||
float yd = Math.abs(this.getYawDelta(1));
|
||||
float pd = Math.abs(this.getPitchDelta(1));
|
||||
return (float)Math.sqrt(yd * yd + pd * pd);
|
||||
}
|
||||
|
||||
public static float calculateAngleOffset(Location eyeLoc, Location targetCenterLoc) {
|
||||
Vector toTarget = targetCenterLoc.toVector().subtract(eyeLoc.toVector()).normalize();
|
||||
Vector lookDir = eyeLoc.getDirection().normalize();
|
||||
double dot = Math.max(-1.0, Math.min(1.0, lookDir.dot(toTarget)));
|
||||
return (float)Math.toDegrees(Math.acos(dot));
|
||||
}
|
||||
|
||||
public static KinematicHistory.RaycastHitResult raycastTargetHitbox(Location eyeLoc, LivingEntity victim, double latencyMargin, double maxDistance) {
|
||||
Vector origin = eyeLoc.toVector();
|
||||
Vector direction = eyeLoc.getDirection().normalize();
|
||||
BoundingBox box = victim.getBoundingBox().clone().expand(Math.max(0.18, latencyMargin + 0.08));
|
||||
Vector center = box.getCenter();
|
||||
float angleOffset = calculateAngleOffset(eyeLoc, center.toLocation(victim.getWorld()));
|
||||
RayTraceResult result = box.rayTrace(origin, direction, maxDistance);
|
||||
if (result != null && result.getHitPosition() != null) {
|
||||
Vector hitPos = result.getHitPosition();
|
||||
double hitDist = origin.distance(hitPos);
|
||||
double hx = Math.max(1.0E-4, box.getWidthX() / 2.0);
|
||||
double hy = Math.max(1.0E-4, box.getHeight() / 2.0);
|
||||
double hz = Math.max(1.0E-4, box.getWidthZ() / 2.0);
|
||||
double nx = Math.abs(hitPos.getX() - center.getX()) / hx;
|
||||
double ny = Math.abs(hitPos.getY() - center.getY()) / hy;
|
||||
double nz = Math.abs(hitPos.getZ() - center.getZ()) / hz;
|
||||
float edgeProximity = (float)Math.min(1.0, Math.max(nx, Math.max(ny, nz)));
|
||||
return new KinematicHistory.RaycastHitResult(true, (float)hitDist, angleOffset, edgeProximity);
|
||||
} else {
|
||||
double clampedX = Math.max(box.getMinX(), Math.min(box.getMaxX(), origin.getX()));
|
||||
double clampedY = Math.max(box.getMinY(), Math.min(box.getMaxY(), origin.getY()));
|
||||
double clampedZ = Math.max(box.getMinZ(), Math.min(box.getMaxZ(), origin.getZ()));
|
||||
double minDistanceToBox = origin.distance(new Vector(clampedX, clampedY, clampedZ));
|
||||
return new KinematicHistory.RaycastHitResult(false, (float)minDistanceToBox, angleOffset, 1.0F);
|
||||
}
|
||||
}
|
||||
|
||||
public record RaycastHitResult(boolean hit, float distance, float angleOffsetDeg, float hitboxEdgeProximity) {
|
||||
}
|
||||
|
||||
public record Snapshot(float yaw, float pitch, double x, double y, double z, long time) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
package net.synapselabs.anticheat.update;
|
||||
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URI;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class UpdateChecker {
|
||||
public static final String DEFAULT_REPO = "Smuzik/SynapseAiAnticheat";
|
||||
public static final String DEFAULT_RELEASE_TAG_URL = "https://github.com/Smuzik/SynapseAiAnticheat/releases/tag/v3.0.0";
|
||||
private static final String API_URL_FORMAT = "https://api.github.com/repos/%s/releases/latest";
|
||||
private static final int TIMEOUT_MS = 5000;
|
||||
private static final Pattern VERSION_PATTERN = Pattern.compile("(?i)^v?([0-9]+(?:\\.[0-9]+)*)(?:-.*)?$");
|
||||
private final String repo;
|
||||
private final String currentVersion;
|
||||
private final Executor asyncExecutor;
|
||||
private final Executor syncExecutor;
|
||||
private volatile UpdateChecker.UpdateResult lastResult;
|
||||
|
||||
public UpdateChecker(String repo, String currentVersion) {
|
||||
this(repo, currentVersion, CompletableFuture::runAsync, Runnable::run);
|
||||
}
|
||||
|
||||
public UpdateChecker(String repo, String currentVersion, Executor asyncExecutor, Executor syncExecutor) {
|
||||
this.repo = repo != null && !repo.isBlank() ? repo.trim() : "Smuzik/SynapseAiAnticheat";
|
||||
this.currentVersion = currentVersion != null && !currentVersion.isBlank() ? currentVersion.trim() : "3.0";
|
||||
this.asyncExecutor = asyncExecutor != null ? asyncExecutor : CompletableFuture::runAsync;
|
||||
this.syncExecutor = syncExecutor != null ? syncExecutor : Runnable::run;
|
||||
}
|
||||
|
||||
public UpdateChecker.UpdateResult getLastResult() {
|
||||
return this.lastResult;
|
||||
}
|
||||
|
||||
public CompletableFuture<UpdateChecker.UpdateResult> checkForUpdatesAsync() {
|
||||
CompletableFuture<UpdateChecker.UpdateResult> future = new CompletableFuture<>();
|
||||
this.asyncExecutor.execute(() -> {
|
||||
UpdateChecker.UpdateResult result = this.fetchLatestRelease();
|
||||
this.lastResult = result;
|
||||
future.complete(result);
|
||||
});
|
||||
return future;
|
||||
}
|
||||
|
||||
public void checkForUpdates(Consumer<UpdateChecker.UpdateResult> consumer) {
|
||||
this.checkForUpdatesAsync().thenAccept(result -> {
|
||||
if (consumer != null) {
|
||||
this.syncExecutor.execute(() -> consumer.accept(result));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public UpdateChecker.UpdateResult fetchLatestRelease() {
|
||||
String apiUrl = String.format("https://api.github.com/repos/%s/releases/latest", this.repo);
|
||||
HttpURLConnection conn = null;
|
||||
|
||||
try {
|
||||
URL url = URI.create(apiUrl).toURL();
|
||||
conn = (HttpURLConnection)url.openConnection();
|
||||
conn.setRequestMethod("GET");
|
||||
conn.setConnectTimeout(5000);
|
||||
conn.setReadTimeout(5000);
|
||||
conn.setRequestProperty("User-Agent", "SynapseAI-UpdateChecker/" + this.currentVersion);
|
||||
conn.setRequestProperty("Accept", "application/vnd.github.v3+json");
|
||||
int responseCode = conn.getResponseCode();
|
||||
if (responseCode != 200) {
|
||||
return new UpdateChecker.UpdateResult(
|
||||
UpdateChecker.Status.ERROR,
|
||||
this.currentVersion,
|
||||
null,
|
||||
null,
|
||||
"https://github.com/Smuzik/SynapseAiAnticheat/releases/tag/v3.0.0",
|
||||
null,
|
||||
"GitHub HTTP error: " + responseCode
|
||||
);
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
String line;
|
||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
|
||||
while ((line = reader.readLine()) != null) {
|
||||
sb.append(line);
|
||||
}
|
||||
}
|
||||
|
||||
return parseReleaseJson(sb.toString(), this.currentVersion, this.repo);
|
||||
} catch (Exception e) {
|
||||
return new UpdateChecker.UpdateResult(
|
||||
UpdateChecker.Status.ERROR,
|
||||
this.currentVersion,
|
||||
null,
|
||||
null,
|
||||
"https://github.com/Smuzik/SynapseAiAnticheat/releases/tag/v3.0.0",
|
||||
null,
|
||||
e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName()
|
||||
);
|
||||
} finally {
|
||||
if (conn != null) {
|
||||
conn.disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static UpdateChecker.UpdateResult parseReleaseJson(String json, String currentVersion, String repo) {
|
||||
try {
|
||||
JsonObject root = JsonParser.parseString(json).getAsJsonObject();
|
||||
String tagName = root.has("tag_name") && !root.get("tag_name").isJsonNull() ? root.get("tag_name").getAsString() : "";
|
||||
String releaseName = root.has("name") && !root.get("name").isJsonNull() ? root.get("name").getAsString() : tagName;
|
||||
String htmlUrl = root.has("html_url") && !root.get("html_url").isJsonNull()
|
||||
? root.get("html_url").getAsString()
|
||||
: "https://github.com/" + repo + "/releases/tag/" + tagName;
|
||||
String downloadUrl = htmlUrl;
|
||||
if (root.has("assets") && root.get("assets").isJsonArray()) {
|
||||
for (JsonElement elem : root.getAsJsonArray("assets")) {
|
||||
if (elem.isJsonObject()) {
|
||||
JsonObject assetObj = elem.getAsJsonObject();
|
||||
if (assetObj.has("browser_download_url")) {
|
||||
downloadUrl = assetObj.get("browser_download_url").getAsString();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int cmp = compareVersions(currentVersion, tagName);
|
||||
UpdateChecker.Status status;
|
||||
if (cmp > 0) {
|
||||
status = UpdateChecker.Status.UPDATE_AVAILABLE;
|
||||
} else if (cmp < 0) {
|
||||
status = UpdateChecker.Status.DEV_BUILD;
|
||||
} else {
|
||||
status = UpdateChecker.Status.UP_TO_DATE;
|
||||
}
|
||||
|
||||
return new UpdateChecker.UpdateResult(status, currentVersion, tagName, releaseName, htmlUrl, downloadUrl, null);
|
||||
} catch (Exception e) {
|
||||
return new UpdateChecker.UpdateResult(
|
||||
UpdateChecker.Status.ERROR,
|
||||
currentVersion,
|
||||
null,
|
||||
null,
|
||||
"https://github.com/" + repo + "/releases",
|
||||
null,
|
||||
"Failed to parse release JSON: " + e.getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public static int compareVersions(String current, String remote) {
|
||||
int[] currParts = parseVersionParts(current);
|
||||
int[] remoteParts = parseVersionParts(remote);
|
||||
int maxLen = Math.max(currParts.length, remoteParts.length);
|
||||
|
||||
for (int i = 0; i < maxLen; i++) {
|
||||
int c = i < currParts.length ? currParts[i] : 0;
|
||||
int r = i < remoteParts.length ? remoteParts[i] : 0;
|
||||
if (r != c) {
|
||||
return Integer.compare(r, c);
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int[] parseVersionParts(String version) {
|
||||
if (version != null && !version.trim().isEmpty()) {
|
||||
String cleaned = version.trim();
|
||||
Matcher matcher = VERSION_PATTERN.matcher(cleaned);
|
||||
String numbersOnly;
|
||||
if (matcher.find()) {
|
||||
numbersOnly = matcher.group(1);
|
||||
} else {
|
||||
numbersOnly = cleaned.replaceAll("[^0-9.]", "");
|
||||
}
|
||||
|
||||
if (numbersOnly.isEmpty()) {
|
||||
return new int[]{0};
|
||||
}
|
||||
|
||||
String[] split = numbersOnly.split("\\.");
|
||||
int[] parts = new int[split.length];
|
||||
|
||||
for (int i = 0; i < split.length; i++) {
|
||||
try {
|
||||
parts[i] = Integer.parseInt(split[i]);
|
||||
} catch (NumberFormatException ignored) {
|
||||
parts[i] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
return parts;
|
||||
} else {
|
||||
return new int[]{0};
|
||||
}
|
||||
}
|
||||
|
||||
public enum Status {
|
||||
UP_TO_DATE,
|
||||
UPDATE_AVAILABLE,
|
||||
DEV_BUILD,
|
||||
ERROR;
|
||||
}
|
||||
|
||||
public static class UpdateResult {
|
||||
private final UpdateChecker.Status status;
|
||||
private final String currentVersion;
|
||||
private final String latestVersion;
|
||||
private final String releaseName;
|
||||
private final String releaseUrl;
|
||||
private final String downloadUrl;
|
||||
private final String errorMessage;
|
||||
|
||||
public UpdateResult(
|
||||
UpdateChecker.Status status,
|
||||
String currentVersion,
|
||||
String latestVersion,
|
||||
String releaseName,
|
||||
String releaseUrl,
|
||||
String downloadUrl,
|
||||
String errorMessage
|
||||
) {
|
||||
this.status = status;
|
||||
this.currentVersion = currentVersion;
|
||||
this.latestVersion = latestVersion;
|
||||
this.releaseName = releaseName;
|
||||
this.releaseUrl = releaseUrl;
|
||||
this.downloadUrl = downloadUrl;
|
||||
this.errorMessage = errorMessage;
|
||||
}
|
||||
|
||||
public UpdateChecker.Status getStatus() {
|
||||
return this.status;
|
||||
}
|
||||
|
||||
public String getCurrentVersion() {
|
||||
return this.currentVersion;
|
||||
}
|
||||
|
||||
public String getLatestVersion() {
|
||||
return this.latestVersion;
|
||||
}
|
||||
|
||||
public String getReleaseName() {
|
||||
return this.releaseName;
|
||||
}
|
||||
|
||||
public String getReleaseUrl() {
|
||||
return this.releaseUrl;
|
||||
}
|
||||
|
||||
public String getDownloadUrl() {
|
||||
return this.downloadUrl;
|
||||
}
|
||||
|
||||
public String getErrorMessage() {
|
||||
return this.errorMessage;
|
||||
}
|
||||
|
||||
public boolean isUpdateAvailable() {
|
||||
return this.status == UpdateChecker.Status.UPDATE_AVAILABLE;
|
||||
}
|
||||
|
||||
public boolean isSuccess() {
|
||||
return this.status != UpdateChecker.Status.ERROR;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package net.synapselabs.anticheat.webhook;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonObject;
|
||||
import java.io.OutputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.Locale;
|
||||
import net.synapselabs.anticheat.AiAnticheatPlugin;
|
||||
import net.synapselabs.anticheat.compat.CompatUtils;
|
||||
import net.synapselabs.anticheat.lang.LanguageManager;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
public class DiscordWebhookService {
|
||||
private final AiAnticheatPlugin plugin;
|
||||
|
||||
public DiscordWebhookService(AiAnticheatPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
public void testWebhook(CommandSender sender) {
|
||||
boolean enabled = this.plugin.getConfig().getBoolean("discord.webhook.enabled", false);
|
||||
String webhookUrl = this.plugin.getConfig().getString("discord.webhook.url", "");
|
||||
if (enabled && webhookUrl != null && !webhookUrl.isBlank() && !webhookUrl.contains("YOUR_WEBHOOK_HERE")) {
|
||||
sender.sendMessage(CompatUtils.color("�d2ff[SynapseAI] Sending test alert to Discord webhook..."));
|
||||
Bukkit.getScheduler().runTaskAsynchronously(this.plugin, () -> {
|
||||
try {
|
||||
JsonObject payload = new JsonObject();
|
||||
payload.addProperty("username", "Synapse AI-AntiCheat");
|
||||
payload.addProperty("avatar_url", "https://i.imgur.com/r62KqGZ.png");
|
||||
JsonArray embeds = new JsonArray();
|
||||
JsonObject embed = new JsonObject();
|
||||
embed.addProperty("title", "✅ Synapse AI-AntiCheat Test Webhook");
|
||||
embed.addProperty("description", "Discord webhook integration is successfully connected and working!");
|
||||
embed.addProperty("color", 58879);
|
||||
JsonArray fields = new JsonArray();
|
||||
JsonObject f1 = new JsonObject();
|
||||
f1.addProperty("name", "Status");
|
||||
f1.addProperty("value", "`ONLINE & ACTIVE`");
|
||||
f1.addProperty("inline", true);
|
||||
fields.add(f1);
|
||||
JsonObject f2 = new JsonObject();
|
||||
f2.addProperty("name", "Server");
|
||||
f2.addProperty("value", "`Purpur AI-AntiCheat v3.0`");
|
||||
f2.addProperty("inline", true);
|
||||
fields.add(f2);
|
||||
embed.add("fields", fields);
|
||||
JsonObject footer = new JsonObject();
|
||||
footer.addProperty("text", "Synapse Labs Studio • https://dsc.gg/synapselabs");
|
||||
embed.add("footer", footer);
|
||||
embed.addProperty("timestamp", Instant.now().toString());
|
||||
embeds.add(embed);
|
||||
payload.add("embeds", embeds);
|
||||
int code = this.executePost(webhookUrl, payload.toString());
|
||||
if (code >= 200 && code < 300) {
|
||||
sender.sendMessage(CompatUtils.color("�ff88[SynapseAI] Test webhook sent successfully! (HTTP " + code + ")"));
|
||||
} else {
|
||||
sender.sendMessage(CompatUtils.color("&#ff2244[SynapseAI] Discord returned error HTTP " + code));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
sender.sendMessage(CompatUtils.color("&#ff2244[SynapseAI] Failed to send webhook: " + e.getMessage()));
|
||||
}
|
||||
});
|
||||
} else {
|
||||
sender.sendMessage(CompatUtils.color("&#ff2244[SynapseAI] Discord webhook is disabled or URL is not set in config.yml!"));
|
||||
}
|
||||
}
|
||||
|
||||
public void sendFlagAlert(String playerName, String cheatType, int confidencePercent, int totalFlags, int ping, double distance, float angleOffset) {
|
||||
boolean enabled = this.plugin.getConfig().getBoolean("discord.webhook.enabled", false);
|
||||
if (enabled) {
|
||||
String webhookUrl = this.plugin.getConfig().getString("discord.webhook.url", "");
|
||||
if (webhookUrl != null && !webhookUrl.isBlank() && !webhookUrl.contains("YOUR_WEBHOOK_HERE")) {
|
||||
int minFlags = this.plugin.getConfig().getInt("discord.webhook.min_flags_to_send", 1);
|
||||
if (totalFlags >= minFlags) {
|
||||
String inviteUrl = this.plugin.getConfig().getString("discord.invite_url", "https://dsc.gg/synapselabs");
|
||||
LanguageManager lang = this.plugin.getLanguageManager();
|
||||
String defLang = lang.getPlayerLanguage(Bukkit.getConsoleSender());
|
||||
String embedTitle = lang.getRaw("discord.embed_title", defLang);
|
||||
String fieldPlayer = lang.getRaw("discord.field_player", defLang);
|
||||
String fieldCheat = lang.getRaw("discord.field_cheat", defLang);
|
||||
String fieldConfidence = lang.getRaw("discord.field_confidence", defLang);
|
||||
String fieldFlags = lang.getRaw("discord.field_flags", defLang);
|
||||
String fieldPing = lang.getRaw("discord.field_ping", defLang);
|
||||
String fieldMetrics = lang.getRaw("discord.field_metrics", defLang);
|
||||
String metricsValue = lang.getRaw("discord.metrics_value", defLang)
|
||||
.replace("{distance}", String.format(Locale.US, "%.2f", distance))
|
||||
.replace("{angle}", String.format(Locale.US, "%.1f", angleOffset));
|
||||
Bukkit.getScheduler().runTaskAsynchronously(this.plugin, () -> {
|
||||
try {
|
||||
JsonObject payload = new JsonObject();
|
||||
payload.addProperty("username", "Synapse AI-AntiCheat");
|
||||
payload.addProperty("avatar_url", "https://i.imgur.com/r62KqGZ.png");
|
||||
JsonArray embeds = new JsonArray();
|
||||
JsonObject embed = new JsonObject();
|
||||
embed.addProperty("title", embedTitle);
|
||||
embed.addProperty("color", 58879);
|
||||
JsonObject thumbnail = new JsonObject();
|
||||
thumbnail.addProperty("url", "https://mc-heads.net/avatar/" + playerName + "/64");
|
||||
embed.add("thumbnail", thumbnail);
|
||||
JsonArray fields = new JsonArray();
|
||||
JsonObject f1 = new JsonObject();
|
||||
f1.addProperty("name", fieldPlayer);
|
||||
f1.addProperty("value", "`" + playerName + "`");
|
||||
f1.addProperty("inline", true);
|
||||
fields.add(f1);
|
||||
JsonObject f2 = new JsonObject();
|
||||
f2.addProperty("name", fieldCheat);
|
||||
f2.addProperty("value", "`" + cheatType + "`");
|
||||
f2.addProperty("inline", true);
|
||||
fields.add(f2);
|
||||
JsonObject f3 = new JsonObject();
|
||||
f3.addProperty("name", fieldConfidence);
|
||||
f3.addProperty("value", "`" + confidencePercent + "%`");
|
||||
f3.addProperty("inline", true);
|
||||
fields.add(f3);
|
||||
JsonObject f4 = new JsonObject();
|
||||
f4.addProperty("name", fieldFlags);
|
||||
f4.addProperty("value", "`" + totalFlags + "`");
|
||||
f4.addProperty("inline", true);
|
||||
fields.add(f4);
|
||||
JsonObject f5 = new JsonObject();
|
||||
f5.addProperty("name", fieldPing);
|
||||
f5.addProperty("value", "`" + ping + " ms`");
|
||||
f5.addProperty("inline", true);
|
||||
fields.add(f5);
|
||||
JsonObject f6 = new JsonObject();
|
||||
f6.addProperty("name", fieldMetrics);
|
||||
f6.addProperty("value", metricsValue);
|
||||
f6.addProperty("inline", false);
|
||||
fields.add(f6);
|
||||
embed.add("fields", fields);
|
||||
JsonObject footer = new JsonObject();
|
||||
footer.addProperty("text", "Synapse Labs Studio • " + inviteUrl);
|
||||
embed.add("footer", footer);
|
||||
embed.addProperty("timestamp", Instant.now().toString());
|
||||
embeds.add(embed);
|
||||
payload.add("embeds", embeds);
|
||||
int code = this.executePost(webhookUrl, payload.toString());
|
||||
if (code >= 400) {
|
||||
this.plugin.getLogger().warning("Discord webhook returned error HTTP " + code);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
this.plugin.getLogger().warning("Failed to dispatch Discord webhook: " + e.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int executePost(String webhookUrl, String jsonPayload) throws Exception {
|
||||
URL url = new URL(webhookUrl);
|
||||
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
|
||||
conn.setRequestMethod("POST");
|
||||
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
|
||||
conn.setRequestProperty("User-Agent", "SynapseLabs-AntiCheat");
|
||||
conn.setConnectTimeout(5000);
|
||||
conn.setReadTimeout(5000);
|
||||
conn.setDoOutput(true);
|
||||
|
||||
try (OutputStream os = conn.getOutputStream()) {
|
||||
byte[] input = jsonPayload.getBytes(StandardCharsets.UTF_8);
|
||||
os.write(input, 0, input.length);
|
||||
}
|
||||
|
||||
int responseCode = conn.getResponseCode();
|
||||
conn.disconnect();
|
||||
return responseCode;
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,202 @@
|
||||
# ==============================================================================
|
||||
# Synapse AI-AntiCheat v3.1.0
|
||||
# Developed by: Synapse Labs Studio
|
||||
# Official Discord: https://dsc.gg/synapselabs
|
||||
# Supported Platforms: Spigot, Paper, Purpur (1.16.5 - 1.20.4+)
|
||||
# ==============================================================================
|
||||
|
||||
# Setup Gate: Set to true once an administrator executes /aiac and chooses the server language.
|
||||
# When false, the AI detection is in standby mode and prompts admins on join.
|
||||
setup_completed: false
|
||||
|
||||
# Default Anticheat Language: "en" for English, "ru" for Russian
|
||||
language: "ru"
|
||||
|
||||
# Update Checker Settings
|
||||
updates:
|
||||
# Check for updates on startup (asynchronous)
|
||||
check_for_updates: true
|
||||
# Notify staff (aianticheat.admin) on join if an update is available
|
||||
notify_admins_on_join: true
|
||||
# GitHub repository to check for releases
|
||||
github_repo: "Smuzik/SynapseAiAnticheat"
|
||||
|
||||
# Studio Branding & Community Links
|
||||
discord:
|
||||
invite_url: "https://dsc.gg/synapselabs"
|
||||
webhook:
|
||||
enabled: false
|
||||
url: "https://discord.com/api/webhooks/YOUR_WEBHOOK_HERE"
|
||||
min_flags_to_send: 1
|
||||
title: "🚨 Cheat Violation Detected"
|
||||
embed_color: "#00E5FF"
|
||||
|
||||
# Logging Settings (Console & Text Files)
|
||||
logging:
|
||||
console:
|
||||
# Enable console detection alerts
|
||||
enabled: true
|
||||
# Verbose mode (log real-time combat kinematic traces per hit)
|
||||
verbose: true
|
||||
files:
|
||||
# Save all cheat detections, staff alerts, and punishment actions to text file (plugins/SynapseAiAnticheat/logs/detections.log)
|
||||
detections: true
|
||||
# Save detailed combat debug telemetry to text file (plugins/SynapseAiAnticheat/logs/combat_debug.log)
|
||||
combat_debug: true
|
||||
|
||||
# ==============================================================================
|
||||
# BAN & PUNISHMENT INTEGRATION (LiteBans, AdvancedBan, LibertyBans, Essentials, Bukkit)
|
||||
# ==============================================================================
|
||||
punishment:
|
||||
# Master toggle for automatic punishment actions. Set to false for Shadow Mode (monitoring/logging only).
|
||||
enabled: true
|
||||
# Master Auto-Kick toggle: set to false to completely disable automatic kicking for cheat flags
|
||||
# (Alerts, staff notifications, logs and dossiers will still work normally!)
|
||||
auto_kick: true
|
||||
# Mode: AUTO (detects installed ban manager), CUSTOM_COMMAND, or BUKKIT
|
||||
mode: "AUTO"
|
||||
commands:
|
||||
manual_ban: "ban {player} 30d Unfair Advantage [SynapseAI] -s"
|
||||
auto_ban: "tempban {player} 14d Auto-Ban: Cheating [SynapseAI] -s"
|
||||
leave_on_freeze_ban: "tempban {player} 30d Refusal of Cheat Inspection [SynapseAI] -s"
|
||||
kick: "kick {player} {reason}"
|
||||
|
||||
# AI Neural Engine Model
|
||||
model:
|
||||
file: "anticheat_model.onnx"
|
||||
|
||||
# ==============================================================================
|
||||
# DETECTION ENGINE SETTINGS
|
||||
# ==============================================================================
|
||||
detection:
|
||||
# Only analyze Player vs Player combat (prevents mob farming/PvE false positives)
|
||||
pvp_only: true
|
||||
|
||||
# Minimum AI neural confidence (0.00 - 1.00) required to treat hit as suspicious
|
||||
min_confidence: 0.75
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# RISK ENGINE CALIBRATION (Phase 1)
|
||||
# The verdict is NEVER "one signal = cheat". Every event produces a set of weighted signals
|
||||
# (Aim / Rotation / Combat / Hard checks / AI), context multiplies them up or down, and the
|
||||
# result is aggregated over time (30s half-life) before a verdict is drawn. These are the two
|
||||
# thresholds on that aggregated 0..100 risk score.
|
||||
# risk >= cheat_threshold -> CHEAT (punishable)
|
||||
# risk >= suspicious_threshold -> SUSPICIOUS (alert only, never punished)
|
||||
# Raise these to be more lenient; lower them to be stricter.
|
||||
calibration:
|
||||
suspicious_threshold: 25.0
|
||||
cheat_threshold: 60.0
|
||||
platt_a: 2.0
|
||||
platt_b: -0.04
|
||||
|
||||
# Multi-Hit Confirmation (guarantees no instant ban on single-hit anomalies)
|
||||
multi_hit:
|
||||
required_hits: 5
|
||||
confidence_threshold: 0.75
|
||||
|
||||
# Server Lag & TPS Protection
|
||||
tps_protection:
|
||||
enabled: true
|
||||
min_tps: 17.5
|
||||
|
||||
# Hard Combat Checks (now emit SIGNALS for the Risk Engine — they no longer punish on their own)
|
||||
hard_checks:
|
||||
# Reach below this is never even considered a reach signal (vanilla melee allowance is 3.00).
|
||||
max_reach: 3.10
|
||||
# Lag-compensated reach at/above this that STILL exceeds the ping+knockback allowance is the only
|
||||
# thing that triggers a protective, reversible damage cancel (never a punishment by itself).
|
||||
reach_hard_flag: 3.65
|
||||
# Ray must miss the hitbox by more than this angle (deg) to raise a hitbox-miss signal.
|
||||
fov_outer_deg: 70.0
|
||||
|
||||
# Extra Modular Checks (FastBreak, FastPlace, AutoClicker, FastInteract)
|
||||
extra_checks:
|
||||
fastbreak:
|
||||
enabled: true
|
||||
max_speed_multiplier: 1.25
|
||||
fastplace:
|
||||
enabled: true
|
||||
max_blocks_per_second: 20
|
||||
autoclicker:
|
||||
enabled: true
|
||||
max_cps: 22
|
||||
min_stddev: 0.08
|
||||
fastinteract:
|
||||
enabled: true
|
||||
min_eat_ticks: 25
|
||||
min_bow_ticks: 15
|
||||
|
||||
# GrimAC Integration Bridge (automatically ingests GrimAC detections)
|
||||
grimac_bridge:
|
||||
enabled: true
|
||||
# Forward GrimAC violations to SynapseAI ThreatState & alerts
|
||||
ingest_flags: true
|
||||
# Boost suspicion on GrimAC Reach / Hitbox flags
|
||||
boost_suspicion: true
|
||||
|
||||
# Punishment Thresholds
|
||||
punishments:
|
||||
# Set to false to disable all automated in-combat kicks and damage cancels (Shadow Mode)
|
||||
enabled: true
|
||||
# Auto-kick toggle for detections (set to false to disable automated kicking)
|
||||
auto_kick: true
|
||||
# Hard Checks (Blatant: Reach > 3.65m, Out-of-FOV > 65 deg, Robotic Snap)
|
||||
hard:
|
||||
# Auto-kick on hard check violations (set to false or flags_to_kick: 0 to disable)
|
||||
auto_kick: true
|
||||
flags_to_kick: 2
|
||||
flags_to_cancel_damage: 1
|
||||
cooldown_seconds: 10
|
||||
# AI Checks (KillAura, Smooth-Aim, SilentAura)
|
||||
ai:
|
||||
# Auto-kick on AI check violations (set to false or flags_to_kick: 0 to disable)
|
||||
auto_kick: true
|
||||
flags_to_kick: 4
|
||||
flags_to_cancel_damage: 1
|
||||
cooldown_seconds: 20
|
||||
|
||||
# Kick Message
|
||||
kick_message: "&#ff3333[SynapseAI] &fYou were disconnected for unfair play (&c{reason}&f).\n&7Appeal in Discord: �d2ff{discord_url}"
|
||||
|
||||
# Staff Sound Alerts
|
||||
sound_alert:
|
||||
enabled: true
|
||||
sound: "ENTITY_EXPERIENCE_ORB_PICKUP"
|
||||
|
||||
# ==============================================================================
|
||||
# OVERHEAD HEAD DISPLAY (TextDisplay visible to staff with LuckPerms permissions)
|
||||
# ==============================================================================
|
||||
overhead_display:
|
||||
enabled: true
|
||||
required_permission: "aianticheat.overhead"
|
||||
height_offset: 2.25
|
||||
|
||||
# ==============================================================================
|
||||
# PLAYER INSPECTION & FREEZE SYSTEM (/aiac freeze)
|
||||
# ==============================================================================
|
||||
freeze:
|
||||
cooldown_seconds: 3
|
||||
teleport:
|
||||
enabled: true
|
||||
use_custom_location: false
|
||||
custom_location:
|
||||
world: "world"
|
||||
x: 0.5
|
||||
y: 100.0
|
||||
z: 0.5
|
||||
yaw: 0.0
|
||||
pitch: 0.0
|
||||
teleport_to_spawn_on_pass: true
|
||||
|
||||
# ==============================================================================
|
||||
# DATASET COLLECTION ENGINE (/aiac dataset)
|
||||
# ==============================================================================
|
||||
dataset:
|
||||
# Master toggle to enable dataset collection system (keep disabled by default)
|
||||
enabled: false
|
||||
# Directory where dataset CSV files will be stored (relative to plugin data folder)
|
||||
directory: "datasets"
|
||||
# Automatic disk flush interval in seconds
|
||||
auto_flush_interval_seconds: 15
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
# Synapse AI-AntiCheat - English Language File
|
||||
prefix: "�d2ff&lSynapseAC &8» &f"
|
||||
ai_prefix: "&#ff7700&lSynapseAI &8» &f"
|
||||
|
||||
# Help and Information
|
||||
help:
|
||||
header: "�d2ff&l🧠 Synapse AI-AntiCheat &fv{version} &8| &#ffa500Command Help"
|
||||
author: "&7Developer: &eSynapse Labs Studio &8| �d2ffSynapseLabs"
|
||||
menu: "&e/aiac menu &8(or /aiac gui) &7— Open Main Admin GUI"
|
||||
inspect: "&e/aiac inspect <player> &7— View player AI dossier"
|
||||
freeze: "&e/aiac freeze <player> &7— Freeze player for inspection"
|
||||
unfreeze: "&e/aiac unfreeze <player> &7— Unfreeze player"
|
||||
dataset: "&e/aiac dataset &7— Manage AI dataset collection"
|
||||
reload: "&e/aiac reload &7— Reload configuration files"
|
||||
debug: "&e/aiac debug [player|visual|off] &7— Toggle developer hit/angle/corner debug"
|
||||
lang: "&e/aiac lang [en|ru] &7— Switch anticheat language"
|
||||
update: "&e/aiac update &7— Check for plugin updates"
|
||||
discord: "&7Official Discord: �d2ff{url}"
|
||||
|
||||
setup:
|
||||
required_prompt: "&#ff2244&l[SynapseAI] &ePlease type &6/aiac &eto complete setup and select your language!"
|
||||
completed: "�ff88&l[SynapseAI] &aSetup completed! Language set to &e{lang}&a. AI protection is now ACTIVE."
|
||||
|
||||
lang_selector:
|
||||
header: "�d2ff================================================="
|
||||
prompt: "�d2ff&l🌐 Select Anticheat Language &8| &fВыберите язык:"
|
||||
current: "&7Current language: &e{current}"
|
||||
btn_en: "�d2ff[🇺🇸 English]"
|
||||
btn_ru: "�ff88[🇷🇺 Русский]"
|
||||
btn_en_hover: "&bClick to select English"
|
||||
btn_ru_hover: "&aНажмите для выбора русского языка"
|
||||
changed: "&aAnticheat language successfully changed to &e{lang}&a!"
|
||||
|
||||
about:
|
||||
header: "&b================================================="
|
||||
title: "&b&lSynapse AI-AntiCheat &fv{version}"
|
||||
author: "&fPlugin Author: &e&lSynapse Labs Studio"
|
||||
studio: "&fStudio: &b&lSynapseLabs"
|
||||
discord: "&fOfficial Discord: &a&l{url}"
|
||||
description: "&7Real-time Neural Engine & Kinematic AntiCheat with GrimAC Integration."
|
||||
engine: "&7Engine: &fONNX Runtime Machine Learning + GrimAC Deep Ingestion"
|
||||
|
||||
alerts:
|
||||
hard: "&#ff3344&l[SynapseAC] &#ff5555[Hard-Check] &fPlayer &e{player} &ffailed: &#ff2244&l{check} &7(&cFlags: &#ff3344{flags}&7)"
|
||||
ai: "&#ff3344&l[SynapseAI] &#ff6666[AI-Combat] &fPlayer &e{player} &fflagged for: &#ff2244&l{check} &7(&cConf: &#ff5555{confidence}%&7, {state} &7| &cAI Flags: &#ff3344{flags}&7)"
|
||||
grim: "&#ff3344&l[SynapseAC] &#ff7777[GrimAC Bridge] &fPlayer &e{player} &ffailed: &#ff2244&l{check} &7(&cVL: &#ff5555{vl}&7, &cTotal: &#ff3344{flags}&7)"
|
||||
btn_dossier: "Dossier"
|
||||
btn_spectate: "Spectate"
|
||||
btn_freeze: "Freeze"
|
||||
btn_kick: "Kick"
|
||||
btn_dossier_hover: "&eClick to open player AI dossier"
|
||||
btn_spectate_hover: "&dSpectate player"
|
||||
btn_freeze_hover: "&bCall player for inspection"
|
||||
btn_kick_hover: "&cKick player from server"
|
||||
kick_reason: "Unfair Advantage [SynapseAI]"
|
||||
banned_ip_join: "&#ff2244&l[SynapseAI ALERT] &fPlayer &e{player} &fjoined from IP &c{ip}&f which has &#ff0055&lBANNED ACCOUNTS&f!"
|
||||
|
||||
# Threat state labels
|
||||
threat_state:
|
||||
clean: "�ff88✔ &aCLEAN"
|
||||
suspicious: "&#ffaa00⚠ &#ffcc00SUSPICIOUS"
|
||||
high_confidence: "&#ff7700⚠ &#ffa500HIGH RISK"
|
||||
confirmed: "&#ff2244⚡ &#ff0055CONFIRMED (CHEAT)"
|
||||
|
||||
# GUI Localization
|
||||
gui:
|
||||
main_title: "�d2ffAdmin Dashboard 󙀸| &#ffa500Synapse AI"
|
||||
inspect_title: "�d2ff[Dossier] &#ffa500{player}"
|
||||
top_title: "�d2ff&l🧠 Synapse AI-AntiCheat v3.1.0"
|
||||
engine: "&fEngine: �d2ffONNX Runtime Machine Learning"
|
||||
inference_speed: "&fInference latency: �ff88< 0.3 ms (RAM ThreadPool)"
|
||||
grim_status: "&fGrimAC Bridge: {status}"
|
||||
grim_connected: "�ff88CONNECTED (HYBRID)"
|
||||
grim_standalone: "&#ffaa00STANDALONE"
|
||||
discord: "&fDiscord: �d2ff{url}"
|
||||
update_status: "&fUpdates: {status}"
|
||||
update_status_latest: "�ff88v{version} (LATEST)"
|
||||
update_status_available: "&#ffaa00v{latest} AVAILABLE"
|
||||
system_active: "�ff88✔ SYSTEM ACTIVE & PROTECTING SERVER"
|
||||
threat_info_title: "&#ffa500&l⚡ AI Architecture & Threat Levels"
|
||||
threat_clean: "�ff88✔ CLEAN (0-24%) &7— Fair gameplay without anomalies"
|
||||
threat_suspicious: "&#ffaa00⚠ SUSPICIOUS (25-59%) &7— Staff alert, elevated confidence"
|
||||
threat_cheat: "&#ff2244⚡ CHEAT (60-100%) &7— Actionable detection / Concurring evidence"
|
||||
player_threat: "&7• Detector Status: {state}"
|
||||
player_risk: "&7• Risk Score: {bar} {score}%"
|
||||
player_killaura: "&7• Killaura: {bar} {score}%"
|
||||
player_aim: "&7• Aim Assist: {bar} {score}%"
|
||||
player_ping: "&7• Ping: {color}{ping} ms"
|
||||
player_ip: "&7• IP Address: &f{ip}"
|
||||
player_alts: "&7• Known accounts: {color}{alts}"
|
||||
player_banned_on_ip: "&7• Banned on IP: {status}"
|
||||
banned_yes: "&#ff2244&lYES (DANGER)"
|
||||
banned_no: "�ff88NO (CLEAN)"
|
||||
player_flags: "&7• Total flags: &#ffa500{total} &8(Hard: �d2ff{hard}&8, AI: &#ff7700{ai}&8)"
|
||||
player_last_flag: "&7• Last violation: &c{reason}"
|
||||
player_gamemode: "&7• Mode: &e{gamemode}"
|
||||
player_click_inspect: "�ff88▶ Click to open player dossier"
|
||||
inspect_first_join: "&7• First login: &f{time}"
|
||||
inspect_ip: "&7• IP address: &f{ip}"
|
||||
inspect_status: "&7• Threat status: {state}"
|
||||
inspect_freeze_state: "&7• Freeze state: {state}"
|
||||
freeze_frozen: "&#ff2244&lFROZEN"
|
||||
freeze_free: "�ff88FREE"
|
||||
inspect_alts_title: "&#ffa500&l🌐 Known Accounts ({count})"
|
||||
inspect_alts_header: "&7All accounts recorded from IP {ip}:"
|
||||
inspect_combat_diag: "�d2ff&l🎯 AI Combat Diagnostics"
|
||||
inspect_network_diag: "�d2ff&l📶 Network Diagnostics"
|
||||
inspect_network_quality: "&7• Connection quality: {quality}"
|
||||
network_stable: "�ff88Stable"
|
||||
network_lag: "&#ffaa00High Jitter / Lag"
|
||||
inspect_btn_unfreeze: "�ff88&l🔓 Unfreeze Player"
|
||||
inspect_btn_unfreeze_lore: "&7Finish inspection and teleport to spawn."
|
||||
inspect_btn_freeze: "�d2ff&l❄️ Call for Inspection"
|
||||
inspect_btn_freeze_lore: "&7Teleport to inspection room and freeze movements."
|
||||
inspect_btn_reset: "�ff88&l⚡ Reset Flags"
|
||||
inspect_btn_reset_lore: "&7Clear suspicion and flag counters."
|
||||
inspect_btn_spectate: "&#a855f7&l👁️ Spectate (First Person)"
|
||||
inspect_btn_spectate_lore: "&7Watch player in first person mode."
|
||||
inspect_btn_kick: "&#ffaa00&l🚫 Kick Player"
|
||||
inspect_btn_kick_lore: "&7Disconnect suspect from server."
|
||||
inspect_btn_ban: "&#ff2244&l🔨 Ban Account"
|
||||
inspect_btn_ban_lore: "&7Issue permanent ban via punishment system."
|
||||
inspect_btn_back: "&#ffa500&l⬅️ Back to Menu"
|
||||
target_offline: "&#ff2244[SynapseAI] Target player is offline."
|
||||
flags_reset: "�ff88[SynapseAI] Flags and suspicion for &e{player} �ff88were successfully reset!"
|
||||
spectate_msg: "�d2ff[SynapseAI] You are now spectating &e{player} �d2ffin Spectator Mode."
|
||||
kick_msg: "&#ff3333[SynapseAI] You were disconnected by an administrator."
|
||||
kick_admin: "&#ff2244[SynapseAI] Player &e{player} &#ff2244was kicked."
|
||||
ban_admin: "&#ff2244[SynapseAI] Player &e{player} &#ff2244was banned via {system}!"
|
||||
ban_reason: "Cheating / Unfair Play"
|
||||
freeze_reason: "Inspection by Administrator"
|
||||
|
||||
freeze:
|
||||
title_frozen: "&c&lFROZEN FOR INSPECTION!"
|
||||
subtitle_discord: "&fDiscord: &b{discord_url}"
|
||||
title_passed: "&a&lINSPECTION PASSED!"
|
||||
subtitle_passed: "&fYou passed the cheat inspection!"
|
||||
title_warning: "&c&lCHEAT INSPECTION!"
|
||||
actionbar_warning: "&c[!] You are under inspection! Type in chat to reply to the moderator."
|
||||
frozen_target: "&c=================================================\n&c&l[!] YOU HAVE BEEN TELEPORTED AND FROZEN FOR INSPECTION!\n&fReason: &e{reason}\n&fPlease do not leave the game and join our Discord:\n&b👉 {discord_url}\n&a💬 You can type in chat — the inspecting moderator sees your messages.\n&7(If you leave the game you will be automatically banned for refusing inspection)\n&c================================================="
|
||||
unfrozen_target: "&a=================================================\n&a&l[SynapseAI] INSPECTION SUCCESSFULLY COMPLETED!\n&fYou have been cleared as a fair player and teleported to spawn.\n&fEnjoy the game on the server!\n&a================================================="
|
||||
staff_start: "&b=================================================\n&b&l[SynapseAI] YOU HAVE STARTED INSPECTING PLAYER: &e&l{player}\n&fThe player has been teleported for inspection.\n&fTo talk in the private inspection chat, prefix messages with &e! &f(e.g. &e!Your Discord?&f)\n&b================================================="
|
||||
staff_passed: "&a[SynapseAI] Player &e{player} &ahas passed the inspection and was sent to spawn."
|
||||
frozen_staff: "�d2ff[SynapseAI] Player &e{player} �d2ffhas been frozen for inspection!"
|
||||
unfrozen_staff: "�ff88[SynapseAI] Player &e{player} �ff88has been unfrozen."
|
||||
already_frozen: "&cPlayer {player} is already frozen!"
|
||||
not_frozen: "&cPlayer {player} is not frozen!"
|
||||
cannot_move: "&cYou are frozen! Join Discord for inspection: &b{discord_url}"
|
||||
cooldown_wait: "&c[SynapseAI] Please wait {seconds}s before repeating this action."
|
||||
command_blocked: "&c[!] Using commands during inspection is not allowed! Type your answers directly in chat."
|
||||
role_moderator: "&b[Moderator]"
|
||||
role_suspect: "&c[Suspect]"
|
||||
interrogation_format: "&8[&c&lINSPECTION&8] {role} &e{sender} &8» &f{message}"
|
||||
quit_ban_broadcast: "&8[&c&lAI-AC&8] &fPlayer &e{player} &cleft during a cheat inspection (Inspection refused — BANNED)!"
|
||||
|
||||
punishment:
|
||||
kick_message: "&#ff3333[SynapseAI] &fYou were disconnected for unfair play (&c{reason}&f).\n&7Appeal in Discord: �d2ff{discord_url}"
|
||||
ban_reason: "&4[SynapseAI] {reason}\n&7Appeal: &b{discord_url}"
|
||||
ban_reason_refusal: "&4[SynapseAI] Refusal of cheat inspection\n&7Appeal: &b{discord_url}"
|
||||
reloaded: "&aConfiguration and language files successfully reloaded!"
|
||||
|
||||
# Command feedback
|
||||
commands:
|
||||
access_denied: "&cAccess denied."
|
||||
lang_usage: "&cUsage: /aiac lang <en|ru>"
|
||||
lang_current_default: "Current default language: {lang}"
|
||||
players_only_gui: "GUI menu is only available to players in-game."
|
||||
ingame_only: "In-game only command."
|
||||
separator: "&b================================================="
|
||||
ping_specify: "&cSpecify player: /aiac ping <player>"
|
||||
ping_rating_excellent: "�ff88Excellent (Optimal PvP)"
|
||||
ping_rating_normal: "&#ffaa00Normal (Stable)"
|
||||
ping_rating_elevated: "&#ff7700Elevated (Slight delay)"
|
||||
ping_rating_high: "&#ff2244High (Network lag)"
|
||||
ping_header: "�d2ff&l📶 Connection Telemetry: &e&l{player}"
|
||||
ping_current: "&7• Current Ping: &f{ping} ms ({rating}&7)"
|
||||
ping_ip: "&7• IP Address: &f{ip}"
|
||||
ping_tps: "&7• Server TPS: �ff8820.0 (Optimal)"
|
||||
ping_grim: "&7• GrimAC Link: {status}"
|
||||
grim_synced: "�ff88Synced"
|
||||
grim_standalone: "&7Standalone"
|
||||
unknown: "Unknown"
|
||||
freezeloc_set: "�ff88[SynapseAI] Freeze location set to your current position!"
|
||||
chat_not_inspecting: "&c[SynapseAI] You are not currently inspecting any player."
|
||||
player_not_found_online: "&cPlayer not found online."
|
||||
player_not_found: "&cPlayer not found."
|
||||
status_model: "�d2ff[SynapseAI] &fONNX ML Model: {status}"
|
||||
status_bridge: "�d2ff[SynapseAI] &fGrimAC Bridge: {status}"
|
||||
status_ban: "�d2ff[SynapseAI] &fBan System: �ff88{system}"
|
||||
status_overhead: "�d2ff[SynapseAI] &fOverhead Display: �ff88ACTIVE (LuckPerms Filtered)"
|
||||
status_discord: "�d2ff[SynapseAI] &fDiscord Invite: �d2ff{url}"
|
||||
status_webhook: "�d2ff[SynapseAI] &fDiscord Webhook: {status}"
|
||||
status_update: "�d2ff[SynapseAI] &fUpdate Status: {status}"
|
||||
status_up_to_date: "�ff88UP TO DATE (v{version})"
|
||||
status_update_available: "&#ffaa00UPDATE AVAILABLE (v{latest})"
|
||||
status_model_active: "�ff88ACTIVE (<0.3ms)"
|
||||
status_model_error: "&cERROR"
|
||||
status_bridge_connected: "�ff88CONNECTED (HYBRID)"
|
||||
status_bridge_standalone: "&#ffaa00STANDALONE"
|
||||
status_enabled: "�ff88ENABLED"
|
||||
status_disabled: "&7DISABLED"
|
||||
check_header: "�d2ff[SynapseAI] &#ffa500Player AI Diagnostics: &e{player}"
|
||||
check_threat: "&7• Threat Status: {state}"
|
||||
check_killaura: "&7• Killaura Confidence: {bar} {score}%"
|
||||
check_aim: "&7• Aim Confidence: {bar} {score}%"
|
||||
check_suspicion: "&7• Historical Suspicion: {bar} {score}%"
|
||||
check_flags: "&7• Total Flags: &#ffa500{total} &8(Hard: �d2ff{hard}&8, AI: &#ff7700{ai}&8, Grim: &bdf8{grim}&8)"
|
||||
debug_enabled_all: "�ff88[SynapseAI Debug] &fDeveloper debug mode &aENABLED &f(monitoring all players)."
|
||||
debug_enabled_player: "�ff88[SynapseAI Debug] &fDeveloper debug mode &aENABLED &f(monitoring: &e{player}&f)."
|
||||
debug_disabled: "&#ffaa00[SynapseAI Debug] &fDeveloper debug mode &cDISABLED&f."
|
||||
debug_visual_on: "�ff88[SynapseAI Debug] &fVisual 3D particle ray & hitbox visualization &aENABLED&f."
|
||||
debug_visual_off: "&#ffaa00[SynapseAI Debug] &fVisual 3D particle ray & hitbox visualization &cDISABLED&f."
|
||||
debug_cleared: "�ff88[SynapseAI Debug] &fAll active debug sessions were cleared."
|
||||
debug_card_header: "&8[&bAIAC-DEBUG&8] &e{attacker} &8(&7ping: &f{attacker_ping}ms&8) &7⚔ &c{victim} &8(&7ping: &f{victim_ping}ms&8)"
|
||||
debug_card_geometry: "&7• &bGeometry: &fAngle: &e{angle}° &8| &fReach: &e{reach}m &7(comp: &a{comp_reach}m&7, raw: &e{raw_reach}m&7)"
|
||||
debug_card_hitbox: "&7• &bHitbox: &fRayHit: {ray_hit} &8| &fEdgeProx: &e{edge_prox} &8| &fMargin: &e+{margin}m &8| &fCorner: {corner} &8| &fWall: {wall}"
|
||||
debug_card_kinematics: "&7• &bKinematics: &fYawΔ: &e1t:{yaw_1t}° 5t:{yaw_5t}° &8| &fPitchΔ: &e1t:{pitch_1t}° 5t:{pitch_5t}°"
|
||||
debug_card_dynamics: "&7• &bDynamics: &fRotVel: &e{rot_vel}°/t &8| &fYawAccel: &e{yaw_accel} &8| &fJerk: &e{yaw_jerk} &8| &fVar10t: &e{rot_var} &8| &fRotAge: &e{rot_age}ms"
|
||||
debug_card_combat: "&7• &bCombat: &fCooldown: &e{cooldown}% &8| &fInterval: &e{interval}t &7(~{cps} CPS) &8| &fCrit: {crit} &8| &fKB: {kb}"
|
||||
debug_card_ai: "&7• &6AI & Risk: &fModel P: &e{model_p} ({model_pct}%) &8| &fEventRisk: &e{event_risk} &8| &fAggRisk: {agg_risk}/100 &8| &fVerdict: {verdict}"
|
||||
debug_card_signals: "&7• &6Signals: &f{signals}"
|
||||
debug_card_contribs: "&7• &6Contributors: &f{contribs}"
|
||||
|
||||
# Discord webhook embed labels
|
||||
discord:
|
||||
embed_title: "🚨 Cheat Violation Detected on the Server"
|
||||
field_player: "👤 Player"
|
||||
field_cheat: "⚔️ Cheat Type"
|
||||
field_confidence: "📊 AI Confidence"
|
||||
field_flags: "⚠️ Total Flags"
|
||||
field_ping: "📶 Ping"
|
||||
field_metrics: "📐 Hit Metrics"
|
||||
metrics_value: "Distance: `{distance}m` | Angle: `{angle}°`"
|
||||
|
||||
# Update notifications
|
||||
updates:
|
||||
checking: "�d2ff[SynapseAI] &fChecking for updates on GitHub..."
|
||||
up_to_date: "�ff88[SynapseAI] &fYou are running the latest version of Synapse AI-AntiCheat (&e{version}&f)."
|
||||
available: "�d2ff&l[SynapseAI UPDATE] &fA new version is available: �ff88&lv{latest} &7(Current: &c{current}&7)!"
|
||||
release_name: "&7• Release: &e{title}"
|
||||
release_url: "&7• GitHub: �d2ff{url}"
|
||||
btn_github: "GitHub Releases"
|
||||
btn_github_hover: "&bClick to open GitHub release page:\n&e{url}"
|
||||
error: "&#ff3344[SynapseAI] &cFailed to check for updates: {error}"
|
||||
|
||||
# Dataset Collection Localization
|
||||
dataset:
|
||||
disabled: "&c[SynapseAI Dataset] Dataset collection is disabled in config.yml (set dataset.enabled: true)."
|
||||
usage: "&c[SynapseAI Dataset] Usage: /aiac dataset <start|stop|stats|export|clear>"
|
||||
usage_start: "&c[SynapseAI Dataset] Usage: /aiac dataset start <player> <legit|cheat>"
|
||||
invalid_label: "&c[SynapseAI Dataset] Invalid label! Use 'legit' or 'cheat'."
|
||||
started: "�ff88[SynapseAI Dataset] Started recording combat dataset for &e{player} �ff88as &6{label}�ff88."
|
||||
stopped_player: "&#ffaa00[SynapseAI Dataset] Stopped recording dataset for &e{player}&#ffaa00."
|
||||
stopped_all: "&#ffaa00[SynapseAI Dataset] Stopped all active dataset sessions (&e{count} &#ffaa00stopped)."
|
||||
not_recording: "&c[SynapseAI Dataset] That player does not have an active recording session."
|
||||
stats_header: "�d2ff&l[SynapseAI Dataset Collection Telemetry]"
|
||||
stats_active: "&7• Active Recording Sessions: �ff88{count}"
|
||||
stats_memory: "&7• Unsaved Memory Queue: &#ffa500{count} &7samples"
|
||||
stats_legit: "&7• Total Legit Samples Collected: �ff88{count}"
|
||||
stats_cheat: "&7• Total Cheat Samples Collected: &#ff2244{count}"
|
||||
exported: "�ff88[SynapseAI Dataset] Successfully exported dataset to &eplugins/SynapseAiAnticheat/datasets/{file}�ff88!"
|
||||
export_empty: "&c[SynapseAI Dataset] Memory queue is empty. Nothing to export."
|
||||
cleared: "&#ffaa00[SynapseAI Dataset] Memory dataset queue was cleared."
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
# Synapse AI-AntiCheat - Russian Language File
|
||||
prefix: "�d2ff&lSynapseAC &8» &f"
|
||||
ai_prefix: "&#ff7700&lSynapseAI &8» &f"
|
||||
|
||||
# Помощь и информация
|
||||
help:
|
||||
header: "�d2ff&l🧠 Synapse AI-AntiCheat &fv{version} &8| &#ffa500Помощь по командам"
|
||||
author: "&7Автор: &eSynapse Labs Studio &8| �d2ffSynapseLabs"
|
||||
menu: "&e/aiac menu &8(или /aiac gui) &7— Открыть главное GUI-меню"
|
||||
inspect: "&e/aiac inspect <игрок> &7— Посмотреть ИИ-досье игрока"
|
||||
freeze: "&e/aiac freeze <игрок> &7— Вызвать игрока на проверку (заморозить)"
|
||||
unfreeze: "&e/aiac unfreeze <игрок> &7— Разморозить игрока"
|
||||
dataset: "&e/aiac dataset &7— Управление сбором обучающих датасетов"
|
||||
reload: "&e/aiac reload &7— Перезагрузить конфигурацию"
|
||||
debug: "&e/aiac debug [игрок|visual|off] &7— Вкл/выкл отладку ударов, углов и хитбоксов"
|
||||
lang: "&e/aiac lang [en|ru] &7— Сменить язык античита"
|
||||
update: "&e/aiac update &7— Проверить наличие обновлений"
|
||||
discord: "&7Официальный Discord: �d2ff{url}"
|
||||
|
||||
setup:
|
||||
required_prompt: "&#ff2244&l[SynapseAI] &eПожалуйста, введите &6/aiac &eдля выбора языка и завершения настройки!"
|
||||
completed: "�ff88&l[SynapseAI] &aНастройка завершена! Язык установлен на &e{lang}&a. Защита античита АКТИВНА."
|
||||
|
||||
lang_selector:
|
||||
header: "�d2ff================================================="
|
||||
prompt: "�d2ff&l🌐 Выбор языка античита &8| &fSelect Language:"
|
||||
current: "&7Текущий язык: &e{current}"
|
||||
btn_en: "�d2ff[🇺🇸 English]"
|
||||
btn_ru: "�ff88[🇷🇺 Русский]"
|
||||
btn_en_hover: "&bClick to select English"
|
||||
btn_ru_hover: "&aНажмите для выбора русского языка"
|
||||
changed: "&aЯзык античита успешно изменен на &e{lang}&a!"
|
||||
|
||||
about:
|
||||
header: "&b================================================="
|
||||
title: "&b&lSynapse AI-AntiCheat &fv{version}"
|
||||
author: "&fАвтор плагина: &e&lSynapse Labs Studio"
|
||||
studio: "&fСтудия: &b&lSynapseLabs"
|
||||
discord: "&fОфициальный Discord: &a&l{url}"
|
||||
description: "&7Нейросетевой античит в реальном времени с кинематическим анализом и мостом к GrimAC."
|
||||
engine: "&7Движок: &fONNX Runtime Machine Learning + GrimAC Deep Ingestion"
|
||||
|
||||
alerts:
|
||||
hard: "&#ff3344&l[SynapseAC] &#ff5555[Hard-Check] &fИгрок &e{player} &fпровалил проверку: &#ff2244&l{check} &7(&cHard-Флаги: &#ff3344{flags}&7)"
|
||||
ai: "&#ff3344&l[SynapseAI] &#ff6666[ИИ-Анализ] &fИгрок &e{player} &fподозрение: &#ff2244&l{check} &7(&cУверенность: &#ff5555{confidence}%&7, {state} &7| &cAI-Флаги: &#ff3344{flags}&7)"
|
||||
grim: "&#ff3344&l[SynapseAC] &#ff7777[GrimAC Bridge] &fИгрок &e{player} &fпровал: &#ff2244&l{check} &7(&cVL: &#ff5555{vl}&7, &cВсего: &#ff3344{flags}&7)"
|
||||
btn_dossier: "Досье"
|
||||
btn_spectate: "Спектатор"
|
||||
btn_freeze: "Заморозка"
|
||||
btn_kick: "Кик"
|
||||
btn_dossier_hover: "&eНажмите, чтобы открыть досье игрока"
|
||||
btn_spectate_hover: "&dНаблюдать за игроком"
|
||||
btn_freeze_hover: "&bВызвать на проверку"
|
||||
btn_kick_hover: "&cКикнуть игрока с сервера"
|
||||
kick_reason: "Нечестное преимущество [SynapseAI]"
|
||||
banned_ip_join: "&#ff2244&l[SynapseAI ВНИМАНИЕ] &fИгрок &e{player} &fзашёл с IP &c{ip}&f, на котором есть &#ff0055&lЗАБАНЕННЫЕ АККАУНТЫ&f!"
|
||||
|
||||
# Метки статуса угрозы
|
||||
threat_state:
|
||||
clean: "�ff88✔ &aЧИСТ"
|
||||
suspicious: "&#ffaa00⚠ &#ffcc00ПОДОЗРЕНИЕ"
|
||||
high_confidence: "&#ff7700⚠ &#ffa500ВЫСОКИЙ РИСК"
|
||||
confirmed: "&#ff2244⚡ &#ff0055ПОДТВЕРЖДЕН (ЧИТ)"
|
||||
|
||||
# Локализация GUI
|
||||
gui:
|
||||
main_title: "�d2ffПанель Администратора 󙀸| &#ffa500Synapse AI"
|
||||
inspect_title: "�d2ff[Досье] &#ffa500{player}"
|
||||
top_title: "�d2ff&l🧠 Synapse AI-AntiCheat v3.1.0"
|
||||
engine: "&fДвижок: �d2ffONNX Runtime Machine Learning"
|
||||
inference_speed: "&fСкорость инференса: �ff88< 0.3 мс (RAM ThreadPool)"
|
||||
grim_status: "&fСтатус GrimAC: {status}"
|
||||
grim_connected: "�ff88ПОДКЛЮЧЕН (HYBRID)"
|
||||
grim_standalone: "&#ffaa00STANDALONE"
|
||||
discord: "&fDiscord: �d2ff{url}"
|
||||
update_status: "&fОбновления: {status}"
|
||||
update_status_latest: "�ff88v{version} (АКТУАЛЬНО)"
|
||||
update_status_available: "&#ffaa00ДОСТУПНА v{latest}"
|
||||
system_active: "�ff88✔ СИСТЕМА АКТИВНА И ЗАЩИЩАЕТ СЕРВЕР"
|
||||
threat_info_title: "&#ffa500&l⚡ Архитектура ИИ и Статусы Оценки"
|
||||
threat_clean: "�ff88✔ CLEAN (0-24%) &7— Честная игра без аномалий"
|
||||
threat_suspicious: "&#ffaa00⚠ SUSPICIOUS (25-59%) &7— Оповещение персонала, повышенный риск"
|
||||
threat_cheat: "&#ff2244⚡ CHEAT (60-100%) &7— Подтвержденное нарушение / Совокупность сигналов"
|
||||
player_threat: "&7• Статус детектора: {state}"
|
||||
player_risk: "&7• Уровень риска: {bar} {score}%"
|
||||
player_killaura: "&7• Killaura: {bar} {score}%"
|
||||
player_aim: "&7• Aim Assist: {bar} {score}%"
|
||||
player_ping: "&7• Пинг: {color}{ping} ms"
|
||||
player_ip: "&7• IP адрес: &f{ip}"
|
||||
player_alts: "&7• Известных аккаунтов: {color}{alts}"
|
||||
player_banned_on_ip: "&7• Баны на IP: {status}"
|
||||
banned_yes: "&#ff2244&lДА (ОПАСНО)"
|
||||
banned_no: "�ff88НЕТ (ЧИСТО)"
|
||||
player_flags: "&7• Всего флагов: &#ffa500{total} &8(Hard: �d2ff{hard}&8, AI: &#ff7700{ai}&8)"
|
||||
player_last_flag: "&7• Последнее нарушение: &c{reason}"
|
||||
player_gamemode: "&7• Режим: &e{gamemode}"
|
||||
player_click_inspect: "�ff88▶ Нажмите для открытия досье"
|
||||
inspect_first_join: "&7• Первый вход: &f{time}"
|
||||
inspect_ip: "&7• IP адрес: &f{ip}"
|
||||
inspect_status: "&7• Статус угрозы: {state}"
|
||||
inspect_freeze_state: "&7• Заморозка: {state}"
|
||||
freeze_frozen: "&#ff2244&lЗАМОРОЖЕН"
|
||||
freeze_free: "�ff88СВОБОДЕН"
|
||||
inspect_alts_title: "&#ffa500&l🌐 Известные аккаунты ({count})"
|
||||
inspect_alts_header: "&7Все аккаунты, замеченные с IP {ip}:"
|
||||
inspect_combat_diag: "�d2ff&l🎯 ИИ-Диагностика Боя"
|
||||
inspect_network_diag: "�d2ff&l📶 Сетевой Анализ"
|
||||
inspect_network_quality: "&7• Качество соединения: {quality}"
|
||||
network_stable: "�ff88Стабильно"
|
||||
network_lag: "&#ffaa00Возможны задержки"
|
||||
inspect_btn_unfreeze: "�ff88&l🔓 Разморозить игрока"
|
||||
inspect_btn_unfreeze_lore: "&7Завершить проверку и отправить на спавн."
|
||||
inspect_btn_freeze: "�d2ff&l❄️ Вызвать на проверку"
|
||||
inspect_btn_freeze_lore: "&7Телепортировать в комнату проверок и заблокировать движения."
|
||||
inspect_btn_reset: "�ff88&l⚡ Сбросить флаги"
|
||||
inspect_btn_reset_lore: "&7Обнулить счетчики флагов и подозрительности."
|
||||
inspect_btn_spectate: "&#a855f7&l👁️ Наблюдать (Спектатор)"
|
||||
inspect_btn_spectate_lore: "&7Следить за игроком от первого лица."
|
||||
inspect_btn_kick: "&#ffaa00&l🚫 Кикнуть игрока"
|
||||
inspect_btn_kick_lore: "&7Отключить подозреваемого от сервера."
|
||||
inspect_btn_ban: "&#ff2244&l🔨 Заблокировать аккаунт"
|
||||
inspect_btn_ban_lore: "&7Выдать перманентный бан через систему наказаний."
|
||||
inspect_btn_back: "&#ffa500&l⬅️ Назад в меню"
|
||||
target_offline: "&#ff2244[SynapseAI] Целевой игрок вышел из сети."
|
||||
flags_reset: "�ff88[SynapseAI] Флаги и подозрительность игрока &e{player} �ff88успешно сброшены!"
|
||||
spectate_msg: "�d2ff[SynapseAI] Вы наблюдаете за игроком &e{player} �d2ffв режиме Наблюдателя."
|
||||
kick_msg: "&#ff3333[SynapseAI] Вы были отключены администратором."
|
||||
kick_admin: "&#ff2244[SynapseAI] Игрок &e{player} &#ff2244был кикнут."
|
||||
ban_admin: "&#ff2244[SynapseAI] Игрок &e{player} &#ff2244был забанен через {system}!"
|
||||
ban_reason: "Использование читов"
|
||||
freeze_reason: "Вызов на проверку администратором"
|
||||
|
||||
freeze:
|
||||
title_frozen: "&c&lЗАМОРОЖЕН НА ПРОВЕРКУ!"
|
||||
subtitle_discord: "&fDiscord: &b{discord_url}"
|
||||
title_passed: "&a&lПРОВЕРКА ПРОЙДЕНА!"
|
||||
subtitle_passed: "&fВы успешно прошли проверку на читы!"
|
||||
title_warning: "&c&lПРОВЕРКА НА ЧИТЫ!"
|
||||
actionbar_warning: "&c[!] Вы на проверке! Пишите в чат для ответа модератору."
|
||||
frozen_target: "&c=================================================\n&c&l[!] ВЫ БЫЛИ ТЕЛЕПОРТИРОВАНЫ И ЗАМОРОЖЕНЫ НА ПРОВЕРКУ!\n&fПричина: &e{reason}\n&fПожалуйста, не выходите из игры и зайдите в Discord:\n&b👉 {discord_url}\n&a💬 Вы можете писать в чат — ваши сообщения видит модератор проверки.\n&7(При выходе из игры вы получите автоматический бан за отказ от проверки)\n&c================================================="
|
||||
unfrozen_target: "&a=================================================\n&a&l[SynapseAI] ПРОВЕРКА УСПЕШНО ЗАВЕРШЕНА!\n&fВы признаны честным игроком и телепортированы на спавн.\n&fПриятной игры на сервере!\n&a================================================="
|
||||
staff_start: "&b=================================================\n&b&l[SynapseAI] ВЫ НАЧАЛИ ПРОВЕРКУ ИГРОКА: &e&l{player}\n&fИгрок телепортирован на проверку.\n&fДля общения в приватном чате проверки пишите с префиксом &e! &f(например: &e!Ваш Discord?&f)\n&b================================================="
|
||||
staff_passed: "&a[SynapseAI] Игрок &e{player} &aуспешно прошел проверку и отправлен на спавн."
|
||||
frozen_staff: "�d2ff[SynapseAI] Игрок &e{player} �d2ffвызван на проверку!"
|
||||
unfrozen_staff: "�ff88[SynapseAI] Игрок &e{player} �ff88разморожен."
|
||||
already_frozen: "&cИгрок {player} уже заморожен!"
|
||||
not_frozen: "&cИгрок {player} не заморожен!"
|
||||
cannot_move: "&cВы заморожены! Пройдите в Discord: &b{discord_url}"
|
||||
cooldown_wait: "&c[SynapseAI] Подождите {seconds} сек перед повторным действием."
|
||||
command_blocked: "&c[!] Использование команд во время проверки запрещено! Пишите ответы прямо в чат."
|
||||
role_moderator: "&b[Модератор]"
|
||||
role_suspect: "&c[Подозреваемый]"
|
||||
interrogation_format: "&8[&c&lПРОВЕРКА&8] {role} &e{sender} &8» &f{message}"
|
||||
quit_ban_broadcast: "&8[&c&lAI-AC&8] &fИгрок &e{player} &cвышел во время проверки на читы (Отказ от проверки — ЗАБАНЕН)!"
|
||||
|
||||
punishment:
|
||||
kick_message: "&#ff3333[SynapseAI] &fВы были отключены за использование постороннего ПО (&c{reason}&f).\n&7Апелляция в Discord: �d2ff{discord_url}"
|
||||
ban_reason: "&4[SynapseAI] {reason}\n&7Апелляция: &b{discord_url}"
|
||||
ban_reason_refusal: "&4[SynapseAI] Отказ от проверки на читы\n&7Апелляция: &b{discord_url}"
|
||||
reloaded: "&aКонфигурация и файлы локализации успешно перезагружены!"
|
||||
|
||||
# Ответы команд
|
||||
commands:
|
||||
access_denied: "&cДоступ запрещён."
|
||||
lang_usage: "&cИспользование: /aiac lang <en|ru>"
|
||||
lang_current_default: "Текущий язык по умолчанию: {lang}"
|
||||
players_only_gui: "GUI-меню доступно только игрокам в игре."
|
||||
ingame_only: "Команда доступна только в игре."
|
||||
separator: "&b================================================="
|
||||
ping_specify: "&cУкажите игрока: /aiac ping <player>"
|
||||
ping_rating_excellent: "�ff88Отличный (Оптимально для PvP)"
|
||||
ping_rating_normal: "&#ffaa00Нормальный (Стабильно)"
|
||||
ping_rating_elevated: "&#ff7700Повышенный (Небольшая задержка)"
|
||||
ping_rating_high: "&#ff2244Высокий (Сетевые задержки)"
|
||||
ping_header: "�d2ff&l📶 Connection Telemetry: &e&l{player}"
|
||||
ping_current: "&7• Текущий пинг: &f{ping} ms ({rating}&7)"
|
||||
ping_ip: "&7• IP адрес: &f{ip}"
|
||||
ping_tps: "&7• TPS сервера: �ff8820.0 (Оптимально)"
|
||||
ping_grim: "&7• Мост GrimAC: {status}"
|
||||
grim_synced: "�ff88Синхронизирован"
|
||||
grim_standalone: "&7Standalone"
|
||||
unknown: "Неизвестно"
|
||||
freezeloc_set: "�ff88[SynapseAI] Локация для проверок установлена на вашу текущую позицию!"
|
||||
chat_not_inspecting: "&c[SynapseAI] Вы не проводите проверку ни одного игрока."
|
||||
player_not_found_online: "&cИгрок не найден в сети."
|
||||
player_not_found: "&cИгрок не найден."
|
||||
status_model: "�d2ff[SynapseAI] &fONNX ML Модель: {status}"
|
||||
status_bridge: "�d2ff[SynapseAI] &fМост GrimAC: {status}"
|
||||
status_ban: "�d2ff[SynapseAI] &fСистема банов: �ff88{system}"
|
||||
status_overhead: "�d2ff[SynapseAI] &fНадголовной дисплей: �ff88АКТИВЕН (Фильтр LuckPerms)"
|
||||
status_discord: "�d2ff[SynapseAI] &fDiscord сервер: �d2ff{url}"
|
||||
status_webhook: "�d2ff[SynapseAI] &fDiscord Webhook: {status}"
|
||||
status_update: "�d2ff[SynapseAI] &fСтатус обновлений: {status}"
|
||||
status_up_to_date: "�ff88АКТУАЛЬНАЯ ВЕРСИЯ (v{version})"
|
||||
status_update_available: "&#ffaa00ДОСТУПНО ОБНОВЛЕНИЕ (v{latest})"
|
||||
status_model_active: "�ff88АКТИВНА (<0.3ms)"
|
||||
status_model_error: "&cОШИБКА"
|
||||
status_bridge_connected: "�ff88ПОДКЛЮЧЕН (HYBRID)"
|
||||
status_bridge_standalone: "&#ffaa00STANDALONE"
|
||||
status_enabled: "�ff88ВКЛЮЧЕН"
|
||||
status_disabled: "&7ОТКЛЮЧЕН"
|
||||
check_header: "�d2ff[SynapseAI] &#ffa500ИИ-Диагностика игрока: &e{player}"
|
||||
check_threat: "&7• Статус угрозы: {state}"
|
||||
check_killaura: "&7• Уверенность Killaura: {bar} {score}%"
|
||||
check_aim: "&7• Уверенность Aim: {bar} {score}%"
|
||||
check_suspicion: "&7• Историческая подозрительность: {bar} {score}%"
|
||||
check_flags: "&7• Всего флагов: &#ffa500{total} &8(Hard: �d2ff{hard}&8, AI: &#ff7700{ai}&8, Grim: &bdf8{grim}&8)"
|
||||
debug_enabled_all: "�ff88[SynapseAI Debug] &fРежим отладки для разработчиков &aВКЛЮЧЕН &f(все игроки)."
|
||||
debug_enabled_player: "�ff88[SynapseAI Debug] &fРежим отладки для разработчиков &aВКЛЮЧЕН &f(игрок: &e{player}&f)."
|
||||
debug_disabled: "&#ffaa00[SynapseAI Debug] &fРежим отладки для разработчиков &cВЫКЛЮЧЕН&f."
|
||||
debug_visual_on: "�ff88[SynapseAI Debug] &fВизуализация луча атаки и хитбоксов частицами &aВКЛЮЧЕНА&f."
|
||||
debug_visual_off: "&#ffaa00[SynapseAI Debug] &fВизуализация луча атаки и хитбоксов частицами &cВЫКЛЮЧЕНА&f."
|
||||
debug_cleared: "�ff88[SynapseAI Debug] &fВсе активные сессии отладки были сброшены."
|
||||
debug_card_header: "&8[&bAIAC-DEBUG&8] &e{attacker} &8(&7пинг: &f{attacker_ping}мс&8) &7⚔ &c{victim} &8(&7пинг: &f{victim_ping}мс&8)"
|
||||
debug_card_geometry: "&7• &bГеометрия: &fУгол: &e{angle}° &8| &fReach: &e{reach}m &7(comp: &a{comp_reach}m&7, raw: &e{raw_reach}m&7)"
|
||||
debug_card_hitbox: "&7• &bХитбокс: &fRayHit: {ray_hit} &8| &fEdgeProx: &e{edge_prox} &8| &fMargin: &e+{margin}m &8| &fУгол стен: {corner} &8| &fСтена: {wall}"
|
||||
debug_card_kinematics: "&7• &bКинематика: &fYawΔ: &e1t:{yaw_1t}° 5t:{yaw_5t}° &8| &fPitchΔ: &e1t:{pitch_1t}° 5t:{pitch_5t}°"
|
||||
debug_card_dynamics: "&7• &bДинамика: &fСкорость: &e{rot_vel}°/t &8| &fYawAccel: &e{yaw_accel} &8| &fРывок: &e{yaw_jerk} &8| &fVar10t: &e{rot_var} &8| &fRotAge: &e{rot_age}ms"
|
||||
debug_card_combat: "&7• &bБой: &fКулдаун: &e{cooldown}% &8| &fИнтервал: &e{interval}t &7(~{cps} CPS) &8| &fКрит: {crit} &8| &fKB: {kb}"
|
||||
debug_card_ai: "&7• &6ИИ & Риск: &fМодель P: &e{model_p} ({model_pct}%) &8| &fEventRisk: &e{event_risk} &8| &fAggRisk: {agg_risk}/100 &8| &fВердикт: {verdict}"
|
||||
debug_card_signals: "&7• &6Сигналы: &f{signals}"
|
||||
debug_card_contribs: "&7• &6Вклад сигналов: &f{contribs}"
|
||||
|
||||
# Discord webhook embed labels
|
||||
discord:
|
||||
embed_title: "🚨 На сервере зафиксировано нарушение (Чит)"
|
||||
field_player: "👤 Игрок"
|
||||
field_cheat: "⚔️ Тип чита"
|
||||
field_confidence: "📊 Уверенность ИИ"
|
||||
field_flags: "⚠️ Всего флагов"
|
||||
field_ping: "📶 Пинг"
|
||||
field_metrics: "📐 Метрики удара"
|
||||
metrics_value: "Дистанция: `{distance}m` | Угол: `{angle}°`"
|
||||
|
||||
# Оповещения об обновлениях
|
||||
updates:
|
||||
checking: "�d2ff[SynapseAI] &fПроверка обновлений на GitHub..."
|
||||
up_to_date: "�ff88[SynapseAI] &fВы используете последнюю версию Synapse AI-AntiCheat (&e{version}&f)."
|
||||
available: "�d2ff&l[SynapseAI ОБНОВЛЕНИЕ] &fДоступна новая версия: �ff88&lv{latest} &7(Текущая: &c{current}&7)!"
|
||||
release_name: "&7• Релиз: &e{title}"
|
||||
release_url: "&7• GitHub: �d2ff{url}"
|
||||
btn_github: "GitHub Релизы"
|
||||
btn_github_hover: "&bНажмите, чтобы открыть страницу релиза на GitHub:\n&e{url}"
|
||||
error: "&#ff3344[SynapseAI] &cНе удалось проверить обновления: {error}"
|
||||
|
||||
# Локализация сбора датасетов
|
||||
dataset:
|
||||
disabled: "&c[SynapseAI Датасет] Сбор датасетов выключен в config.yml (установите dataset.enabled: true)."
|
||||
usage: "&c[SynapseAI Датасет] Использование: /aiac dataset <start|stop|stats|export|clear>"
|
||||
usage_start: "&c[SynapseAI Датасет] Использование: /aiac dataset start <игрок> <legit|cheat>"
|
||||
invalid_label: "&c[SynapseAI Датасет] Неверный класс! Используйте 'legit' или 'cheat'."
|
||||
started: "�ff88[SynapseAI Датасет] Начата запись датасета для игрока &e{player} �ff88с меткой &6{label}�ff88."
|
||||
stopped_player: "&#ffaa00[SynapseAI Датасет] Запись датасета для игрока &e{player} &#ffaa00остановлена."
|
||||
stopped_all: "&#ffaa00[SynapseAI Датасет] Остановлены все активные сессии записи (&e{count} &#ffaa00сессий)."
|
||||
not_recording: "&c[SynapseAI Датасет] Для этого игрока нет активной сессии записи."
|
||||
stats_header: "�d2ff&l[SynapseAI Телеметрия сбора датасета]"
|
||||
stats_active: "&7• Активных сессий записи: �ff88{count}"
|
||||
stats_memory: "&7• Несохранённых записей в ОЗУ: &#ffa500{count} &7ударов"
|
||||
stats_legit: "&7• Всего собрано легитных (LEGIT) записей: �ff88{count}"
|
||||
stats_cheat: "&7• Всего собрано читерских (CHEAT) записей: &#ff2244{count}"
|
||||
exported: "�ff88[SynapseAI Датасет] Датасет успешно экспортирован в файл &eplugins/SynapseAiAnticheat/datasets/{file}�ff88!"
|
||||
export_empty: "&c[SynapseAI Датасет] Буфер в памяти пуст. Экспортировать нечего."
|
||||
cleared: "&#ffaa00[SynapseAI Датасет] Буфер записей в памяти был очищен."
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
name: SynapseAiAnticheat
|
||||
version: '3.2'
|
||||
main: net.synapselabs.anticheat.AiAnticheatPlugin
|
||||
api-version: '1.16'
|
||||
authors: [Synapse Labs Studio]
|
||||
website: https://dsc.gg/synapselabs
|
||||
description: Next-Gen AI Machine Learning & Hybrid Anticheat for Spigot, Paper and Purpur
|
||||
softdepend: [GrimAC, LuckPerms]
|
||||
commands:
|
||||
aianticheat:
|
||||
description: Главная команда управления Synapse AI-AntiCheat
|
||||
permission: aianticheat.admin
|
||||
aliases: [aiac, synapse, synapseac]
|
||||
permissions:
|
||||
aianticheat.admin:
|
||||
description: Полные права администратора Synapse AI-AntiCheat
|
||||
default: op
|
||||
aianticheat.alerts:
|
||||
description: Получение алертов о читерах в реальном времени
|
||||
default: op
|
||||
aianticheat.overhead:
|
||||
description: Отображение оценки вероятности читов (Killaura/Aim) над головами игроков
|
||||
default: op
|
||||
aianticheat.freeze:
|
||||
description: Право на заморозку подозрительных игроков
|
||||
default: op
|
||||
aianticheat.update:
|
||||
description: Получение уведомлений о доступных обновлениях
|
||||
default: op
|
||||
aianticheat.debug:
|
||||
description: Режим отладки телеметрии ударов, углов и хитбоксов для разработчиков
|
||||
default: op
|
||||
Reference in new issue
Block a user