Upload files to "core"

This commit is contained in:
2026-07-24 15:38:53 +00:00
parent 9d94ae38b9
commit 730999840e
5 changed files with 358 additions and 0 deletions

124
core/auth.py Normal file
View 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}/"