Files
website/serve.py
T
2026-10-19 17:08:44 -05:00

67 lines
2.6 KiB
Python

"""Local static preview with a same-origin API proxy; use Apache in production."""
import argparse
import http.client
from functools import partial
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
class Handler(SimpleHTTPRequestHandler):
api_port = 8787
def end_headers(self):
self.send_header("X-Content-Type-Options", "nosniff")
self.send_header("Referrer-Policy", "same-origin")
self.send_header("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'")
super().end_headers()
def proxy(self):
try:
length = int(self.headers.get("Content-Length", "0"))
except ValueError:
self.send_error(400)
return
if length > 16384 or length < 0:
self.send_error(413)
return
headers = {name:self.headers[name] for name in ("Content-Type","Cookie","Origin","X-CSRF-Token","Authorization") if name in self.headers}
connection = http.client.HTTPConnection("127.0.0.1", self.api_port, timeout=20)
try:
connection.request(self.command, self.path, self.rfile.read(length) if length else None, headers)
response = connection.getresponse()
data = response.read()
self.send_response(response.status)
for name,value in response.getheaders():
if name.lower() in ("content-type","set-cookie","retry-after","cache-control"):
self.send_header(name,value)
self.send_header("Content-Length",str(len(data)))
self.end_headers()
self.wfile.write(data)
except OSError:
self.send_error(502,"licensing service unavailable")
finally:
connection.close()
def do_GET(self):
if self.path.startswith("/api/"):
self.proxy()
else:
super().do_GET()
def do_POST(self):
if self.path.startswith("/api/"):
self.proxy()
else:
self.send_error(405)
if __name__ == "__main__":
parser=argparse.ArgumentParser()
parser.add_argument("--port",type=int,default=5173)
parser.add_argument("--api-port",type=int,default=8787)
args=parser.parse_args()
Handler.api_port=args.api_port
handler=partial(Handler,directory=str(Path(__file__).parent / "public"))
print(f"Website: http://127.0.0.1:{args.port}",flush=True)
ThreadingHTTPServer(("127.0.0.1",args.port),handler).serve_forever()