import os import threading import urllib.request import json from core.state import db, ws_registry, session_mgr from core.ws_helpers import push_kick, push_presence from core.constants import DORM_ROOM_GUID from core.config import discord as _discord_cfg _WEBHOOK_URL = _discord_cfg.get("webhook_anticheat", "") _offense_counts: dict[int, int] = {} _active_sessions: dict[int, str] = {} _lock = threading.Lock() _SUSPECTS_FILE = os.path.join(os.path.dirname(__file__), "..", "tracking", "anticheat_suspects.json") def _load_suspects() -> None: global _offense_counts try: if os.path.exists(_SUSPECTS_FILE): with open(_SUSPECTS_FILE) as f: data = json.load(f) _offense_counts = {int(k): v for k, v in data.items()} except Exception as e: print(f"[AntiCheat] Failed to load suspects: {e}") def _save_suspects() -> None: try: with open(_SUSPECTS_FILE, "w") as f: json.dump({str(k): v for k, v in _offense_counts.items()}, f) except Exception as e: print(f"[AntiCheat] Failed to save suspects: {e}") def get_suspects() -> list: with _lock: counts = dict(_offense_counts) if not counts: return [] pids = list(counts.keys()) profiles = db.get_profiles_batch(pids) result = [] for pid, count in sorted(counts.items(), key=lambda x: -x[1]): p = profiles.get(pid) if p: result.append({"id": pid, "username": p["Username"], "level": p["Level"], "offenses": count, "banned": bool(p.get("Banned"))}) return result _load_suspects() def _send_webhook(title: str, color: int, fields: list[dict]) -> None: try: payload = {"embeds": [{"title": title, "color": color, "fields": fields}]} data = json.dumps(payload).encode() req = urllib.request.Request( _WEBHOOK_URL, data=data, headers={"Content-Type": "application/json"}, method="POST", ) urllib.request.urlopen(req, timeout=5) except Exception as e: print(f"[AntiCheat] Webhook failed: {e}") def check_banned_room_join(player_id: int, activity_guid: str) -> bool: """ Called on every room join attempt. Returns True and handles enforcement if player is banned trying to join a non-dorm room. """ if activity_guid == DORM_ROOM_GUID: return False if not db.is_banned(player_id): return False with _lock: _offense_counts[player_id] = _offense_counts.get(player_id, 0) + 1 offense = _offense_counts[player_id] _save_suspects() try: import core.admin_ws as awr awr.push({"type": "suspects", "suspects": get_suspects()}) except Exception: pass profile = db.get_profile(player_id) username = profile.get("Username", str(player_id)) if profile else str(player_id) if offense == 1: print(f"[AntiCheat] Banned player {player_id} ({username}) tried to join room — " f"kicking to dorm (offense 1)") push_kick(player_id, message="You are banned and cannot join rooms.") ws_registry.unregister(player_id) session_mgr.leave_session(player_id) push_presence(player_id, None, online=False) else: print(f"[AntiCheat] Banned player {player_id} ({username}) bypassed — " f"closing game (offense {offense})") ws_registry.send(player_id, {"Id": 20, "Msg": {}}) ws_registry.unregister(player_id) session_mgr.leave_session(player_id) push_presence(player_id, None, online=False) threading.Thread( target=_send_webhook, args=( "Banned Player Attempted Room Join", 0xFF4444, [ {"name": "Player", "value": f"{username} (id={player_id})", "inline": True}, {"name": "Offense #", "value": str(offense), "inline": True}, {"name": "Room", "value": activity_guid, "inline": False}, {"name": "Action", "value": "Game force-closed (Application.Quit)", "inline": False}, ], ), daemon=True, ).start() try: from core.discord import send_admin send_admin(title="AntiCheat: Banned Room Join Attempt", color=0xFF4444, fields=[{"name": "Player", "value": f"{username} (id={player_id})", "inline": True}, {"name": "Offense #", "value": str(offense), "inline": True}, {"name": "Room", "value": activity_guid[:80], "inline": False}]) except Exception: pass return True def check_dual_login(player_id: int, jti: str) -> None: """ Called whenever a new token is issued for a player. If the player already has an active WS session, fires a webhook alert. """ if not ws_registry.send.__self__ if hasattr(ws_registry.send, '__self__') else False: return online = player_id in ws_registry.connected_ids() if not online: with _lock: _active_sessions.pop(player_id, None) return with _lock: prev_jti = _active_sessions.get(player_id) _active_sessions[player_id] = jti if prev_jti and prev_jti != jti: profile = db.get_profile(player_id) username = profile.get("Username", str(player_id)) if profile else str(player_id) print(f"[AntiCheat] Dual login detected for player {player_id} ({username})") threading.Thread( target=_send_webhook, args=( "Dual Login Detected", 0xFF8C00, [ {"name": "Player", "value": f"{username} (id={player_id})", "inline": True}, {"name": "Status", "value": "Already online when new login occurred", "inline": False}, ], ), daemon=True, ).start() try: from core.discord import send_admin send_admin(title="AntiCheat: Dual Login", color=0xFF8C00, fields=[{"name": "Player", "value": f"{username} (id={player_id})", "inline": True}, {"name": "Note", "value": "New login while already online", "inline": False}]) except Exception: pass def on_token_issued(player_id: int, jti: str) -> None: """Call this whenever a JWT is issued for a player.""" online = player_id in ws_registry.connected_ids() if not online: return profile = db.get_profile(player_id) username = profile.get("Username", str(player_id)) if profile else str(player_id) print(f"[AntiCheat] New login while online for player {player_id} ({username})") threading.Thread( target=_send_webhook, args=( "Dual Login Detected", 0xFF8C00, [ {"name": "Player", "value": f"{username} (id={player_id})", "inline": True}, {"name": "Note", "value": "Player logged in from a second location while already online", "inline": False}, ], ), daemon=True, ).start() def reset_offenses(player_id: int) -> None: with _lock: _offense_counts.pop(player_id, None) _active_sessions.pop(player_id, None) _save_suspects() try: import core.admin_ws as awr awr.push({"type": "suspects", "suspects": get_suspects()}) except Exception: pass