Delete admin_panel.py
Browse files- admin_panel.py +0 -1221
admin_panel.py
DELETED
|
@@ -1,1221 +0,0 @@
|
|
| 1 |
-
# ══════════════════════════════════════════════════════════════════
|
| 2 |
-
# admin_panel.py — Web-based admin dashboard
|
| 3 |
-
#
|
| 4 |
-
# Mounted at /admin/* by app.py.
|
| 5 |
-
#
|
| 6 |
-
# Auth:
|
| 7 |
-
# • Form-based login → /admin/login (POST) validates ADMIN_TOKEN
|
| 8 |
-
# • Cookie `admin_session` = "expiry.hmac(ADMIN_TOKEN, expiry)[:32]"
|
| 9 |
-
# → stateless, survives worker restarts, works across processes
|
| 10 |
-
# • Rate-limited login (5 attempts / 15 min / IP)
|
| 11 |
-
# • CSRF mitigation: Origin/Referer host check on POST
|
| 12 |
-
#
|
| 13 |
-
# Pages:
|
| 14 |
-
# /admin → redirect
|
| 15 |
-
# /admin/login → login form
|
| 16 |
-
# /admin/dashboard → live stats + API health + recent activity
|
| 17 |
-
# /admin/users → paginated user list + ban/unban
|
| 18 |
-
# /admin/logs → activity log with filters + CSV export
|
| 19 |
-
# /admin/bans → banned users + reasons
|
| 20 |
-
# /admin/config → env config view (masked) + feature toggles
|
| 21 |
-
# /admin/broadcast → send message to all users
|
| 22 |
-
# /admin/maintenance → toggle maintenance mode
|
| 23 |
-
# /admin/logout → clear cookie
|
| 24 |
-
#
|
| 25 |
-
# JSON API:
|
| 26 |
-
# GET /admin/api/stats
|
| 27 |
-
# GET /admin/api/users
|
| 28 |
-
# GET /admin/api/logs
|
| 29 |
-
# GET /admin/api/bans
|
| 30 |
-
# GET /admin/api/apistatus
|
| 31 |
-
# GET /admin/api/export
|
| 32 |
-
# POST /admin/api/ban
|
| 33 |
-
# POST /admin/api/unban
|
| 34 |
-
# POST /admin/api/maintenance
|
| 35 |
-
# POST /admin/api/broadcast
|
| 36 |
-
# POST /admin/api/backup
|
| 37 |
-
#
|
| 38 |
-
# Pure f-string HTML + inline CSS/JS. No Jinja, no external deps.
|
| 39 |
-
# ══════════════════════════════════════════════════════════════════
|
| 40 |
-
|
| 41 |
-
import asyncio
|
| 42 |
-
import csv
|
| 43 |
-
import hashlib
|
| 44 |
-
import hmac
|
| 45 |
-
import html
|
| 46 |
-
import io
|
| 47 |
-
import json
|
| 48 |
-
import logging
|
| 49 |
-
import threading
|
| 50 |
-
import time
|
| 51 |
-
from collections import deque
|
| 52 |
-
from typing import Optional
|
| 53 |
-
|
| 54 |
-
from fastapi import Request
|
| 55 |
-
from fastapi.responses import (
|
| 56 |
-
HTMLResponse, JSONResponse, RedirectResponse, Response,
|
| 57 |
-
)
|
| 58 |
-
from starlette.routing import Route as StarletteRoute
|
| 59 |
-
|
| 60 |
-
import config
|
| 61 |
-
import bot
|
| 62 |
-
import engine
|
| 63 |
-
|
| 64 |
-
log = logging.getLogger("admin")
|
| 65 |
-
|
| 66 |
-
COOKIE_NAME = "admin_session"
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
# ══════════════════════════════════════════════════════════════════
|
| 70 |
-
# 1. AUTH — HMAC cookie, rate limit, CSRF
|
| 71 |
-
# ══════════════════════════════════════════════════════════════════
|
| 72 |
-
_login_attempts = {} # ip -> [ts, ts, ...]
|
| 73 |
-
_login_lock = threading.Lock()
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
def _make_cookie() -> str:
|
| 77 |
-
expiry = int(time.time()) + config.ADMIN_SESSION_TTL
|
| 78 |
-
sig = hmac.new(
|
| 79 |
-
config.ADMIN_TOKEN.encode(),
|
| 80 |
-
str(expiry).encode(),
|
| 81 |
-
hashlib.sha256,
|
| 82 |
-
).hexdigest()[:32]
|
| 83 |
-
return f"{expiry}.{sig}"
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
def _verify_cookie(val: str) -> bool:
|
| 87 |
-
if not val or "." not in val or not config.ADMIN_TOKEN:
|
| 88 |
-
return False
|
| 89 |
-
try:
|
| 90 |
-
expiry_str, sig = val.split(".", 1)
|
| 91 |
-
expiry = int(expiry_str)
|
| 92 |
-
except Exception:
|
| 93 |
-
return False
|
| 94 |
-
if expiry < time.time():
|
| 95 |
-
return False
|
| 96 |
-
expected = hmac.new(
|
| 97 |
-
config.ADMIN_TOKEN.encode(),
|
| 98 |
-
expiry_str.encode(),
|
| 99 |
-
hashlib.sha256,
|
| 100 |
-
).hexdigest()[:32]
|
| 101 |
-
return hmac.compare_digest(sig, expected)
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
def _is_authed(request: Request) -> bool:
|
| 105 |
-
if not config.ADMIN_TOKEN:
|
| 106 |
-
return False
|
| 107 |
-
return _verify_cookie(request.cookies.get(COOKIE_NAME, ""))
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
def _check_login_rate(ip: str) -> bool:
|
| 111 |
-
"""True = allowed, False = rate-limited."""
|
| 112 |
-
max_attempts, window = config.ADMIN_LOGIN_RATE
|
| 113 |
-
now = time.time()
|
| 114 |
-
with _login_lock:
|
| 115 |
-
dq = _login_attempts.setdefault(ip, [])
|
| 116 |
-
dq[:] = [t for t in dq if t > now - window]
|
| 117 |
-
if len(dq) >= max_attempts:
|
| 118 |
-
return False
|
| 119 |
-
dq.append(now)
|
| 120 |
-
return True
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
def _check_csrf(request: Request) -> bool:
|
| 124 |
-
"""Reject cross-origin POSTs. Non-browser clients (no Origin) allowed."""
|
| 125 |
-
origin = request.headers.get("origin") or request.headers.get("referer") or ""
|
| 126 |
-
if not origin:
|
| 127 |
-
return True
|
| 128 |
-
host = request.headers.get("host", "")
|
| 129 |
-
return bool(host and host in origin)
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
def _client_ip(request: Request) -> str:
|
| 133 |
-
fwd = request.headers.get("x-forwarded-for", "")
|
| 134 |
-
if fwd:
|
| 135 |
-
return fwd.split(",")[0].strip()
|
| 136 |
-
if request.client:
|
| 137 |
-
return request.client.host
|
| 138 |
-
return "?"
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
# ── Decorators ──
|
| 142 |
-
def authed_page(handler):
|
| 143 |
-
"""Page route — redirect to /admin/login if not authed."""
|
| 144 |
-
async def wrapper(request: Request):
|
| 145 |
-
if not _is_authed(request):
|
| 146 |
-
return RedirectResponse("/admin/login", status_code=303)
|
| 147 |
-
return await handler(request)
|
| 148 |
-
wrapper.__name__ = handler.__name__
|
| 149 |
-
return wrapper
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
def authed_api(handler):
|
| 153 |
-
"""JSON API — 401 if not authed."""
|
| 154 |
-
async def wrapper(request: Request):
|
| 155 |
-
if not _is_authed(request):
|
| 156 |
-
return JSONResponse({"error": "unauthorized"}, status_code=401)
|
| 157 |
-
if request.method == "POST" and not _check_csrf(request):
|
| 158 |
-
return JSONResponse({"error": "csrf"}, status_code=403)
|
| 159 |
-
return await handler(request)
|
| 160 |
-
wrapper.__name__ = handler.__name__
|
| 161 |
-
return wrapper
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
# ══════════════════════════════════════════════════════════════════
|
| 165 |
-
# 2. HELPERS
|
| 166 |
-
# ══════════════════════════════════════════════════════════════════
|
| 167 |
-
def _esc(x) -> str:
|
| 168 |
-
if x is None:
|
| 169 |
-
return ""
|
| 170 |
-
return html.escape(str(x), quote=False)
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
def _fmt_ts(ts: float) -> str:
|
| 174 |
-
return time.strftime("%H:%M:%S", time.localtime(ts))
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
def _fmt_dt(ts: float) -> str:
|
| 178 |
-
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts))
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
def _mask(secret: str, keep: int = 4) -> str:
|
| 182 |
-
if not secret:
|
| 183 |
-
return "(empty)"
|
| 184 |
-
if len(secret) <= keep * 2:
|
| 185 |
-
return "*" * len(secret)
|
| 186 |
-
return secret[:keep] + "*" * (len(secret) - keep * 2) + secret[-keep:]
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
# ── Cached API health (avoids hammering endpoints every refresh) ──
|
| 190 |
-
_health_cache = {"ts": 0.0, "data": {}}
|
| 191 |
-
_health_lock = threading.Lock()
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
async def _get_api_health_cached() -> dict:
|
| 195 |
-
now = time.time()
|
| 196 |
-
with _health_lock:
|
| 197 |
-
if now - _health_cache["ts"] < config.API_HEALTH_INTERVAL:
|
| 198 |
-
return _health_cache["data"]
|
| 199 |
-
try:
|
| 200 |
-
data = await engine.check_api_health()
|
| 201 |
-
with _health_lock:
|
| 202 |
-
_health_cache["ts"] = now
|
| 203 |
-
_health_cache["data"] = data
|
| 204 |
-
return data
|
| 205 |
-
except Exception as e:
|
| 206 |
-
log.warning(f"[health] {e!r}")
|
| 207 |
-
return {}
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
# ══════════════════════════════════════════════════════════════════
|
| 211 |
-
# 3. HTML TEMPLATE + CSS
|
| 212 |
-
# ══════════════════════════════════════════════════════════════════
|
| 213 |
-
_CSS = """
|
| 214 |
-
:root{--bg:#0d1117;--panel:#161b22;--border:#30363d;--text:#c9d1d9;--muted:#8b949e;--accent:#58a6ff;--green:#3fb950;--red:#f85149;--yellow:#d29922;--blue:#1f6feb}
|
| 215 |
-
*{box-sizing:border-box}
|
| 216 |
-
body{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;background:var(--bg);color:var(--text);line-height:1.5;font-size:14px}
|
| 217 |
-
a{color:var(--accent);text-decoration:none}
|
| 218 |
-
a:hover{text-decoration:underline}
|
| 219 |
-
nav{background:var(--panel);border-bottom:1px solid var(--border);padding:10px 24px;display:flex;flex-wrap:wrap;gap:4px;align-items:center}
|
| 220 |
-
nav a{color:var(--text);padding:6px 12px;border-radius:6px;font-weight:500}
|
| 221 |
-
nav a:hover,nav a.active{background:#21262d;color:var(--accent);text-decoration:none}
|
| 222 |
-
nav .brand{font-weight:700;margin-right:16px;color:var(--accent)}
|
| 223 |
-
.container{max-width:1280px;margin:0 auto;padding:24px}
|
| 224 |
-
h1{font-size:22px;margin:0 0 20px 0;font-weight:600}
|
| 225 |
-
h2{font-size:13px;margin:24px 0 12px 0;color:var(--muted);text-transform:uppercase;letter-spacing:0.5px;font-weight:600}
|
| 226 |
-
.tiles{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px;margin-bottom:8px}
|
| 227 |
-
.tile{background:var(--panel);border:1px solid var(--border);border-radius:8px;padding:14px 16px}
|
| 228 |
-
.tile-label{color:var(--muted);font-size:11px;text-transform:uppercase;letter-spacing:0.5px;margin-bottom:6px;font-weight:600}
|
| 229 |
-
.tile-value{font-size:24px;font-weight:700;color:var(--accent);line-height:1.2}
|
| 230 |
-
.tile-value.green{color:var(--green)}.tile-value.red{color:var(--red)}.tile-value.yellow{color:var(--yellow)}
|
| 231 |
-
.panel{background:var(--panel);border:1px solid var(--border);border-radius:8px;padding:20px;margin-bottom:16px}
|
| 232 |
-
.panel.tight{padding:0;overflow-x:auto}
|
| 233 |
-
table{width:100%;border-collapse:collapse;font-size:13px}
|
| 234 |
-
th,td{text-align:left;padding:9px 12px;border-bottom:1px solid var(--border);vertical-align:top}
|
| 235 |
-
th{color:var(--muted);font-weight:600;font-size:11px;text-transform:uppercase;letter-spacing:0.3px;background:#0d1117}
|
| 236 |
-
tr:last-child td{border-bottom:none}
|
| 237 |
-
tr:hover td{background:#1c2128}
|
| 238 |
-
.btn{display:inline-block;background:var(--blue);color:#fff;border:none;padding:7px 14px;border-radius:6px;cursor:pointer;font-size:13px;font-weight:500;text-decoration:none}
|
| 239 |
-
.btn:hover{background:#388bfd;text-decoration:none}
|
| 240 |
-
.btn-red{background:var(--red)}.btn-red:hover{background:#da3633}
|
| 241 |
-
.btn-green{background:var(--green);color:#0d1117}.btn-green:hover{background:#56d364}
|
| 242 |
-
.btn-ghost{background:transparent;color:var(--text);border:1px solid var(--border)}
|
| 243 |
-
.btn-ghost:hover{background:#21262d;border-color:var(--accent)}
|
| 244 |
-
.btn-sm{padding:4px 10px;font-size:12px}
|
| 245 |
-
.badge{display:inline-block;padding:2px 8px;border-radius:12px;font-size:11px;font-weight:600}
|
| 246 |
-
.badge-green{background:rgba(63,185,80,0.15);color:var(--green)}
|
| 247 |
-
.badge-red{background:rgba(248,81,73,0.15);color:var(--red)}
|
| 248 |
-
.badge-yellow{background:rgba(210,153,34,0.15);color:var(--yellow)}
|
| 249 |
-
.badge-blue{background:rgba(88,166,255,0.15);color:var(--accent)}
|
| 250 |
-
.badge-gray{background:rgba(139,148,158,0.15);color:var(--muted)}
|
| 251 |
-
input,textarea,select{background:#0d1117;border:1px solid var(--border);color:var(--text);padding:8px 12px;border-radius:6px;font-family:inherit;font-size:13px;width:100%}
|
| 252 |
-
input:focus,textarea:focus{outline:none;border-color:var(--accent)}
|
| 253 |
-
textarea{min-height:120px;resize:vertical;font-family:inherit}
|
| 254 |
-
label{display:block;color:var(--muted);font-size:11px;text-transform:uppercase;letter-spacing:0.5px;margin:12px 0 6px 0;font-weight:600}
|
| 255 |
-
.pagination{display:flex;gap:8px;align-items:center;margin-top:16px}
|
| 256 |
-
.muted{color:var(--muted)}
|
| 257 |
-
.center{text-align:center}
|
| 258 |
-
.flash{padding:12px 16px;border-radius:6px;margin-bottom:16px}
|
| 259 |
-
.flash-err{background:rgba(248,81,73,0.1);border:1px solid var(--red);color:var(--red)}
|
| 260 |
-
.flash-ok{background:rgba(63,185,80,0.1);border:1px solid var(--green);color:var(--green)}
|
| 261 |
-
.flash-info{background:rgba(88,166,255,0.1);border:1px solid var(--accent);color:var(--accent)}
|
| 262 |
-
.health-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:10px}
|
| 263 |
-
.health-card{background:#0d1117;border:1px solid var(--border);border-radius:6px;padding:10px 12px}
|
| 264 |
-
.health-card.ok{border-color:var(--green)}
|
| 265 |
-
.health-card.fail{border-color:var(--red)}
|
| 266 |
-
.health-name{font-weight:600;font-size:13px;margin-bottom:3px}
|
| 267 |
-
.health-lat{color:var(--muted);font-size:11px}
|
| 268 |
-
code{background:#0d1117;padding:1px 6px;border-radius:4px;font-size:12px;border:1px solid var(--border)}
|
| 269 |
-
.form-row{margin-bottom:14px}
|
| 270 |
-
.form-actions{display:flex;gap:8px;margin-top:16px}
|
| 271 |
-
.kv{display:grid;grid-template-columns:200px 1fr;gap:8px 16px;font-size:13px}
|
| 272 |
-
.kv-key{color:var(--muted);font-weight:600}
|
| 273 |
-
.kv-val{word-break:break-all}
|
| 274 |
-
"""
|
| 275 |
-
|
| 276 |
-
_NAV_ITEMS = [
|
| 277 |
-
("dashboard", "/admin/dashboard", "📊 Dashboard"),
|
| 278 |
-
("users", "/admin/users", "👥 Users"),
|
| 279 |
-
("logs", "/admin/logs", "📜 Logs"),
|
| 280 |
-
("bans", "/admin/bans", "🚫 Bans"),
|
| 281 |
-
("broadcast", "/admin/broadcast", "📢 Broadcast"),
|
| 282 |
-
("maintenance", "/admin/maintenance", "🛠️ Maintenance"),
|
| 283 |
-
("config", "/admin/config", "⚙️ Config"),
|
| 284 |
-
("logout", "/admin/logout", "🚪 Logout"),
|
| 285 |
-
]
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
def _nav(active: str = "") -> str:
|
| 289 |
-
parts = [f'<span class="brand">🛡️ {config.BOT_NAME} Admin</span>']
|
| 290 |
-
for key, href, label in _NAV_ITEMS:
|
| 291 |
-
cls = "active" if key == active else ""
|
| 292 |
-
parts.append(f'<a class="{cls}" href="{href}">{label}</a>')
|
| 293 |
-
return f'<nav>{"".join(parts)}</nav>'
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
def _page(title: str, body: str,
|
| 297 |
-
extra_head: str = "", extra_js: str = "",
|
| 298 |
-
active_nav: str = "") -> str:
|
| 299 |
-
return f"""<!DOCTYPE html>
|
| 300 |
-
<html lang="en">
|
| 301 |
-
<head>
|
| 302 |
-
<meta charset="utf-8">
|
| 303 |
-
<meta name="viewport" content="width=device-width,initial-scale=1">
|
| 304 |
-
<title>{_esc(title)} · Admin</title>
|
| 305 |
-
<style>{_CSS}</style>
|
| 306 |
-
{extra_head}
|
| 307 |
-
</head>
|
| 308 |
-
<body>
|
| 309 |
-
{_nav(active_nav)}
|
| 310 |
-
<main class="container">
|
| 311 |
-
{body}
|
| 312 |
-
</main>
|
| 313 |
-
{extra_js}
|
| 314 |
-
</body>
|
| 315 |
-
</html>"""
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
# ══════════════════════════════════════════════════════════════════
|
| 319 |
-
# 4. LOGIN
|
| 320 |
-
# ══════════════════════════════════════════════════════════════════
|
| 321 |
-
def _login_html(error: str = "", info: str = "") -> str:
|
| 322 |
-
flash = ""
|
| 323 |
-
if error:
|
| 324 |
-
flash = f'<div class="flash flash-err">{_esc(error)}</div>'
|
| 325 |
-
elif info:
|
| 326 |
-
flash = f'<div class="flash flash-info">{_esc(info)}</div>'
|
| 327 |
-
body = f"""
|
| 328 |
-
<div style="max-width:420px;margin:60px auto">
|
| 329 |
-
<h1 style="text-align:center">🔐 Admin Login</h1>
|
| 330 |
-
{flash}
|
| 331 |
-
<form method="post" action="/admin/login" class="panel">
|
| 332 |
-
<label for="token">Admin Token</label>
|
| 333 |
-
<input type="password" name="token" id="token" autofocus required autocomplete="current-password">
|
| 334 |
-
<div class="form-actions">
|
| 335 |
-
<button class="btn" type="submit" style="width:100%">Sign In</button>
|
| 336 |
-
</div>
|
| 337 |
-
</form>
|
| 338 |
-
</div>
|
| 339 |
-
"""
|
| 340 |
-
return _page("Login", body)
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
async def login_page(request: Request):
|
| 344 |
-
# If already authed → dashboard
|
| 345 |
-
if _is_authed(request):
|
| 346 |
-
return RedirectResponse("/admin/dashboard", status_code=303)
|
| 347 |
-
if not config.ADMIN_TOKEN:
|
| 348 |
-
return HTMLResponse(_login_html(
|
| 349 |
-
error="ADMIN_TOKEN is not configured on the server."
|
| 350 |
-
), status_code=503)
|
| 351 |
-
if request.query_params.get("logout"):
|
| 352 |
-
return HTMLResponse(_login_html(info="Signed out."))
|
| 353 |
-
return HTMLResponse(_login_html())
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
async def login_submit(request: Request):
|
| 357 |
-
ip = _client_ip(request)
|
| 358 |
-
if not _check_login_rate(ip):
|
| 359 |
-
log.warning(f"[login] rate-limited IP {ip}")
|
| 360 |
-
return HTMLResponse(_login_html(
|
| 361 |
-
error="Too many attempts. Try again in 15 minutes."
|
| 362 |
-
), status_code=429)
|
| 363 |
-
if not _check_csrf(request):
|
| 364 |
-
return HTMLResponse(_login_html(error="Invalid origin."), status_code=403)
|
| 365 |
-
|
| 366 |
-
try:
|
| 367 |
-
form = await request.form()
|
| 368 |
-
token = (form.get("token") or "").strip()
|
| 369 |
-
except Exception:
|
| 370 |
-
token = ""
|
| 371 |
-
|
| 372 |
-
if not config.ADMIN_TOKEN:
|
| 373 |
-
return HTMLResponse(_login_html(error="ADMIN_TOKEN not set."), status_code=503)
|
| 374 |
-
|
| 375 |
-
if not token or not hmac.compare_digest(token, config.ADMIN_TOKEN):
|
| 376 |
-
log.info(f"[login] failed from {ip}")
|
| 377 |
-
return HTMLResponse(_login_html(error="Invalid token."), status_code=401)
|
| 378 |
-
|
| 379 |
-
log.info(f"[login] success from {ip}")
|
| 380 |
-
resp = RedirectResponse("/admin/dashboard", status_code=303)
|
| 381 |
-
resp.set_cookie(
|
| 382 |
-
COOKIE_NAME,
|
| 383 |
-
_make_cookie(),
|
| 384 |
-
max_age=config.ADMIN_SESSION_TTL,
|
| 385 |
-
httponly=True,
|
| 386 |
-
samesite="lax",
|
| 387 |
-
path="/admin",
|
| 388 |
-
)
|
| 389 |
-
return resp
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
async def logout(request: Request):
|
| 393 |
-
resp = RedirectResponse("/admin/login?logout=1", status_code=303)
|
| 394 |
-
resp.delete_cookie(COOKIE_NAME, path="/admin")
|
| 395 |
-
return resp
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
async def admin_root(request: Request):
|
| 399 |
-
if _is_authed(request):
|
| 400 |
-
return RedirectResponse("/admin/dashboard", status_code=303)
|
| 401 |
-
return RedirectResponse("/admin/login", status_code=303)
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
# ══════════════════════════════════════════════════════════════════
|
| 405 |
-
# 5. DASHBOARD
|
| 406 |
-
# ══════════════════════════════════════════════════════════════════
|
| 407 |
-
def _tile(label: str, value, element_id: str = "", extra_class: str = "") -> str:
|
| 408 |
-
id_attr = f'id="{element_id}"' if element_id else ""
|
| 409 |
-
return (
|
| 410 |
-
f'<div class="tile">'
|
| 411 |
-
f'<div class="tile-label">{_esc(label)}</div>'
|
| 412 |
-
f'<div class="tile-value {extra_class}" {id_attr}>{_esc(value)}</div>'
|
| 413 |
-
f'</div>'
|
| 414 |
-
)
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
@authed_page
|
| 418 |
-
async def dashboard(request: Request):
|
| 419 |
-
s = bot._get_stats()
|
| 420 |
-
health = await _get_api_health_cached()
|
| 421 |
-
m_on, m_reason = bot._get_maintenance()
|
| 422 |
-
uptime_min = (time.time() - bot.STATS["started"]) / 60
|
| 423 |
-
|
| 424 |
-
banner = ""
|
| 425 |
-
if m_on:
|
| 426 |
-
banner = (
|
| 427 |
-
f'<div class="flash flash-err">🔴 <b>Maintenance ON</b> — '
|
| 428 |
-
f'{_esc(m_reason or "(no reason)")}</div>'
|
| 429 |
-
)
|
| 430 |
-
|
| 431 |
-
tiles = (
|
| 432 |
-
_tile("Unique Users", s["unique_users"], "stat-users") +
|
| 433 |
-
_tile("Live Now", s["live_users"], "stat-live", "green") +
|
| 434 |
-
_tile("Searches Today", s["today_searches"], "stat-today") +
|
| 435 |
-
_tile("Total Searches", s["total_searches"], "stat-total") +
|
| 436 |
-
_tile("Banned", s["banned_count"], "stat-banned", "red") +
|
| 437 |
-
_tile("Cached", s["cached_searches"], "stat-cached") +
|
| 438 |
-
_tile("Backup Sent", s["backup_sent"], "stat-backup") +
|
| 439 |
-
_tile("Uptime", f"{uptime_min:.0f} min", "stat-uptime")
|
| 440 |
-
)
|
| 441 |
-
|
| 442 |
-
# API health grid
|
| 443 |
-
if health:
|
| 444 |
-
cards = []
|
| 445 |
-
for name, h in health.items():
|
| 446 |
-
cls = "ok" if h.get("ok") else "fail"
|
| 447 |
-
icon = "✅" if h.get("ok") else "❌"
|
| 448 |
-
lat = h.get("latency_ms", "?")
|
| 449 |
-
err = h.get("error", "")
|
| 450 |
-
cards.append(
|
| 451 |
-
f'<div class="health-card {cls}">'
|
| 452 |
-
f'<div class="health-name">{icon} {_esc(name)}</div>'
|
| 453 |
-
f'<div class="health-lat">{_esc(lat)}ms'
|
| 454 |
-
+ (f' · {_esc(err)[:60]}' if err else '') +
|
| 455 |
-
'</div></div>'
|
| 456 |
-
)
|
| 457 |
-
health_html = f'<div class="health-grid">{"".join(cards)}</div>'
|
| 458 |
-
else:
|
| 459 |
-
health_html = '<div class="muted">No health data yet — refreshing…</div>'
|
| 460 |
-
|
| 461 |
-
# Recent activity
|
| 462 |
-
with bot._activity_lock:
|
| 463 |
-
recent = list(bot.ACTIVITY_LOG)[-15:][::-1]
|
| 464 |
-
if recent:
|
| 465 |
-
rows = []
|
| 466 |
-
for e in recent:
|
| 467 |
-
uname = e.get("username") or e.get("first_name") or "(anon)"
|
| 468 |
-
rows.append(f"""<tr>
|
| 469 |
-
<td class="muted">{_esc(_fmt_ts(e['ts']))}</td>
|
| 470 |
-
<td>{_esc(uname)}<br><span class="muted">id {e['user_id']}</span></td>
|
| 471 |
-
<td><span class="badge badge-blue">{_esc(e['action'])}</span></td>
|
| 472 |
-
<td><code>{_esc((e['input'] or '-')[:30])}</code></td>
|
| 473 |
-
<td>{_esc((e.get('summary') or e.get('reply_type') or '-')[:80])}</td>
|
| 474 |
-
<td class="muted">{e.get('elapsed_ms', 0)}ms</td>
|
| 475 |
-
</tr>""")
|
| 476 |
-
activity_html = (
|
| 477 |
-
'<div class="panel tight">'
|
| 478 |
-
'<table><tr><th>Time</th><th>User</th><th>Action</th>'
|
| 479 |
-
'<th>Input</th><th>Result</th><th>Time</th></tr>'
|
| 480 |
-
+ "".join(rows) +
|
| 481 |
-
'</table></div>'
|
| 482 |
-
)
|
| 483 |
-
else:
|
| 484 |
-
activity_html = '<div class="panel muted center">No activity yet.</div>'
|
| 485 |
-
|
| 486 |
-
body = f"""
|
| 487 |
-
{banner}
|
| 488 |
-
<h1>📊 Dashboard</h1>
|
| 489 |
-
<div class="tiles">{tiles}</div>
|
| 490 |
-
|
| 491 |
-
<h2>🔧 API Health <span class="muted" style="text-transform:none;font-weight:400">(refreshes every {config.API_HEALTH_INTERVAL}s)</span></h2>
|
| 492 |
-
<div class="panel">{health_html}</div>
|
| 493 |
-
|
| 494 |
-
<h2>📜 Recent Activity</h2>
|
| 495 |
-
{activity_html}
|
| 496 |
-
"""
|
| 497 |
-
|
| 498 |
-
js = f"""
|
| 499 |
-
<script>
|
| 500 |
-
async function refresh() {{
|
| 501 |
-
try {{
|
| 502 |
-
const r = await fetch('/admin/api/stats');
|
| 503 |
-
if (!r.ok) return;
|
| 504 |
-
const d = await r.json();
|
| 505 |
-
const set = (id, v) => {{ const el = document.getElementById(id); if (el) el.textContent = v; }};
|
| 506 |
-
set('stat-users', d.unique_users);
|
| 507 |
-
set('stat-live', d.live_users);
|
| 508 |
-
set('stat-today', d.today_searches);
|
| 509 |
-
set('stat-total', d.total_searches);
|
| 510 |
-
set('stat-banned', d.banned_count);
|
| 511 |
-
set('stat-cached', d.cached_searches);
|
| 512 |
-
set('stat-backup', d.backup_sent);
|
| 513 |
-
}} catch (e) {{}}
|
| 514 |
-
}}
|
| 515 |
-
setInterval(refresh, {config.WEB_PANEL_REFRESH_SEC * 1000});
|
| 516 |
-
</script>
|
| 517 |
-
"""
|
| 518 |
-
return HTMLResponse(_page("Dashboard", body, extra_js=js, active_nav="dashboard"))
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
# ══════════════════════════════════════════════════════════════════
|
| 522 |
-
# 6. USERS PAGE
|
| 523 |
-
# ══════════════════════════════════════════════════════════════════
|
| 524 |
-
@authed_page
|
| 525 |
-
async def users_page(request: Request):
|
| 526 |
-
try:
|
| 527 |
-
page = int(request.query_params.get("page", "0"))
|
| 528 |
-
except ValueError:
|
| 529 |
-
page = 0
|
| 530 |
-
q = (request.query_params.get("q") or "").strip().lower()
|
| 531 |
-
|
| 532 |
-
users = sorted(bot.UNIQUE_USERS.items(), key=lambda kv: -kv[1]["last_seen"])
|
| 533 |
-
if q:
|
| 534 |
-
users = [
|
| 535 |
-
(uid, info) for uid, info in users
|
| 536 |
-
if q in (info.get("username") or "").lower()
|
| 537 |
-
or q in (info.get("first_name") or "").lower()
|
| 538 |
-
or q in str(uid)
|
| 539 |
-
]
|
| 540 |
-
|
| 541 |
-
page_size = config.WEB_PANEL_PAGE_SIZE
|
| 542 |
-
total = len(users)
|
| 543 |
-
total_pages = max(1, (total + page_size - 1) // page_size)
|
| 544 |
-
page = max(0, min(page, total_pages - 1))
|
| 545 |
-
chunk = users[page * page_size:(page + 1) * page_size]
|
| 546 |
-
|
| 547 |
-
rows = []
|
| 548 |
-
for uid, info in chunk:
|
| 549 |
-
uname = info.get("username")
|
| 550 |
-
first = info.get("first_name") or ""
|
| 551 |
-
name = f"@{uname}" if uname else (first or "(anon)")
|
| 552 |
-
with bot._state_lock:
|
| 553 |
-
banned = uid in bot.BANNED_USERS
|
| 554 |
-
reason = bot.BAN_REASONS.get(uid) or ""
|
| 555 |
-
badge = '<span class="badge badge-red">banned</span>' if banned else ''
|
| 556 |
-
action = (
|
| 557 |
-
f'<button class="btn btn-ghost btn-sm" onclick="unban({uid})">Unban</button>'
|
| 558 |
-
if banned else
|
| 559 |
-
f'<button class="btn btn-ghost btn-sm" onclick="ban({uid})">Ban</button>'
|
| 560 |
-
)
|
| 561 |
-
rows.append(f"""<tr>
|
| 562 |
-
<td>{_esc(name)} {badge}<br><span class="muted">id {uid}</span></td>
|
| 563 |
-
<td>{info['count']}</td>
|
| 564 |
-
<td class="muted">{_esc(_fmt_dt(info['last_seen']))}</td>
|
| 565 |
-
<td>{_esc(reason) if banned else ''}</td>
|
| 566 |
-
<td>{action}</td>
|
| 567 |
-
</tr>""")
|
| 568 |
-
|
| 569 |
-
pag = ""
|
| 570 |
-
if total_pages > 1:
|
| 571 |
-
parts = ['<div class="pagination">']
|
| 572 |
-
if page > 0:
|
| 573 |
-
parts.append(f'<a class="btn btn-ghost btn-sm" href="?page={page-1}&q={_esc(q)}">◀ Prev</a>')
|
| 574 |
-
parts.append(f'<span class="muted">Page {page+1} / {total_pages}</span>')
|
| 575 |
-
if page < total_pages - 1:
|
| 576 |
-
parts.append(f'<a class="btn btn-ghost btn-sm" href="?page={page+1}&q={_esc(q)}">Next ▶</a>')
|
| 577 |
-
parts.append('</div>')
|
| 578 |
-
pag = "".join(parts)
|
| 579 |
-
|
| 580 |
-
body = f"""
|
| 581 |
-
<h1>👥 Users ({total})</h1>
|
| 582 |
-
<div class="panel tight">
|
| 583 |
-
<div style="padding:16px">
|
| 584 |
-
<form method="get" style="display:flex;gap:8px">
|
| 585 |
-
<input type="text" name="q" placeholder="Search username / first name / id" value="{_esc(q)}">
|
| 586 |
-
<button class="btn" type="submit">Search</button>
|
| 587 |
-
{'<a class="btn btn-ghost" href="/admin/users">Clear</a>' if q else ''}
|
| 588 |
-
</form>
|
| 589 |
-
</div>
|
| 590 |
-
<table>
|
| 591 |
-
<tr><th>User</th><th>Requests</th><th>Last Seen</th><th>Ban Reason</th><th>Actions</th></tr>
|
| 592 |
-
{''.join(rows) or '<tr><td colspan="5" class="center muted" style="padding:24px">No users found.</td></tr>'}
|
| 593 |
-
</table>
|
| 594 |
-
<div style="padding:12px">{pag}</div>
|
| 595 |
-
</div>
|
| 596 |
-
"""
|
| 597 |
-
js = """
|
| 598 |
-
<script>
|
| 599 |
-
async function ban(uid) {
|
| 600 |
-
const reason = prompt("Ban reason (optional):");
|
| 601 |
-
if (reason === null) return;
|
| 602 |
-
const r = await fetch('/admin/api/ban', {
|
| 603 |
-
method: 'POST',
|
| 604 |
-
headers: {'Content-Type': 'application/json'},
|
| 605 |
-
body: JSON.stringify({user_id: uid, reason: reason || ''}),
|
| 606 |
-
});
|
| 607 |
-
if (r.ok) location.reload();
|
| 608 |
-
else alert('Failed: ' + (await r.text()));
|
| 609 |
-
}
|
| 610 |
-
async function unban(uid) {
|
| 611 |
-
const r = await fetch('/admin/api/unban', {
|
| 612 |
-
method: 'POST',
|
| 613 |
-
headers: {'Content-Type': 'application/json'},
|
| 614 |
-
body: JSON.stringify({user_id: uid}),
|
| 615 |
-
});
|
| 616 |
-
if (r.ok) location.reload();
|
| 617 |
-
else alert('Failed: ' + (await r.text()));
|
| 618 |
-
}
|
| 619 |
-
</script>
|
| 620 |
-
"""
|
| 621 |
-
return HTMLResponse(_page("Users", body, extra_js=js, active_nav="users"))
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
# ══════════════════════════════════════════════════════════════════
|
| 625 |
-
# 7. LOGS PAGE
|
| 626 |
-
# ══════════════════════════════════════════════════════════════════
|
| 627 |
-
@authed_page
|
| 628 |
-
async def logs_page(request: Request):
|
| 629 |
-
try:
|
| 630 |
-
page = int(request.query_params.get("page", "0"))
|
| 631 |
-
except ValueError:
|
| 632 |
-
page = 0
|
| 633 |
-
user_filter = (request.query_params.get("user") or "").strip()
|
| 634 |
-
action_filter = (request.query_params.get("action") or "").strip().lower()
|
| 635 |
-
phone_filter = (request.query_params.get("phone") or "").strip()
|
| 636 |
-
|
| 637 |
-
with bot._activity_lock:
|
| 638 |
-
entries = list(bot.ACTIVITY_LOG)
|
| 639 |
-
entries.reverse()
|
| 640 |
-
|
| 641 |
-
if user_filter:
|
| 642 |
-
try:
|
| 643 |
-
uid = int(user_filter)
|
| 644 |
-
entries = [e for e in entries if e["user_id"] == uid]
|
| 645 |
-
except ValueError:
|
| 646 |
-
uf = user_filter.lstrip("@").lower()
|
| 647 |
-
entries = [e for e in entries
|
| 648 |
-
if (e.get("username") or "").lower() == uf]
|
| 649 |
-
if action_filter:
|
| 650 |
-
entries = [e for e in entries if e["action"].lower() == action_filter]
|
| 651 |
-
if phone_filter:
|
| 652 |
-
entries = [e for e in entries if (e.get("input") or "") == phone_filter]
|
| 653 |
-
|
| 654 |
-
page_size = 50
|
| 655 |
-
total = len(entries)
|
| 656 |
-
total_pages = max(1, (total + page_size - 1) // page_size)
|
| 657 |
-
page = max(0, min(page, total_pages - 1))
|
| 658 |
-
chunk = entries[page * page_size:(page + 1) * page_size]
|
| 659 |
-
|
| 660 |
-
rows = []
|
| 661 |
-
for e in chunk:
|
| 662 |
-
uname = e.get("username") or e.get("first_name") or "(anon)"
|
| 663 |
-
rows.append(f"""<tr>
|
| 664 |
-
<td class="muted">{_esc(_fmt_dt(e['ts']))}</td>
|
| 665 |
-
<td>{_esc(uname)}<br><span class="muted">id {e['user_id']}</span></td>
|
| 666 |
-
<td><span class="badge badge-blue">{_esc(e['action'])}</span></td>
|
| 667 |
-
<td><code>{_esc((e['input'] or '-')[:60])}</code></td>
|
| 668 |
-
<td>{_esc((e.get('summary') or e.get('reply_type') or '-')[:120])}</td>
|
| 669 |
-
<td class="muted">{e.get('elapsed_ms', 0)}ms</td>
|
| 670 |
-
<td class="muted">{_esc(e.get('source') or '')}</td>
|
| 671 |
-
</tr>""")
|
| 672 |
-
|
| 673 |
-
qs_base = f"user={_esc(user_filter)}&action={_esc(action_filter)}&phone={_esc(phone_filter)}"
|
| 674 |
-
pag = ""
|
| 675 |
-
if total_pages > 1:
|
| 676 |
-
parts = ['<div class="pagination">']
|
| 677 |
-
if page > 0:
|
| 678 |
-
parts.append(f'<a class="btn btn-ghost btn-sm" href="?{qs_base}&page={page-1}">◀ Prev</a>')
|
| 679 |
-
parts.append(f'<span class="muted">Page {page+1} / {total_pages}</span>')
|
| 680 |
-
if page < total_pages - 1:
|
| 681 |
-
parts.append(f'<a class="btn btn-ghost btn-sm" href="?{qs_base}&page={page+1}">Next ▶</a>')
|
| 682 |
-
parts.append('</div>')
|
| 683 |
-
pag = "".join(parts)
|
| 684 |
-
|
| 685 |
-
body = f"""
|
| 686 |
-
<h1>📜 Activity Log <span class="muted" style="font-size:14px">({total} entries)</span></h1>
|
| 687 |
-
<div class="panel tight">
|
| 688 |
-
<div style="padding:16px">
|
| 689 |
-
<form method="get" style="display:flex;gap:8px;flex-wrap:wrap">
|
| 690 |
-
<input type="text" name="user" placeholder="user_id or @username" value="{_esc(user_filter)}" style="flex:1;min-width:140px">
|
| 691 |
-
<input type="text" name="action" placeholder="action (search, admin…)" value="{_esc(action_filter)}" style="flex:1;min-width:140px">
|
| 692 |
-
<input type="text" name="phone" placeholder="phone (10 digits)" value="{_esc(phone_filter)}" style="flex:1;min-width:140px">
|
| 693 |
-
<button class="btn" type="submit">Filter</button>
|
| 694 |
-
<a class="btn btn-ghost" href="/admin/api/export?{qs_base}">⬇ CSV</a>
|
| 695 |
-
<a class="btn btn-ghost" href="/admin/logs">Clear</a>
|
| 696 |
-
</form>
|
| 697 |
-
</div>
|
| 698 |
-
<table>
|
| 699 |
-
<tr><th>Time</th><th>User</th><th>Action</th><th>Input</th><th>Result</th><th>Latency</th><th>Source</th></tr>
|
| 700 |
-
{''.join(rows) or '<tr><td colspan="7" class="center muted" style="padding:24px">No log entries matched.</td></tr>'}
|
| 701 |
-
</table>
|
| 702 |
-
<div style="padding:12px">{pag}</div>
|
| 703 |
-
</div>
|
| 704 |
-
"""
|
| 705 |
-
return HTMLResponse(_page("Logs", body, active_nav="logs"))
|
| 706 |
-
|
| 707 |
-
|
| 708 |
-
# ══════════════════════════════════════════════════════════════════
|
| 709 |
-
# 8. BANS PAGE
|
| 710 |
-
# ══════════════��═══════════════════════════════════════════════════
|
| 711 |
-
@authed_page
|
| 712 |
-
async def bans_page(request: Request):
|
| 713 |
-
with bot._state_lock:
|
| 714 |
-
banned = list(bot.BANNED_USERS)
|
| 715 |
-
reasons = dict(bot.BAN_REASONS)
|
| 716 |
-
rows = []
|
| 717 |
-
for uid in banned:
|
| 718 |
-
uname = (bot.UNIQUE_USERS.get(uid) or {}).get("username")
|
| 719 |
-
first = (bot.UNIQUE_USERS.get(uid) or {}).get("first_name")
|
| 720 |
-
name = f"@{uname}" if uname else (first or "(unknown)")
|
| 721 |
-
rows.append(f"""<tr>
|
| 722 |
-
<td>{_esc(name)}<br><span class="muted">id {uid}</span></td>
|
| 723 |
-
<td>{_esc(reasons.get(uid) or '(no reason)')}</td>
|
| 724 |
-
<td><button class="btn btn-ghost btn-sm" onclick="unban({uid})">Unban</button></td>
|
| 725 |
-
</tr>""")
|
| 726 |
-
|
| 727 |
-
body = f"""
|
| 728 |
-
<h1>🚫 Banned Users ({len(banned)})</h1>
|
| 729 |
-
<div class="panel tight">
|
| 730 |
-
<table>
|
| 731 |
-
<tr><th>User</th><th>Reason</th><th>Action</th></tr>
|
| 732 |
-
{''.join(rows) or '<tr><td colspan="3" class="center muted" style="padding:24px">No banned users.</td></tr>'}
|
| 733 |
-
</table>
|
| 734 |
-
</div>
|
| 735 |
-
<div class="panel">
|
| 736 |
-
<h2 style="margin-top:0">Ban a User</h2>
|
| 737 |
-
<div style="display:flex;gap:8px;flex-wrap:wrap">
|
| 738 |
-
<input type="number" id="ban-uid" placeholder="Telegram user ID" style="flex:1;min-width:180px">
|
| 739 |
-
<input type="text" id="ban-reason" placeholder="Reason (optional)" style="flex:2;min-width:200px">
|
| 740 |
-
<button class="btn btn-red" onclick="manualBan()">Ban</button>
|
| 741 |
-
</div>
|
| 742 |
-
</div>
|
| 743 |
-
"""
|
| 744 |
-
js = """
|
| 745 |
-
<script>
|
| 746 |
-
async function unban(uid) {
|
| 747 |
-
const r = await fetch('/admin/api/unban', {
|
| 748 |
-
method: 'POST',
|
| 749 |
-
headers: {'Content-Type': 'application/json'},
|
| 750 |
-
body: JSON.stringify({user_id: uid}),
|
| 751 |
-
});
|
| 752 |
-
if (r.ok) location.reload();
|
| 753 |
-
else alert('Failed: ' + (await r.text()));
|
| 754 |
-
}
|
| 755 |
-
async function manualBan() {
|
| 756 |
-
const uid = parseInt(document.getElementById('ban-uid').value, 10);
|
| 757 |
-
const reason = document.getElementById('ban-reason').value;
|
| 758 |
-
if (!uid) { alert('Invalid user ID'); return; }
|
| 759 |
-
const r = await fetch('/admin/api/ban', {
|
| 760 |
-
method: 'POST',
|
| 761 |
-
headers: {'Content-Type': 'application/json'},
|
| 762 |
-
body: JSON.stringify({user_id: uid, reason}),
|
| 763 |
-
});
|
| 764 |
-
if (r.ok) location.reload();
|
| 765 |
-
else alert('Failed: ' + (await r.text()));
|
| 766 |
-
}
|
| 767 |
-
</script>
|
| 768 |
-
"""
|
| 769 |
-
return HTMLResponse(_page("Bans", body, extra_js=js, active_nav="bans"))
|
| 770 |
-
|
| 771 |
-
|
| 772 |
-
# ══════════════════════════════════════════════════════════════════
|
| 773 |
-
# 9. CONFIG PAGE
|
| 774 |
-
# ══════════════════════════════════════════════════════════════════
|
| 775 |
-
@authed_page
|
| 776 |
-
async def config_page(request: Request):
|
| 777 |
-
m_on, m_reason = bot._get_maintenance()
|
| 778 |
-
warning_list = config._sanity_check()
|
| 779 |
-
warnings_html = ""
|
| 780 |
-
if warning_list:
|
| 781 |
-
items = "".join(f"<li>{_esc(w)}</li>" for w in warning_list)
|
| 782 |
-
warnings_html = (
|
| 783 |
-
f'<div class="panel"><h2 style="margin-top:0">⚠️ Configuration Warnings</h2>'
|
| 784 |
-
f'<ul>{items}</ul></div>'
|
| 785 |
-
)
|
| 786 |
-
|
| 787 |
-
kv_pairs = [
|
| 788 |
-
("Version", config.VERSION),
|
| 789 |
-
("Bot token", _mask(config.BOT_TOKEN)),
|
| 790 |
-
("Webhook secret", _mask(config.WEBHOOK_SECRET)),
|
| 791 |
-
("Admin token", _mask(config.ADMIN_TOKEN)),
|
| 792 |
-
("ASUR key", _mask(config.ASUR_KEY)),
|
| 793 |
-
("Space URL", config.SPACE_URL or config.SPACE_HOST or "(unset)"),
|
| 794 |
-
("Telegram proxy", config.TELEGRAM_PROXY or "(direct)"),
|
| 795 |
-
("Force-join channel", config.FORCE_JOIN_CHANNEL or "(disabled)"),
|
| 796 |
-
("Backup channel", config.BACKUP_CHANNEL_ID or "(disabled)"),
|
| 797 |
-
("Backup forwarding", "ON" if bot.BACKUP_ENABLED else "OFF"),
|
| 798 |
-
("Owners", ", ".join(str(x) for x in sorted(config.OWNER_IDS)) or "(none)"),
|
| 799 |
-
("Daily quota", f"{config.DAILY_QUOTA}/user"),
|
| 800 |
-
("Flood mute", f"{config.FLOOD_MAX} msgs / {config.FLOOD_WINDOW}s → {config.FLOOD_MUTE_SEC}s"),
|
| 801 |
-
("HiTeck parquet files", str(len(config.PARQUET_URLS))),
|
| 802 |
-
("Flipkart parquet", str(len(config.FLIPKART_URLS))),
|
| 803 |
-
("850MindData parts", ", ".join(config.DATASET_850_PARTS)),
|
| 804 |
-
("APIs enabled", ", ".join(k for k, v in config.API_ENABLED.items() if v) or "(none)"),
|
| 805 |
-
("Maintenance", "ON" if m_on else "OFF"),
|
| 806 |
-
("Maintenance reason", m_reason or "—"),
|
| 807 |
-
("Search cache size", str(len(bot.SEARCH_CACHE))),
|
| 808 |
-
("Membership cache", str(len(bot._member_cache))),
|
| 809 |
-
]
|
| 810 |
-
kv_rows = "".join(
|
| 811 |
-
f'<div class="kv-key">{_esc(k)}</div><div class="kv-val"><code>{_esc(v)}</code></div>'
|
| 812 |
-
for k, v in kv_pairs
|
| 813 |
-
)
|
| 814 |
-
|
| 815 |
-
api_rows = []
|
| 816 |
-
for name, enabled in config.API_ENABLED.items():
|
| 817 |
-
badge = "badge-green\">ON" if enabled else "badge-gray\">OFF"
|
| 818 |
-
api_rows.append(f"""<tr>
|
| 819 |
-
<td><code>{_esc(name)}</code></td>
|
| 820 |
-
<td><span class="badge {badge}</span></td>
|
| 821 |
-
<td><button class="btn btn-ghost btn-sm" onclick="toggleApi('{name}', {str(not enabled).lower()})">
|
| 822 |
-
{'Disable' if enabled else 'Enable'}
|
| 823 |
-
</button></td>
|
| 824 |
-
</tr>""")
|
| 825 |
-
|
| 826 |
-
body = f"""
|
| 827 |
-
<h1>⚙️ Configuration</h1>
|
| 828 |
-
{warnings_html}
|
| 829 |
-
<h2>Environment</h2>
|
| 830 |
-
<div class="panel"><div class="kv">{kv_rows}</div></div>
|
| 831 |
-
|
| 832 |
-
<h2>Runtime Toggles</h2>
|
| 833 |
-
<div class="panel">
|
| 834 |
-
<div style="display:flex;gap:12px;flex-wrap:wrap;margin-bottom:16px">
|
| 835 |
-
<button class="btn {'btn-red' if bot.BACKUP_ENABLED else 'btn-green'}"
|
| 836 |
-
onclick="toggleBackup({str(not bot.BACKUP_ENABLED).lower()})">
|
| 837 |
-
{'🚫 Disable' if bot.BACKUP_ENABLED else '✅ Enable'} Backup Forwarding
|
| 838 |
-
</button>
|
| 839 |
-
</div>
|
| 840 |
-
<table>
|
| 841 |
-
<tr><th>API</th><th>Status</th><th>Action</th></tr>
|
| 842 |
-
{''.join(api_rows)}
|
| 843 |
-
</table>
|
| 844 |
-
</div>
|
| 845 |
-
"""
|
| 846 |
-
js = """
|
| 847 |
-
<script>
|
| 848 |
-
async function toggleBackup(on) {
|
| 849 |
-
const r = await fetch('/admin/api/backup', {
|
| 850 |
-
method: 'POST',
|
| 851 |
-
headers: {'Content-Type': 'application/json'},
|
| 852 |
-
body: JSON.stringify({on}),
|
| 853 |
-
});
|
| 854 |
-
if (r.ok) location.reload();
|
| 855 |
-
else alert('Failed');
|
| 856 |
-
}
|
| 857 |
-
async function toggleApi(name, enable) {
|
| 858 |
-
// API_ENABLED toggles are runtime-only (reset on restart)
|
| 859 |
-
alert('API toggles are not persisted. Edit API_ENABLED in config.py to make permanent.');
|
| 860 |
-
}
|
| 861 |
-
</script>
|
| 862 |
-
"""
|
| 863 |
-
return HTMLResponse(_page("Config", body, extra_js=js, active_nav="config"))
|
| 864 |
-
|
| 865 |
-
|
| 866 |
-
# ══════════════════════════════════════════════════════════════════
|
| 867 |
-
# 10. BROADCAST PAGE
|
| 868 |
-
# ══════════════════════════════════════════════════════════════════
|
| 869 |
-
@authed_page
|
| 870 |
-
async def broadcast_page(request: Request):
|
| 871 |
-
total_users = len(bot.UNIQUE_USERS)
|
| 872 |
-
body = f"""
|
| 873 |
-
<h1>📢 Broadcast</h1>
|
| 874 |
-
<div class="panel">
|
| 875 |
-
<div class="flash flash-info">
|
| 876 |
-
Message will be sent to <b>{total_users}</b> users. Banned users skipped.
|
| 877 |
-
Telegram markdown NOT supported — plain text + HTML entities only.
|
| 878 |
-
</div>
|
| 879 |
-
<label for="msg">Message</label>
|
| 880 |
-
<textarea id="msg" placeholder="Your announcement…" maxlength="{config.BROADCAST_MAX_LEN}"></textarea>
|
| 881 |
-
<div class="form-actions">
|
| 882 |
-
<button class="btn" onclick="sendBroadcast()">📢 Send to all users</button>
|
| 883 |
-
</div>
|
| 884 |
-
<div id="broadcast-status" class="muted" style="margin-top:12px"></div>
|
| 885 |
-
</div>
|
| 886 |
-
"""
|
| 887 |
-
js = """
|
| 888 |
-
<script>
|
| 889 |
-
async function sendBroadcast() {
|
| 890 |
-
const msg = document.getElementById('msg').value.trim();
|
| 891 |
-
if (!msg) { alert('Message is empty'); return; }
|
| 892 |
-
if (!confirm('Send to ALL users?')) return;
|
| 893 |
-
const st = document.getElementById('broadcast-status');
|
| 894 |
-
st.textContent = 'Queuing…';
|
| 895 |
-
const r = await fetch('/admin/api/broadcast', {
|
| 896 |
-
method: 'POST',
|
| 897 |
-
headers: {'Content-Type': 'application/json'},
|
| 898 |
-
body: JSON.stringify({message: msg}),
|
| 899 |
-
});
|
| 900 |
-
if (r.ok) {
|
| 901 |
-
st.textContent = '✅ Queued — check server logs / Telegram for progress.';
|
| 902 |
-
document.getElementById('msg').value = '';
|
| 903 |
-
} else {
|
| 904 |
-
st.textContent = '❌ Failed: ' + (await r.text());
|
| 905 |
-
}
|
| 906 |
-
}
|
| 907 |
-
</script>
|
| 908 |
-
"""
|
| 909 |
-
return HTMLResponse(_page("Broadcast", body, extra_js=js, active_nav="broadcast"))
|
| 910 |
-
|
| 911 |
-
|
| 912 |
-
# ══════════════════════════════════════════════════════════════════
|
| 913 |
-
# 11. MAINTENANCE PAGE
|
| 914 |
-
# ══════════════════════════════════════════════════════════════════
|
| 915 |
-
@authed_page
|
| 916 |
-
async def maintenance_page(request: Request):
|
| 917 |
-
m_on, m_reason = bot._get_maintenance()
|
| 918 |
-
state_badge = (
|
| 919 |
-
'<span class="badge badge-red">ON</span>' if m_on
|
| 920 |
-
else '<span class="badge badge-green">OFF</span>'
|
| 921 |
-
)
|
| 922 |
-
body = f"""
|
| 923 |
-
<h1>🛠️ Maintenance Mode</h1>
|
| 924 |
-
<div class="panel">
|
| 925 |
-
<div class="kv">
|
| 926 |
-
<div class="kv-key">Current status</div>
|
| 927 |
-
<div class="kv-val">{state_badge}</div>
|
| 928 |
-
<div class="kv-key">Reason</div>
|
| 929 |
-
<div class="kv-val">{_esc(m_reason or '—')}</div>
|
| 930 |
-
</div>
|
| 931 |
-
</div>
|
| 932 |
-
<div class="panel">
|
| 933 |
-
<h2 style="margin-top:0">Toggle</h2>
|
| 934 |
-
<label for="reason">Reason (used when turning ON)</label>
|
| 935 |
-
<input type="text" id="reason" placeholder="e.g. DB reindexing" value="{_esc(m_reason)}">
|
| 936 |
-
<div class="form-actions">
|
| 937 |
-
<button class="btn btn-red" onclick="setMaint(true)">🔴 Turn ON</button>
|
| 938 |
-
<button class="btn btn-green" onclick="setMaint(false)">🟢 Turn OFF</button>
|
| 939 |
-
</div>
|
| 940 |
-
</div>
|
| 941 |
-
"""
|
| 942 |
-
js = """
|
| 943 |
-
<script>
|
| 944 |
-
async function setMaint(on) {
|
| 945 |
-
const reason = on ? document.getElementById('reason').value : '';
|
| 946 |
-
const r = await fetch('/admin/api/maintenance', {
|
| 947 |
-
method: 'POST',
|
| 948 |
-
headers: {'Content-Type': 'application/json'},
|
| 949 |
-
body: JSON.stringify({on, reason}),
|
| 950 |
-
});
|
| 951 |
-
if (r.ok) location.reload();
|
| 952 |
-
else alert('Failed: ' + (await r.text()));
|
| 953 |
-
}
|
| 954 |
-
</script>
|
| 955 |
-
"""
|
| 956 |
-
return HTMLResponse(_page("Maintenance", body, extra_js=js, active_nav="maintenance"))
|
| 957 |
-
|
| 958 |
-
|
| 959 |
-
# ══════════════════════════════════════════════════════════════════
|
| 960 |
-
# 12. JSON API
|
| 961 |
-
# ══════════════════════════════════════════════════════════════════
|
| 962 |
-
@authed_api
|
| 963 |
-
async def api_stats(request: Request):
|
| 964 |
-
s = bot._get_stats()
|
| 965 |
-
s["uptime_min"] = round((time.time() - bot.STATS["started"]) / 60, 2)
|
| 966 |
-
s["backup_enabled"] = bot.BACKUP_ENABLED
|
| 967 |
-
s["maintenance_reason"] = bot.MAINTENANCE_REASON
|
| 968 |
-
s["version"] = config.VERSION
|
| 969 |
-
s["api_health"] = await _get_api_health_cached()
|
| 970 |
-
return JSONResponse(s)
|
| 971 |
-
|
| 972 |
-
|
| 973 |
-
@authed_api
|
| 974 |
-
async def api_users(request: Request):
|
| 975 |
-
try:
|
| 976 |
-
page = int(request.query_params.get("page", "0"))
|
| 977 |
-
except ValueError:
|
| 978 |
-
page = 0
|
| 979 |
-
page_size = int(request.query_params.get("size", str(config.WEB_PANEL_PAGE_SIZE)))
|
| 980 |
-
page_size = max(1, min(page_size, 200))
|
| 981 |
-
|
| 982 |
-
users = sorted(bot.UNIQUE_USERS.items(), key=lambda kv: -kv[1]["last_seen"])
|
| 983 |
-
total = len(users)
|
| 984 |
-
total_pages = max(1, (total + page_size - 1) // page_size)
|
| 985 |
-
page = max(0, min(page, total_pages - 1))
|
| 986 |
-
chunk = users[page * page_size:(page + 1) * page_size]
|
| 987 |
-
|
| 988 |
-
with bot._state_lock:
|
| 989 |
-
banned_set = set(bot.BANNED_USERS)
|
| 990 |
-
data = [
|
| 991 |
-
{
|
| 992 |
-
"user_id": uid,
|
| 993 |
-
"username": info.get("username"),
|
| 994 |
-
"first_name": info.get("first_name"),
|
| 995 |
-
"count": info.get("count", 0),
|
| 996 |
-
"last_seen": info.get("last_seen", 0),
|
| 997 |
-
"banned": uid in banned_set,
|
| 998 |
-
}
|
| 999 |
-
for uid, info in chunk
|
| 1000 |
-
]
|
| 1001 |
-
return JSONResponse({
|
| 1002 |
-
"total": total, "page": page, "total_pages": total_pages,
|
| 1003 |
-
"page_size": page_size, "users": data,
|
| 1004 |
-
})
|
| 1005 |
-
|
| 1006 |
-
|
| 1007 |
-
@authed_api
|
| 1008 |
-
async def api_logs(request: Request):
|
| 1009 |
-
try:
|
| 1010 |
-
page = int(request.query_params.get("page", "0"))
|
| 1011 |
-
except ValueError:
|
| 1012 |
-
page = 0
|
| 1013 |
-
page_size = int(request.query_params.get("size", "50"))
|
| 1014 |
-
page_size = max(1, min(page_size, 500))
|
| 1015 |
-
|
| 1016 |
-
with bot._activity_lock:
|
| 1017 |
-
entries = list(bot.ACTIVITY_LOG)
|
| 1018 |
-
entries.reverse()
|
| 1019 |
-
|
| 1020 |
-
total = len(entries)
|
| 1021 |
-
total_pages = max(1, (total + page_size - 1) // page_size)
|
| 1022 |
-
page = max(0, min(page, total_pages - 1))
|
| 1023 |
-
chunk = entries[page * page_size:(page + 1) * page_size]
|
| 1024 |
-
return JSONResponse({
|
| 1025 |
-
"total": total, "page": page, "total_pages": total_pages,
|
| 1026 |
-
"entries": chunk,
|
| 1027 |
-
})
|
| 1028 |
-
|
| 1029 |
-
|
| 1030 |
-
@authed_api
|
| 1031 |
-
async def api_bans(request: Request):
|
| 1032 |
-
with bot._state_lock:
|
| 1033 |
-
banned = list(bot.BANNED_USERS)
|
| 1034 |
-
reasons = dict(bot.BAN_REASONS)
|
| 1035 |
-
return JSONResponse({
|
| 1036 |
-
"count": len(banned),
|
| 1037 |
-
"bans": [{"user_id": uid, "reason": reasons.get(uid) or ""} for uid in banned],
|
| 1038 |
-
})
|
| 1039 |
-
|
| 1040 |
-
|
| 1041 |
-
@authed_api
|
| 1042 |
-
async def api_apistatus(request: Request):
|
| 1043 |
-
data = await _get_api_health_cached()
|
| 1044 |
-
return JSONResponse({"ts": _health_cache["ts"], "endpoints": data})
|
| 1045 |
-
|
| 1046 |
-
|
| 1047 |
-
@authed_api
|
| 1048 |
-
async def api_ban(request: Request):
|
| 1049 |
-
try:
|
| 1050 |
-
body = await request.json()
|
| 1051 |
-
except Exception:
|
| 1052 |
-
return JSONResponse({"error": "bad JSON"}, status_code=400)
|
| 1053 |
-
try:
|
| 1054 |
-
uid = int(body.get("user_id"))
|
| 1055 |
-
except (TypeError, ValueError):
|
| 1056 |
-
return JSONResponse({"error": "invalid user_id"}, status_code=400)
|
| 1057 |
-
reason = (body.get("reason") or "")[:500]
|
| 1058 |
-
bot._ban_user(uid, reason)
|
| 1059 |
-
log.info(f"[web-ban] uid={uid} reason={reason!r}")
|
| 1060 |
-
return JSONResponse({"ok": True, "user_id": uid, "reason": reason})
|
| 1061 |
-
|
| 1062 |
-
|
| 1063 |
-
@authed_api
|
| 1064 |
-
async def api_unban(request: Request):
|
| 1065 |
-
try:
|
| 1066 |
-
body = await request.json()
|
| 1067 |
-
except Exception:
|
| 1068 |
-
return JSONResponse({"error": "bad JSON"}, status_code=400)
|
| 1069 |
-
try:
|
| 1070 |
-
uid = int(body.get("user_id"))
|
| 1071 |
-
except (TypeError, ValueError):
|
| 1072 |
-
return JSONResponse({"error": "invalid user_id"}, status_code=400)
|
| 1073 |
-
ok = bot._unban_user(uid)
|
| 1074 |
-
log.info(f"[web-unban] uid={uid} was_banned={ok}")
|
| 1075 |
-
return JSONResponse({"ok": True, "was_banned": ok})
|
| 1076 |
-
|
| 1077 |
-
|
| 1078 |
-
@authed_api
|
| 1079 |
-
async def api_maintenance(request: Request):
|
| 1080 |
-
try:
|
| 1081 |
-
body = await request.json()
|
| 1082 |
-
except Exception:
|
| 1083 |
-
return JSONResponse({"error": "bad JSON"}, status_code=400)
|
| 1084 |
-
on = bool(body.get("on"))
|
| 1085 |
-
reason = (body.get("reason") or "")[:200]
|
| 1086 |
-
bot._set_maintenance(on, reason)
|
| 1087 |
-
log.info(f"[web-maint] on={on} reason={reason!r}")
|
| 1088 |
-
return JSONResponse({"ok": True, "on": on, "reason": reason})
|
| 1089 |
-
|
| 1090 |
-
|
| 1091 |
-
@authed_api
|
| 1092 |
-
async def api_broadcast(request: Request):
|
| 1093 |
-
try:
|
| 1094 |
-
body = await request.json()
|
| 1095 |
-
except Exception:
|
| 1096 |
-
return JSONResponse({"error": "bad JSON"}, status_code=400)
|
| 1097 |
-
msg = (body.get("message") or "").strip()
|
| 1098 |
-
if not msg:
|
| 1099 |
-
return JSONResponse({"error": "empty message"}, status_code=400)
|
| 1100 |
-
if len(msg) > config.BROADCAST_MAX_LEN:
|
| 1101 |
-
msg = msg[:config.BROADCAST_MAX_LEN]
|
| 1102 |
-
# Fire-and-forget
|
| 1103 |
-
asyncio.create_task(_run_web_broadcast(msg))
|
| 1104 |
-
log.info(f"[web-broadcast] queued, {len(msg)} chars")
|
| 1105 |
-
return JSONResponse({"ok": True, "queued": True, "length": len(msg)})
|
| 1106 |
-
|
| 1107 |
-
|
| 1108 |
-
async def _run_web_broadcast(msg: str):
|
| 1109 |
-
"""Run bot._run_broadcast; route completion message to backup channel if set."""
|
| 1110 |
-
try:
|
| 1111 |
-
target = 0
|
| 1112 |
-
if config.BACKUP_CHANNEL_ID:
|
| 1113 |
-
try:
|
| 1114 |
-
target = int(config.BACKUP_CHANNEL_ID)
|
| 1115 |
-
except (TypeError, ValueError):
|
| 1116 |
-
target = 0
|
| 1117 |
-
await bot._run_broadcast(target, msg)
|
| 1118 |
-
except Exception as e:
|
| 1119 |
-
log.warning(f"[web-broadcast] {e!r}")
|
| 1120 |
-
|
| 1121 |
-
|
| 1122 |
-
@authed_api
|
| 1123 |
-
async def api_backup(request: Request):
|
| 1124 |
-
try:
|
| 1125 |
-
body = await request.json()
|
| 1126 |
-
except Exception:
|
| 1127 |
-
return JSONResponse({"error": "bad JSON"}, status_code=400)
|
| 1128 |
-
on = bool(body.get("on"))
|
| 1129 |
-
bot.BACKUP_ENABLED = on
|
| 1130 |
-
log.info(f"[web-backup] enabled={on}")
|
| 1131 |
-
return JSONResponse({"ok": True, "enabled": on})
|
| 1132 |
-
|
| 1133 |
-
|
| 1134 |
-
@authed_api
|
| 1135 |
-
async def api_export(request: Request):
|
| 1136 |
-
with bot._activity_lock:
|
| 1137 |
-
entries = list(bot.ACTIVITY_LOG)
|
| 1138 |
-
buf = io.StringIO()
|
| 1139 |
-
w = csv.writer(buf)
|
| 1140 |
-
w.writerow([
|
| 1141 |
-
"timestamp_iso", "timestamp_local", "user_id", "username",
|
| 1142 |
-
"first_name", "action", "input", "reply_type", "summary",
|
| 1143 |
-
"elapsed_ms", "source",
|
| 1144 |
-
])
|
| 1145 |
-
for e in entries:
|
| 1146 |
-
w.writerow([
|
| 1147 |
-
datetime_iso(e["ts"]),
|
| 1148 |
-
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(e["ts"])),
|
| 1149 |
-
e["user_id"], e.get("username") or "", e.get("first_name") or "",
|
| 1150 |
-
e["action"], e.get("input", ""), e.get("reply_type", ""),
|
| 1151 |
-
e.get("summary", ""), e.get("elapsed_ms", 0), e.get("source", ""),
|
| 1152 |
-
])
|
| 1153 |
-
data = buf.getvalue().encode("utf-8")
|
| 1154 |
-
ts = time.strftime("%Y%m%d_%H%M%S")
|
| 1155 |
-
return Response(
|
| 1156 |
-
content=data,
|
| 1157 |
-
media_type="text/csv",
|
| 1158 |
-
headers={
|
| 1159 |
-
"Content-Disposition": f'attachment; filename="activity_log_{ts}.csv"'
|
| 1160 |
-
},
|
| 1161 |
-
)
|
| 1162 |
-
|
| 1163 |
-
|
| 1164 |
-
def datetime_iso(ts: float) -> str:
|
| 1165 |
-
from datetime import datetime, timezone
|
| 1166 |
-
return datetime.fromtimestamp(ts, tz=timezone.utc).isoformat()
|
| 1167 |
-
|
| 1168 |
-
|
| 1169 |
-
# ══════════════════════════════════════════════════════════════════
|
| 1170 |
-
# 13. ROUTE LIST (called by app.py)
|
| 1171 |
-
# ══════════════════════════════════════════════════════════════════
|
| 1172 |
-
def get_admin_routes() -> list:
|
| 1173 |
-
"""Return list of Starlette Routes to inject into live_app.router."""
|
| 1174 |
-
if not config.ADMIN_TOKEN:
|
| 1175 |
-
log.info("[admin] ADMIN_TOKEN not set — web panel routes NOT injected")
|
| 1176 |
-
return []
|
| 1177 |
-
|
| 1178 |
-
return [
|
| 1179 |
-
# ── Pages ──
|
| 1180 |
-
StarletteRoute("/admin", admin_root, methods=["GET"]),
|
| 1181 |
-
StarletteRoute("/admin/login", login_page, methods=["GET"]),
|
| 1182 |
-
StarletteRoute("/admin/login", login_submit, methods=["POST"]),
|
| 1183 |
-
StarletteRoute("/admin/logout", logout, methods=["GET", "POST"]),
|
| 1184 |
-
StarletteRoute("/admin/dashboard", dashboard, methods=["GET"]),
|
| 1185 |
-
StarletteRoute("/admin/users", users_page, methods=["GET"]),
|
| 1186 |
-
StarletteRoute("/admin/logs", logs_page, methods=["GET"]),
|
| 1187 |
-
StarletteRoute("/admin/bans", bans_page, methods=["GET"]),
|
| 1188 |
-
StarletteRoute("/admin/config", config_page, methods=["GET"]),
|
| 1189 |
-
StarletteRoute("/admin/broadcast", broadcast_page, methods=["GET"]),
|
| 1190 |
-
StarletteRoute("/admin/maintenance", maintenance_page, methods=["GET"]),
|
| 1191 |
-
# ── JSON API ──
|
| 1192 |
-
StarletteRoute("/admin/api/stats", api_stats, methods=["GET"]),
|
| 1193 |
-
StarletteRoute("/admin/api/users", api_users, methods=["GET"]),
|
| 1194 |
-
StarletteRoute("/admin/api/logs", api_logs, methods=["GET"]),
|
| 1195 |
-
StarletteRoute("/admin/api/bans", api_bans, methods=["GET"]),
|
| 1196 |
-
StarletteRoute("/admin/api/apistatus", api_apistatus, methods=["GET"]),
|
| 1197 |
-
StarletteRoute("/admin/api/export", api_export, methods=["GET"]),
|
| 1198 |
-
StarletteRoute("/admin/api/ban", api_ban, methods=["POST"]),
|
| 1199 |
-
StarletteRoute("/admin/api/unban", api_unban, methods=["POST"]),
|
| 1200 |
-
StarletteRoute("/admin/api/maintenance", api_maintenance, methods=["POST"]),
|
| 1201 |
-
StarletteRoute("/admin/api/broadcast", api_broadcast, methods=["POST"]),
|
| 1202 |
-
StarletteRoute("/admin/api/backup", api_backup, methods=["POST"]),
|
| 1203 |
-
]
|
| 1204 |
-
|
| 1205 |
-
|
| 1206 |
-
# ══════════════════════════════════════════════════════════════════
|
| 1207 |
-
# SELF-TEST
|
| 1208 |
-
# ══════════════════════════════════════════════════════════════════
|
| 1209 |
-
if __name__ == "__main__":
|
| 1210 |
-
logging.basicConfig(level=logging.INFO)
|
| 1211 |
-
if not config.ADMIN_TOKEN:
|
| 1212 |
-
print("⚠️ ADMIN_TOKEN empty — set it to test login flow")
|
| 1213 |
-
else:
|
| 1214 |
-
c = _make_cookie()
|
| 1215 |
-
print(f"cookie = {c}")
|
| 1216 |
-
print(f"verify = {_verify_cookie(c)}")
|
| 1217 |
-
print(f"expiry_short = {_verify_cookie('1.deadbeef')}")
|
| 1218 |
-
print(f"tampered = {_verify_cookie(c[:-1] + 'x')}")
|
| 1219 |
-
print(f"\nroutes: {len(get_admin_routes())}")
|
| 1220 |
-
for r in get_admin_routes():
|
| 1221 |
-
print(f" {sorted(r.methods)} {r.path}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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