Upload files to "routes"

This commit is contained in:
2026-07-24 15:35:19 +00:00
parent 40f106fd51
commit c128e582ab
5 changed files with 1417 additions and 0 deletions

531
routes/auth.py Normal file
View File

@@ -0,0 +1,531 @@
from flask import Blueprint, request, jsonify, Response
from core.auth import get_current_profile_id, make_token
from core.limiter import limiter
import core.state as _state
from core.state import db
from core.auth_state import current_jti, jti_lock
from core.builders import make_profile_from_db, make_login_response, sanitize_username
from core.profanity import is_clean
bp = Blueprint("auth", __name__)
def _maintenance_block(profile: dict | None) -> dict | None:
with _state.maintenance_lock:
active = _state.maintenance_mode
if not active:
return None
if profile and profile.get("Id") in _state.maintenance_exempt:
return None
return _error_response("KittyRec Is Down For Scheduled Maintenance")
def _get_data() -> dict:
json_data = request.get_json(force=True, silent=True)
if json_data:
return json_data
return {k: v for k, v in request.values.items()}
def _error_response(msg: str) -> dict:
return {
"Error": msg,
"Player": None,
"Token": "",
"FirstLoginOfTheDay": False,
"AnalyticsSessionId": 0,
"CanUseScreenMode": True,
}
def _get_ip() -> str:
return (request.headers.get("X-Forwarded-For", "") or request.remote_addr or "").split(",")[0].strip()
def _award_daily_login(pid: int) -> None:
if pid and db.claim_daily_login_reward(pid, 500):
from core.ws_helpers import push_gift
gift = db.add_gift(pid, xp=100, gift_rarity=10, gift_context=0,
currency_type=2, currency=500,
message="Daily Login Bonus! +500 Tokens")
push_gift(pid, gift)
print(f"[Daily] Player {pid} claimed daily login reward: 500 tokens")
def _ip_is_banned(ip: str) -> bool:
return db.is_ip_banned(ip)
def _compute_assoc_duration(banned_until) -> int:
if not banned_until:
return 0
from datetime import datetime, timezone
try:
exp = datetime.fromisoformat(banned_until)
if exp.tzinfo is None:
exp = exp.replace(tzinfo=timezone.utc)
delta = exp - datetime.now(timezone.utc)
return max(1, int(delta.total_seconds() / 3600))
except Exception:
return 24
def _cascade_ban_if_linked(profile_id: int) -> dict | None:
from core.ban_service import kick_player
from core.ban_tracker import record_ban_group
assoc = db.get_associated_ban(profile_id)
if assoc is None:
return None
source_name = assoc["_source_name"]
source_id = assoc["_source_id"]
duration_h = _compute_assoc_duration(assoc.get("banned_until"))
reason = f"Banned by association with {source_name}"
db.ban_player(profile_id, reason=reason, duration_hours=duration_h, admin_name="AntiCheat")
kick_player(profile_id)
print(f"[AntiCheat] Cascade ban: player {profile_id} ← association with {source_name} (id={source_id})")
associated = db.get_associated_accounts_with_evidence(profile_id)
for linked_id, evidence in associated.items():
if db.is_banned(linked_id):
continue
db.ban_player(linked_id, reason=reason, duration_hours=duration_h, admin_name="AntiCheat")
kick_player(linked_id)
print(f"[AntiCheat] Cascade ban: player {linked_id} ← association with {source_name} (id={source_id}) via IPs={evidence['shared_ips']} platforms={evidence['shared_platform_ids']}")
record_ban_group(source_id, source_name, {profile_id: {"shared_ips": [], "shared_platform_ids": []}, **associated}, reason)
ban = db.get_ban_info(profile_id)
if ban:
return _error_response(db.format_ban_message(ban))
return None
def _notify_password_change_if_needed(profile_id: int) -> None:
from tracking.password_tracking import has_real_password
if has_real_password(profile_id):
return
from core.system_messages import send_and_await, has_pending
if has_pending(profile_id):
return
send_and_await(profile_id,
"You need to set a password before you can change your username! "
"Reply to this message with a password (8+ chars) to get started.",
"password_change", expires_in=0)
def _issue_token(profile_id: int, ttl=None) -> str:
ip = _get_ip()
if ip:
db.record_ip_login(profile_id, ip)
db.update_last_login(profile_id)
token = make_token(profile_id, ttl=ttl)
from core.anticheat import on_token_issued
from core.auth_state import current_jti
on_token_issued(profile_id, current_jti.get(profile_id, ""))
return token
@bp.route("/api/platformlogin/v1/loginaccount", methods=["POST"])
@limiter.limit("10 per minute")
def login_account():
data = _get_data()
username = data.get("Username", "")
password = data.get("Password", "")
profile = db.check_password(username, password)
if profile is None:
print(f"[SECURITY] Login fail: username={username!r} ip={_get_ip()}")
return jsonify(_error_response("Invalid username or password"))
block = _maintenance_block(profile)
if block:
return jsonify(block)
ban = db.get_ban_info(profile["Id"])
if ban:
return jsonify(_error_response(db.format_ban_message(ban)))
ip = _get_ip()
if ip and ip not in ("127.0.0.1", "::1") and db.is_ip_banned(ip):
print(f"[SECURITY] IP-banned login attempt: ip={ip} username={username!r}")
return jsonify(_error_response("This IP address is banned."))
cascade = _cascade_ban_if_linked(profile["Id"])
if cascade:
return jsonify(cascade)
platform = str(data.get("Platform", ""))
platform_id = str(data.get("PlatformId", ""))
if not platform_id.isdigit():
platform_id = ""
if platform and platform_id and platform_id != "0":
already = db.get_profiles_by_platform(platform, platform_id)
already_ids = [p["Id"] for p in already]
if not already_ids or profile["Id"] in already_ids:
db.update_profile_platform(profile["Id"], platform, platform_id)
db.link_platform_to_profile(platform, platform_id, profile["Id"])
from datetime import timedelta
remember_me = bool(data.get("RememberMe", False))
ttl = timedelta(hours=8) if remember_me else None
token = _issue_token(profile["Id"], ttl=ttl)
db.add_cached_login(profile["Id"], current_jti[profile["Id"]])
_award_daily_login(profile["Id"])
_notify_password_change_if_needed(profile["Id"])
try:
from core.discord import notify_player_login
notify_player_login(profile["Username"], profile["Id"])
except Exception:
pass
return jsonify(make_login_response(make_profile_from_db(profile), token))
@bp.route("/api/platformlogin/v1/logincached", methods=["POST"])
@limiter.limit("10 per minute")
def login_cached():
data = _get_data()
try:
player_id = int(data.get("PlayerId", 0))
except (TypeError, ValueError):
player_id = 0
if not player_id:
return jsonify(_error_response("Account not found"))
platform = str(data.get("Platform", ""))
platform_id = str(data.get("PlatformId", ""))
if not platform_id.isdigit():
platform_id = ""
if not (platform and platform_id and platform_id != "0"):
return jsonify(_error_response("Authentication required"))
linked = db.get_profiles_by_platform(platform, platform_id)
if not any(p["Id"] == player_id for p in linked):
print(f"[SECURITY] logincached fail: pid={player_id} platform={platform}/{platform_id} ip={_get_ip()}")
return jsonify(_error_response("Account not found"))
profile = db.get_profile(player_id)
if profile is None:
return jsonify(_error_response("Account not found"))
block = _maintenance_block(profile)
if block:
return jsonify(block)
ban = db.get_ban_info(profile["Id"])
if ban:
return jsonify(_error_response(db.format_ban_message(ban)))
ip = _get_ip()
if ip and ip not in ("127.0.0.1", "::1") and db.is_ip_banned(ip):
return jsonify(_error_response("This IP address is banned."))
cascade = _cascade_ban_if_linked(profile["Id"])
if cascade:
return jsonify(cascade)
db.update_profile_platform(profile["Id"], platform, platform_id)
token = _issue_token(profile["Id"])
db.add_cached_login(profile["Id"], current_jti[profile["Id"]])
_award_daily_login(profile["Id"])
_notify_password_change_if_needed(profile["Id"])
try:
from core.discord import notify_player_login
notify_player_login(profile["Username"], profile["Id"])
except Exception:
pass
return jsonify(make_login_response(make_profile_from_db(profile), token))
_RESERVED_USERNAMES = {
"admin", "administrator", "moderator", "mod", "staff", "owner",
"system", "kittyrec", "kitty", "server", "support", "help",
"player", "guest", "root", "superuser", "sudo",
}
_BLOCKED_WARP_TAGS: set[str] = {}
_GLOBAL_CREATE_LIMIT = 0
_GLOBAL_CREATE_LOCK = __import__("threading").Lock()
_GLOBAL_CREATE_WINDOW: list = []
def _global_create_check() -> bool:
import time
now = time.time()
with _GLOBAL_CREATE_LOCK:
_GLOBAL_CREATE_WINDOW[:] = [t for t in _GLOBAL_CREATE_WINDOW if now - t < 60]
if len(_GLOBAL_CREATE_WINDOW) >= 15:
return False
_GLOBAL_CREATE_WINDOW.append(now)
return True
@bp.route("/api/platformlogin/v1/createaccount", methods=["POST"])
@limiter.limit("2 per 5 minutes")
def create_account():
block = _maintenance_block(None)
if block:
return jsonify(block)
warp_tag = request.headers.get("Cf-Warp-Tag-Id", "").strip()
if warp_tag and warp_tag in _BLOCKED_WARP_TAGS:
try:
from core.discord import send_security
send_security(
title="Blocked Warp Tag Attempt",
color=0xE74C3C,
fields=[
{"name": "Warp Tag", "value": warp_tag, "inline": True},
{"name": "IP", "value": _get_ip(), "inline": True},
],
description="A blocked Cloudflare Warp client tried to create an account.",
throttle_key=f"warp_{warp_tag}",
throttle_secs=120,
)
except Exception:
pass
if _ip_is_banned(_get_ip()):
return jsonify(_error_response("Account creation is not allowed from this network.")), 403
data = _get_data()
username = sanitize_username(data.get("Username", ""))
password = data.get("Password", "")
display_name = sanitize_username(data.get("DisplayName", ""))
platform = str(data.get("Platform", "0"))
platform_id = str(data.get("PlatformId", ""))
if not platform_id.isdigit():
platform_id = ""
if username.lower() in _RESERVED_USERNAMES:
return jsonify(_error_response("That username is not allowed."))
if username and not is_clean(username):
return jsonify(_error_response("That username is not allowed."))
if not username and platform_id and platform_id != "0":
import random as _rnd
auto_name = f"KittyRecPlayer{_rnd.randint(0, 999):03d}"
profile = db.create_account(auto_name, "", auto_name, created_via="game")
if profile is None:
auto_name = f"KittyRecPlayer{_rnd.randint(0, 999):03d}"
profile = db.create_account(auto_name, "", auto_name, created_via="game")
if profile is None:
return jsonify(_error_response("Could not create account, please try again"))
db.link_platform_to_profile(platform, platform_id, profile["Id"])
ban = db.get_ban_info(profile["Id"])
if ban:
return jsonify(_error_response(db.format_ban_message(ban)))
cascade = _cascade_ban_if_linked(profile["Id"])
if cascade:
return jsonify(cascade)
token = _issue_token(profile["Id"])
db.add_cached_login(profile["Id"], current_jti[profile["Id"]])
_award_daily_login(profile["Id"])
print(f"[Auth] createaccount: new account platform={platform} id={platform_id} "
f"→ pid={profile['Id']} ({profile['Username']})")
try:
from core.discord import send_public, record_signup, send_admin
send_public(
title="New Player Joined!",
color=0x9B59B6,
fields=[{"name": "Username", "value": profile["Username"], "inline": True},
{"name": "Player ID", "value": str(profile["Id"]), "inline": True},
{"name": "Created Via", "value": "In-Game", "inline": True}],
description=f"**{profile['Username']}** just created an account on KittyRec!",
throttle_key=f"newplayer_{profile['Id']}",
throttle_secs=0,
)
if record_signup():
send_admin(
title="Registration Burst Detected",
color=0xE67E22,
fields=[{"name": "Threshold", "value": "5+ signups in 60s", "inline": True},
{"name": "Latest", "value": profile["Username"], "inline": True}],
)
except Exception:
pass
return jsonify(make_login_response(make_profile_from_db(profile), token))
if not username:
return jsonify(_error_response("Username is required"))
real_platform = platform if platform and platform != "0" else "Steam"
real_platform_id = platform_id if platform_id and platform_id != "0" else None
profile = db.create_account(username, password, display_name or username,
platform=real_platform, platform_id=real_platform_id,
created_via="game")
if profile is None:
return jsonify(_error_response("Username already taken"))
if password:
from tracking.password_tracking import mark_password_set
mark_password_set(profile["Id"])
if platform and platform_id and platform_id != "0":
db.link_platform_to_profile(platform, platform_id, profile["Id"])
ban = db.get_ban_info(profile["Id"])
if ban:
return jsonify(_error_response(db.format_ban_message(ban)))
cascade = _cascade_ban_if_linked(profile["Id"])
if cascade:
return jsonify(cascade)
token = _issue_token(profile["Id"])
db.add_cached_login(profile["Id"], current_jti[profile["Id"]])
_award_daily_login(profile["Id"])
try:
from core.discord import send_public, record_signup, send_admin
send_public(
title="New Player Joined!",
color=0x9B59B6,
fields=[{"name": "Username", "value": profile["Username"], "inline": True},
{"name": "Player ID", "value": str(profile["Id"]), "inline": True},
{"name": "Created Via", "value": "In-Game", "inline": True}],
description=f"**{profile['Username']}** just created an account on KittyRec!",
throttle_key=f"newplayer_{profile['Id']}",
throttle_secs=0,
)
if record_signup():
send_admin(
title="Registration Burst Detected",
color=0xE67E22,
fields=[{"name": "Threshold", "value": "5+ signups in 60s", "inline": True},
{"name": "Latest", "value": profile["Username"], "inline": True}],
)
except Exception:
pass
return jsonify(make_login_response(make_profile_from_db(profile), token))
@bp.route("/api/platformlogin/v1/registeraccount", methods=["POST"])
@limiter.limit("10 per minute")
def register_account():
if _ip_is_banned(_get_ip()):
return jsonify(_error_response("Account creation is not allowed from this network.")), 403
data = _get_data()
if "Email" in data and "Platform" not in data and "PlatformId" not in data:
pid = get_current_profile_id()
if pid:
from werkzeug.security import generate_password_hash
username = sanitize_username(data.get("Username", "")) or None
password = data.get("Password", "")
conn = db._get_conn()
if username:
if not is_clean(username):
return jsonify(_error_response("That username is not allowed."))
existing = conn.execute("SELECT id FROM profiles WHERE username = ? AND id != ?", (username, pid)).fetchone()
if existing:
return jsonify(_error_response("Username already taken"))
conn.execute("UPDATE profiles SET username=?, display_name=? WHERE id=?", (username, username, pid))
if password:
conn.execute("UPDATE profiles SET password=? WHERE id=?", (generate_password_hash(password), pid))
from tracking.password_tracking import mark_password_set
mark_password_set(pid)
conn.execute("UPDATE profiles SET registration_status=2 WHERE id=?", (pid,))
conn.commit()
from core.ws_helpers import push_profile_update
push_profile_update(pid)
print(f"[Auth] registeraccount email: pid={pid} username={username}")
profile = db.get_profile(pid)
token = _issue_token(pid)
db.add_cached_login(pid, current_jti[pid])
return jsonify(make_login_response(make_profile_from_db(profile), token))
return jsonify({"Success": True, "Message": ""})
platform = str(data.get("Platform", 0))
platform_id = str(data.get("PlatformId", "0"))
if not platform_id or platform_id == "0":
return jsonify(_error_response("Platform authentication required"))
existing = db.get_profiles_by_platform(platform, platform_id)
if len(existing) > 3:
return jsonify(_error_response("Too many accounts linked to this platform ID"))
import random as _rnd
username = f"KittyRecPlayer{_rnd.randint(0, 999):03d}"
profile = db.get_or_create_profile(platform, platform_id, username)
db.link_platform_to_profile(platform, platform_id, profile["Id"])
ban = db.get_ban_info(profile["Id"])
if ban:
return jsonify(_error_response(db.format_ban_message(ban)))
cascade = _cascade_ban_if_linked(profile["Id"])
if cascade:
return jsonify(cascade)
block = _maintenance_block(profile)
if block:
return jsonify(block)
token = _issue_token(profile["Id"])
db.add_cached_login(profile["Id"], current_jti[profile["Id"]])
_award_daily_login(profile["Id"])
return jsonify(make_login_response(make_profile_from_db(profile), token))
@bp.route("/api/platformlogin/v1/refreshlogin", methods=["GET", "POST"])
@limiter.limit("20 per minute")
def refresh_login():
pid = get_current_profile_id(allow_expired=True)
if pid:
profile = db.get_profile(pid)
if profile:
ban = db.get_ban_info(profile["Id"])
if ban:
return jsonify(_error_response(db.format_ban_message(ban)))
cascade = _cascade_ban_if_linked(profile["Id"])
if cascade:
return jsonify(cascade)
block = _maintenance_block(profile)
if block:
return jsonify(block)
token = _issue_token(profile["Id"])
db.add_cached_login(profile["Id"], current_jti[profile["Id"]])
return jsonify(make_login_response(make_profile_from_db(profile), token))
return Response("Unauthorized", 401)
@bp.route("/api/platformlogin/v1/logout", methods=["POST"])
def logout():
pid = get_current_profile_id(allow_expired=True)
if pid:
with jti_lock:
current_jti.pop(pid, None)
db.remove_cached_login(pid)
try:
profile = db.get_profile(pid)
if profile:
from core.discord import notify_player_logout
notify_player_logout(profile["Username"], pid)
except Exception:
pass
return Response("OK", 200)
@bp.route("/api/platformlogin/v1/getcachedlogins", methods=["POST", "GET"])
@limiter.limit("10 per minute")
def get_cached_logins():
data = _get_data()
platform = str(data.get("Platform", ""))
platform_id = str(data.get("PlatformId", ""))
if platform and platform_id and platform_id != "0":
profiles = db.get_profiles_by_platform(platform, platform_id)
if profiles:
result = []
for profile in profiles:
if not db.get_ban_info(profile["Id"]):
_cascade_ban_if_linked(profile["Id"])
result.append(make_profile_from_db(profile))
print(f"[Auth] getcachedlogins: platform={platform} id={platform_id} → pids={[p['Id'] for p in profiles]}")
return jsonify(result)
print(f"[Auth] getcachedlogins: no accounts for platform={platform} id={platform_id}")
return jsonify([])
@bp.route("/api/platformlogin/v1/removecachedlogin", methods=["POST"])
def remove_cached_login():
data = _get_data()
try:
player_id = int(data.get("PlayerId", 0))
except (TypeError, ValueError):
player_id = 0
if not player_id:
return Response("OK", 200)
pid = get_current_profile_id(allow_expired=True)
if pid != player_id:
return Response("OK", 200)
db.remove_cached_login(player_id)
return Response("OK", 200)
@bp.route("/api/platformlogin/<path:action>", methods=["GET", "POST"])
def platformlogin_catchall(action):
return jsonify({"Error": "Not found", "Player": None, "Token": ""}), 404