From f84b149521531dc900da3ae6266690f74c25af34 Mon Sep 17 00:00:00 2001 From: admin Date: Fri, 24 Jul 2026 15:20:30 +0000 Subject: [PATCH] Upload files to "/" --- .gitignore | 20 +++ ReadMe.md | 65 ++++++++ app.py | 382 +++++++++++++++++++++++++++++++++++++++++++++++ gunicorn.conf.py | 18 +++ requirements.txt | 9 ++ 5 files changed, 494 insertions(+) create mode 100644 .gitignore create mode 100644 ReadMe.md create mode 100644 app.py create mode 100644 gunicorn.conf.py create mode 100644 requirements.txt diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8aabb64 --- /dev/null +++ b/.gitignore @@ -0,0 +1,20 @@ +.secret_key +config.yaml +.claude/ +ClaudeReadHere/ +__pycache__/ +*.py[cod] +*.pyo +venv/ +.env +*.db +*.db-shm +*.db-wal +*.log +uploads/ +public/ +data/ +gamecode/ +music/*.wav +aws/ +awscliv2.zip diff --git a/ReadMe.md b/ReadMe.md new file mode 100644 index 0000000..dde792c --- /dev/null +++ b/ReadMe.md @@ -0,0 +1,65 @@ +# KittyRec + +a 2018 RecRoom server reimplmentation built for the june 7th 2018 build. the goal is full API support for everything that was in the game at that point and add new stuff that was never in the orignal. + +live at **kittyrec.tabbycluster.net** + +--- + + +## whats implemented + +- **auth** — login, cached login, account creation, platform linking, daily login bonus, token refresh +- **profiles** — xp, levels, display names, avatar/outfit, swatches, item ownership +- **multiplayer** — game sessions, matchmaking, session joining, rec royale, reporting join results +- **store** — storefronts, token purchases, elite items, pinned featured items, store reroll +- **gifts** — gift drops, gift box opening, sending gifts between players, daily token rewards +- **relationships** — friends, blocking, following, player search +- **chat** — direct messages, chat thread +- **Progression** — box caps, drops, chances, etc +- **avatar** — outfit saving, wardrobe, item equipping, color swatches +- **downloads** — chunked build uploads, public download page, auto extracts to compiled/ +- **websocket** — real time presence, session events, gift notifs, profile updates +- **admin panel** — player managment, bans, gifts, live sessions, store, weekly challenege scheduler + +--- + +## stack + +- Python + Flask +- SQLite +- WebSockets (flask-sock) +- port 8080 + +--- + +## running + +```bash +pip install -r requirements.txt +python app.py +``` + +--- + +## "anticheat" + +serverside anticheat (if you can even call it that) handles cascade bans accross linked accounts, IP bans, dual login detection, and banned room joins. linked acounts get caught on login even if they made a new account. + +--- + +## notes + +- built against the june 7 2018 game client, field names and response formats are **reverse engineered from the compiled game code** (sometimes) +- database auto creates on first run + +--- + +## Credits + +- MyaWired - Leading the project, Hosting the server, working on backends +- EggRecRoom - Build Mods +- WeeBoi - Build Mods +- Claude Code - fixing alot of stuff also breaking alot of stuff + +god bless all the kind souls who made this project real (not claude tho... claude is a clanker..) diff --git a/app.py b/app.py new file mode 100644 index 0000000..e36917e --- /dev/null +++ b/app.py @@ -0,0 +1,382 @@ +import json +import os +import secrets +import time as _time +import uuid +from flask import Flask, request, jsonify, Response, g as _g +from flask_sock import Sock +from flask_compress import Compress +from core.limiter import limiter +from core.config import server as _server_cfg, seed_account as _seed_cfg +from core.logging_setup import setup_logging + +SERVER_NAME = _server_cfg.get("name", "KittyRec") +SERVER_BUILD = _server_cfg.get("build", "") + +_file_log, _err_log, _access_log, _INSTANCE_ID = setup_logging(os.path.dirname(__file__)) + +_key_file = os.path.join(os.path.dirname(__file__), ".secret_key") +_env_key = os.environ.get("SECRET_KEY") +if _env_key: + _jwt_secret = _env_key +elif os.path.exists(_key_file): + with open(_key_file) as _f: + _jwt_secret = _f.read().strip() +else: + _jwt_secret = secrets.token_hex(32) + with open(_key_file, "w") as _f: + _f.write(_jwt_secret) + print("[Security] Generated new SECRET_KEY saved to .secret_key " + "(set SECRET_KEY env var for production)") + +import core.auth as _auth_mod +_auth_mod.JWT_SECRET = _jwt_secret + + +from core.state import db +from core.auth_state import current_jti, jti_lock +from core.auth import get_current_profile_id + +from routes.nameserver import bp as nameserver_bp +from routes.KittyLoader import bp as KittyLoader_bp + +from routes.auth import bp as auth_bp +from routes.config import bp as config_bp +from routes.players import bp as players_bp +from routes.relationships import bp as relationships_bp +from routes.chat import bp as chat_bp +from routes.avatar import bp as avatar_bp +from routes.settings import bp as settings_bp +from routes.presence import bp as presence_bp +from routes.sessions import bp as sessions_bp +from routes.rooms import bp as rooms_bp +from routes.storefronts import bp as storefronts_bp +from routes.images import bp as images_bp +from routes.misc import bp as misc_bp +from routes.inventory import bp as inventory_bp +from routes.portal import bp as portal_bp +from routes.music import bp as music_bp +from routes.media import bp as media_bp +from routes.downloads import bp as downloads_bp +from routes.sdk import bp as sdk_bp +from routes.health import bp as health_bp +from routes.ugc import bp as ugc_bp + +from werkzeug.middleware.proxy_fix import ProxyFix + +app = Flask(__name__) +app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1) +app.secret_key = _jwt_secret +app.config["SOCK_SERVER_OPTIONS"] = {"ping_interval": 25} +app.config["MAX_CONTENT_LENGTH"] = 20 * 1024 * 1024 +app.config["SESSION_COOKIE_SECURE"] = True +app.config["SESSION_COOKIE_HTTPONLY"] = True +app.config["SESSION_COOKIE_SAMESITE"] = "Lax" +app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + os.path.join(os.path.dirname(__file__), "kittyrec.db") +app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False +app.config["COMPRESS_MIMETYPES"] = [ + "application/json", "text/html", "text/css", + "text/javascript", "application/javascript", +] +app.config["COMPRESS_MIN_SIZE"] = 1024 +Compress(app) +sock = Sock(app) + +from core.models import sql_db +sql_db.init_app(app) + +from core.admin_panel import create_admin +create_admin(app) + +limiter.init_app(app) + +db.seed_account(_seed_cfg["username"], _seed_cfg["password"], _seed_cfg["display_name"], developer=True) + + +_restored = 0 +for _jti, _pid in db.get_cached_login_tokens(): + current_jti[_pid] = _jti + _restored += 1 +import datetime as _dt +print(f"[KittyRec] {SERVER_BUILD} instance={_INSTANCE_ID} started={_dt.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')}Z") +if _restored: + print(f"[Startup] Restored {_restored} cached session(s)") + +import os as _os +_sentinel = f"/tmp/_kr_started_{_os.getppid()}" +if not _os.path.exists(_sentinel): + try: + open(_sentinel, 'w').close() + except Exception: + pass + try: + from core.discord import send_admin as _disc_admin + _disc_admin( + title="Server Started", + color=0x2ECC71, + fields=[{"name": "Build", "value": SERVER_BUILD, "inline": True}, + {"name": "Sessions Restored", "value": str(_restored), "inline": True}], + ) + except Exception: + pass + +app.register_blueprint(nameserver_bp) +app.register_blueprint(KittyLoader_bp) + +app.register_blueprint(auth_bp) +app.register_blueprint(config_bp) +app.register_blueprint(players_bp) +app.register_blueprint(relationships_bp) +app.register_blueprint(chat_bp) +app.register_blueprint(avatar_bp) +app.register_blueprint(settings_bp) +app.register_blueprint(presence_bp) +app.register_blueprint(sessions_bp) +app.register_blueprint(rooms_bp) +app.register_blueprint(storefronts_bp) +app.register_blueprint(images_bp) +app.register_blueprint(misc_bp) +app.register_blueprint(inventory_bp) +app.register_blueprint(portal_bp) +app.register_blueprint(music_bp) +app.register_blueprint(media_bp) +app.register_blueprint(downloads_bp) +app.register_blueprint(sdk_bp) +app.register_blueprint(health_bp) +app.register_blueprint(ugc_bp) + +_maint_file = os.path.join(os.path.dirname(__file__), "tracking", "settings", "maintenance.json") +if os.path.exists(_maint_file): + try: + from core.state import maintenance_lock as _ml + import core.state as _cs + with open(_maint_file) as _f: + _mdata = json.load(_f) + with _ml: + _cs.maintenance_mode = bool(_mdata.get("enabled", False)) + _cs.maintenance_exempt = set(int(x) for x in _mdata.get("exempt_ids", [])) + if _cs.maintenance_mode: + print(f"[Startup] Maintenance mode RESTORED (exempt: {_cs.maintenance_exempt})") + except Exception as _e: + print(f"[Startup] Failed to load maintenance state: {_e}") + +from routes.ws import register_ws +register_ws(sock) + +from routes.portal import register_console_ws +register_console_ws(sock) + +from routes.admin_ws import register_admin_ws +register_admin_ws(sock) + + +from core.daemons import start_ban_enforcer, start_player_count_recorder, register_graceful_shutdown, start_presence_watchdog, start_quest_gift_daemon +from routes.storefronts import start_store_watcher +start_ban_enforcer() +start_player_count_recorder() +start_presence_watchdog() +start_quest_gift_daemon() +register_graceful_shutdown() +start_store_watcher() + + +@app.errorhandler(429) +def handle_ratelimit(e): + try: + from core.discord import send_admin + pid = get_current_profile_id() + ip = (request.headers.get("X-Forwarded-For", "") or request.remote_addr or "unknown").split(",")[0].strip() + print(f"[SECURITY] Rate limit: {request.method} {request.path} ip={ip} pid={pid or 'unauth'}") + send_admin( + title="Rate Limit Hit", + color=0xF1C40F, + fields=[{"name": "Endpoint", "value": f"`{request.method} {request.path}`", "inline": True}, + {"name": "IP", "value": ip, "inline": True}, + {"name": "Player", "value": str(pid) if pid else "unauthenticated", "inline": True}], + ) + except Exception: + pass + return jsonify({"error": "Too many requests"}), 429 + + +@app.errorhandler(Exception) +def handle_exception(e): + from werkzeug.exceptions import HTTPException + if isinstance(e, HTTPException): + return e + import traceback + tb = traceback.format_exc() + print("\n" + "=" * 60) + print(f" !! 500 ERROR: {request.method} {request.path}") + print("=" * 60) + print(tb) + print("=" * 60 + "\n") + try: + from core.discord import send_admin + truncated = tb[-3800:] if len(tb) > 3800 else tb + send_admin( + title="Server Error (500)", + color=0xE74C3C, + fields=[{"name": "Endpoint", "value": f"`{request.method} {request.path}`", "inline": True}], + description=f"```\n{truncated}\n```", + ) + except Exception: + pass + return jsonify({"error": "Internal server error"}), 500 + + +@app.context_processor +def _inject_build_vars(): + return { + "server_name": _server_cfg.get("name", "KittyRec"), + "build": _server_cfg.get("build", ""), + "app_version": _server_cfg.get("app_version", ""), + "app_version_long": _server_cfg.get("app_version_long", _server_cfg.get("app_version", "")), + "build_date_human": _server_cfg.get("build_date_human", ""), + } + + +@app.after_request +def set_security_headers(response): + response.headers["X-Content-Type-Options"] = "nosniff" + response.headers["X-Frame-Options"] = "DENY" + response.headers["X-XSS-Protection"] = "1; mode=block" + return response + + +@app.route("/api/", methods=["GET", "POST", "PUT", "DELETE", "PATCH"]) +def api_catchall(path): + ip = (request.headers.get("X-Forwarded-For", "") or request.remote_addr or "?").split(",")[0].strip() + pid = get_current_profile_id() + print(f"[API] UNHANDLED: {request.method} /api/{path} ip={ip} pid={pid or 'unauth'}") + if request.method == "GET": + return jsonify([]) + return jsonify({}) + +_LOG_SKIP = ("/api/analytics", "/static", "/admin/api/console") +_LOG_SKIP_BODY = ( + "/api/platformlogin/v1/loginaccount", + "/api/platformlogin/v1/createaccount", + "/api/platformlogin/v1/registeraccount", +) + +@app.before_request +def log_request(): + path = request.path + for prefix in _LOG_SKIP: + if path.startswith(prefix): + return + + _g._req_start = _time.perf_counter() + _g._req_id = uuid.uuid4().hex[:6] + + is_ws = request.environ.get("HTTP_UPGRADE", "").lower() == "websocket" + pid = get_current_profile_id() + pid_str = f"pid={pid}" if pid else "unauth" + _g._client_ip = (request.headers.get("X-Forwarded-For", "") or request.remote_addr or "-").split(",")[0].strip() + _g._client_pid_str = pid_str + + url = path + if request.query_string: + url += "?" + request.query_string.decode("utf-8", errors="replace") + + print(f"\n>>> {request.method} {url} [{pid_str}] id={_g._req_id}") + + for k, v in request.headers: + if k.lower() in ("cookie", "set-cookie"): + continue + if k.lower() == "authorization": + v = v[:20] + "..." if len(v) > 20 else v + print(f" {k}: {v}") + + skip_body = any(path.startswith(p) for p in _LOG_SKIP_BODY) + if not is_ws and not skip_body: + content_type = request.content_type or "" + try: + if "json" in content_type or "form" in content_type or (request.content_length and request.content_length > 0): + if "form" in content_type and request.form: + print(f" Body (form): {dict(request.form)}") + else: + body = request.get_json(force=True, silent=True) + if body is not None: + body_str = json.dumps(body, indent=2) + if len(body_str) > 4000: + body_str = body_str[:4000] + "\n ... (truncated)" + print(f" Body (JSON):\n{body_str}") + else: + raw = request.get_data() + if raw: + print(f" Body (raw, {len(raw)} bytes): {raw[:500]!r}") + except Exception as exc: + print(f" [log error reading body: {exc}]") + +@app.after_request +def log_response(response): + try: + path = request.path + for prefix in _LOG_SKIP: + if path.startswith(prefix): + return response + + elapsed_ms = int((_time.perf_counter() - getattr(_g, "_req_start", _time.perf_counter())) * 1000) + req_id = getattr(_g, "_req_id", "------") + content_type = response.content_type or "" + print(f"<<< {response.status} [{content_type}] {elapsed_ms}ms id={req_id}") + for k, v in response.headers: + print(f" {k}: {v}") + + if "json" in content_type: + body = response.get_data(as_text=True) + if len(body) > 4000: + print(f" {body[:4000]}\n ... (truncated, {len(body)} bytes total)") + else: + print(f" {body}") + elif "text" in content_type: + print(f" {response.get_data(as_text=True)!r}") + + if response.status_code >= 500: + _err_log.error("[%s] %s %s → %s (%dms)", req_id, request.method, path, response.status, elapsed_ms) + elif response.status_code >= 400: + _err_log.warning("[%s] %s %s → %s (%dms)", req_id, request.method, path, response.status, elapsed_ms) + _access_log.info( + "%-6s %-55s | %-12s | %-20s | %s | %dms", + request.method, path[:55], + getattr(_g, "_client_pid_str", "unauth"), + getattr(_g, "_client_ip", "-"), + response.status_code, + elapsed_ms, + ) + except Exception as exc: + print(f" [log error: {exc}]") + return response + +_system_started = False + +@app.before_request +def _ensure_system_online(): + global _system_started + if not _system_started: + _system_started = True + from core.state import bring_system_account_online + bring_system_account_online() + +@app.before_request +def _burst_detect(): + from core.limiter import _get_client_ip + from core.burst_detector import record + record(_get_client_ip(), request.path) + +if __name__ == "__main__": + print("=" * 60) + print(f" INSTANCE {_INSTANCE_ID} started at {__import__('datetime').datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')} UTC") + print(f" KittyRec indev (RecRoom 2018 Build {_server_cfg.get('app_version_long', _server_cfg.get('app_version', ''))})") + print(" Listening on 0.0.0.0:8080") + print("") + print(" NameServer: http://localhost:8080/?v=1") + print(" API Base: http://localhost:8080/") + print(" Web Portal: http://localhost:8080/") + print("") + print(" Default account: myawired / myawired") + print(" Auth: JWT Bearer Token (via /api/platformlogin/v1/loginaccount)") + print("=" * 60) + app.run(host=_server_cfg.get("host", "0.0.0.0"), port=_server_cfg.get("port", 8080), debug=False, threaded=True) diff --git a/gunicorn.conf.py b/gunicorn.conf.py new file mode 100644 index 0000000..f09985f --- /dev/null +++ b/gunicorn.conf.py @@ -0,0 +1,18 @@ +worker_class = "gevent" +workers = 1 +worker_connections = 1000 +bind = "0.0.0.0:8080" +timeout = 120 +keepalive = 5 +loglevel = "warning" +accesslog = "-" +errorlog = "-" + + +def on_starting(server): + import glob, os + for f in glob.glob('/tmp/_kr_started_*'): + try: + os.unlink(f) + except Exception: + pass diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..95c0761 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,9 @@ +flask +flask-sock +Flask-Limiter +flask-admin +flask-sqlalchemy +flask-compress +pyyaml +Pillow +better-profanity