Spaces:
Running

File size: 5,092 Bytes
8f3b9c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
"""Shared stdlib HTTP server utilities for the pipeline and detector test servers."""

from __future__ import annotations

import json
import logging
import mimetypes
from collections.abc import Callable, Sequence
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

from core import config

logger = logging.getLogger(__name__)

_STATIC_CONTENT_TYPES: dict[str, str] = {
    ".html": "text/html; charset=utf-8",
    ".css": "text/css; charset=utf-8",
    ".js": "text/javascript; charset=utf-8",
    ".mjs": "text/javascript; charset=utf-8",
    ".json": "application/json; charset=utf-8",
    ".svg": "image/svg+xml",
}


def configure_logging() -> None:
    """Configure consistent console logging across servers."""
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s  %(levelname)-7s  %(message)s",
        datefmt="%H:%M:%S",
    )


class BodyTooLargeError(ValueError):
    """Raised when Content-Length exceeds the configured body limit."""


class JsonRequestHandler(BaseHTTPRequestHandler):
    """Base HTTP handler with CORS, JSON helpers, body size cap, and safe static file serving."""

    allow_cors: bool | None = None
    max_body_bytes: int = config.MAX_BODY_BYTES

    def _cors_enabled(self) -> bool:
        if self.allow_cors is None:
            return config.ENABLE_CORS
        return self.allow_cors

    def send_cors_headers(self) -> None:
        if not self._cors_enabled():
            return
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "Content-Type")

    def do_OPTIONS(self) -> None:
        self.send_response(204)
        self.send_cors_headers()
        self.end_headers()

    def send_json(self, status: int, body: object) -> None:
        payload = json.dumps(body, ensure_ascii=False).encode("utf-8")
        try:
            self.send_response(status)
            self.send_header("Content-Type", "application/json; charset=utf-8")
            self.send_header("Content-Length", str(len(payload)))
            self.send_cors_headers()
            self.end_headers()
            self.wfile.write(payload)
        except (ConnectionAbortedError, BrokenPipeError, ConnectionResetError):
            pass  # Client disconnected before response finished.

    def read_json_body(self) -> object | None:
        """Read and parse JSON body; raise BodyTooLargeError if over limit, or None if invalid."""
        raw_len = self.headers.get("Content-Length", "0")
        try:
            length = int(raw_len)
        except (TypeError, ValueError):
            return None
        if length < 0:
            return None
        if length > self.max_body_bytes:
            raise BodyTooLargeError(f"Request body exceeds {self.max_body_bytes} bytes")
        if length == 0:
            return {}
        try:
            return json.loads(self.rfile.read(length))
        except (json.JSONDecodeError, ValueError, UnicodeDecodeError):
            return None

    def serve_static_file(self, web_dir: Path) -> None:
        """Serve static assets inside web_dir with path traversal protection."""
        rel = self.path.split("?", 1)[0].split("#", 1)[0].lstrip("/")
        if not rel:
            rel = "index.html"

        root = web_dir.resolve()
        target = (root / rel).resolve()
        try:
            target.relative_to(root)
        except ValueError:
            self.send_json(403, {"error": "Access denied."})
            return

        if not target.is_file():
            self.send_json(404, {"error": "File not found."})
            return

        ctype = (
            _STATIC_CONTENT_TYPES.get(target.suffix.lower())
            or mimetypes.guess_type(str(target))[0]
            or "application/octet-stream"
        )
        try:
            data = target.read_bytes()
            self.send_response(200)
            self.send_header("Content-Type", ctype)
            self.send_header("Content-Length", str(len(data)))
            self.send_cors_headers()
            self.end_headers()
            self.wfile.write(data)
        except (ConnectionAbortedError, BrokenPipeError, ConnectionResetError):
            pass

    def log_message(self, format: str, *args: object) -> None:
        logger.info("%-6s %s", args[0] if args else "", args[1] if len(args) > 1 else "")


def run_http_server(
    host: str,
    port: int,
    handler_cls: type[BaseHTTPRequestHandler],
    *,
    startup_messages: Sequence[str] = (),
    on_shutdown: Callable[[], None] | None = None,
) -> None:
    """Start a multithreaded HTTP server and handle clean shutdown on KeyboardInterrupt."""
    server = ThreadingHTTPServer((host, port), handler_cls)
    for msg in startup_messages:
        logger.info("%s", msg)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        logger.info("Server stopped.")
        if on_shutdown is not None:
            on_shutdown()
        server.server_close()