Initial commit: OpenAntiSpoof-FullOpsec

This commit is contained in:
notme_ssa committed 2026-11-29 20:07:47 +07:00
commit d66f60533e
106 files changed
+10281

No files matched your search

@@ -0,0 +1,7 @@
package com.gigazelensky.antispoof.data;
public enum AssetCheckType {
TEXTURES,
FONT,
CORRUPTION
}
@@ -0,0 +1,17 @@
package com.gigazelensky.antispoof.data;
public enum CheckMode {
SAFE,
LEGACY;
public static CheckMode parse(String raw, CheckMode fallback) {
if (raw == null || raw.isBlank()) {
return fallback;
}
try {
return valueOf(raw.trim().toUpperCase(java.util.Locale.ROOT));
} catch (IllegalArgumentException ignored) {
return fallback;
}
}
}
@@ -0,0 +1,41 @@
package com.gigazelensky.antispoof.data;
import java.util.Locale;
public enum ClientPlatform {
LUNAR("Lunar Client", "lunar"),
FEATHER("Feather Client", "feather"),
BADLION("Badlion Client", "blc"),
LABYMOD("LabyMod", "laby");
private final String displayName;
private final String shortAlias;
ClientPlatform(String displayName, String shortAlias) {
this.displayName = displayName;
this.shortAlias = shortAlias;
}
public String getDisplayName() {
return displayName;
}
public String getShortAlias() {
return shortAlias;
}
public static ClientPlatform parse(String raw) {
if (raw == null || raw.isBlank()) {
return null;
}
String norm = raw.trim().toLowerCase(Locale.ROOT).replace(" ", "").replace("-", "").replace("_", "");
for (ClientPlatform p : values()) {
if (p.name().toLowerCase(Locale.ROOT).equals(norm)
|| p.shortAlias.equals(norm)
|| p.displayName.toLowerCase(Locale.ROOT).replace(" ", "").equals(norm)) {
return p;
}
}
return null;
}
}
@@ -0,0 +1,7 @@
package com.gigazelensky.antispoof.data;
public enum DetectionTriggerSource {
BRAND,
CHANNEL,
TRANSLATABLE
}
@@ -0,0 +1,7 @@
package com.gigazelensky.antispoof.data;
public enum IdentityProbeStage {
WAITING_FOR_HIDER,
PROBING_CACHE,
MARKING_NEW
}
@@ -0,0 +1,21 @@
package com.gigazelensky.antispoof.data;
import java.util.List;
public final class IdentityRecord {
private final List<String> allAccounts;
private final List<String> altAccounts;
public IdentityRecord(List<String> allAccounts, List<String> altAccounts) {
this.allAccounts = allAccounts == null ? List.of() : List.copyOf(allAccounts);
this.altAccounts = altAccounts == null ? List.of() : List.copyOf(altAccounts);
}
public List<String> getAllAccounts() {
return allAccounts;
}
public List<String> getAltAccounts() {
return altAccounts;
}
}
@@ -0,0 +1,23 @@
package com.gigazelensky.antispoof.data;
public final class LogEntry {
private long timestamp;
private LogType logType;
private String message;
private PlayerSnapshotData snapshot;
public LogEntry() {
}
public LogEntry(long timestamp, LogType logType, String message, PlayerSnapshotData snapshot) {
this.timestamp = timestamp;
this.logType = logType == null ? LogType.INFO : logType;
this.message = message == null ? "" : message;
this.snapshot = snapshot;
}
public long getTimestamp() { return timestamp; }
public LogType getLogType() { return logType; }
public String getMessage() { return message; }
public PlayerSnapshotData getSnapshot() { return snapshot; }
}
@@ -0,0 +1,94 @@
package com.gigazelensky.antispoof.data;
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Parses historical player log files to compute violation counts and leaderboard stats (reconstructed from IlIlIlIIIIlIIll).
*/
public final class LogReaderParser {
private static final Pattern TOTAL_FLAGS_PATTERN = Pattern.compile("(?i)total\\s*flags\\s*:\\s*(\\d+)");
private final AntiSpoofPlugin plugin;
public LogReaderParser(AntiSpoofPlugin plugin) {
this.plugin = plugin;
}
public CompletableFuture<Integer> getHistoricalViolationCount(UUID uniqueId) {
return CompletableFuture.supplyAsync(() -> countViolations(uniqueId, TimeRange.ALL));
}
public int countViolations(UUID uniqueId, TimeRange range) {
PlayerLogManager logMgr = plugin.getPlayerLogManager();
if (logMgr == null || uniqueId == null) {
return 0;
}
long cutoff = cutoffFor(range);
File file = logMgr.getPlayerLogFile(uniqueId);
if (!file.exists()) {
return 0;
}
int count = 0;
try {
List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
for (String line : lines) {
Matcher m = TOTAL_FLAGS_PATTERN.matcher(line);
if (m.find()) {
count = Math.max(count, Integer.parseInt(m.group(1)));
} else if (line.contains("[FLAG]") || line.contains("[PUNISH]")) {
if (cutoff <= 0L || file.lastModified() >= cutoff) {
count++;
}
}
}
} catch (IOException | NumberFormatException ignored) {
}
return count;
}
public Map<UUID, Integer> getFlagLeaderboard(TimeRange range) {
PlayerLogManager logMgr = plugin.getPlayerLogManager();
if (logMgr == null) {
return Collections.emptyMap();
}
Map<UUID, Integer> counts = new LinkedHashMap<>();
for (UUID uuid : logMgr.listLoggedPlayers()) {
int c = countViolations(uuid, range);
if (c > 0) {
counts.put(uuid, c);
}
}
List<Map.Entry<UUID, Integer>> sorted = counts.entrySet().stream()
.sorted((a, b) -> Integer.compare(b.getValue(), a.getValue()))
.toList();
Map<UUID, Integer> out = new LinkedHashMap<>();
for (Map.Entry<UUID, Integer> e : sorted) {
out.put(e.getKey(), e.getValue());
}
return out;
}
private static long cutoffFor(TimeRange range) {
if (range == null || range == TimeRange.ALL) {
return 0L;
}
long now = System.currentTimeMillis();
return switch (range) {
case WEEK -> now - TimeUnit.DAYS.toMillis(7L);
case MONTH -> now - TimeUnit.DAYS.toMillis(30L);
case ALL -> 0L;
};
}
}
@@ -0,0 +1,26 @@
package com.gigazelensky.antispoof.data;
public enum LogSortMode {
FLAGS("Flags"),
LOGS("Logs"),
AVG_FLAGS("Average Flags"),
ALPHABETICAL_AZ("A-Z"),
ALPHABETICAL_ZA("Z-A"),
LATEST("Latest"),
OLDEST("Oldest");
private final String label;
LogSortMode(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
public LogSortMode next() {
LogSortMode[] vals = values();
return vals[(ordinal() + 1) % vals.length];
}
}
@@ -0,0 +1,9 @@
package com.gigazelensky.antispoof.data;
public enum LogType {
INFO,
FLAG,
PUNISH,
PROBE,
ADMIN
}
@@ -0,0 +1,7 @@
package com.gigazelensky.antispoof.data;
public enum MatchConfidence {
EXACT,
INFERRED,
NONE
}
@@ -0,0 +1,9 @@
package com.gigazelensky.antispoof.data;
public enum ModLoaderCategory {
UNSPECIFIED,
FABRIC_INTERNAL,
FABRIC_EXTERNAL,
FORGE_INTERNAL,
FORGE_EXTERNAL
}
@@ -0,0 +1,25 @@
package com.gigazelensky.antispoof.data;
public class OsInfo {
private final String osName;
private final double confidence;
private final String source;
public OsInfo(String osName, double confidence, String source) {
this.osName = (osName == null || osName.isBlank()) ? "Unknown" : osName;
this.confidence = Math.max(0.0, Math.min(confidence, 1.0));
this.source = source == null ? "unknown" : source;
}
public String getOsName() {
return osName;
}
public double getConfidence() {
return confidence;
}
public String getSource() {
return source;
}
}
@@ -0,0 +1,142 @@
package com.gigazelensky.antispoof.data;
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
import org.bukkit.entity.Player;
/**
* Per-player append-only JSON-lines log writer and reader (reconstructed from IllIIIllllllllI).
*/
public final class PlayerLogManager {
private static final DateTimeFormatter TS_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault());
private final AntiSpoofPlugin plugin;
private final File logsDir;
private final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
public PlayerLogManager(AntiSpoofPlugin plugin) {
this.plugin = plugin;
this.logsDir = new File(plugin.getDataFolder(), "logs");
if (!logsDir.exists()) {
logsDir.mkdirs();
}
}
public File getLogsDir() {
return logsDir;
}
public File getPlayerLogFile(UUID uniqueId) {
return new File(logsDir, uniqueId + ".log");
}
public void log(Player player, LogType type, String message) {
if (player == null || !plugin.getConfigManager().isLogsEnabled()) {
return;
}
if (type == LogType.INFO && !plugin.getConfigManager().isLogsAlways()) {
return;
}
UUID uuid = player.getUniqueId();
PlayerProfile profile = plugin.getPlayerProfiles().get(uuid);
OsInfo os = plugin.getOsInfo(uuid);
PlayerSnapshotData snap = profile != null
? profile.toSnapshotData(
plugin.getPlayerBrand(player),
plugin.getPlayerVersion(player),
plugin.getPlayerLocale(player),
os != null ? os.getOsName() : "Unknown",
plugin.isBedrock(player))
: null;
LogEntry entry = new LogEntry(System.currentTimeMillis(), type, message, snap);
appendAsync(uuid, entry);
}
public void log(UUID uniqueId, LogType type, String message) {
if (uniqueId == null || !plugin.getConfigManager().isLogsEnabled()) {
return;
}
appendAsync(uniqueId, new LogEntry(System.currentTimeMillis(), type, message, null));
}
private void appendAsync(UUID uniqueId, LogEntry entry) {
String line = "[" + TS_FMT.format(Instant.ofEpochMilli(entry.getTimestamp())) + "] [" + entry.getLogType().name() + "] "
+ entry.getMessage() + " | JSON:" + gson.toJson(entry);
CompletableFuture.runAsync(() -> {
File file = getPlayerLogFile(uniqueId);
synchronized (this) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file, StandardCharsets.UTF_8, true))) {
bw.write(line);
bw.newLine();
} catch (IOException e) {
plugin.getLogger().log(Level.WARNING, "Could not write log file for " + uniqueId, e);
}
}
});
}
public List<LogEntry> readEntries(UUID uniqueId) {
File file = getPlayerLogFile(uniqueId);
if (!file.exists()) {
return Collections.emptyList();
}
List<LogEntry> result = new ArrayList<>();
try {
for (String line : Files.readAllLines(file.toPath(), StandardCharsets.UTF_8)) {
int marker = line.indexOf(" | JSON:");
if (marker != -1) {
String json = line.substring(marker + " | JSON:".length()).trim();
try {
LogEntry parsed = gson.fromJson(json, LogEntry.class);
if (parsed != null) {
result.add(parsed);
continue;
}
} catch (Exception ignored) {
}
}
if (!line.isBlank()) {
LogType type = line.contains("[FLAG]") ? LogType.FLAG
: line.contains("[PUNISH]") ? LogType.PUNISH
: line.contains("[PROBE]") ? LogType.PROBE
: line.contains("[ADMIN]") ? LogType.ADMIN : LogType.INFO;
result.add(new LogEntry(file.lastModified(), type, line, null));
}
}
} catch (IOException e) {
plugin.getLogger().log(Level.WARNING, "Could not read log file for " + uniqueId, e);
}
return result;
}
public List<UUID> listLoggedPlayers() {
File[] files = logsDir.listFiles((dir, name) -> name.endsWith(".log"));
if (files == null) {
return Collections.emptyList();
}
List<UUID> uuids = new ArrayList<>();
for (File f : files) {
String base = f.getName().substring(0, f.getName().length() - 4);
try {
uuids.add(UUID.fromString(base));
} catch (IllegalArgumentException ignored) {
}
}
return uuids;
}
}
@@ -0,0 +1,146 @@
package com.gigazelensky.antispoof.data;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* Live per-session verification state for a connected player (reconstructed from IlIlIlIIIIIIllI).
*/
public final class PlayerProfile {
private final UUID uniqueId;
private final long joinTimeMillis;
private final ProxyState proxyState = new ProxyState();
private final Set<String> channels = ConcurrentHashMap.newKeySet();
private final Set<String> allChannels = ConcurrentHashMap.newKeySet();
private final Set<String> filteredChannels = ConcurrentHashMap.newKeySet();
private final Set<String> detectedMods = ConcurrentHashMap.newKeySet();
private final Set<String> alertedMods = ConcurrentHashMap.newKeySet();
private final Set<String> alertedKeys = ConcurrentHashMap.newKeySet();
private final Set<String> alertedCombinations = ConcurrentHashMap.newKeySet();
private final Set<String> violations = ConcurrentHashMap.newKeySet();
private final Set<String> sessionViolations = ConcurrentHashMap.newKeySet();
private final Set<String> lastTranslatedKeys = ConcurrentHashMap.newKeySet();
private final Set<String> lastMissingKeys = ConcurrentHashMap.newKeySet();
private final Set<String> flaggedMods = ConcurrentHashMap.newKeySet();
private final Set<String> clientReportedMods = ConcurrentHashMap.newKeySet();
private volatile ProbeStatus probeStatus = ProbeStatus.NOT_STARTED;
private volatile boolean alreadyPunished;
private volatile boolean initialChannelsRegistered;
private volatile String virtualHost;
private volatile long threatLevel;
public PlayerProfile(UUID uniqueId) {
this.uniqueId = uniqueId;
this.joinTimeMillis = System.currentTimeMillis();
}
public UUID getUniqueId() { return uniqueId; }
public long getJoinTimeMillis() { return joinTimeMillis; }
public ProxyState getProxyState() { return proxyState; }
public Set<String> getChannels() { return Collections.unmodifiableSet(channels); }
public Set<String> getAllChannels() { return Collections.unmodifiableSet(allChannels); }
public Set<String> getFilteredChannels() { return Collections.unmodifiableSet(filteredChannels); }
public Set<String> getDetectedMods() { return Collections.unmodifiableSet(detectedMods); }
public Set<String> getAlertedMods() { return Collections.unmodifiableSet(alertedMods); }
public Set<String> getAlertedKeys() { return Collections.unmodifiableSet(alertedKeys); }
public Set<String> getAlertedCombinations() { return Collections.unmodifiableSet(alertedCombinations); }
public Set<String> getViolations() { return Collections.unmodifiableSet(violations); }
public Set<String> getSessionViolations() { return Collections.unmodifiableSet(sessionViolations); }
public Set<String> getLastTranslatedKeys() { return Collections.unmodifiableSet(lastTranslatedKeys); }
public Set<String> getLastMissingKeys() { return Collections.unmodifiableSet(lastMissingKeys); }
public Set<String> getFlaggedMods() { return Collections.unmodifiableSet(flaggedMods); }
public Set<String> getClientReportedMods() { return Collections.unmodifiableSet(clientReportedMods); }
public void addChannel(String channel, boolean filtered) {
if (channel == null || channel.isBlank()) {
return;
}
allChannels.add(channel);
channels.add(channel);
if (filtered) {
filteredChannels.add(channel);
}
}
public void addDetectedMod(String mod) {
if (mod != null && !mod.isBlank()) {
detectedMods.add(mod);
}
}
public void addAlertedMod(String mod) {
if (mod != null && !mod.isBlank()) {
alertedMods.add(mod);
flaggedMods.add(mod);
}
}
public void addAlertedKey(String key) {
if (key != null && !key.isBlank()) {
alertedKeys.add(key);
}
}
public void addAlertedCombination(String combo) {
if (combo != null && !combo.isBlank()) {
alertedCombinations.add(combo);
}
}
public void addViolation(String reason) {
if (reason != null && !reason.isBlank()) {
violations.add(reason);
sessionViolations.add(reason);
}
}
public void addClientReportedMod(String mod) {
if (mod != null && !mod.isBlank()) {
clientReportedMods.add(mod);
}
}
public void setLastProbeKeys(Set<String> translated, Set<String> missing) {
lastTranslatedKeys.clear();
if (translated != null) lastTranslatedKeys.addAll(translated);
lastMissingKeys.clear();
if (missing != null) lastMissingKeys.addAll(missing);
}
public ProbeStatus getProbeStatus() { return probeStatus; }
public void setProbeStatus(ProbeStatus probeStatus) { this.probeStatus = probeStatus == null ? ProbeStatus.NOT_STARTED : probeStatus; }
public boolean isAlreadyPunished() { return alreadyPunished; }
public void setAlreadyPunished(boolean alreadyPunished) { this.alreadyPunished = alreadyPunished; }
public boolean isInitialChannelsRegistered() { return initialChannelsRegistered; }
public void setInitialChannelsRegistered(boolean initialChannelsRegistered) { this.initialChannelsRegistered = initialChannelsRegistered; }
public String getVirtualHost() { return virtualHost; }
public void setVirtualHost(String virtualHost) { this.virtualHost = virtualHost; }
public long getThreatLevel() { return threatLevel; }
public synchronized long addThreatLevel(long delta) {
this.threatLevel = Math.max(0L, this.threatLevel + delta);
return this.threatLevel;
}
public synchronized void setThreatLevel(long threatLevel) {
this.threatLevel = Math.max(0L, threatLevel);
}
public PlayerSnapshotData toSnapshotData(String brand, String version, String locale, String os, boolean bedrock) {
return new PlayerSnapshotData(
brand,
version,
locale,
os,
bedrock,
new LinkedHashSet<>(channels),
new LinkedHashSet<>(detectedMods),
new LinkedHashSet<>(violations),
new LinkedHashSet<>(flaggedMods)
);
}
}
@@ -0,0 +1,54 @@
package com.gigazelensky.antispoof.data;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Serializable snapshot of a player's state embedded inside log entries.
*/
public final class PlayerSnapshotData {
private String brand;
private String version;
private String locale;
private String operatingSystem;
private boolean bedrock;
private Set<String> channels = new LinkedHashSet<>();
private Set<String> detectedMods = new LinkedHashSet<>();
private Set<String> violations = new LinkedHashSet<>();
private Set<String> flaggedMods = new LinkedHashSet<>();
public PlayerSnapshotData() {
}
public PlayerSnapshotData(
String brand,
String version,
String locale,
String operatingSystem,
boolean bedrock,
Set<String> channels,
Set<String> detectedMods,
Set<String> violations,
Set<String> flaggedMods
) {
this.brand = brand;
this.version = version;
this.locale = locale;
this.operatingSystem = operatingSystem;
this.bedrock = bedrock;
if (channels != null) this.channels.addAll(channels);
if (detectedMods != null) this.detectedMods.addAll(detectedMods);
if (violations != null) this.violations.addAll(violations);
if (flaggedMods != null) this.flaggedMods.addAll(flaggedMods);
}
public String getBrand() { return brand; }
public String getVersion() { return version; }
public String getLocale() { return locale; }
public String getOperatingSystem() { return operatingSystem; }
public boolean isBedrock() { return bedrock; }
public Set<String> getChannels() { return channels; }
public Set<String> getDetectedMods() { return detectedMods; }
public Set<String> getViolations() { return violations; }
public Set<String> getFlaggedMods() { return flaggedMods; }
}
@@ -0,0 +1,214 @@
package com.gigazelensky.antispoof.data;
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
/**
* Persistent Gson storage for player identity fingerprints, alt-account clusters, and staff alert preferences
* (reconstructed from lIlIIlllllIIlII).
*/
public final class PlayerStorageManager {
private static final Type PLAYER_MAP_TYPE = new TypeToken<Map<String, StoredPlayerRecord>>() {}.getType();
private final AntiSpoofPlugin plugin;
private final File storageDir;
private final File playerMapFile;
private final File staffPrefsFile;
private final Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
private final Map<UUID, StoredPlayerRecord> recordsByUuid = new ConcurrentHashMap<>();
private final Map<String, Set<UUID>> uuidsByFingerprint = new ConcurrentHashMap<>();
private final Map<UUID, Boolean> staffAlertPrefs = new ConcurrentHashMap<>();
private final AtomicLong nextClusterId = new AtomicLong(1L);
public static final class StoredPlayerRecord {
public String uuid;
public String lastName;
public String fingerprint;
public long clusterId;
public long firstSeen;
public long lastSeen;
public boolean banned;
public boolean flagged;
}
public PlayerStorageManager(AntiSpoofPlugin plugin) {
this.plugin = plugin;
this.storageDir = new File(plugin.getDataFolder(), "data");
if (!storageDir.exists()) {
storageDir.mkdirs();
}
this.playerMapFile = new File(storageDir, "player_map.json");
this.staffPrefsFile = new File(storageDir, "staff_alerts.json");
loadAll();
}
public synchronized void loadAll() {
recordsByUuid.clear();
uuidsByFingerprint.clear();
if (playerMapFile.exists()) {
try {
String json = Files.readString(playerMapFile.toPath(), StandardCharsets.UTF_8);
Map<String, StoredPlayerRecord> map = gson.fromJson(json, PLAYER_MAP_TYPE);
if (map != null) {
long maxCluster = 0L;
for (Map.Entry<String, StoredPlayerRecord> e : map.entrySet()) {
try {
UUID u = UUID.fromString(e.getKey());
StoredPlayerRecord rec = e.getValue();
if (rec == null) continue;
rec.uuid = u.toString();
recordsByUuid.put(u, rec);
if (rec.fingerprint != null && !rec.fingerprint.isBlank()) {
uuidsByFingerprint.computeIfAbsent(rec.fingerprint, k -> ConcurrentHashMap.newKeySet()).add(u);
}
if (rec.clusterId > maxCluster) {
maxCluster = rec.clusterId;
}
} catch (IllegalArgumentException ignored) {
}
}
nextClusterId.set(maxCluster + 1L);
}
} catch (Exception e) {
plugin.getLogger().log(Level.WARNING, "Failed to load player_map.json", e);
}
}
staffAlertPrefs.clear();
if (staffPrefsFile.exists()) {
try {
Type prefType = new TypeToken<Map<String, Boolean>>() {}.getType();
Map<String, Boolean> map = gson.fromJson(Files.readString(staffPrefsFile.toPath(), StandardCharsets.UTF_8), prefType);
if (map != null) {
for (Map.Entry<String, Boolean> e : map.entrySet()) {
try {
staffAlertPrefs.put(UUID.fromString(e.getKey()), Boolean.TRUE.equals(e.getValue()));
} catch (IllegalArgumentException ignored) {
}
}
}
} catch (Exception e) {
plugin.getLogger().log(Level.WARNING, "Failed to load staff_alerts.json", e);
}
}
}
public synchronized void saveAll() {
try {
Map<String, StoredPlayerRecord> out = new LinkedHashMap<>();
for (Map.Entry<UUID, StoredPlayerRecord> e : recordsByUuid.entrySet()) {
out.put(e.getKey().toString(), e.getValue());
}
Files.writeString(playerMapFile.toPath(), gson.toJson(out), StandardCharsets.UTF_8);
} catch (IOException e) {
plugin.getLogger().log(Level.WARNING, "Failed to save player_map.json", e);
}
try {
Map<String, Boolean> out = new LinkedHashMap<>();
for (Map.Entry<UUID, Boolean> e : staffAlertPrefs.entrySet()) {
out.put(e.getKey().toString(), e.getValue());
}
Files.writeString(staffPrefsFile.toPath(), gson.toJson(out), StandardCharsets.UTF_8);
} catch (IOException e) {
plugin.getLogger().log(Level.WARNING, "Failed to save staff_alerts.json", e);
}
}
public long recordIdentity(UUID uuid, String name, String fingerprint, long timestamp, boolean flagged, boolean banned) {
if (uuid == null || fingerprint == null || fingerprint.isBlank()) {
return -1L;
}
Set<UUID> existing = uuidsByFingerprint.computeIfAbsent(fingerprint, k -> ConcurrentHashMap.newKeySet());
long clusterId = -1L;
for (UUID member : existing) {
StoredPlayerRecord mr = recordsByUuid.get(member);
if (mr != null && mr.clusterId > 0L) {
clusterId = mr.clusterId;
break;
}
}
if (clusterId <= 0L) {
clusterId = nextClusterId.getAndIncrement();
}
final long assignedCluster = clusterId;
StoredPlayerRecord rec = recordsByUuid.computeIfAbsent(uuid, k -> {
StoredPlayerRecord r = new StoredPlayerRecord();
r.uuid = uuid.toString();
r.firstSeen = timestamp;
return r;
});
rec.lastName = name;
rec.fingerprint = fingerprint;
rec.clusterId = assignedCluster;
rec.lastSeen = timestamp;
if (flagged) rec.flagged = true;
if (banned) rec.banned = true;
existing.add(uuid);
saveAll();
return assignedCluster;
}
public Optional<String> getFingerprint(UUID uuid) {
StoredPlayerRecord rec = recordsByUuid.get(uuid);
return rec == null || rec.fingerprint == null ? Optional.empty() : Optional.of(rec.fingerprint);
}
public Optional<IdentityRecord> getIdentityRecord(UUID uuid) {
StoredPlayerRecord rec = recordsByUuid.get(uuid);
if (rec == null || rec.fingerprint == null) {
return Optional.empty();
}
Set<UUID> cluster = uuidsByFingerprint.getOrDefault(rec.fingerprint, Collections.emptySet());
List<String> all = new ArrayList<>();
List<String> alts = new ArrayList<>();
for (UUID member : cluster) {
StoredPlayerRecord mr = recordsByUuid.get(member);
String label = mr != null && mr.lastName != null ? mr.lastName : member.toString();
all.add(label);
if (!member.equals(uuid)) {
alts.add(label);
}
}
return Optional.of(new IdentityRecord(all, alts));
}
public Set<UUID> getLinkedAccounts(UUID uuid) {
StoredPlayerRecord rec = recordsByUuid.get(uuid);
if (rec == null || rec.fingerprint == null) {
return Collections.emptySet();
}
return Collections.unmodifiableSet(new LinkedHashSet<>(uuidsByFingerprint.getOrDefault(rec.fingerprint, Set.of())));
}
public Map<UUID, StoredPlayerRecord> getAllRecords() {
return Collections.unmodifiableMap(recordsByUuid);
}
public Boolean getStaffAlertPreference(UUID uuid) {
return staffAlertPrefs.get(uuid);
}
public void setStaffAlertPreference(UUID uuid, boolean enabled) {
staffAlertPrefs.put(uuid, enabled);
saveAll();
}
}
@@ -0,0 +1,7 @@
package com.gigazelensky.antispoof.data;
public enum ProbeKeyType {
TRANSLATE,
KEYBIND,
BOTH
}
@@ -0,0 +1,18 @@
package com.gigazelensky.antispoof.data;
public enum ProbeMode {
SIGN,
ANVIL,
BOTH;
public static ProbeMode parse(String raw, ProbeMode fallback) {
if (raw == null || raw.isBlank()) {
return fallback;
}
try {
return valueOf(raw.trim().toUpperCase(java.util.Locale.ROOT));
} catch (IllegalArgumentException ignored) {
return fallback;
}
}
}
@@ -0,0 +1,8 @@
package com.gigazelensky.antispoof.data;
public enum ProbeStatus {
NOT_STARTED,
RUNNING,
CLEAN,
FAILED
}
@@ -0,0 +1,7 @@
package com.gigazelensky.antispoof.data;
public enum ProbeStepResult {
WAITING,
FAILED,
SUCCEEDED
}
@@ -0,0 +1,18 @@
package com.gigazelensky.antispoof.data;
public record ProxyEvaluation(
boolean enabled,
boolean snifferActive,
ProxyMetrics metrics,
int minSamples,
int warnThresholdMs,
int thresholdMs,
double averageDiffMs,
double minDiffMs,
double maxDiffMs,
double lastDiffMs,
boolean suspected,
boolean warning,
String status
) {
}
@@ -0,0 +1,19 @@
package com.gigazelensky.antispoof.data;
import java.util.List;
public record ProxyMetrics(
long handshakeRttMs,
long lastPingMs,
String lastPingSource,
long lastDiffMs,
double averageDiffMs,
long minDiffMs,
long maxDiffMs,
int sampleCount,
long lastSampleAt,
List<Long> recentDiffs,
List<Long> recentPings,
List<Long> recentHandshakeRtts
) {
}
@@ -0,0 +1,97 @@
package com.gigazelensky.antispoof.data;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
/**
* Per-player sliding window tracking TCP handshake RTT vs in-game KeepAlive/Ping RTT for proxy/VPN heuristics.
*/
public final class ProxyState {
private static final int MAX_HISTORY = 32;
private final Deque<Long> recentDiffs = new ArrayDeque<>();
private final Deque<Long> recentPings = new ArrayDeque<>();
private final Deque<Long> recentHandshakeRtts = new ArrayDeque<>();
private long handshakeRttMs;
private long lastPingMs;
private String lastPingSource;
private long lastDiffMs;
private long lastSampleAt;
public synchronized void recordHandshakeRtt(long rttMs) {
if (rttMs <= 0L) {
return;
}
this.handshakeRttMs = rttMs;
recentHandshakeRtts.addLast(rttMs);
while (recentHandshakeRtts.size() > MAX_HISTORY) {
recentHandshakeRtts.removeFirst();
}
}
public synchronized void recordPingSample(long pingMs, String source) {
if (pingMs < 0L) {
return;
}
this.lastPingMs = pingMs;
this.lastPingSource = source;
this.lastSampleAt = System.currentTimeMillis();
recentPings.addLast(pingMs);
while (recentPings.size() > MAX_HISTORY) {
recentPings.removeFirst();
}
if (handshakeRttMs > 0L) {
long diff = Math.abs(pingMs - handshakeRttMs);
this.lastDiffMs = diff;
recentDiffs.addLast(diff);
while (recentDiffs.size() > MAX_HISTORY) {
recentDiffs.removeFirst();
}
}
}
public synchronized ProxyMetrics snapshot(int windowSize) {
int limit = windowSize > 0 ? Math.min(windowSize, recentDiffs.size()) : recentDiffs.size();
List<Long> diffs = tail(recentDiffs, limit);
List<Long> pings = tail(recentPings, windowSize > 0 ? windowSize : recentPings.size());
List<Long> handshakes = tail(recentHandshakeRtts, windowSize > 0 ? windowSize : recentHandshakeRtts.size());
long sum = 0L;
long min = diffs.isEmpty() ? 0L : Long.MAX_VALUE;
long max = diffs.isEmpty() ? 0L : Long.MIN_VALUE;
for (long d : diffs) {
sum += d;
if (d < min) min = d;
if (d > max) max = d;
}
double avg = diffs.isEmpty() ? 0.0 : (double) sum / diffs.size();
return new ProxyMetrics(
handshakeRttMs,
lastPingMs,
lastPingSource,
lastDiffMs,
avg,
min,
max,
diffs.size(),
lastSampleAt,
diffs,
pings,
handshakes
);
}
private static List<Long> tail(Deque<Long> deque, int max) {
if (deque.isEmpty() || max <= 0) {
return List.of();
}
List<Long> all = new ArrayList<>(deque);
if (all.size() <= max) {
return List.copyOf(all);
}
return List.copyOf(all.subList(all.size() - max, all.size()));
}
}
@@ -0,0 +1,7 @@
package com.gigazelensky.antispoof.data;
public enum SurgeGuardAction {
OFF,
DELAY,
BYPASS
}
@@ -0,0 +1,7 @@
package com.gigazelensky.antispoof.data;
public enum TimeRange {
WEEK,
MONTH,
ALL
}
@@ -0,0 +1,8 @@
package com.gigazelensky.antispoof.data;
public enum TranslationOutcome {
TRANSLATED,
REQUIRED_MISS,
MISSING_SEGMENT,
ZERO
}
@@ -0,0 +1,11 @@
package com.gigazelensky.antispoof.data;
public enum VerificationSubsystem {
TRANSLATABLE,
ANVIL,
COMMAND_BOOK,
IDENTITY_LINKER,
ASSET_PROBE,
PROXY,
ACTIVE_RECON
}