Files
videoreg.ru/deploy/serve-local.py
T

111 lines
3.7 KiB
Python

#!/usr/bin/env python3
"""Serve the reviewed static candidate, confined to its exported public tree."""
from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler
from pathlib import Path
from urllib.parse import urlsplit, unquote
import json
import os
import re
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / 'web-front/out'
def resolve_public(root: Path, request_path: str):
path = unquote(urlsplit(request_path).path)
if '\\' in path or '..' in Path(path).parts or '\x00' in path:
return None
target = root / path.lstrip('/')
if not path.startswith('/health/') and Path(str(target) + '.html').is_file():
target = Path(str(target) + '.html')
try:
target.resolve().relative_to(root.resolve())
except (ValueError, OSError):
return None
return target
def legacy_destination(request_path: str):
"""Redirect only an exact evidenced query or proved presentation defaults."""
rules = json.loads((ROOT / 'deploy/legacy-matchers.json').read_text())
parsed = urlsplit(request_path)
key = unquote(parsed.path) + '|' + parsed.query
for rule in rules:
if re.fullmatch(rule['pattern'], key):
return rule['destination']
return None
class Handler(SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=str(OUT), **kwargs)
def list_directory(self, path):
self.send_error(404)
return None
def send_error(self, code, message=None, explain=None):
page = resolve_public(OUT, '/404.html')
if code == 404 and page and page.is_file():
body = page.read_bytes()
self.send_response(404)
self.send_header('Content-Type', 'text/html; charset=utf-8')
self.send_header('Content-Length', str(len(body)))
self.end_headers()
if self.command != 'HEAD':
self.wfile.write(body)
return
super().send_error(code, message, explain)
def copyfile(self, source, outputfile):
if self.command != "HEAD":
super().copyfile(source, outputfile)
def do_HEAD(self):
self.do_GET()
def do_POST(self):
self.send_error(404)
def do_GET(self):
target = resolve_public(OUT, self.path)
if target is None:
self.send_error(404)
return
destination = legacy_destination(self.path)
if destination:
self.send_response(308)
self.send_header('Location', destination)
self.end_headers()
return
path = unquote(urlsplit(self.path).path)
if path.startswith('/api/') or path.rstrip('/').endswith('/showcase'):
self.send_error(404)
return
if path.startswith('/health/') and target.is_file():
body = target.read_bytes()
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Length', str(len(body)))
self.end_headers()
if self.command != "HEAD":
self.wfile.write(body)
return
relative = target.relative_to(OUT).as_posix()
self.path = '/' if relative == '.' else '/' + relative
super().do_GET()
def main():
httpd = ThreadingHTTPServer(('127.0.0.1', int(os.environ.get('VIDEOREG_PREVIEW_PORT', '0'))), Handler)
runtime = ROOT / '.local-run'
runtime.mkdir(exist_ok=True)
state = dict(port=httpd.server_port, pid=os.getpid(), url=f'http://127.0.0.1:{httpd.server_port}')
(runtime / 'server.json').write_text(json.dumps(state, indent=2) + '\n')
print(json.dumps(state), flush=True)
httpd.serve_forever()
if __name__ == '__main__':
main()