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 from .belki.api import ApiError, calculate_and_store, inspect_bulk_payload, resolve_identity_payload from .belki.history import CalculationStore from .belki.applications import ApplicationError, ApplicationStore, validate_application from .belki.google_sheets_export import GoogleSheetsExportService from .belki.identity import IdentityDirectory from .belki.image_host import ImageHostClient, ImageHostError ROOT = Path(__file__).resolve().parents[1] WEB_ROOT = ROOT / "web" _HISTORY_STORE: CalculationStore | None = None _IDENTITY_DIR: IdentityDirectory | None = None _APPLICATION_STORE: ApplicationStore | None = None _ADMIN_SESSIONS: set[str] = set() MAX_JSON_BODY_BYTES = 20 * 1024 * 1024 MAX_UPLOAD_BYTES = 15 * 1024 * 1024 def detect_raster_image_type(body: bytes) -> str | None: """Returns the MIME type for supported raster image signatures only.""" if body.startswith(b"\x89PNG\r\n\x1a\n"): return "image/png" if body.startswith(b"\xff\xd8\xff"): return "image/jpeg" if len(body) >= 12 and body.startswith(b"RIFF") and body[8:12] == b"WEBP": return "image/webp" return None def safe_upload_name(value: object, content_type: str) -> str: """Drops path-like input and supplies a stable name for the image host.""" name = str(value or "").replace("\\", "/").split("/")[-1].replace("\x00", "").strip() if not name: suffix = {"image/png": "png", "image/jpeg": "jpg", "image/webp": "webp"}[content_type] return f"screenshot.{suffix}" return name[:255] def history_store() -> CalculationStore: global _HISTORY_STORE if _HISTORY_STORE is None: _HISTORY_STORE = CalculationStore.from_environment() return _HISTORY_STORE def identity_dir() -> IdentityDirectory: global _IDENTITY_DIR if _IDENTITY_DIR is None: _IDENTITY_DIR = IdentityDirectory.from_environment(persistent=True) return _IDENTITY_DIR def application_store() -> ApplicationStore: global _APPLICATION_STORE if _APPLICATION_STORE is None: _APPLICATION_STORE = ApplicationStore.from_environment() return _APPLICATION_STORE def sync_application_exports() -> int: """No-op until the explicitly disabled Google export is configured.""" return GoogleSheetsExportService(application_store()).sync_pending() 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") self.send_response(status) self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Length", str(len(encoded))) 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 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 def _json_with_cookie(self, status: int, body: dict, cookie: str) -> None: encoded = json.dumps(body, ensure_ascii=False).encode("utf-8") self.send_response(status) self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Set-Cookie", cookie) self.send_header("Content-Length", str(len(encoded))) 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"): self._json(200, {"status": "ok"}) return if path in ("/", "/belki", "/belki/", "/calculator.html"): self._file(WEB_ROOT / "calculator.html") return if path == "/admin": self._file(WEB_ROOT / "admin.html") return 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 query = parse_qs(urlparse(self.path).query) sort_by = query.get("sort", ["escort_id"])[0] descending = query.get("direction", ["desc"])[0] != "asc" try: limit = int(query.get("limit", ["100"])[0]) except ValueError: limit = 100 self._json(200, {"items": history_store().list_calculations(sort_by=sort_by, descending=descending, limit=limit)}) return if path == "/api/admin/applications": if not self._admin_authorized(): return query = parse_qs(urlparse(self.path).query) status = query.get("status", [None])[0] or None self._json(200, {"items": application_store().list(status=status)}) return requested = unquote(path).lstrip("/") candidate = (WEB_ROOT / requested).resolve() if candidate.is_file() and WEB_ROOT.resolve() in candidate.parents: self._file(candidate) return self._json(404, {"error": "Не найдено"}) def _file(self, path: Path) -> None: content = path.read_bytes() self.send_response(200) self.send_header("Content-Type", mimetypes.guess_type(path.name)[0] or "application/octet-stream") self.send_header("Content-Length", str(len(content))) self.end_headers() self.wfile.write(content) def _read_json_body(self) -> dict: """Read a bounded JSON request before passing it to public handlers.""" content_type = self.headers.get("Content-Type", "") if not content_type.lower().startswith("application/json"): raise ApiError("Ожидалось содержимое в формате JSON") try: length = int(self.headers.get("Content-Length", "")) except ValueError as exc: raise ApiError("Некорректный размер запроса") from exc if not 0 <= length <= MAX_JSON_BODY_BYTES: raise ApiError(f"Слишком большой запрос (максимум {MAX_JSON_BODY_BYTES // 1024 // 1024} МБ)") try: payload = json.loads(self.rfile.read(length)) if length else {} except json.JSONDecodeError as exc: raise ApiError("Не удалось прочитать JSON") from exc if not isinstance(payload, dict): raise ApiError("Ожидался JSON-объект") return payload def do_POST(self) -> None: # noqa: N802 if self.path not in ("/api/admin/auth", "/api/admin/logout", "/api/web/upload", "/api/calculate", "/api/inspect-bulk", "/api/resolve-identity", "/api/applications"): self._json(404, {"error": "Не найдено"}) return try: payload = self._read_json_body() 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/upload": raw = str(payload.get("data", "")) if "," in raw: raw = raw.split(",", 1)[1] try: body = base64.b64decode(raw, validate=True) except (ValueError, TypeError) as exc: raise ApiError("Не удалось прочитать изображение") from exc if len(body) > MAX_UPLOAD_BYTES: raise ApiError("Файл слишком большой (максимум 15 МБ)") content_type = detect_raster_image_type(body) if content_type is None: raise ApiError("Поддерживаются только изображения PNG, JPEG и WebP") declared_type = str(payload.get("type", "")).split(";", 1)[0].strip().lower() if declared_type and declared_type != content_type: raise ApiError("Тип файла не совпадает с содержимым изображения") try: url = ImageHostClient(api_url=os.getenv("BELKI_IMAGE_HOST_API_URL", "https://nyan.nyan404.ru")).upload_bytes( body, safe_upload_name(payload.get("name"), content_type), content_type ) except ImageHostError as exc: raise ApiError(f"Не удалось загрузить изображение: {exc}") from exc if not url: raise ApiError("Хранилище изображений не настроено") self._json(200, {"url": url, "name": safe_upload_name(payload.get("name"), content_type)}) elif self.path == "/api/inspect-bulk": self._json(200, inspect_bulk_payload(payload)) elif self.path == "/api/resolve-identity": self._json(200, resolve_identity_payload(payload)) elif self.path == "/api/applications": application = validate_application(payload) application_id = application_store().create(application=application, actor_id=None, reply_peer_id=None, source="web") sync_application_exports() self._json(201, {"id": application_id, "status": "pending", "message": "Заявка отправлена на рассмотрение."}) else: self._json(200, calculate_and_store(payload, actor_id=None, source="web")) except (ApiError, ApplicationError) as exc: self._json(400, {"error": str(exc)}) except (ValueError, json.JSONDecodeError) as exc: self._json(400, {"error": str(exc)}) except Exception: self._json(500, {"error": "Внутренняя ошибка калькулятора"}) def do_DELETE(self) -> None: # noqa: N802 parsed = urlparse(self.path) prefix = "/api/admin/calculations/" if not parsed.path.startswith(prefix): self._json(404, {"error": "Не найдено"}) return if not self._admin_authorized(): return raw_id = parsed.path[len(prefix):] try: calculation_id = int(raw_id) deleted = history_store().delete_calculation(calculation_id) except ValueError as exc: self._json(400, {"error": str(exc)}) return if not deleted: self._json(404, {"error": "Запись не найдена"}) return self._json(200, {"deleted": calculation_id}) def do_PATCH(self) -> None: # noqa: N802 parsed = urlparse(self.path) prefix = "/api/admin/applications/" if not parsed.path.startswith(prefix) or not parsed.path.endswith("/accept"): self._json(404, {"error": "Не найдено"}) return if not self._admin_authorized(): return raw_id = parsed.path[len(prefix):-len("/accept")].strip("/") try: application = application_store().accept(int(raw_id)) except (ValueError, ApplicationError) as exc: self._json(400, {"error": str(exc)}) return if application is None: self._json(404, {"error": "Заявка не найдена или уже принята"}) return sync_application_exports() self._json(200, {"item": application}) def log_message(self, format: str, *args: object) -> None: if os.getenv("BELKI_ACCESS_LOG", "0") == "1": super().log_message(format, *args) def serve() -> None: host = os.getenv("BELKI_HOST", "0.0.0.0") port = int(os.getenv("BELKI_PORT", "8080")) ThreadingHTTPServer((host, port), Handler).serve_forever() if __name__ == "__main__": serve()