Upload files to "core"
This commit is contained in:
124
core/auth.py
Normal file
124
core/auth.py
Normal file
@@ -0,0 +1,124 @@
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from functools import wraps
|
||||
|
||||
from flask import request, jsonify, g
|
||||
|
||||
from .auth_state import current_jti, jti_lock
|
||||
|
||||
JWT_SECRET: str | None = None
|
||||
JWT_ALGO = "HS256"
|
||||
JWT_TTL = timedelta(hours=4)
|
||||
|
||||
|
||||
def _b64url_enc(data: bytes) -> str:
|
||||
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
|
||||
|
||||
|
||||
def _b64url_dec(s: str) -> bytes:
|
||||
pad = (-len(s)) % 4
|
||||
return base64.urlsafe_b64decode(s + "=" * pad)
|
||||
|
||||
|
||||
def _jwt_encode(payload: dict, secret: str) -> str:
|
||||
header = _b64url_enc(json.dumps({"alg": "HS256", "typ": "JWT"}, separators=(",", ":")).encode())
|
||||
body = _b64url_enc(json.dumps(payload, separators=(",", ":")).encode())
|
||||
signing_input = f"{header}.{body}".encode()
|
||||
sig = hmac.new(secret.encode(), signing_input, hashlib.sha256).digest()
|
||||
return f"{header}.{body}.{_b64url_enc(sig)}"
|
||||
|
||||
|
||||
def _jwt_decode(token: str, secret: str, verify_exp: bool = True) -> dict:
|
||||
"""Decode and verify an HS256 JWT. Raises ValueError on any failure."""
|
||||
parts = token.split(".")
|
||||
if len(parts) != 3:
|
||||
raise ValueError("malformed token")
|
||||
header_b, payload_b, sig_b = parts
|
||||
signing_input = f"{header_b}.{payload_b}".encode()
|
||||
expected = hmac.new(secret.encode(), signing_input, hashlib.sha256).digest()
|
||||
actual = _b64url_dec(sig_b)
|
||||
if not hmac.compare_digest(expected, actual):
|
||||
raise ValueError("invalid signature")
|
||||
payload = json.loads(_b64url_dec(payload_b))
|
||||
if verify_exp:
|
||||
exp = payload.get("exp")
|
||||
if exp is None or datetime.now(timezone.utc).timestamp() > exp:
|
||||
raise ValueError("token expired")
|
||||
return payload
|
||||
|
||||
|
||||
def make_token(profile_id: int, ttl: timedelta | None = None) -> str:
|
||||
jti = str(uuid.uuid4())
|
||||
now = datetime.now(timezone.utc)
|
||||
payload = {
|
||||
"sub": profile_id,
|
||||
"jti": jti,
|
||||
"iat": int(now.timestamp()),
|
||||
"exp": int((now + (ttl or JWT_TTL)).timestamp()),
|
||||
}
|
||||
token = _jwt_encode(payload, JWT_SECRET)
|
||||
with jti_lock:
|
||||
current_jti[profile_id] = jti
|
||||
return token
|
||||
|
||||
|
||||
def _req_ip() -> str:
|
||||
return (request.headers.get("X-Forwarded-For", "") or request.remote_addr or "?").split(",")[0].strip()
|
||||
|
||||
|
||||
def get_current_profile_id(allow_expired: bool = False) -> int | None:
|
||||
auth = request.headers.get("Authorization", "")
|
||||
if not auth.startswith("Bearer "):
|
||||
return None
|
||||
raw = auth.split(" ", 1)[1].strip()
|
||||
try:
|
||||
payload = _jwt_decode(raw, JWT_SECRET, verify_exp=not allow_expired)
|
||||
except ValueError as exc:
|
||||
if not getattr(g, "_jwt_fail_logged", False):
|
||||
g._jwt_fail_logged = True
|
||||
print(f"[SECURITY] JWT reject: {exc} ip={_req_ip()} path={request.path}")
|
||||
return None
|
||||
except Exception:
|
||||
return None
|
||||
pid = payload.get("sub")
|
||||
jti = payload.get("jti")
|
||||
if pid is None or jti is None:
|
||||
return None
|
||||
with jti_lock:
|
||||
if current_jti.get(pid) != jti:
|
||||
if not getattr(g, "_jwt_fail_logged", False):
|
||||
g._jwt_fail_logged = True
|
||||
print(f"[SECURITY] JTI mismatch: pid={pid} ip={_req_ip()} path={request.path}")
|
||||
return None
|
||||
return pid
|
||||
|
||||
|
||||
def check_auth(f):
|
||||
@wraps(f)
|
||||
def decorated(*args, **kwargs):
|
||||
pid = get_current_profile_id()
|
||||
if pid is None:
|
||||
return jsonify({"error": "Unauthorized"}), 401
|
||||
from . import state as _st
|
||||
with _st.maintenance_lock:
|
||||
maint = _st.maintenance_mode
|
||||
if maint and pid not in _st.maintenance_exempt:
|
||||
return jsonify({"error": "Server is under maintenance"}), 403
|
||||
if _st.db.is_banned(pid):
|
||||
print(f"[SECURITY] Banned player attempt: pid={pid} ip={_req_ip()} {request.method} {request.path}")
|
||||
return jsonify({"error": "Banned", "IsBanned": True}), 403
|
||||
ip = _req_ip()
|
||||
if ip and ip not in ("127.0.0.1", "::1") and _st.db.is_ip_banned(ip):
|
||||
print(f"[SECURITY] IP-banned attempt: ip={ip} pid={pid} {request.method} {request.path}")
|
||||
return jsonify({"error": "Banned", "IsBanned": True}), 403
|
||||
return f(*args, **kwargs)
|
||||
return decorated
|
||||
|
||||
|
||||
def get_server_base() -> str:
|
||||
return f"http://{request.host}/"
|
||||
11
core/auth_state.py
Normal file
11
core/auth_state.py
Normal file
@@ -0,0 +1,11 @@
|
||||
|
||||
import threading
|
||||
|
||||
from .state import db
|
||||
|
||||
current_jti: dict[int, str] = {}
|
||||
jti_lock = threading.Lock()
|
||||
|
||||
_saved = db.get_latest_jtis()
|
||||
if _saved:
|
||||
current_jti.update(_saved)
|
||||
52
core/ban_service.py
Normal file
52
core/ban_service.py
Normal file
@@ -0,0 +1,52 @@
|
||||
|
||||
from .state import db, ws_registry, session_mgr
|
||||
from .ws_helpers import push_presence
|
||||
|
||||
|
||||
def kick_player(player_id: int) -> bool:
|
||||
ws_registry.send(player_id, {"Id": 20, "Msg": {}})
|
||||
closed = ws_registry.close_and_unregister(player_id)
|
||||
session_mgr.leave_session(player_id)
|
||||
push_presence(player_id, None, online=False)
|
||||
return closed
|
||||
|
||||
|
||||
def cascade_ban(primary_id: int, reason: str, duration_h: int, admin_name: str) -> None:
|
||||
from .ban_tracker import record_ban_group
|
||||
primary = db.get_profile(primary_id)
|
||||
primary_name = primary.get("Username", str(primary_id)) if primary else str(primary_id)
|
||||
if not db.is_banned(primary_id):
|
||||
db.ban_player(primary_id, reason=reason, duration_hours=duration_h, admin_name=admin_name)
|
||||
associated = db.get_associated_accounts_with_evidence(primary_id)
|
||||
print(f"[Ban] {primary_name} ({primary_id}): found {len(associated)} linked account(s): {list(associated.keys())}")
|
||||
for pid, evidence in associated.items():
|
||||
p = db.get_profile(pid)
|
||||
pname = p.get("Username", str(pid)) if p else str(pid)
|
||||
print(f"[Ban] → pid={pid} ({pname}) via IPs={evidence['shared_ips']} platforms={evidence['shared_platform_ids']}")
|
||||
if not db.is_banned(pid):
|
||||
db.ban_player(pid, reason=f"Banned by association with {primary_name}: {reason}", duration_hours=duration_h, admin_name=admin_name)
|
||||
record_ban_group(primary_id, primary_name, associated, reason)
|
||||
kick_player(primary_id)
|
||||
for pid in associated:
|
||||
kick_player(pid)
|
||||
|
||||
|
||||
def cascade_unban(primary_id: int, admin_name: str) -> None:
|
||||
db.unban_player(primary_id, admin_name=admin_name)
|
||||
print(f"[Ban] Unban: pid={primary_id} (cascade handled by unban_player)")
|
||||
|
||||
|
||||
def cascade_kick_linked(primary_id: int) -> None:
|
||||
from .ban_tracker import record_ban_group
|
||||
primary = db.get_profile(primary_id)
|
||||
primary_name = primary.get("Username", str(primary_id)) if primary else str(primary_id)
|
||||
reason = f"Banned by association with {primary_name}"
|
||||
associated = db.get_associated_accounts_with_evidence(primary_id)
|
||||
for linked_id, evidence in associated.items():
|
||||
if db.is_banned(linked_id):
|
||||
continue
|
||||
db.ban_player(linked_id, reason=reason, duration_hours=0, admin_name="AntiCheat")
|
||||
kick_player(linked_id)
|
||||
print(f"[AntiCheat] Cascade ban+kick: player {linked_id} ← {primary_name} ({primary_id}) via IPs={evidence['shared_ips']} platforms={evidence['shared_platform_ids']}")
|
||||
if associated:
|
||||
record_ban_group(primary_id, primary_name, associated, reason)
|
||||
61
core/ban_tracker.py
Normal file
61
core/ban_tracker.py
Normal file
@@ -0,0 +1,61 @@
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime, timezone
|
||||
|
||||
_TRACKING_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "tracking", "moderation")
|
||||
|
||||
|
||||
def _path(primary_id: int) -> str:
|
||||
return os.path.join(_TRACKING_DIR, f"{primary_id}.json")
|
||||
|
||||
|
||||
def record_ban_group(primary_id: int, primary_name: str, associated: dict, reason: str) -> None:
|
||||
data = {
|
||||
"primary_id": primary_id,
|
||||
"primary_name": primary_name,
|
||||
"reason": reason,
|
||||
"banned_at": datetime.now(timezone.utc).isoformat(),
|
||||
"associated_ids": [int(i) for i in associated if int(i) != primary_id],
|
||||
"links": {
|
||||
str(pid): ev for pid, ev in associated.items() if int(pid) != primary_id
|
||||
},
|
||||
}
|
||||
with open(_path(primary_id), "w") as f:
|
||||
json.dump(data, f, indent=2)
|
||||
|
||||
|
||||
def get_ban_group(primary_id: int) -> dict | None:
|
||||
p = _path(primary_id)
|
||||
if not os.path.exists(p):
|
||||
return None
|
||||
try:
|
||||
with open(p) as f:
|
||||
return json.load(f)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def clear_ban_group(primary_id: int) -> None:
|
||||
p = _path(primary_id)
|
||||
if os.path.exists(p):
|
||||
os.remove(p)
|
||||
|
||||
|
||||
def find_group_for_member(member_id: int) -> dict | None:
|
||||
try:
|
||||
for fname in os.listdir(_TRACKING_DIR):
|
||||
if not fname.endswith(".json"):
|
||||
continue
|
||||
fpath = os.path.join(_TRACKING_DIR, fname)
|
||||
try:
|
||||
with open(fpath) as f:
|
||||
data = json.load(f)
|
||||
if data.get("primary_id") == member_id:
|
||||
return data
|
||||
if member_id in data.get("associated_ids", []):
|
||||
return data
|
||||
except Exception:
|
||||
continue
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
110
core/builders.py
Normal file
110
core/builders.py
Normal file
@@ -0,0 +1,110 @@
|
||||
|
||||
import datetime
|
||||
import re
|
||||
import time
|
||||
|
||||
from flask import request as _flask_request
|
||||
|
||||
from .constants import KNOWN_ACTIVITIES
|
||||
|
||||
|
||||
def now_iso() -> str:
|
||||
return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
def get_request_data() -> dict:
|
||||
j = _flask_request.get_json(force=True, silent=True)
|
||||
if j and isinstance(j, dict):
|
||||
return j
|
||||
return _flask_request.values.to_dict()
|
||||
|
||||
_USERNAME_RE = re.compile(r"[^\w\-]")
|
||||
|
||||
def sanitize_username(name: str, max_len: int = 32) -> str:
|
||||
name = name.strip()
|
||||
name = _USERNAME_RE.sub("", name)
|
||||
return name[:max_len]
|
||||
|
||||
def now_ticks() -> int:
|
||||
return int(time.time() * 10_000_000) + 621355968000000000
|
||||
|
||||
def activity_info(guid: str) -> tuple[str, str, bool]:
|
||||
return KNOWN_ACTIVITIES.get(guid, ("Custom Room", "custom", False))
|
||||
|
||||
def make_player_reputation(reputation: int = 0, player_id: int = 0, selected_cheer: int = 0) -> dict:
|
||||
from core.state import db as _db
|
||||
sub_count = _db.get_subscriber_count(player_id) if player_id else 0
|
||||
subd_count = len(_db.get_subscriptions(player_id)) if player_id else 0
|
||||
return {
|
||||
"Noteriety": min(1.0, reputation / 100.0),
|
||||
"CheerGeneral": reputation,
|
||||
"CheerHelpful": 0,
|
||||
"CheerGreatHost": 0,
|
||||
"CheerSportsman": 0,
|
||||
"CheerCreative": 0,
|
||||
"CheerCredit": 0,
|
||||
"SubscriberCount": sub_count,
|
||||
"SubscribedCount": subd_count,
|
||||
"SelectedCheer": selected_cheer,
|
||||
}
|
||||
|
||||
_PLATFORM_NAMES = {"steam": 0, "oculus": 1, "ps4": 2, "microsoft": 3}
|
||||
|
||||
def _platform_int(raw) -> int:
|
||||
if raw is None:
|
||||
return 0
|
||||
try:
|
||||
return int(raw)
|
||||
except (ValueError, TypeError):
|
||||
return _PLATFORM_NAMES.get(str(raw).lower(), 0)
|
||||
|
||||
def _platform_id_str(db_profile: dict) -> str:
|
||||
pid_str = str(db_profile.get("platform_id") or db_profile.get("PlatformId") or "")
|
||||
try:
|
||||
val = int(pid_str)
|
||||
if val > 0:
|
||||
return pid_str
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
return "0"
|
||||
|
||||
def make_profile_from_db(db_profile: dict) -> dict:
|
||||
from core.constants import xp_for_client
|
||||
cumulative_xp = db_profile.get("XP", 0)
|
||||
level = db_profile.get("Level", 1)
|
||||
return {
|
||||
"Id": int(db_profile["Id"]),
|
||||
"Username": db_profile["Username"],
|
||||
"DisplayName": db_profile["DisplayName"],
|
||||
"Bio": db_profile.get("Bio", ""),
|
||||
"XP": xp_for_client(cumulative_xp, level),
|
||||
"Level": level,
|
||||
|
||||
"RegistrationStatus": db_profile.get("RegistrationStatus", 2),
|
||||
"Developer": bool(db_profile.get("Developer", False)),
|
||||
"CanReceiveInvites": True,
|
||||
"ProfileImageName": db_profile.get("ProfileImageName", ""),
|
||||
"JuniorProfile": False,
|
||||
"ForceJuniorImages": False,
|
||||
"PendingJunior": False,
|
||||
"HasBirthday": True,
|
||||
"AvoidJuniors": False,
|
||||
"IsJunior": False,
|
||||
"NumFollowers": 0,
|
||||
"NumFollowing": 0,
|
||||
"PlayerReputation": make_player_reputation(int(db_profile.get("Reputation", 0)), int(db_profile["Id"]), int(db_profile.get("SelectedCheer", 0))),
|
||||
"PlatformId": {
|
||||
"Platform": _platform_int(db_profile.get("platform") or db_profile.get("Platform")),
|
||||
"PlatformId": _platform_id_str(db_profile),
|
||||
},
|
||||
}
|
||||
|
||||
def make_login_response(profile: dict, token: str) -> dict:
|
||||
return {
|
||||
"Error": "",
|
||||
"Player": profile,
|
||||
"Token": token,
|
||||
"FirstLoginOfTheDay": False,
|
||||
"AnalyticsSessionId": 1,
|
||||
"CanUseScreenMode": True,
|
||||
}
|
||||
Reference in New Issue
Block a user