#!/usr/bin/env python3 # The edge of the network's QR session-transfer service (qr.sh), what the Caddyfile of did-key-associator is in prod: # TLS on the network's address, the static site, /xrpc/* to the backend on loopback with the client's address in # X-Qr-Client-Ip. Usage: qr-front.py import http.client import http.server import mimetypes import os import ssl import sys addr, port, cert, key, www, backend = sys.argv[1], int(sys.argv[2]), sys.argv[3], sys.argv[4], os.path.realpath(sys.argv[5]), int(sys.argv[6]) FORWARD = ("authorization", "content-type", "accept", "x-oauth-qr-nonce") class Edge(http.server.BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def log_message(self, fmt, *args): sys.stderr.write("%s %s\n" % (self.client_address[0], fmt % args)) def reply(self, status, ctype, body): self.send_response(status) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(body))) self.send_header("Cache-Control", "no-cache") self.end_headers() if self.command != "HEAD": self.wfile.write(body) def proxy(self): n = int(self.headers.get("Content-Length") or 0) body = self.rfile.read(n) if n else None headers = {k: v for k, v in self.headers.items() if k.lower() in FORWARD} headers["X-Qr-Client-Ip"] = self.client_address[0] try: conn = http.client.HTTPConnection("127.0.0.1", backend, timeout=30) conn.request(self.command, self.path, body=body, headers=headers) res = conn.getresponse() data = res.read() conn.close() except OSError as e: self.reply(502, "application/json", b'{"error":"BackendUnreachable"}') sys.stderr.write("backend: %s\n" % e) return self.reply(res.status, res.getheader("Content-Type") or "application/json", data) def static(self): rel = self.path.split("?", 1)[0].split("#", 1)[0].lstrip("/") or "index.html" path = os.path.realpath(os.path.join(www, rel)) if not (path == www or path.startswith(www + os.sep)) or not os.path.isfile(path): self.reply(404, "text/plain", b"not found\n") return with open(path, "rb") as f: data = f.read() self.reply(200, mimetypes.guess_type(path)[0] or "application/octet-stream", data) def do_GET(self): if self.path.startswith("/xrpc/"): self.proxy() else: self.static() do_HEAD = do_GET def do_POST(self): if self.path.startswith("/xrpc/"): self.proxy() else: self.reply(405, "text/plain", b"method not allowed\n") mimetypes.add_type("text/javascript", ".js") mimetypes.add_type("application/json", ".json") mimetypes.add_type("application/json", ".map") server = http.server.ThreadingHTTPServer((addr, port), Edge) ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) ctx.load_cert_chain(cert, key) server.socket = ctx.wrap_socket(server.socket, server_side=True) server.serve_forever()