aienos.com
Source of www.aienos.com, served from my own hardware
Brought by drakestapleton
aienos.com / scripts / allen / dev_proxy.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Development only: serve a built site and pass /allen/api/ to a local gateway, |
| 3 | so the page and the API share an origin in a local browser test. Never deployed; |
| 4 | production routing is hub nginx (nginx-allen-location.conf).""" |
| 5 | |
| 6 | import argparse |
| 7 | import http.client |
| 8 | import os |
| 9 | from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer |
| 10 | from urllib.parse import urlsplit |
| 11 | |
| 12 | TYPES = {".html": "text/html; charset=utf-8", ".js": "text/javascript", ".css": "text/css", |
| 13 | ".svg": "image/svg+xml", ".wasm": "application/wasm", ".json": "application/json", |
| 14 | ".png": "image/png", ".ico": "image/x-icon", ".txt": "text/plain", ".mp3": "audio/mpeg"} |
| 15 | # Upstream headers the page reads or the browser needs; nothing else is forwarded. |
| 16 | FORWARD = ("Content-Type", "Cache-Control", "Retry-After", "X-Allen-Source", "X-OH-Model", |
| 17 | "X-OH-Volunteer", "X-Content-Type-Options", "Content-Security-Policy") |
| 18 | |
| 19 | |
| 20 | def index(dist): |
| 21 | """URL path -> file for every regular file under dist, built once at start, so a |
| 22 | request path is only ever a dictionary key and never reaches the filesystem.""" |
| 23 | root = os.path.realpath(dist) |
| 24 | files = {} |
| 25 | for d, _, names in os.walk(root): |
| 26 | for n in names: |
| 27 | full = os.path.join(d, n) |
| 28 | if os.path.isfile(full): |
| 29 | url = "/" + os.path.relpath(full, root).replace(os.sep, "/") |
| 30 | files[url] = full |
| 31 | if n == "index.html": |
| 32 | files[url[:-len("index.html")]] = full |
| 33 | files[url[:-len("/index.html")] or "/"] = full |
| 34 | return files |
| 35 | |
| 36 | |
| 37 | class H(BaseHTTPRequestHandler): |
| 38 | protocol_version = "HTTP/1.1" |
| 39 | |
| 40 | def log_message(self, *a): |
| 41 | pass |
| 42 | |
| 43 | def proxy(self): |
| 44 | n = int(self.headers.get("Content-Length", "0") or 0) |
| 45 | body = self.rfile.read(n) if n else None |
| 46 | host, _, port = self.server.gateway.rpartition(":") |
| 47 | c = http.client.HTTPConnection(host, int(port), timeout=200) |
| 48 | hdrs = {"Content-Type": self.headers.get("Content-Type", ""), |
| 49 | "X-Real-IP": self.headers.get("X-Real-IP", self.client_address[0])} |
| 50 | for k, v in self.headers.items(): # the page's identity and conversation headers, and |
| 51 | # Origin / Sec-Fetch-Site so the gateway's cross-site gate (F1) sees what nginx passes |
| 52 | if k.lower().startswith("x-allen-") or k.lower() in ("origin", "sec-fetch-site"): |
| 53 | hdrs[k] = v |
| 54 | c.request(self.command, self.path, body, hdrs) |
| 55 | r = c.getresponse() |
| 56 | self.send_response(r.status) |
| 57 | for k in FORWARD: |
| 58 | v = r.getheader(k) |
| 59 | # A value carrying CR or LF would split this response; drop it. |
| 60 | if v is not None and "\r" not in v and "\n" not in v: |
| 61 | self.send_header(k, v.replace("\r", "").replace("\n", "")) |
| 62 | self.send_header("Connection", "close") |
| 63 | self.end_headers() |
| 64 | self.close_connection = True |
| 65 | while True: |
| 66 | chunk = r.read1(65536) |
| 67 | if not chunk: |
| 68 | break |
| 69 | self.wfile.write(chunk) |
| 70 | self.wfile.flush() |
| 71 | |
| 72 | def static(self): |
| 73 | full = self.server.files.get(urlsplit(self.path).path) |
| 74 | if full is None: |
| 75 | self.send_error(404) |
| 76 | return |
| 77 | with open(full, "rb") as f: |
| 78 | data = f.read() |
| 79 | self.send_response(200) |
| 80 | self.send_header("Content-Type", TYPES.get(os.path.splitext(full)[1], "application/octet-stream")) |
| 81 | self.send_header("Content-Length", str(len(data))) |
| 82 | self.send_header("Cache-Control", "no-store") |
| 83 | self.end_headers() |
| 84 | self.wfile.write(data) |
| 85 | |
| 86 | def do_GET(self): |
| 87 | return self.proxy() if self.path.startswith("/allen/api/") else self.static() |
| 88 | |
| 89 | def do_POST(self): |
| 90 | return self.proxy() if self.path.startswith("/allen/api/") else self.send_error(405) |
| 91 | |
| 92 | |
| 93 | ap = argparse.ArgumentParser() |
| 94 | ap.add_argument("--dist", required=True) |
| 95 | ap.add_argument("--listen", default="127.0.0.1:18112") |
| 96 | ap.add_argument("--gateway", default="127.0.0.1:18111") |
| 97 | a = ap.parse_args() |
| 98 | h, _, p = a.listen.rpartition(":") |
| 99 | srv = ThreadingHTTPServer((h, int(p)), H) |
| 100 | srv.daemon_threads = True |
| 101 | srv.files, srv.gateway = index(a.dist), a.gateway |
| 102 | print("dev proxy on %s -> %s" % (a.listen, a.gateway), flush=True) |
| 103 | srv.serve_forever() |