""" ArianKing — Multi-Game License Key Server Runs on HuggingFace Spaces (Docker SDK) Supports: CS2, Apex, and future games """ from fastapi import FastAPI, HTTPException from fastapi.responses import HTMLResponse from pydantic import BaseModel import json, os, secrets, string, time, shutil from datetime import datetime, timedelta from pathlib import Path from threading import Lock from typing import Optional app = FastAPI(title="ArianKing Key Server") # ── Storage ────────────────────────────────────────────────────────────────── if Path("/data").exists(): DATA_DIR = Path("/data") elif Path("/home/user/app").exists(): DATA_DIR = Path("/home/user/app") else: DATA_DIR = Path(".") KEYS_FILE = DATA_DIR / "keys.json" BACKUP_FILE = DATA_DIR / "keys_backup.json" file_lock = Lock() ADMIN_PASSWORD = os.environ.get("ADMIN_PASSWORD", "ArianKing2026") # Supported games VALID_GAMES = ["cs2", "apex", "all"] # ── Models ─────────────────────────────────────────────────────────────────── class CreateKeyRequest(BaseModel): admin_password: str days: int = 30 label: str = "" username: str = "" game: str = "cs2" # "cs2", "apex", or "all" class ToggleKeyRequest(BaseModel): admin_password: str key: str active: bool class DeleteKeyRequest(BaseModel): admin_password: str key: str class ListKeysRequest(BaseModel): admin_password: str game: Optional[str] = None # filter by game, None = show all class ValidateRequest(BaseModel): key: str hwid: str username: str = "" game: str = "cs2" # which game is requesting validation # ── Helpers ────────────────────────────────────────────────────────────────── def load_keys() -> dict: for filepath in [KEYS_FILE, BACKUP_FILE]: if filepath.exists(): try: with open(filepath, "r") as f: data = json.load(f) if isinstance(data, dict): return data except (json.JSONDecodeError, IOError): continue return {} def save_keys(keys: dict): with file_lock: tmp_file = DATA_DIR / "keys_tmp.json" try: with open(tmp_file, "w") as f: json.dump(keys, f, indent=2) shutil.move(str(tmp_file), str(KEYS_FILE)) with open(BACKUP_FILE, "w") as f: json.dump(keys, f, indent=2) except Exception: with open(KEYS_FILE, "w") as f: json.dump(keys, f, indent=2) def generate_key(game: str) -> str: """Generate key like ARIAN-CS2-XXXX-XXXX or ARIAN-APEX-XXXX-XXXX""" chars = string.ascii_uppercase + string.digits parts = ["".join(secrets.choice(chars) for _ in range(4)) for _ in range(2)] prefix = game.upper() if game != "all" else "ALL" return f"ARIAN-{prefix}-{parts[0]}-{parts[1]}" def check_admin(password: str): if password != ADMIN_PASSWORD: raise HTTPException(status_code=403, detail="Invalid admin password") def game_matches(key_game: str, request_game: str) -> bool: """Check if a key's game matches the requesting game""" if key_game == "all": return True return key_game.lower() == request_game.lower() # ── API Endpoints ──────────────────────────────────────────────────────────── @app.post("/api/create-key") def create_key(req: CreateKeyRequest): check_admin(req.admin_password) if not req.username.strip(): raise HTTPException(status_code=400, detail="Username is required") game = req.game.lower() if game not in VALID_GAMES: raise HTTPException(status_code=400, detail=f"Invalid game. Valid: {', '.join(VALID_GAMES)}") key = generate_key(game) now = datetime.utcnow() expires = now + timedelta(days=req.days) keys = load_keys() keys[key] = { "created": now.isoformat(), "expires": expires.isoformat(), "days": req.days, "label": req.label, "username": req.username.strip(), "game": game, "active": True, "hwid": None, "last_used": None, "uses": 0 } save_keys(keys) return { "success": True, "key": key, "username": req.username.strip(), "game": game, "expires": expires.isoformat(), "days": req.days } @app.post("/api/validate") def validate_key(req: ValidateRequest): """Called by the cheat to check if a key is valid + bind HWID""" keys = load_keys() if req.key not in keys: return {"valid": False, "message": "Invalid key"} entry = keys[req.key] if not entry["active"]: return {"valid": False, "message": "Key deactivated"} # Check expiration expires = datetime.fromisoformat(entry["expires"]) if datetime.utcnow() > expires: return {"valid": False, "message": "Key expired"} # Check game — key must match requesting game (or be "all") key_game = entry.get("game", "cs2") if not game_matches(key_game, req.game): game_label = key_game.upper() if key_game != "all" else "All Games" return {"valid": False, "message": f"Key is for {game_label}, not {req.game.upper()}"} # Check username expected_user = entry.get("username", "") if expected_user and req.username.strip().lower() != expected_user.strip().lower(): return {"valid": False, "message": "Invalid username for this key"} # HWID binding if entry["hwid"] is None: entry["hwid"] = req.hwid elif entry["hwid"] != req.hwid: return {"valid": False, "message": "Key bound to different device"} # Update usage entry["last_used"] = datetime.utcnow().isoformat() entry["uses"] += 1 keys[req.key] = entry save_keys(keys) remaining = expires - datetime.utcnow() days_left = max(0, remaining.days) hours_left = max(0, remaining.seconds // 3600) game_display = key_game.upper() if key_game != "all" else "All Games" return { "valid": True, "message": f"Welcome {expected_user}! {days_left}d {hours_left}h remaining [{game_display}]", "days_left": days_left, "username": expected_user, "game": key_game, "expires": entry["expires"] } @app.post("/api/toggle-key") def toggle_key(req: ToggleKeyRequest): check_admin(req.admin_password) keys = load_keys() if req.key not in keys: raise HTTPException(status_code=404, detail="Key not found") keys[req.key]["active"] = req.active save_keys(keys) return {"success": True, "key": req.key, "active": req.active} @app.post("/api/delete-key") def delete_key(req: DeleteKeyRequest): check_admin(req.admin_password) keys = load_keys() if req.key not in keys: raise HTTPException(status_code=404, detail="Key not found") del keys[req.key] save_keys(keys) return {"success": True} @app.post("/api/reset-hwid") def reset_hwid(req: DeleteKeyRequest): check_admin(req.admin_password) keys = load_keys() if req.key not in keys: raise HTTPException(status_code=404, detail="Key not found") keys[req.key]["hwid"] = None save_keys(keys) return {"success": True, "key": req.key} @app.post("/api/list-keys") def list_keys(req: ListKeysRequest): check_admin(req.admin_password) keys = load_keys() result = [] now = datetime.utcnow() for key, data in keys.items(): # Migrate old keys without game field key_game = data.get("game", "cs2") # Filter by game if requested if req.game and req.game.lower() != "all": if not game_matches(key_game, req.game): continue expires = datetime.fromisoformat(data["expires"]) remaining = expires - now days_left = max(0, remaining.days) if remaining.total_seconds() > 0 else 0 expired = now > expires result.append({ "key": key, "label": data.get("label", ""), "username": data.get("username", ""), "game": key_game, "days": data["days"], "days_left": days_left, "expired": expired, "active": data["active"], "hwid": data["hwid"], "created": data["created"], "expires": data["expires"], "last_used": data.get("last_used"), "uses": data.get("uses", 0) }) result.sort(key=lambda x: (not x["active"], x["expired"], x["created"])) return {"keys": result, "total": len(result)} # ── Admin Panel (HTML) ─────────────────────────────────────────────────────── ADMIN_HTML = """ ArianKing - Key Manager

ArianKing

Multi-Game Key Management

Admin Login

""" @app.get("/", response_class=HTMLResponse) def admin_panel(): return ADMIN_HTML @app.get("/api/health") def health(): return {"status": "ok", "service": "ArianKing Multi-Game Key Server", "games": VALID_GAMES}