Arian8888 commited on
Commit
eb862a5
Β·
1 Parent(s): 6856202

Add key server

Browse files
Files changed (4) hide show
  1. Dockerfile +13 -0
  2. README.md +3 -5
  3. app.py +736 -0
  4. requirements.txt +2 -0
Dockerfile ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9
2
+
3
+ RUN useradd -m -u 1000 user
4
+ USER user
5
+ ENV PATH="/home/user/.local/bin:$PATH"
6
+
7
+ WORKDIR /app
8
+
9
+ COPY --chown=user ./requirements.txt requirements.txt
10
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
11
+
12
+ COPY --chown=user . /app
13
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
README.md CHANGED
@@ -1,10 +1,8 @@
1
  ---
2
  title: Cheat Key
3
- emoji: 🌍
4
- colorFrom: gray
5
- colorTo: red
6
  sdk: docker
7
  pinned: false
8
  ---
9
-
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
  title: Cheat Key
3
+ emoji: πŸ”‘
4
+ colorFrom: purple
5
+ colorTo: blue
6
  sdk: docker
7
  pinned: false
8
  ---
 
 
app.py ADDED
@@ -0,0 +1,736 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ArianKing CS2 β€” License Key Server
3
+ Runs on HuggingFace Spaces (Docker SDK)
4
+ """
5
+
6
+ from fastapi import FastAPI, HTTPException
7
+ from fastapi.responses import HTMLResponse
8
+ from pydantic import BaseModel
9
+ import json, os, secrets, string, time
10
+ from datetime import datetime, timedelta
11
+ from pathlib import Path
12
+ from threading import Lock
13
+
14
+ app = FastAPI(title="ArianKing Key Server")
15
+
16
+ # ── Storage ──────────────────────────────────────────────────────────────────
17
+ # HuggingFace persistent storage is at /data (enable in Space settings)
18
+ # Falls back to current dir if /data doesn't exist
19
+ DATA_DIR = Path("/data") if Path("/data").exists() else Path(".")
20
+ KEYS_FILE = DATA_DIR / "keys.json"
21
+ file_lock = Lock()
22
+
23
+ # Admin password β€” change this or set ADMIN_PASSWORD env var
24
+ ADMIN_PASSWORD = os.environ.get("ADMIN_PASSWORD", "ArianKing2026")
25
+
26
+
27
+ # ── Models ───────────────────────────────────────────────────────────────────
28
+ class CreateKeyRequest(BaseModel):
29
+ admin_password: str
30
+ days: int = 30
31
+ label: str = ""
32
+
33
+ class ToggleKeyRequest(BaseModel):
34
+ admin_password: str
35
+ key: str
36
+ active: bool
37
+
38
+ class DeleteKeyRequest(BaseModel):
39
+ admin_password: str
40
+ key: str
41
+
42
+ class ListKeysRequest(BaseModel):
43
+ admin_password: str
44
+
45
+ class ValidateRequest(BaseModel):
46
+ key: str
47
+ hwid: str
48
+
49
+
50
+ # ── Helpers ──────────────────────────────────────────────────────────────────
51
+ def load_keys() -> dict:
52
+ if KEYS_FILE.exists():
53
+ with open(KEYS_FILE, "r") as f:
54
+ return json.load(f)
55
+ return {}
56
+
57
+ def save_keys(keys: dict):
58
+ with file_lock:
59
+ with open(KEYS_FILE, "w") as f:
60
+ json.dump(keys, f, indent=2)
61
+
62
+ def generate_key() -> str:
63
+ """Generate key like ARIAN-XXXX-XXXX-XXXX"""
64
+ chars = string.ascii_uppercase + string.digits
65
+ parts = ["".join(secrets.choice(chars) for _ in range(4)) for _ in range(3)]
66
+ return f"ARIAN-{parts[0]}-{parts[1]}-{parts[2]}"
67
+
68
+ def check_admin(password: str):
69
+ if password != ADMIN_PASSWORD:
70
+ raise HTTPException(status_code=403, detail="Invalid admin password")
71
+
72
+
73
+ # ── API Endpoints ────────────────────────────────────────────────────────────
74
+
75
+ @app.post("/api/create-key")
76
+ def create_key(req: CreateKeyRequest):
77
+ check_admin(req.admin_password)
78
+
79
+ key = generate_key()
80
+ now = datetime.utcnow()
81
+ expires = now + timedelta(days=req.days)
82
+
83
+ keys = load_keys()
84
+ keys[key] = {
85
+ "created": now.isoformat(),
86
+ "expires": expires.isoformat(),
87
+ "days": req.days,
88
+ "label": req.label,
89
+ "active": True,
90
+ "hwid": None, # bound on first use
91
+ "last_used": None,
92
+ "uses": 0
93
+ }
94
+ save_keys(keys)
95
+
96
+ return {"success": True, "key": key, "expires": expires.isoformat(), "days": req.days}
97
+
98
+
99
+ @app.post("/api/validate")
100
+ def validate_key(req: ValidateRequest):
101
+ """Called by the DLL to check if a key is valid + bind HWID"""
102
+ keys = load_keys()
103
+
104
+ if req.key not in keys:
105
+ return {"valid": False, "message": "Invalid key"}
106
+
107
+ entry = keys[req.key]
108
+
109
+ if not entry["active"]:
110
+ return {"valid": False, "message": "Key deactivated"}
111
+
112
+ # Check expiration
113
+ expires = datetime.fromisoformat(entry["expires"])
114
+ if datetime.utcnow() > expires:
115
+ return {"valid": False, "message": "Key expired"}
116
+
117
+ # HWID binding: first use binds the key to this hardware
118
+ if entry["hwid"] is None:
119
+ entry["hwid"] = req.hwid
120
+ elif entry["hwid"] != req.hwid:
121
+ return {"valid": False, "message": "Key bound to different device"}
122
+
123
+ # Update usage
124
+ entry["last_used"] = datetime.utcnow().isoformat()
125
+ entry["uses"] += 1
126
+ keys[req.key] = entry
127
+ save_keys(keys)
128
+
129
+ # Calculate remaining time
130
+ remaining = expires - datetime.utcnow()
131
+ days_left = max(0, remaining.days)
132
+ hours_left = max(0, remaining.seconds // 3600)
133
+
134
+ return {
135
+ "valid": True,
136
+ "message": f"OK|{days_left}d {hours_left}h remaining",
137
+ "days_left": days_left,
138
+ "expires": entry["expires"]
139
+ }
140
+
141
+
142
+ @app.post("/api/toggle-key")
143
+ def toggle_key(req: ToggleKeyRequest):
144
+ check_admin(req.admin_password)
145
+
146
+ keys = load_keys()
147
+ if req.key not in keys:
148
+ raise HTTPException(status_code=404, detail="Key not found")
149
+
150
+ keys[req.key]["active"] = req.active
151
+ save_keys(keys)
152
+ return {"success": True, "key": req.key, "active": req.active}
153
+
154
+
155
+ @app.post("/api/delete-key")
156
+ def delete_key(req: DeleteKeyRequest):
157
+ check_admin(req.admin_password)
158
+
159
+ keys = load_keys()
160
+ if req.key not in keys:
161
+ raise HTTPException(status_code=404, detail="Key not found")
162
+
163
+ del keys[req.key]
164
+ save_keys(keys)
165
+ return {"success": True}
166
+
167
+
168
+ @app.post("/api/reset-hwid")
169
+ def reset_hwid(req: DeleteKeyRequest):
170
+ """Reset HWID binding so key can be used on a new device"""
171
+ check_admin(req.admin_password)
172
+
173
+ keys = load_keys()
174
+ if req.key not in keys:
175
+ raise HTTPException(status_code=404, detail="Key not found")
176
+
177
+ keys[req.key]["hwid"] = None
178
+ save_keys(keys)
179
+ return {"success": True, "key": req.key}
180
+
181
+
182
+ @app.post("/api/list-keys")
183
+ def list_keys(req: ListKeysRequest):
184
+ check_admin(req.admin_password)
185
+ keys = load_keys()
186
+
187
+ result = []
188
+ now = datetime.utcnow()
189
+ for key, data in keys.items():
190
+ expires = datetime.fromisoformat(data["expires"])
191
+ remaining = expires - now
192
+ days_left = max(0, remaining.days) if remaining.total_seconds() > 0 else 0
193
+ expired = now > expires
194
+
195
+ result.append({
196
+ "key": key,
197
+ "label": data.get("label", ""),
198
+ "days": data["days"],
199
+ "days_left": days_left,
200
+ "expired": expired,
201
+ "active": data["active"],
202
+ "hwid": data["hwid"],
203
+ "created": data["created"],
204
+ "expires": data["expires"],
205
+ "last_used": data.get("last_used"),
206
+ "uses": data.get("uses", 0)
207
+ })
208
+
209
+ # Sort: active first, then by creation date
210
+ result.sort(key=lambda x: (not x["active"], x["expired"], x["created"]), reverse=False)
211
+ return {"keys": result, "total": len(result)}
212
+
213
+
214
+ # ── Admin Panel (HTML) ───────────────────────────────────────────────────────
215
+
216
+ ADMIN_HTML = """<!DOCTYPE html>
217
+ <html lang="en">
218
+ <head>
219
+ <meta charset="UTF-8">
220
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
221
+ <title>ArianKing - Key Manager</title>
222
+ <style>
223
+ * { margin: 0; padding: 0; box-sizing: border-box; }
224
+ body {
225
+ background: #0a0a0f;
226
+ color: #e0e0e8;
227
+ font-family: 'Segoe UI', system-ui, sans-serif;
228
+ min-height: 100vh;
229
+ }
230
+
231
+ /* Header */
232
+ .header {
233
+ background: linear-gradient(135deg, #7832ff 0%, #2878ff 100%);
234
+ padding: 20px 30px;
235
+ display: flex;
236
+ align-items: center;
237
+ justify-content: space-between;
238
+ box-shadow: 0 4px 20px rgba(120, 50, 255, 0.3);
239
+ }
240
+ .header h1 {
241
+ font-size: 24px;
242
+ font-weight: 700;
243
+ color: white;
244
+ text-shadow: 0 2px 4px rgba(0,0,0,0.3);
245
+ }
246
+ .header span {
247
+ color: rgba(255,255,255,0.7);
248
+ font-size: 14px;
249
+ }
250
+
251
+ /* Login */
252
+ .login-container {
253
+ max-width: 400px;
254
+ margin: 80px auto;
255
+ padding: 30px;
256
+ background: #12121a;
257
+ border-radius: 12px;
258
+ border: 1px solid #1e1e30;
259
+ }
260
+ .login-container h2 {
261
+ color: #8b5cf6;
262
+ margin-bottom: 20px;
263
+ text-align: center;
264
+ }
265
+
266
+ /* Main */
267
+ .container {
268
+ max-width: 1100px;
269
+ margin: 20px auto;
270
+ padding: 0 20px;
271
+ }
272
+
273
+ /* Cards */
274
+ .card {
275
+ background: #12121a;
276
+ border-radius: 10px;
277
+ padding: 20px;
278
+ margin-bottom: 16px;
279
+ border: 1px solid #1e1e30;
280
+ }
281
+ .card h3 {
282
+ color: #8b5cf6;
283
+ margin-bottom: 12px;
284
+ font-size: 16px;
285
+ }
286
+
287
+ /* Inputs */
288
+ input, select {
289
+ background: #1a1a28;
290
+ border: 1px solid #2a2a40;
291
+ color: #e0e0e8;
292
+ padding: 10px 14px;
293
+ border-radius: 6px;
294
+ font-size: 14px;
295
+ width: 100%;
296
+ outline: none;
297
+ transition: border-color 0.2s;
298
+ }
299
+ input:focus, select:focus {
300
+ border-color: #7832ff;
301
+ }
302
+ .input-group {
303
+ margin-bottom: 12px;
304
+ }
305
+ .input-group label {
306
+ display: block;
307
+ margin-bottom: 4px;
308
+ color: #888;
309
+ font-size: 12px;
310
+ text-transform: uppercase;
311
+ letter-spacing: 1px;
312
+ }
313
+ .input-row {
314
+ display: flex;
315
+ gap: 12px;
316
+ }
317
+ .input-row > * {
318
+ flex: 1;
319
+ }
320
+
321
+ /* Buttons */
322
+ .btn {
323
+ padding: 10px 20px;
324
+ border: none;
325
+ border-radius: 6px;
326
+ font-size: 14px;
327
+ font-weight: 600;
328
+ cursor: pointer;
329
+ transition: all 0.2s;
330
+ color: white;
331
+ }
332
+ .btn-primary {
333
+ background: linear-gradient(135deg, #7832ff, #5a20d0);
334
+ }
335
+ .btn-primary:hover {
336
+ background: linear-gradient(135deg, #8b45ff, #6b30e0);
337
+ box-shadow: 0 4px 15px rgba(120, 50, 255, 0.4);
338
+ }
339
+ .btn-danger {
340
+ background: #dc2626;
341
+ }
342
+ .btn-danger:hover {
343
+ background: #ef4444;
344
+ }
345
+ .btn-success {
346
+ background: #16a34a;
347
+ }
348
+ .btn-success:hover {
349
+ background: #22c55e;
350
+ }
351
+ .btn-warning {
352
+ background: #d97706;
353
+ }
354
+ .btn-warning:hover {
355
+ background: #f59e0b;
356
+ }
357
+ .btn-sm {
358
+ padding: 6px 12px;
359
+ font-size: 12px;
360
+ }
361
+
362
+ /* Table */
363
+ .keys-table {
364
+ width: 100%;
365
+ border-collapse: collapse;
366
+ }
367
+ .keys-table th {
368
+ text-align: left;
369
+ padding: 10px;
370
+ color: #888;
371
+ font-size: 11px;
372
+ text-transform: uppercase;
373
+ letter-spacing: 1px;
374
+ border-bottom: 1px solid #1e1e30;
375
+ }
376
+ .keys-table td {
377
+ padding: 10px;
378
+ border-bottom: 1px solid #1a1a28;
379
+ font-size: 13px;
380
+ }
381
+ .keys-table tr:hover td {
382
+ background: #1a1a28;
383
+ }
384
+
385
+ /* Badges */
386
+ .badge {
387
+ display: inline-block;
388
+ padding: 3px 8px;
389
+ border-radius: 4px;
390
+ font-size: 11px;
391
+ font-weight: 600;
392
+ }
393
+ .badge-active {
394
+ background: rgba(22, 163, 74, 0.2);
395
+ color: #4ade80;
396
+ }
397
+ .badge-inactive {
398
+ background: rgba(220, 38, 38, 0.2);
399
+ color: #f87171;
400
+ }
401
+ .badge-expired {
402
+ background: rgba(217, 119, 6, 0.2);
403
+ color: #fbbf24;
404
+ }
405
+
406
+ .key-text {
407
+ font-family: 'Consolas', 'Courier New', monospace;
408
+ color: #c4b5fd;
409
+ font-size: 13px;
410
+ cursor: pointer;
411
+ }
412
+ .key-text:hover {
413
+ color: #8b5cf6;
414
+ }
415
+
416
+ .hwid-text {
417
+ font-family: monospace;
418
+ font-size: 11px;
419
+ color: #666;
420
+ max-width: 120px;
421
+ overflow: hidden;
422
+ text-overflow: ellipsis;
423
+ white-space: nowrap;
424
+ }
425
+
426
+ .stats {
427
+ display: flex;
428
+ gap: 16px;
429
+ margin-bottom: 16px;
430
+ }
431
+ .stat-box {
432
+ background: #12121a;
433
+ border: 1px solid #1e1e30;
434
+ border-radius: 8px;
435
+ padding: 16px 20px;
436
+ flex: 1;
437
+ text-align: center;
438
+ }
439
+ .stat-box .number {
440
+ font-size: 28px;
441
+ font-weight: 700;
442
+ color: #8b5cf6;
443
+ }
444
+ .stat-box .label {
445
+ font-size: 12px;
446
+ color: #666;
447
+ margin-top: 4px;
448
+ }
449
+
450
+ .toast {
451
+ position: fixed;
452
+ top: 20px;
453
+ right: 20px;
454
+ background: #16a34a;
455
+ color: white;
456
+ padding: 12px 20px;
457
+ border-radius: 8px;
458
+ font-size: 14px;
459
+ display: none;
460
+ z-index: 1000;
461
+ box-shadow: 0 4px 15px rgba(0,0,0,0.3);
462
+ }
463
+ .toast.error {
464
+ background: #dc2626;
465
+ }
466
+
467
+ .actions {
468
+ display: flex;
469
+ gap: 4px;
470
+ }
471
+
472
+ .hidden { display: none; }
473
+
474
+ /* Scrollbar */
475
+ ::-webkit-scrollbar { width: 8px; }
476
+ ::-webkit-scrollbar-track { background: #0a0a0f; }
477
+ ::-webkit-scrollbar-thumb { background: #2a2a40; border-radius: 4px; }
478
+ ::-webkit-scrollbar-thumb:hover { background: #3a3a55; }
479
+
480
+ .overflow-x { overflow-x: auto; }
481
+ </style>
482
+ </head>
483
+ <body>
484
+
485
+ <div class="header">
486
+ <h1>ArianKing</h1>
487
+ <span id="headerSub">Key Management System</span>
488
+ </div>
489
+
490
+ <div id="toast" class="toast"></div>
491
+
492
+ <!-- Login Screen -->
493
+ <div id="loginScreen" class="login-container">
494
+ <h2>Admin Login</h2>
495
+ <div class="input-group">
496
+ <label>Password</label>
497
+ <input type="password" id="passwordInput" placeholder="Enter admin password..."
498
+ onkeydown="if(event.key==='Enter')login()">
499
+ </div>
500
+ <button class="btn btn-primary" style="width:100%;margin-top:8px" onclick="login()">Login</button>
501
+ </div>
502
+
503
+ <!-- Main Dashboard -->
504
+ <div id="dashboard" class="container hidden">
505
+
506
+ <!-- Stats -->
507
+ <div class="stats">
508
+ <div class="stat-box">
509
+ <div class="number" id="statTotal">0</div>
510
+ <div class="label">Total Keys</div>
511
+ </div>
512
+ <div class="stat-box">
513
+ <div class="number" id="statActive">0</div>
514
+ <div class="label">Active</div>
515
+ </div>
516
+ <div class="stat-box">
517
+ <div class="number" id="statBound">0</div>
518
+ <div class="label">HWID Bound</div>
519
+ </div>
520
+ <div class="stat-box">
521
+ <div class="number" id="statExpired">0</div>
522
+ <div class="label">Expired</div>
523
+ </div>
524
+ </div>
525
+
526
+ <!-- Create Key -->
527
+ <div class="card">
528
+ <h3>Create New Key</h3>
529
+ <div class="input-row">
530
+ <div class="input-group">
531
+ <label>Duration (Days)</label>
532
+ <input type="number" id="keyDays" value="30" min="1" max="365">
533
+ </div>
534
+ <div class="input-group">
535
+ <label>Label (optional)</label>
536
+ <input type="text" id="keyLabel" placeholder="e.g. Customer name...">
537
+ </div>
538
+ <div style="display:flex;align-items:flex-end">
539
+ <button class="btn btn-primary" onclick="createKey()">Create Key</button>
540
+ </div>
541
+ </div>
542
+ <div id="newKeyResult" class="hidden" style="margin-top:12px;padding:12px;background:#1a1a28;border-radius:6px">
543
+ <span style="color:#888">New Key:</span>
544
+ <span id="newKeyText" class="key-text" style="font-size:18px;margin-left:8px"></span>
545
+ <button class="btn btn-sm btn-primary" style="margin-left:12px" onclick="copyKey()">Copy</button>
546
+ </div>
547
+ </div>
548
+
549
+ <!-- Keys List -->
550
+ <div class="card">
551
+ <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">
552
+ <h3 style="margin:0">License Keys</h3>
553
+ <button class="btn btn-sm btn-primary" onclick="loadKeys()">Refresh</button>
554
+ </div>
555
+ <div class="overflow-x">
556
+ <table class="keys-table">
557
+ <thead>
558
+ <tr>
559
+ <th>Key</th>
560
+ <th>Label</th>
561
+ <th>Status</th>
562
+ <th>Days Left</th>
563
+ <th>HWID</th>
564
+ <th>Uses</th>
565
+ <th>Actions</th>
566
+ </tr>
567
+ </thead>
568
+ <tbody id="keysBody">
569
+ <tr><td colspan="7" style="text-align:center;color:#666">Loading...</td></tr>
570
+ </tbody>
571
+ </table>
572
+ </div>
573
+ </div>
574
+ </div>
575
+
576
+ <script>
577
+ let adminPassword = '';
578
+
579
+ function showToast(msg, isError) {
580
+ const t = document.getElementById('toast');
581
+ t.textContent = msg;
582
+ t.className = 'toast' + (isError ? ' error' : '');
583
+ t.style.display = 'block';
584
+ setTimeout(() => t.style.display = 'none', 3000);
585
+ }
586
+
587
+ async function api(endpoint, body) {
588
+ const res = await fetch('/api/' + endpoint, {
589
+ method: 'POST',
590
+ headers: { 'Content-Type': 'application/json' },
591
+ body: JSON.stringify(body)
592
+ });
593
+ if (!res.ok) {
594
+ const err = await res.json();
595
+ throw new Error(err.detail || 'Request failed');
596
+ }
597
+ return res.json();
598
+ }
599
+
600
+ async function login() {
601
+ adminPassword = document.getElementById('passwordInput').value;
602
+ try {
603
+ await api('list-keys', { admin_password: adminPassword });
604
+ document.getElementById('loginScreen').classList.add('hidden');
605
+ document.getElementById('dashboard').classList.remove('hidden');
606
+ loadKeys();
607
+ } catch(e) {
608
+ showToast('Invalid password', true);
609
+ adminPassword = '';
610
+ }
611
+ }
612
+
613
+ async function loadKeys() {
614
+ try {
615
+ const data = await api('list-keys', { admin_password: adminPassword });
616
+ const keys = data.keys;
617
+
618
+ // Stats
619
+ document.getElementById('statTotal').textContent = keys.length;
620
+ document.getElementById('statActive').textContent = keys.filter(k => k.active && !k.expired).length;
621
+ document.getElementById('statBound').textContent = keys.filter(k => k.hwid).length;
622
+ document.getElementById('statExpired').textContent = keys.filter(k => k.expired).length;
623
+
624
+ // Table
625
+ const tbody = document.getElementById('keysBody');
626
+ if (keys.length === 0) {
627
+ tbody.innerHTML = '<tr><td colspan="7" style="text-align:center;color:#666">No keys yet. Create one above.</td></tr>';
628
+ return;
629
+ }
630
+
631
+ tbody.innerHTML = keys.map(k => {
632
+ let statusBadge;
633
+ if (!k.active) statusBadge = '<span class="badge badge-inactive">Disabled</span>';
634
+ else if (k.expired) statusBadge = '<span class="badge badge-expired">Expired</span>';
635
+ else statusBadge = '<span class="badge badge-active">Active</span>';
636
+
637
+ const hwid = k.hwid
638
+ ? `<span class="hwid-text" title="${k.hwid}">${k.hwid.substring(0,16)}...</span>`
639
+ : '<span style="color:#444">Unbound</span>';
640
+
641
+ const toggleBtn = k.active
642
+ ? `<button class="btn btn-sm btn-warning" onclick="toggleKey('${k.key}',false)">Disable</button>`
643
+ : `<button class="btn btn-sm btn-success" onclick="toggleKey('${k.key}',true)">Enable</button>`;
644
+
645
+ const resetBtn = k.hwid
646
+ ? `<button class="btn btn-sm btn-primary" onclick="resetHwid('${k.key}')">Reset HWID</button>`
647
+ : '';
648
+
649
+ return `<tr>
650
+ <td><span class="key-text" onclick="navigator.clipboard.writeText('${k.key}');showToast('Copied!')" title="Click to copy">${k.key}</span></td>
651
+ <td>${k.label || '-'}</td>
652
+ <td>${statusBadge}</td>
653
+ <td>${k.expired ? '0' : k.days_left + 'd'}</td>
654
+ <td>${hwid}</td>
655
+ <td>${k.uses}</td>
656
+ <td class="actions">
657
+ ${toggleBtn}
658
+ ${resetBtn}
659
+ <button class="btn btn-sm btn-danger" onclick="deleteKey('${k.key}')">Delete</button>
660
+ </td>
661
+ </tr>`;
662
+ }).join('');
663
+ } catch(e) {
664
+ showToast('Failed to load keys: ' + e.message, true);
665
+ }
666
+ }
667
+
668
+ async function createKey() {
669
+ const days = parseInt(document.getElementById('keyDays').value) || 30;
670
+ const label = document.getElementById('keyLabel').value;
671
+ try {
672
+ const data = await api('create-key', {
673
+ admin_password: adminPassword,
674
+ days: days,
675
+ label: label
676
+ });
677
+ document.getElementById('newKeyText').textContent = data.key;
678
+ document.getElementById('newKeyResult').classList.remove('hidden');
679
+ showToast('Key created: ' + data.key);
680
+ loadKeys();
681
+ } catch(e) {
682
+ showToast('Failed: ' + e.message, true);
683
+ }
684
+ }
685
+
686
+ function copyKey() {
687
+ const key = document.getElementById('newKeyText').textContent;
688
+ navigator.clipboard.writeText(key);
689
+ showToast('Key copied to clipboard!');
690
+ }
691
+
692
+ async function toggleKey(key, active) {
693
+ try {
694
+ await api('toggle-key', { admin_password: adminPassword, key: key, active: active });
695
+ showToast(active ? 'Key enabled' : 'Key disabled');
696
+ loadKeys();
697
+ } catch(e) {
698
+ showToast('Failed: ' + e.message, true);
699
+ }
700
+ }
701
+
702
+ async function resetHwid(key) {
703
+ if (!confirm('Reset HWID for ' + key + '? This allows the key to be used on a new device.')) return;
704
+ try {
705
+ await api('reset-hwid', { admin_password: adminPassword, key: key });
706
+ showToast('HWID reset');
707
+ loadKeys();
708
+ } catch(e) {
709
+ showToast('Failed: ' + e.message, true);
710
+ }
711
+ }
712
+
713
+ async function deleteKey(key) {
714
+ if (!confirm('Delete key ' + key + '? This cannot be undone.')) return;
715
+ try {
716
+ await api('delete-key', { admin_password: adminPassword, key: key });
717
+ showToast('Key deleted');
718
+ loadKeys();
719
+ } catch(e) {
720
+ showToast('Failed: ' + e.message, true);
721
+ }
722
+ }
723
+ </script>
724
+ </body>
725
+ </html>"""
726
+
727
+
728
+ @app.get("/", response_class=HTMLResponse)
729
+ def admin_panel():
730
+ return ADMIN_HTML
731
+
732
+
733
+ # ── Health check ─────────────────────────────────────────────────────────────
734
+ @app.get("/api/health")
735
+ def health():
736
+ return {"status": "ok", "service": "ArianKing Key Server"}
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastapi
2
+ uvicorn[standard]