server.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. """Loopback-only read-only HTTP server for the local board viewer."""
  2. from __future__ import annotations
  3. import gzip
  4. import json
  5. import mimetypes
  6. import re
  7. from http import HTTPStatus
  8. from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
  9. from pathlib import Path
  10. from urllib.parse import unquote, urlsplit
  11. from .assets import AssetIntegrityError, AssetValidationResult, validate_generated_assets, validate_generated_bundle
  12. ROOT = Path(__file__).resolve().parents[3]
  13. WEB_FILES = {
  14. "/": "index.html",
  15. "/index.html": "index.html",
  16. "/app.css": "app.css",
  17. "/app.js": "app.js",
  18. "/board-logic.mjs": "board-logic.mjs",
  19. "/cpld-arch-data.mjs": "cpld-arch-data.mjs",
  20. "/wasm-engine.mjs": "wasm-engine.mjs",
  21. "/board-accel.wasm": "board-accel.wasm",
  22. }
  23. GENERATED_FILES = {
  24. "/generated/board-data.json": "board-data.json",
  25. "/generated/board-mask-edge.svg": "board-mask-edge.svg",
  26. "/generated/board-silkscreen.svg": "board-silkscreen.svg",
  27. "/generated/board-copper.svg": "board-copper.svg",
  28. "/generated/board-mask-edge-back.svg": "board-mask-edge-back.svg",
  29. "/generated/board-silkscreen-back.svg": "board-silkscreen-back.svg",
  30. "/generated/board-copper-back.svg": "board-copper-back.svg",
  31. }
  32. GENERATED_V1_1_FILES = {
  33. "/generated-v1_1/board-data.json": "board-data.json",
  34. "/generated-v1_1/board-mask-edge.svg": "board-mask-edge.svg",
  35. "/generated-v1_1/board-silkscreen.svg": "board-silkscreen.svg",
  36. "/generated-v1_1/board-copper.svg": "board-copper.svg",
  37. "/generated-v1_1/board-mask-edge-back.svg": "board-mask-edge-back.svg",
  38. "/generated-v1_1/board-silkscreen-back.svg": "board-silkscreen-back.svg",
  39. "/generated-v1_1/board-copper-back.svg": "board-copper-back.svg",
  40. }
  41. GENERATED_V2_0_FILES = {
  42. "/generated-v2_0/board-data.json": "board-data.json",
  43. "/generated-v2_0/board-mask-edge.svg": "board-mask-edge.svg",
  44. "/generated-v2_0/board-silkscreen.svg": "board-silkscreen.svg",
  45. "/generated-v2_0/board-copper.svg": "board-copper.svg",
  46. "/generated-v2_0/board-mask-edge-back.svg": "board-mask-edge-back.svg",
  47. "/generated-v2_0/board-silkscreen-back.svg": "board-silkscreen-back.svg",
  48. "/generated-v2_0/board-copper-back.svg": "board-copper-back.svg",
  49. }
  50. GENERATED_V2_0_FAN_FILES = {
  51. "/generated-v2_0_fan/board-data.json": "board-data.json",
  52. "/generated-v2_0_fan/board-mask-edge.svg": "board-mask-edge.svg",
  53. "/generated-v2_0_fan/board-silkscreen.svg": "board-silkscreen.svg",
  54. "/generated-v2_0_fan/board-copper.svg": "board-copper.svg",
  55. "/generated-v2_0_fan/board-mask-edge-back.svg": "board-mask-edge-back.svg",
  56. "/generated-v2_0_fan/board-silkscreen-back.svg": "board-silkscreen-back.svg",
  57. "/generated-v2_0_fan/board-copper-back.svg": "board-copper-back.svg",
  58. }
  59. SCHEMATIC_FILES = {
  60. "/schematics/FCB_FPGA+MCU0611.pdf": "reference/original/schematics/FCB_FPGA+MCU0611.pdf",
  61. "/schematics/v1.1.pdf": "reference/original/schematics/FCB_FPGA+MCU0611.pdf",
  62. "/schematics/fcb_v1_1.pdf": "reference/original/schematics/FCB_FPGA+MCU0611.pdf",
  63. "/schematics/fcb_fpga_mcu_v2_0.pdf": "reference/original/schematics/fcb_fpga+mcu_v2_0_0902.pdf",
  64. "/schematics/fcb_v2_0.pdf": "reference/original/schematics/fcb_fpga+mcu_v2_0_0902.pdf",
  65. "/schematics/6400_v2_0_electrical.pdf": "reference/original/schematics/6400高温罩电气图V2.0.pdf",
  66. "/schematics/6400高温罩电气图V2.0.pdf": "reference/original/schematics/6400高温罩电气图V2.0.pdf",
  67. "/schematics/6400_v3_0_electrical.pdf": "reference/original/schematics/6400高温罩电气图V3.0.pdf",
  68. "/schematics/6400高温罩电气图V3.0.pdf": "reference/original/schematics/6400高温罩电气图V3.0.pdf",
  69. "/schematics/8000_v1_2_electrical.pdf": "reference/original/schematics/8000高温罩电气图V1.2.pdf",
  70. "/schematics/8000高温罩电气图V1.2.pdf": "reference/original/schematics/8000高温罩电气图V1.2.pdf",
  71. }
  72. DOC_FILES = {
  73. "/docs/FCB_FAN_V2_0_ANALYSIS.md": "docs/evidence/FCB_FAN_V2_0_ANALYSIS.md",
  74. "/docs/6400-v2-electrical-alignment.md": "docs/evidence/6400-v2-electrical-alignment.md",
  75. }
  76. PHOTO_ASSET = re.compile(r"^board-photo\.(?:png|jpg|jpeg|webp)$")
  77. class BoardViewerServer(ThreadingHTTPServer):
  78. daemon_threads = True
  79. allow_reuse_address = True
  80. def _runtime_payload(result: AssetValidationResult) -> dict[str, object]:
  81. return {
  82. "status": result.status,
  83. "assetErrors": result.asset_errors,
  84. "staleSources": result.stale_sources,
  85. "recommendationsEnabled": result.recommendations_enabled,
  86. "adcCopyEnabled": result.adc_copy_enabled,
  87. "generatedAt": result.build_info.get("generated_at"),
  88. "counts": result.build_info.get("counts"),
  89. }
  90. def _request_path(raw_path: str) -> str | None:
  91. path = unquote(urlsplit(raw_path).path)
  92. if "\x00" in path or "\\" in path:
  93. return None
  94. parts = path.split("/")
  95. if any(part in {".", ".."} for part in parts):
  96. return None
  97. return path
  98. def create_server(
  99. web_root: Path | str,
  100. generated_dir: Path | str,
  101. *,
  102. host: str = "127.0.0.1",
  103. port: int = 8765,
  104. allow_remote: bool = False,
  105. repository_root: Path | str = ROOT,
  106. ) -> BoardViewerServer:
  107. if not allow_remote and host != "127.0.0.1":
  108. raise ValueError("board viewer server must bind exactly to 127.0.0.1")
  109. web = Path(web_root).resolve()
  110. generated = Path(generated_dir).resolve()
  111. repository = Path(repository_root).resolve()
  112. for filename in set(WEB_FILES.values()):
  113. if not (web / filename).is_file():
  114. raise AssetIntegrityError(f"missing web asset: {filename}")
  115. validate_generated_bundle(generated, repository_root=repository)
  116. generated_files = dict(GENERATED_FILES)
  117. board_data = json.loads((generated / "board-data.json").read_text(encoding="utf-8"))
  118. photo_overlay = board_data.get("photo_overlay")
  119. if isinstance(photo_overlay, dict):
  120. photo_asset = str(photo_overlay.get("asset") or "")
  121. if not PHOTO_ASSET.fullmatch(photo_asset):
  122. raise AssetIntegrityError(f"unsafe photo asset name: {photo_asset}")
  123. generated_files[f"/generated/{photo_asset}"] = photo_asset
  124. v1_1_dir = generated.parent / "generated-v1_1"
  125. if not v1_1_dir.is_dir():
  126. v1_1_dir = repository / "tools" / "board-viewer" / "generated-v1_1"
  127. v1_1_files: dict[str, Path] = {}
  128. if v1_1_dir.is_dir():
  129. for url_path, rel_name in GENERATED_V1_1_FILES.items():
  130. candidate = v1_1_dir / rel_name
  131. if candidate.is_file():
  132. v1_1_files[url_path] = candidate
  133. v2_0_dir = generated.parent / "generated-v2_0"
  134. if not v2_0_dir.is_dir():
  135. v2_0_dir = repository / "tools" / "board-viewer" / "generated-v2_0"
  136. v2_0_files: dict[str, Path] = {}
  137. if v2_0_dir.is_dir():
  138. for url_path, rel_name in GENERATED_V2_0_FILES.items():
  139. candidate = v2_0_dir / rel_name
  140. if candidate.is_file():
  141. v2_0_files[url_path] = candidate
  142. v2_0_fan_dir = generated.parent / "generated-v2_0_fan"
  143. if not v2_0_fan_dir.is_dir():
  144. v2_0_fan_dir = repository / "tools" / "board-viewer" / "generated-v2_0_fan"
  145. v2_0_fan_files: dict[str, Path] = {}
  146. if v2_0_fan_dir.is_dir():
  147. for url_path, rel_name in GENERATED_V2_0_FAN_FILES.items():
  148. candidate = v2_0_fan_dir / rel_name
  149. if candidate.is_file():
  150. v2_0_fan_files[url_path] = candidate
  151. schematic_map: dict[str, Path] = {}
  152. for url_path, rel_path in SCHEMATIC_FILES.items():
  153. candidate = repository / rel_path
  154. if candidate.is_file():
  155. schematic_map[url_path] = candidate
  156. doc_map: dict[str, Path] = {}
  157. for url_path, rel_path in DOC_FILES.items():
  158. candidate = repository / rel_path
  159. if candidate.is_file():
  160. doc_map[url_path] = candidate
  161. asset_cache: dict[Path, tuple[int, int, bytes, bytes | None]] = {}
  162. status_cache: dict[str, tuple[int, bytes, int]] = {}
  163. COMPRESSIBLE_SUFFIXES = {".html", ".css", ".js", ".mjs", ".json", ".svg", ".md", ".wasm"}
  164. class Handler(BaseHTTPRequestHandler):
  165. server_version = "BoardViewer/1.0"
  166. sys_version = ""
  167. def log_message(self, format: str, *args: object) -> None:
  168. print(f"[{self.client_address[0]}] {self.command} {self.path}", flush=True)
  169. def _security_headers(self) -> None:
  170. self.send_header("X-Content-Type-Options", "nosniff")
  171. self.send_header("Referrer-Policy", "no-referrer")
  172. self.send_header("Cross-Origin-Resource-Policy", "same-origin")
  173. self.send_header(
  174. "Content-Security-Policy",
  175. "default-src 'self'; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; "
  176. "connect-src 'self'; object-src 'self'; base-uri 'none'; frame-ancestors 'self'; form-action 'none'",
  177. )
  178. self.send_header("Cache-Control", "no-store")
  179. def _accepts_gzip(self) -> bool:
  180. accept_enc = self.headers.get("Accept-Encoding") or ""
  181. return "gzip" in accept_enc.lower()
  182. def _send_bytes(
  183. self,
  184. payload: bytes,
  185. content_type: str,
  186. *,
  187. status: int = 200,
  188. head: bool = False,
  189. gzipped_payload: bytes | None = None,
  190. ) -> None:
  191. use_gzip = gzipped_payload is not None and self._accepts_gzip()
  192. out_bytes = gzipped_payload if use_gzip else payload
  193. self.send_response(status)
  194. self._security_headers()
  195. self.send_header("Content-Type", content_type)
  196. if gzipped_payload is not None:
  197. self.send_header("Vary", "Accept-Encoding")
  198. if use_gzip:
  199. self.send_header("Content-Encoding", "gzip")
  200. self.send_header("Content-Length", str(len(out_bytes)))
  201. self.end_headers()
  202. if not head:
  203. self.wfile.write(out_bytes)
  204. def _send_not_found(self, *, head: bool = False) -> None:
  205. self._send_bytes(b"Not Found\n", "text/plain; charset=utf-8", status=HTTPStatus.NOT_FOUND, head=head)
  206. def _serve(self, *, head: bool = False) -> None:
  207. url_parts = urlsplit(self.path)
  208. path = _request_path(url_parts.path)
  209. if path is None:
  210. self._send_not_found(head=head)
  211. return
  212. if path == "/api/status":
  213. query_str = url_parts.query or ""
  214. target_bundle = generated
  215. ver = "v1_2"
  216. if "version=v2_0_fan" in query_str and v2_0_fan_dir.is_dir():
  217. target_bundle = v2_0_fan_dir
  218. ver = "v2_0_fan"
  219. elif "version=v2_0" in query_str and v2_0_dir.is_dir():
  220. target_bundle = v2_0_dir
  221. ver = "v2_0"
  222. elif "version=v1_1" in query_str and v1_1_dir.is_dir():
  223. target_bundle = v1_1_dir
  224. ver = "v1_1"
  225. try:
  226. result = validate_generated_assets(target_bundle, repository_root=repository)
  227. payload = _runtime_payload(result)
  228. payload["version"] = ver
  229. payload["accelEngine"] = "rust-wasm-v1"
  230. status = HTTPStatus.OK
  231. except AssetIntegrityError as exc:
  232. payload = {
  233. "status": "invalid_assets",
  234. "assetErrors": [str(exc)],
  235. "staleSources": [],
  236. "recommendationsEnabled": False,
  237. "adcCopyEnabled": False,
  238. "message": str(exc),
  239. "version": ver,
  240. }
  241. status = HTTPStatus.SERVICE_UNAVAILABLE
  242. body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
  243. self._send_bytes(body, "application/json; charset=utf-8", status=status, head=head)
  244. return
  245. if path in WEB_FILES:
  246. file_path = web / WEB_FILES[path]
  247. elif path in generated_files:
  248. file_path = generated / generated_files[path]
  249. elif path in v2_0_files:
  250. file_path = v2_0_files[path]
  251. elif path in v2_0_fan_files:
  252. file_path = v2_0_fan_files[path]
  253. elif path in v1_1_files:
  254. file_path = v1_1_files[path]
  255. elif path in schematic_map:
  256. file_path = schematic_map[path]
  257. elif path in doc_map:
  258. file_path = doc_map[path]
  259. else:
  260. self._send_not_found(head=head)
  261. return
  262. try:
  263. st = file_path.stat()
  264. cached = asset_cache.get(file_path)
  265. if cached is not None and cached[0] == st.st_mtime_ns and cached[1] == st.st_size:
  266. body, gz_body = cached[2], cached[3]
  267. else:
  268. body = file_path.read_bytes()
  269. gz_body = (
  270. gzip.compress(body, compresslevel=6)
  271. if file_path.suffix in COMPRESSIBLE_SUFFIXES and len(body) > 512
  272. else None
  273. )
  274. asset_cache[file_path] = (st.st_mtime_ns, st.st_size, body, gz_body)
  275. except OSError:
  276. self._send_not_found(head=head)
  277. return
  278. content_type = mimetypes.guess_type(file_path.name)[0] or "application/octet-stream"
  279. if file_path.suffix == ".pdf":
  280. content_type = "application/pdf"
  281. elif file_path.suffix == ".wasm":
  282. content_type = "application/wasm"
  283. elif file_path.suffix in {".js", ".mjs"}:
  284. content_type = "text/javascript"
  285. elif file_path.suffix == ".md":
  286. content_type = "text/markdown"
  287. if file_path.suffix in {".html", ".css", ".js", ".mjs", ".json", ".svg", ".md"}:
  288. content_type += "; charset=utf-8"
  289. self._send_bytes(body, content_type, head=head, gzipped_payload=gz_body)
  290. def do_GET(self) -> None: # noqa: N802
  291. self._serve(head=False)
  292. def do_HEAD(self) -> None: # noqa: N802
  293. self._serve(head=True)
  294. def _reject_mutation(self) -> None:
  295. payload = b"Method Not Allowed\n"
  296. self.send_response(HTTPStatus.METHOD_NOT_ALLOWED)
  297. self._security_headers()
  298. self.send_header("Allow", "GET, HEAD")
  299. self.send_header("Content-Type", "text/plain; charset=utf-8")
  300. self.send_header("Content-Length", str(len(payload)))
  301. self.end_headers()
  302. self.wfile.write(payload)
  303. do_POST = _reject_mutation # noqa: N815
  304. do_PUT = _reject_mutation # noqa: N815
  305. do_PATCH = _reject_mutation # noqa: N815
  306. do_DELETE = _reject_mutation # noqa: N815
  307. return BoardViewerServer((host, port), Handler)