Cheat_Key / app.py
Arian8888's picture
Multi-Game Keys: CS2, Apex, All
d88622e
Raw History Blame Contribute Delete
25.8 kB
"""
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 = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ArianKing - Key Manager</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
background: #0a0a0f;
color: #e0e0e8;
font-family: 'Segoe UI', system-ui, sans-serif;
min-height: 100vh;
}
.header {
background: linear-gradient(135deg, #7832ff 0%, #2878ff 100%);
padding: 20px 30px;
display: flex;
align-items: center;
justify-content: space-between;
box-shadow: 0 4px 20px rgba(120, 50, 255, 0.3);
}
.header h1 { font-size: 24px; font-weight: 700; color: white; }
.header span { color: rgba(255,255,255,0.7); font-size: 14px; }
.login-container {
max-width: 400px; margin: 80px auto; padding: 30px;
background: #12121a; border-radius: 12px; border: 1px solid #1e1e30;
}
.login-container h2 { color: #8b5cf6; margin-bottom: 20px; text-align: center; }
.container { max-width: 1300px; margin: 20px auto; padding: 0 20px; }
.card {
background: #12121a; border-radius: 10px; padding: 20px;
margin-bottom: 16px; border: 1px solid #1e1e30;
}
.card h3 { color: #8b5cf6; margin-bottom: 12px; font-size: 16px; }
input, select {
background: #1a1a28; border: 1px solid #2a2a40; color: #e0e0e8;
padding: 10px 14px; border-radius: 6px; font-size: 14px;
width: 100%; outline: none; transition: border-color 0.2s;
}
input:focus, select:focus { border-color: #7832ff; }
.input-group { margin-bottom: 12px; }
.input-group label {
display: block; margin-bottom: 4px; color: #888;
font-size: 12px; text-transform: uppercase; letter-spacing: 1px;
}
.input-row { display: flex; gap: 12px; flex-wrap: wrap; }
.input-row > * { flex: 1; min-width: 120px; }
.btn {
padding: 10px 20px; border: none; border-radius: 6px;
font-size: 14px; font-weight: 600; cursor: pointer;
transition: all 0.2s; color: white;
}
.btn-primary { background: linear-gradient(135deg, #7832ff, #5a20d0); }
.btn-primary:hover { background: linear-gradient(135deg, #8b45ff, #6b30e0); box-shadow: 0 4px 15px rgba(120,50,255,0.4); }
.btn-danger { background: #dc2626; }
.btn-danger:hover { background: #ef4444; }
.btn-success { background: #16a34a; }
.btn-success:hover { background: #22c55e; }
.btn-warning { background: #d97706; }
.btn-warning:hover { background: #f59e0b; }
.btn-sm { padding: 6px 12px; font-size: 12px; }
.game-filter {
display: flex; gap: 8px; margin-bottom: 16px;
}
.game-btn {
padding: 8px 18px; border: 2px solid #2a2a40; border-radius: 8px;
background: transparent; color: #888; cursor: pointer;
font-size: 13px; font-weight: 600; transition: all 0.2s;
}
.game-btn:hover { border-color: #7832ff; color: #c4b5fd; }
.game-btn.active { border-color: #7832ff; background: rgba(120,50,255,0.15); color: #c4b5fd; }
.game-badge {
display: inline-block; padding: 3px 8px; border-radius: 4px;
font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px;
}
.game-cs2 { background: rgba(255,165,0,0.2); color: #fbbf24; }
.game-apex { background: rgba(239,68,68,0.2); color: #f87171; }
.game-all { background: rgba(120,50,255,0.2); color: #c4b5fd; }
.keys-table { width: 100%; border-collapse: collapse; }
.keys-table th {
text-align: left; padding: 10px; color: #888;
font-size: 11px; text-transform: uppercase; letter-spacing: 1px;
border-bottom: 1px solid #1e1e30;
}
.keys-table td { padding: 10px; border-bottom: 1px solid #1a1a28; font-size: 13px; }
.keys-table tr:hover td { background: #1a1a28; }
.badge { display: inline-block; padding: 3px 8px; border-radius: 4px; font-size: 11px; font-weight: 600; }
.badge-active { background: rgba(22,163,74,0.2); color: #4ade80; }
.badge-inactive { background: rgba(220,38,38,0.2); color: #f87171; }
.badge-expired { background: rgba(217,119,6,0.2); color: #fbbf24; }
.key-text { font-family: 'Consolas', monospace; color: #c4b5fd; font-size: 13px; cursor: pointer; }
.key-text:hover { color: #8b5cf6; }
.username-text { color: #60a5fa; font-weight: 600; font-size: 13px; }
.hwid-text { font-family: monospace; font-size: 11px; color: #666; max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.stats { display: flex; gap: 16px; margin-bottom: 16px; flex-wrap: wrap; }
.stat-box {
background: #12121a; border: 1px solid #1e1e30;
border-radius: 8px; padding: 16px 20px; flex: 1; text-align: center; min-width: 100px;
}
.stat-box .number { font-size: 28px; font-weight: 700; color: #8b5cf6; }
.stat-box .label { font-size: 12px; color: #666; margin-top: 4px; }
.toast {
position: fixed; top: 20px; right: 20px; background: #16a34a;
color: white; padding: 12px 20px; border-radius: 8px; font-size: 14px;
display: none; z-index: 1000; box-shadow: 0 4px 15px rgba(0,0,0,0.3);
}
.toast.error { background: #dc2626; }
.actions { display: flex; gap: 4px; flex-wrap: wrap; }
.hidden { display: none; }
.overflow-x { overflow-x: auto; }
.new-key-box {
margin-top: 12px; padding: 16px; background: #1a1a28;
border-radius: 8px; border: 1px solid #2a2a40;
}
.new-key-box .key-display { font-family: 'Consolas', monospace; font-size: 20px; color: #c4b5fd; letter-spacing: 1px; }
.new-key-box .user-display { font-size: 14px; color: #60a5fa; margin-top: 4px; }
.copy-all-btn { margin-top: 8px; display: flex; gap: 8px; }
::-webkit-scrollbar { width: 8px; }
::-webkit-scrollbar-track { background: #0a0a0f; }
::-webkit-scrollbar-thumb { background: #2a2a40; border-radius: 4px; }
</style>
</head>
<body>
<div class="header">
<h1>ArianKing</h1>
<span>Multi-Game Key Management</span>
</div>
<div id="toast" class="toast"></div>
<!-- Login -->
<div id="loginScreen" class="login-container">
<h2>Admin Login</h2>
<div class="input-group">
<label>Password</label>
<input type="password" id="passwordInput" placeholder="Enter admin password..."
onkeydown="if(event.key==='Enter')login()">
</div>
<button class="btn btn-primary" style="width:100%;margin-top:8px" onclick="login()">Login</button>
</div>
<!-- Dashboard -->
<div id="dashboard" class="container hidden">
<div class="stats">
<div class="stat-box"><div class="number" id="statTotal">0</div><div class="label">Total Keys</div></div>
<div class="stat-box"><div class="number" id="statActive">0</div><div class="label">Active</div></div>
<div class="stat-box"><div class="number" id="statCS2">0</div><div class="label">CS2</div></div>
<div class="stat-box"><div class="number" id="statApex">0</div><div class="label">Apex</div></div>
<div class="stat-box"><div class="number" id="statExpired">0</div><div class="label">Expired</div></div>
</div>
<!-- Create Key -->
<div class="card">
<h3>Create New Key</h3>
<div class="input-row">
<div class="input-group">
<label>Game *</label>
<select id="keyGame">
<option value="cs2">CS2</option>
<option value="apex">Apex Legends</option>
<option value="all">All Games</option>
</select>
</div>
<div class="input-group">
<label>Username *</label>
<input type="text" id="keyUsername" placeholder="Username...">
</div>
<div class="input-group">
<label>Duration (Days)</label>
<input type="number" id="keyDays" value="30" min="1" max="365">
</div>
<div class="input-group">
<label>Label</label>
<input type="text" id="keyLabel" placeholder="Notes...">
</div>
<div style="display:flex;align-items:flex-end">
<button class="btn btn-primary" onclick="createKey()">Create</button>
</div>
</div>
<div id="newKeyResult" class="new-key-box hidden">
<div style="color:#888;font-size:12px;text-transform:uppercase;letter-spacing:1px">New Key Created</div>
<div class="key-display" id="newKeyText"></div>
<div class="user-display">Username: <span id="newKeyUser"></span> | Game: <span id="newKeyGame"></span></div>
<div class="copy-all-btn">
<button class="btn btn-sm btn-primary" onclick="copyKey()">Copy Key</button>
<button class="btn btn-sm btn-primary" onclick="copyAll()">Copy All</button>
</div>
</div>
</div>
<!-- Keys List -->
<div class="card">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">
<h3 style="margin:0">License Keys</h3>
<button class="btn btn-sm btn-primary" onclick="loadKeys()">Refresh</button>
</div>
<div class="game-filter">
<button class="game-btn active" onclick="filterGame(this,'all')">All</button>
<button class="game-btn" onclick="filterGame(this,'cs2')">CS2</button>
<button class="game-btn" onclick="filterGame(this,'apex')">Apex</button>
</div>
<div class="overflow-x">
<table class="keys-table">
<thead>
<tr>
<th>Key</th>
<th>Game</th>
<th>Username</th>
<th>Label</th>
<th>Status</th>
<th>Days Left</th>
<th>HWID</th>
<th>Uses</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="keysBody">
<tr><td colspan="9" style="text-align:center;color:#666">Loading...</td></tr>
</tbody>
</table>
</div>
</div>
</div>
<script>
let adminPassword = '';
let lastCreatedKey = '';
let lastCreatedUser = '';
let lastCreatedGame = '';
let currentFilter = 'all';
function showToast(msg, isError) {
const t = document.getElementById('toast');
t.textContent = msg;
t.className = 'toast' + (isError ? ' error' : '');
t.style.display = 'block';
setTimeout(() => t.style.display = 'none', 3000);
}
async function api(endpoint, body) {
const res = await fetch('/api/' + endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
if (!res.ok) {
const err = await res.json();
throw new Error(err.detail || 'Request failed');
}
return res.json();
}
async function login() {
adminPassword = document.getElementById('passwordInput').value;
try {
await api('list-keys', { admin_password: adminPassword });
document.getElementById('loginScreen').classList.add('hidden');
document.getElementById('dashboard').classList.remove('hidden');
loadKeys();
} catch(e) {
showToast('Invalid password', true);
adminPassword = '';
}
}
function filterGame(btn, game) {
currentFilter = game;
document.querySelectorAll('.game-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
loadKeys();
}
function getGameBadge(game) {
const g = (game || 'cs2').toLowerCase();
if (g === 'cs2') return '<span class="game-badge game-cs2">CS2</span>';
if (g === 'apex') return '<span class="game-badge game-apex">APEX</span>';
if (g === 'all') return '<span class="game-badge game-all">ALL</span>';
return '<span class="game-badge">' + g.toUpperCase() + '</span>';
}
async function loadKeys() {
try {
const body = { admin_password: adminPassword };
if (currentFilter !== 'all') body.game = currentFilter;
const data = await api('list-keys', body);
const keys = data.keys;
// Stats (always show totals regardless of filter)
const allData = await api('list-keys', { admin_password: adminPassword });
const allKeys = allData.keys;
document.getElementById('statTotal').textContent = allKeys.length;
document.getElementById('statActive').textContent = allKeys.filter(k => k.active && !k.expired).length;
document.getElementById('statCS2').textContent = allKeys.filter(k => (k.game||'cs2') === 'cs2').length;
document.getElementById('statApex').textContent = allKeys.filter(k => k.game === 'apex').length;
document.getElementById('statExpired').textContent = allKeys.filter(k => k.expired).length;
const tbody = document.getElementById('keysBody');
if (keys.length === 0) {
tbody.innerHTML = '<tr><td colspan="9" style="text-align:center;color:#666">No keys found.</td></tr>';
return;
}
tbody.innerHTML = keys.map(k => {
let statusBadge;
if (!k.active) statusBadge = '<span class="badge badge-inactive">Disabled</span>';
else if (k.expired) statusBadge = '<span class="badge badge-expired">Expired</span>';
else statusBadge = '<span class="badge badge-active">Active</span>';
const hwid = k.hwid
? '<span class="hwid-text" title="' + k.hwid + '">' + k.hwid.substring(0,16) + '</span>'
: '<span style="color:#444">Unbound</span>';
const toggleBtn = k.active
? `<button class="btn btn-sm btn-warning" onclick="toggleKey('${k.key}',false)">Disable</button>`
: `<button class="btn btn-sm btn-success" onclick="toggleKey('${k.key}',true)">Enable</button>`;
const resetBtn = k.hwid
? `<button class="btn btn-sm btn-primary" onclick="resetHwid('${k.key}')">Reset</button>`
: '';
return '<tr>' +
`<td><span class="key-text" onclick="navigator.clipboard.writeText('${k.key}');showToast('Copied!')" title="Click to copy">${k.key}</span></td>` +
'<td>' + getGameBadge(k.game) + '</td>' +
'<td><span class="username-text">' + (k.username || '-') + '</span></td>' +
'<td>' + (k.label || '-') + '</td>' +
'<td>' + statusBadge + '</td>' +
'<td>' + (k.expired ? '0' : k.days_left + 'd') + '</td>' +
'<td>' + hwid + '</td>' +
'<td>' + k.uses + '</td>' +
'<td class="actions">' + toggleBtn + resetBtn +
`<button class="btn btn-sm btn-danger" onclick="deleteKey('${k.key}')">Del</button>` +
'</td></tr>';
}).join('');
} catch(e) {
showToast('Failed to load keys: ' + e.message, true);
}
}
async function createKey() {
const game = document.getElementById('keyGame').value;
const username = document.getElementById('keyUsername').value.trim();
const days = parseInt(document.getElementById('keyDays').value) || 30;
const label = document.getElementById('keyLabel').value;
if (!username) {
showToast('Username is required!', true);
document.getElementById('keyUsername').focus();
return;
}
try {
const data = await api('create-key', {
admin_password: adminPassword,
days, label, username, game
});
lastCreatedKey = data.key;
lastCreatedUser = username;
lastCreatedGame = game;
document.getElementById('newKeyText').textContent = data.key;
document.getElementById('newKeyUser').textContent = username;
document.getElementById('newKeyGame').textContent = game.toUpperCase();
document.getElementById('newKeyResult').classList.remove('hidden');
showToast('Key created for ' + username + ' [' + game.toUpperCase() + ']');
document.getElementById('keyUsername').value = '';
document.getElementById('keyLabel').value = '';
loadKeys();
} catch(e) {
showToast('Failed: ' + e.message, true);
}
}
function copyKey() {
navigator.clipboard.writeText(lastCreatedKey);
showToast('Key copied!');
}
function copyAll() {
navigator.clipboard.writeText('Key: ' + lastCreatedKey + '\\nUsername: ' + lastCreatedUser + '\\nGame: ' + lastCreatedGame.toUpperCase());
showToast('Copied!');
}
async function toggleKey(key, active) {
try {
await api('toggle-key', { admin_password: adminPassword, key, active });
showToast(active ? 'Key enabled' : 'Key disabled');
loadKeys();
} catch(e) { showToast('Failed: ' + e.message, true); }
}
async function resetHwid(key) {
if (!confirm('Reset HWID for ' + key + '?')) return;
try {
await api('reset-hwid', { admin_password: adminPassword, key });
showToast('HWID reset');
loadKeys();
} catch(e) { showToast('Failed: ' + e.message, true); }
}
async function deleteKey(key) {
if (!confirm('Delete ' + key + '?')) return;
try {
await api('delete-key', { admin_password: adminPassword, key });
showToast('Key deleted');
loadKeys();
} catch(e) { showToast('Failed: ' + e.message, true); }
}
</script>
</body>
</html>"""
@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}