feat(admin): persist sessions and refresh via websocket

This commit is contained in:
nyan404 committed 2026-08-21 14:13:44 +03:00
1 parent 351ceeb990
commit 0c59d8cb15
5 files changed
+80 -9

No files matched your search

+60 -3
View File
@@ -2,9 +2,11 @@ from __future__ import annotations
import json
import base64
import hashlib
import mimetypes
import os
import secrets
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, unquote, urlparse
@@ -23,6 +25,7 @@ _HISTORY_STORE: CalculationStore | None = None
_IDENTITY_DIR: IdentityDirectory | None = None
_APPLICATION_STORE: ApplicationStore | None = None
_WEB_SESSIONS: set[str] = set()
_ADMIN_SESSIONS: set[str] = set()
def history_store() -> CalculationStore:
@@ -79,6 +82,7 @@ def get_profile():
class Handler(BaseHTTPRequestHandler):
server_version = "BelkiCalculator/0.1"
protocol_version = "HTTP/1.1"
def _json(self, status: int, body: dict) -> None:
encoded = json.dumps(body, ensure_ascii=False).encode("utf-8")
@@ -88,12 +92,19 @@ class Handler(BaseHTTPRequestHandler):
self.end_headers()
self.wfile.write(encoded)
def _session_token(self, name: str) -> str:
cookies = self.headers.get("Cookie", "")
return next((part.strip().split("=", 1)[1] for part in cookies.split(";") if part.strip().startswith(f"{name}=")), "")
def _admin_session_authorized(self) -> bool:
return self._session_token("belki_admin_session") in _ADMIN_SESSIONS
def _admin_authorized(self) -> bool:
expected = os.getenv("BELKI_ADMIN_PASSWORD", "")
if not expected:
self._json(503, {"error": "Админская панель не настроена: задайте BELKI_ADMIN_PASSWORD"})
return False
if self.headers.get("X-Admin-Password", "") != expected:
if not self._admin_session_authorized() and not secrets.compare_digest(self.headers.get("X-Admin-Password", ""), expected):
self._json(401, {"error": "Неверный пароль"})
return False
return True
@@ -119,6 +130,35 @@ class Handler(BaseHTTPRequestHandler):
self.end_headers()
self.wfile.write(encoded)
def _admin_cookie(self, token: str) -> str:
secure = "; Secure" if self.headers.get("X-Forwarded-Proto", "") == "https" else ""
return f"belki_admin_session={token}; Path=/; HttpOnly; SameSite=Lax{secure}"
def _serve_admin_updates(self) -> None:
if not self._admin_session_authorized():
self._json(401, {"error": "Требуется авторизация"})
return
key = self.headers.get("Sec-WebSocket-Key", "")
if self.headers.get("Upgrade", "").lower() != "websocket" or not key:
self._json(400, {"error": "Требуется подключение WebSocket"})
return
accept = base64.b64encode(hashlib.sha1(f"{key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11".encode("ascii")).digest()).decode("ascii")
self.send_response(101, "Switching Protocols")
self.send_header("Upgrade", "websocket")
self.send_header("Connection", "Upgrade")
self.send_header("Sec-WebSocket-Accept", accept)
self.end_headers()
self.close_connection = True
try:
while True:
payload = json.dumps({"type": "refresh"}, ensure_ascii=False).encode("utf-8")
size = len(payload)
header = bytes([0x81, size]) if size < 126 else bytes([0x81, 126]) + size.to_bytes(2, "big")
self.connection.sendall(header + payload)
time.sleep(25)
except (BrokenPipeError, ConnectionError, OSError):
return
def do_GET(self) -> None: # noqa: N802
path = urlparse(self.path).path
if path in ("/health", "/api/health"):
@@ -133,6 +173,12 @@ class Handler(BaseHTTPRequestHandler):
if path in ("/applications", "/applications/"):
self._file(WEB_ROOT / "applications.html")
return
if path == "/api/admin/session":
self._json(200, {"authenticated": self._admin_session_authorized()})
return
if path == "/api/admin/updates":
self._serve_admin_updates()
return
if path == "/api/admin/calculations":
if not self._admin_authorized():
return
@@ -174,14 +220,25 @@ class Handler(BaseHTTPRequestHandler):
self.wfile.write(content)
def do_POST(self) -> None: # noqa: N802
if self.path not in ("/api/web/auth", "/api/web/logout", "/api/web/upload", "/api/calculate", "/api/inspect-bulk", "/api/resolve-identity",
if self.path not in ("/api/admin/auth", "/api/admin/logout", "/api/web/auth", "/api/web/logout", "/api/web/upload", "/api/calculate", "/api/inspect-bulk", "/api/resolve-identity",
"/api/save-profile", "/api/get-profile", "/api/applications"):
self._json(404, {"error": "Не найдено"})
return
try:
length = int(self.headers.get("Content-Length", "0"))
payload = json.loads(self.rfile.read(length)) if length else {}
if self.path == "/api/web/auth":
if self.path == "/api/admin/auth":
expected = os.getenv("BELKI_ADMIN_PASSWORD", "")
if not expected or not secrets.compare_digest(str(payload.get("password", "")), expected):
self._json(401, {"error": "Неверный пароль"})
return
token = secrets.token_urlsafe(32)
_ADMIN_SESSIONS.add(token)
self._json_with_cookie(200, {"authenticated": True}, self._admin_cookie(token))
elif self.path == "/api/admin/logout":
_ADMIN_SESSIONS.discard(self._session_token("belki_admin_session"))
self._json_with_cookie(200, {"authenticated": False}, "belki_admin_session=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax")
elif self.path == "/api/web/auth":
expected = os.getenv("BELKI_WEB_PASSWORD", "")
if not expected or not secrets.compare_digest(str(payload.get("password", "")), expected):
self._json(401, {"error": "Неверный пароль"})