Upload files to "core"
This commit is contained in:
BIN
core/__init__.py
Normal file
BIN
core/__init__.py
Normal file
Binary file not shown.
148
core/admin_auth.py
Normal file
148
core/admin_auth.py
Normal file
@@ -0,0 +1,148 @@
|
|||||||
|
import time
|
||||||
|
import requests
|
||||||
|
from requests.adapters import HTTPAdapter
|
||||||
|
from urllib3.util.retry import Retry
|
||||||
|
from urllib.parse import quote
|
||||||
|
from flask import request, session
|
||||||
|
from core.config import auth as _auth_cfg
|
||||||
|
|
||||||
|
SCOPE_ADMIN = "kittyrec.admin"
|
||||||
|
SCOPE_MOD = "kittyrec.mod"
|
||||||
|
SCOPE_EMERGENCY = "kittyrec.emergency"
|
||||||
|
AUTH_LOGIN_URL = _auth_cfg["login_url"]
|
||||||
|
AUTH_ME_URL = AUTH_LOGIN_URL + "/api/account/me"
|
||||||
|
AUTH_REFRESH_URL = AUTH_LOGIN_URL + "/api/account/refresh/session"
|
||||||
|
EMERGENCY_LOGIN_URL = "/admin/emergency_login"
|
||||||
|
EMERGENCY_PASSWORD = _auth_cfg["emergency_password"]
|
||||||
|
_EMERGENCY_SESSION_TTL = 8 * 3600
|
||||||
|
_CACHE_TTL = 86400
|
||||||
|
|
||||||
|
FORCE_EMERGENCY_MODE = False
|
||||||
|
|
||||||
|
_auth_down_until = 0.0
|
||||||
|
_AUTH_DOWN_TTL = 45
|
||||||
|
|
||||||
|
|
||||||
|
def _mark_auth_down():
|
||||||
|
global _auth_down_until
|
||||||
|
_auth_down_until = time.time() + _AUTH_DOWN_TTL
|
||||||
|
|
||||||
|
|
||||||
|
def is_auth_server_down() -> bool:
|
||||||
|
return time.time() < _auth_down_until
|
||||||
|
|
||||||
|
|
||||||
|
def probe_auth_server() -> bool:
|
||||||
|
if is_auth_server_down():
|
||||||
|
return True
|
||||||
|
try:
|
||||||
|
resp = requests.get(AUTH_ME_URL, timeout=(2, 4))
|
||||||
|
if resp.status_code >= 500:
|
||||||
|
print(f"[Admin Auth] Probe: auth server returned {resp.status_code} — marking down")
|
||||||
|
_mark_auth_down()
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e:
|
||||||
|
print(f"[Admin Auth] Probe: unreachable ({e}) — marking down")
|
||||||
|
_mark_auth_down()
|
||||||
|
return True
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _get_me(sess, token):
|
||||||
|
return sess.get(AUTH_ME_URL, cookies={"Authorization": token}, timeout=(2, 6))
|
||||||
|
|
||||||
|
|
||||||
|
def _authenticate_token(token):
|
||||||
|
if is_auth_server_down():
|
||||||
|
return None, None
|
||||||
|
|
||||||
|
sess = requests.Session()
|
||||||
|
retry = Retry(total=1, backoff_factor=0, status_forcelist=[502, 503, 504], allowed_methods=["GET"])
|
||||||
|
sess.mount("https://", HTTPAdapter(max_retries=retry))
|
||||||
|
try:
|
||||||
|
resp = _get_me(sess, token)
|
||||||
|
|
||||||
|
if resp.status_code in (401, 403):
|
||||||
|
print("[Admin Auth] Token expired, attempting refresh...")
|
||||||
|
refresh = sess.get(AUTH_REFRESH_URL, cookies={"Authorization": token}, timeout=(2, 6))
|
||||||
|
if refresh.status_code != 200:
|
||||||
|
print("[Admin Auth] Refresh failed")
|
||||||
|
return None, []
|
||||||
|
new_token = refresh.cookies.get("Authorization", token)
|
||||||
|
resp = _get_me(sess, new_token)
|
||||||
|
|
||||||
|
if resp.status_code == 200:
|
||||||
|
try:
|
||||||
|
account = resp.json()
|
||||||
|
except Exception:
|
||||||
|
_mark_auth_down()
|
||||||
|
return None, None
|
||||||
|
scopes = account.get("scopes", [])
|
||||||
|
session["admin_cache"] = {
|
||||||
|
"account": account,
|
||||||
|
"scopes": scopes,
|
||||||
|
"token_hint": token[-16:],
|
||||||
|
"cached_at": time.time(),
|
||||||
|
}
|
||||||
|
return account, scopes
|
||||||
|
elif resp.status_code >= 500:
|
||||||
|
print(f"[Admin Auth] Auth server returned {resp.status_code} — treating as down")
|
||||||
|
_mark_auth_down()
|
||||||
|
return None, None
|
||||||
|
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e:
|
||||||
|
print(f"[Admin Auth] Auth server unreachable: {e}")
|
||||||
|
_mark_auth_down()
|
||||||
|
return None, None
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[Admin Auth] {e}")
|
||||||
|
finally:
|
||||||
|
sess.close()
|
||||||
|
return None, []
|
||||||
|
|
||||||
|
|
||||||
|
def _get_cached(token):
|
||||||
|
cache = session.get("admin_cache")
|
||||||
|
if not cache:
|
||||||
|
return None, None
|
||||||
|
if time.time() - cache.get("cached_at", 0) > _CACHE_TTL:
|
||||||
|
session.pop("admin_cache", None)
|
||||||
|
return None, None
|
||||||
|
if cache.get("token_hint") != token[-16:]:
|
||||||
|
session.pop("admin_cache", None)
|
||||||
|
return None, None
|
||||||
|
return cache["account"], cache["scopes"]
|
||||||
|
|
||||||
|
|
||||||
|
def get_admin_account():
|
||||||
|
if FORCE_EMERGENCY_MODE:
|
||||||
|
return {"username": "Emergency", "scopes": [SCOPE_ADMIN]}, [SCOPE_ADMIN]
|
||||||
|
|
||||||
|
emerg = session.get("emergency_admin")
|
||||||
|
if emerg and emerg.get("expires", 0) > time.time():
|
||||||
|
return {"username": "Emergency", "scopes": [SCOPE_ADMIN]}, [SCOPE_ADMIN]
|
||||||
|
|
||||||
|
token = request.cookies.get("Authorization") or request.headers.get("Authorization")
|
||||||
|
if not token:
|
||||||
|
if is_auth_server_down():
|
||||||
|
return None, None
|
||||||
|
return None, []
|
||||||
|
|
||||||
|
account, scopes = _get_cached(token)
|
||||||
|
if account is not None:
|
||||||
|
return account, scopes
|
||||||
|
|
||||||
|
return _authenticate_token(token)
|
||||||
|
|
||||||
|
|
||||||
|
def has_any_admin_scope(scopes):
|
||||||
|
if scopes is None:
|
||||||
|
return False
|
||||||
|
return SCOPE_ADMIN in scopes or SCOPE_MOD in scopes
|
||||||
|
|
||||||
|
|
||||||
|
def make_login_redirect(target_url=None):
|
||||||
|
url = target_url or request.url
|
||||||
|
url = url.replace("http://", "https://", 1)
|
||||||
|
return AUTH_LOGIN_URL + "?redirect=" + quote(url, safe="")
|
||||||
2020
core/admin_panel.py
Normal file
2020
core/admin_panel.py
Normal file
File diff suppressed because it is too large
Load Diff
36
core/admin_ws.py
Normal file
36
core/admin_ws.py
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
import json
|
||||||
|
import threading
|
||||||
|
|
||||||
|
_conns: set = set()
|
||||||
|
_lock = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
def register(ws) -> None:
|
||||||
|
with _lock:
|
||||||
|
_conns.add(ws)
|
||||||
|
|
||||||
|
|
||||||
|
def unregister(ws) -> None:
|
||||||
|
with _lock:
|
||||||
|
_conns.discard(ws)
|
||||||
|
|
||||||
|
|
||||||
|
def connected_count() -> int:
|
||||||
|
with _lock:
|
||||||
|
return len(_conns)
|
||||||
|
|
||||||
|
|
||||||
|
def push(msg: dict) -> None:
|
||||||
|
data = json.dumps(msg)
|
||||||
|
with _lock:
|
||||||
|
targets = list(_conns)
|
||||||
|
dead = []
|
||||||
|
for ws in targets:
|
||||||
|
try:
|
||||||
|
ws.send(data)
|
||||||
|
except Exception:
|
||||||
|
dead.append(ws)
|
||||||
|
if dead:
|
||||||
|
with _lock:
|
||||||
|
for ws in dead:
|
||||||
|
_conns.discard(ws)
|
||||||
206
core/anticheat.py
Normal file
206
core/anticheat.py
Normal file
@@ -0,0 +1,206 @@
|
|||||||
|
|
||||||
|
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
|
||||||
Reference in New Issue
Block a user