Show live Horizon terrain and radar views in the web panel
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
"""Optionally serve the AirDef PWA on a trusted LAN HTTPS origin."""
|
||||
import argparse
|
||||
import contextlib
|
||||
import hashlib
|
||||
from http import HTTPStatus
|
||||
from http.cookies import CookieError, SimpleCookie
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
@@ -8,6 +9,7 @@ import ipaddress
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
import ssl
|
||||
import subprocess
|
||||
@@ -26,6 +28,8 @@ ASSETS = {
|
||||
"/index.html": ("index.html", "text/html; charset=utf-8"),
|
||||
"/app.js": ("app.js", "text/javascript; charset=utf-8"),
|
||||
"/map.js": ("map.js", "text/javascript; charset=utf-8"),
|
||||
"/terrain.js": ("terrain.js", "text/javascript; charset=utf-8"),
|
||||
"/symbols.js": ("symbols.js", "text/javascript; charset=utf-8"),
|
||||
"/live.js": ("live.js", "text/javascript; charset=utf-8"),
|
||||
"/timeline.js": ("timeline.js", "text/javascript; charset=utf-8"),
|
||||
"/app.css": ("app.css", "text/css; charset=utf-8"),
|
||||
@@ -62,10 +66,11 @@ class PanelServer(ThreadingHTTPServer):
|
||||
daemon_threads = True
|
||||
request_queue_size = 24
|
||||
|
||||
def __init__(self, bind, origin, store, bridge, pairing, *, tls=None, allow_launch=False, allow_debug=False):
|
||||
def __init__(self, bind, origin, store, bridge, pairing, *, tls=None, tailscale=False, allow_launch=False, allow_debug=False):
|
||||
self.origin = origin
|
||||
self.host_header = urlsplit(origin).netloc.casefold()
|
||||
self.secure = origin.startswith("https:")
|
||||
self.tailscale = tailscale
|
||||
self.store, self.bridge, self.pairing = store, bridge, pairing
|
||||
self.allow_launch, self.allow_debug = allow_launch, allow_debug
|
||||
self.connections = threading.BoundedSemaphore(24)
|
||||
@@ -112,7 +117,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
def do_DELETE(self):
|
||||
self.route("DELETE")
|
||||
|
||||
def reply(self, status, payload=None, *, content_type="application/json; charset=utf-8", cookie=None):
|
||||
def reply(self, status, payload=None, *, content_type="application/json; charset=utf-8", cookie=None, etag=None):
|
||||
if payload is None:
|
||||
content = b""
|
||||
elif isinstance(payload, bytes):
|
||||
@@ -123,6 +128,8 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(content)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
if etag:
|
||||
self.send_header("ETag", etag)
|
||||
self.send_header("X-Content-Type-Options", "nosniff")
|
||||
self.send_header("Referrer-Policy", "no-referrer")
|
||||
self.send_header("Cross-Origin-Resource-Policy", "same-origin")
|
||||
@@ -137,6 +144,10 @@ class Handler(BaseHTTPRequestHandler):
|
||||
try:
|
||||
if self.headers.get("Host", "").casefold() != self.server.host_header:
|
||||
raise APIError(HTTPStatus.BAD_REQUEST, "Откройте пульт по адресу, показанному на ПК")
|
||||
if self.server.tailscale and (self.headers.get_all("X-Forwarded-Proto") != ["https"]
|
||||
or [x.casefold() for x in self.headers.get_all("X-Forwarded-Host", [])] != [self.server.host_header]
|
||||
or self.headers.get("Tailscale-Funnel-Request") is not None):
|
||||
raise APIError(HTTPStatus.FORBIDDEN, "Откройте пульт через Tailscale Serve по HTTPS")
|
||||
request = urlsplit(self.path)
|
||||
if request.scheme or request.netloc or len(request.query) > 1024:
|
||||
raise APIError(HTTPStatus.BAD_REQUEST, "Неверный адрес")
|
||||
@@ -201,6 +212,24 @@ class Handler(BaseHTTPRequestHandler):
|
||||
return self.reply(HTTPStatus.OK, data)
|
||||
if (verb, path) == ("GET", "/api/raids"):
|
||||
return self.reply(HTTPStatus.OK, self.server.store.raids())
|
||||
if (verb, path) == ("GET", "/api/terrain"):
|
||||
scope = query.get("scope", "")
|
||||
x, z, step = (int(query[key]) for key in ("x", "z", "step"))
|
||||
if step not in (1, 2, 4, 8, 16, 32, 64) or not TOKEN.fullmatch(scope):
|
||||
raise ValueError("bad terrain coordinates")
|
||||
span = 128 * step
|
||||
if any(not -30_000_000 <= v <= 30_000_000 - span or v % span for v in (x, z)):
|
||||
raise ValueError("bad terrain coordinates")
|
||||
tile = self.server.bridge.terrain_tile(scope, x, z, step)
|
||||
if tile is None:
|
||||
return self.reply(HTTPStatus.ACCEPTED)
|
||||
data, known = tile
|
||||
if not known:
|
||||
return self.reply(HTTPStatus.NO_CONTENT)
|
||||
etag = '"' + hashlib.blake2s(data, digest_size=8).hexdigest() + '"'
|
||||
if self.headers.get("If-None-Match") == etag:
|
||||
return self.reply(HTTPStatus.NOT_MODIFIED, etag=etag)
|
||||
return self.reply(HTTPStatus.OK, data, content_type="image/png", etag=etag)
|
||||
if (verb, path) == ("GET", "/api/timeline"):
|
||||
session, raid = query.get("session", ""), number(query.get("raid"))
|
||||
if not TOKEN.fullmatch(session) or raid is None:
|
||||
@@ -265,6 +294,14 @@ def number(raw):
|
||||
|
||||
def transport_options(args):
|
||||
ip = ipaddress.IPv4Address(args.listen)
|
||||
if args.tailscale:
|
||||
if str(ip) != "127.0.0.1" or args.origin or args.cert or args.key:
|
||||
raise ValueError("Tailscale Serve требует 127.0.0.1 и несовместим с --origin, --cert и --key")
|
||||
url = urlsplit(args.tailscale)
|
||||
if (url.scheme != "https" or not re.fullmatch(r"[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+\.ts\.net", url.netloc)
|
||||
or url.path not in ("", "/") or url.query or url.fragment or not 1 <= args.port <= 65535):
|
||||
raise ValueError("Укажите HTTPS-адрес устройства Tailscale без порта и пути: https://device.tailnet.ts.net")
|
||||
return f"https://{url.netloc}", None
|
||||
tls = None
|
||||
if args.cert or args.key:
|
||||
if not args.cert or not args.key:
|
||||
@@ -305,6 +342,7 @@ def run(argv, *, game_home, game_command, default_mod_data):
|
||||
parser.add_argument("--listen", default="127.0.0.1", help="IPv4-интерфейс веб-пульта")
|
||||
parser.add_argument("--port", type=int, default=8765)
|
||||
parser.add_argument("--origin", help="Точный HTTPS-адрес, по которому планшет открывает пульт")
|
||||
parser.add_argument("--tailscale", help="HTTPS-адрес устройства Tailscale Serve (backend только на 127.0.0.1)")
|
||||
parser.add_argument("--cert", type=Path, help="Сертификат HTTPS в PEM")
|
||||
parser.add_argument("--key", type=Path, help="Ключ сертификата PEM")
|
||||
parser.add_argument("--allow-launch", action="store_true", help="Выдать отдельный код оператору")
|
||||
@@ -329,7 +367,7 @@ def run(argv, *, game_home, game_command, default_mod_data):
|
||||
store.revoke_all()
|
||||
pairing = Pairing(args.allow_launch, args.allow_debug)
|
||||
bridge = Bridge(endpoint, data, store, debug=args.allow_debug)
|
||||
with PanelServer((args.listen, args.port), origin, store, bridge, pairing, tls=tls,
|
||||
with PanelServer((args.listen, args.port), origin, store, bridge, pairing, tls=tls, tailscale=bool(args.tailscale),
|
||||
allow_launch=args.allow_launch, allow_debug=args.allow_debug) as server:
|
||||
child = None
|
||||
if not args.attach:
|
||||
|
||||
Reference in New Issue
Block a user