383 lines
14 KiB
Python
383 lines
14 KiB
Python
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/<path:path>", 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)
|