#!/usr/bin/env python3 """The aligned.click proxy: the only thing the tunnel ever exposes. Everything else binds 127.0.0.1 — the OAuth sidecar (credentials), the app, the feed server. This sits in front of them and does three jobs: 1. **Authenticate.** A cookie names a session, and a session names a DID. The login itself is the sidecar's; the cookie here is ours — a random token that means "this browser is that DID", nothing more. The proxy never holds a Bluesky credential. 2. **Route by path.** /xrpc/* → feedgen (the atproto feed server, public) /admin/* → the admin site (loopback, gated by members.json) /api/* and / → the app, with X-Forwarded-DID set when logged in, so /api/request writes the topic record as the right person. Reads are public. The OAuth sidecar is reached only through `ask_sidecar` (login, callback, client metadata, jwks) — its `/oauth/sessions` and `/oauth/logout` admin routes are never forwarded, so they are not on the tunnel. 3. **Refuse nothing that needs refusing.** aligned.click has no allowlist — any atproto handle can log in and request a topic. The gate is "is someone logged in" for writes; reads are open to the world. The one exception is the admin site at /admin, whose gate is private/members.json (only the DIDs listed there get in). python3 auth/proxy.py # serve on 8778 """ import json import os import secrets import sys import urllib.error import urllib.parse import urllib.request from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent)) ROOT = Path(__file__).parent.parent PRIVATE = ROOT / "private" SESSIONS_FILE = PRIVATE / "proxy-sessions.json" PORT = int(os.environ.get("PROXY_PORT", 8778)) SIDECAR = os.environ.get("OAUTH_SIDECAR", "http://127.0.0.1:4098").rstrip("/") APP = os.environ.get("APP_URL", "http://127.0.0.1:8782").rstrip("/") FEEDGEN = os.environ.get("FEEDGEN_URL", "http://127.0.0.1:8784").rstrip("/") ADMIN = os.environ.get("ADMIN_URL", "http://127.0.0.1:8790").rstrip("/") PUBLIC_URL = os.environ.get("PUBLIC_URL", "https://aligned.click").rstrip("/") COOKIE = "aligned_session" SESSION_TTL = int(os.environ.get("SESSION_TTL", 60 * 60 * 24 * 30)) UPSTREAM = {"/xrpc": FEEDGEN, "/admin": ADMIN} STYLE = """""" # Signing in with an atproto account, on their own server. The account-creation # links are the "or" of the first step: aligned.click takes any handle on the # network, so the only thing a person without one needs is somewhere to get one. # Eurosky is listed because it is the European home for an atproto handle — this # site is European too. LOGIN_PAGE = """ aligned.click — sign in """ + STYLE + """

aligned.click

Your identity

You sign in with an atproto account

Not an account here — one you own, on the network. Everything this makes is published to your repo under your name, and works the same if you stop using this site.

Otherwise, create one:

Eurosky — European hosting Bluesky
""" def load_sessions() -> dict[str, str]: if not SESSIONS_FILE.exists(): return {} try: return json.loads(SESSIONS_FILE.read_text()) except json.JSONDecodeError: return {} def save_sessions(sessions: dict[str, str]) -> None: SESSIONS_FILE.parent.mkdir(exist_ok=True) tmp = SESSIONS_FILE.with_suffix(".tmp") tmp.write_text(json.dumps(sessions, indent=2)) os.chmod(tmp, 0o600) tmp.replace(SESSIONS_FILE) class Proxy(BaseHTTPRequestHandler): sessions = load_sessions() # ---- helpers --------------------------------------------------------- def log_message(self, fmt, *args): sys.stderr.write(f"{self.address_string()} {fmt % args}\n") def reply(self, status, body=b"", content_type="application/json", extra=()): if isinstance(body, (dict, list)): body = json.dumps(body).encode() elif isinstance(body, str): body = body.encode() self.send_response(status) self.send_header("Content-Type", content_type) self.send_header("Content-Length", str(len(body))) self.send_header("X-Content-Type-Options", "nosniff") for key, value in extra: self.send_header(key, value) self.end_headers() if self.command != "HEAD": self.wfile.write(body) def cookie_token(self): for part in self.headers.get("Cookie", "").split(";"): name, _, value = part.strip().partition("=") if name == COOKIE: return value return None def set_cookie(self, token): bits = [f"{COOKIE}={token}", "Path=/", "HttpOnly", "SameSite=Lax", f"Max-Age={SESSION_TTL}"] if PUBLIC_URL.startswith("https://"): bits.append("Secure") return ("Set-Cookie", "; ".join(bits)) def did_for(self): return self.sessions.get(self.cookie_token() or "") def ask_sidecar(self, path, method="GET", body=None): req = urllib.request.Request( f"{SIDECAR}{path}", data=body, method=method, headers={"Content-Type": "application/json"} if body else {}, ) try: with urllib.request.urlopen(req, timeout=30) as r: return r.status, r.read() except urllib.error.HTTPError as e: return e.code, e.read() except OSError as e: return 502, json.dumps( {"error": f"OAuth sidecar unreachable: {e}"}).encode() def forward(self, base, method): url = urllib.parse.urlsplit(self.path) body = None if method in ("POST", "PUT", "PATCH", "DELETE"): length = int(self.headers.get("Content-Length") or 0) body = self.rfile.read(length) if length else b"" headers = { "Content-Type": self.headers.get("Content-Type", "application/json"), "X-Forwarded-For": self.client_address[0], "X-Forwarded-Proto": "https", } did = self.did_for() if did: headers["X-Forwarded-DID"] = did req = urllib.request.Request( f"{base}{url.path}{'?' + url.query if url.query else ''}", data=body, method=method, headers=headers, ) try: with urllib.request.urlopen(req, timeout=60) as r: out = r.read() self.send_response(r.status) for key in ("Content-Type", "Content-Length"): if r.headers.get(key): self.send_header(key, r.headers.get(key)) self.end_headers() if self.command != "HEAD": self.wfile.write(out) except urllib.error.HTTPError as e: out = e.read() self.send_response(e.code) self.send_header("Content-Type", e.headers.get("Content-Type", "application/json")) self.end_headers() if self.command != "HEAD": self.wfile.write(out) except OSError as e: self.reply(502, {"error": str(e)}) # ---- routing --------------------------------------------------------- def route(self, method): path = urllib.parse.urlsplit(self.path).path if path == "/healthz": return self.reply(200, {"ok": True, "dids": len(set(self.sessions.values()))}) # Public, necessarily so: the authorization server fetches these # itself, with no cookie and no browser involved. if path in ("/client-metadata.json", "/jwks.json"): status, out = self.ask_sidecar(path) return self.reply(status, out) if path == "/login": return self.begin_login() if path == "/oauth/callback": return self.finish_login() if path == "/logout": return self.logout() # Feed server and sidecar pass through by path prefix. for prefix, base in UPSTREAM.items(): if path == prefix or path.startswith(prefix + "/"): return self.forward(base, method) # Everything else is the app. The X-Forwarded-DID header carries the # logged-in person; the app reads it for writes. return self.forward(APP, method) def do_GET(self): self.route("GET") def do_POST(self): self.route("POST") def do_DELETE(self): self.route("DELETE") # ---- login ----------------------------------------------------------- def begin_login(self): handle = urllib.parse.parse_qs( urllib.parse.urlsplit(self.path).query).get("handle", [""])[0].strip() if not handle: # The front door to signing in: a three-step page that ends in the # handle form below. Logging in from the app goes here. return self.reply(200, LOGIN_PAGE, "text/html; charset=utf-8") status, out = self.ask_sidecar( f"/oauth/login?handle={urllib.parse.quote(handle)}&json=1") try: authorize = json.loads(out)["authorize"] except (ValueError, KeyError): return self.reply(status, out) return self.reply(302, b"", "text/plain", [("Location", authorize)]) def finish_login(self): query = urllib.parse.urlsplit(self.path).query status, out = self.ask_sidecar(f"/oauth/callback?{query}") try: did = json.loads(out)["did"] except (ValueError, KeyError): return self.reply(status, out) token = secrets.token_urlsafe(32) self.sessions[token] = did save_sessions(self.sessions) return self.reply(302, b"", "text/plain", [("Location", "/"), self.set_cookie(token)]) def logout(self): token = self.cookie_token() if token: self.sessions.pop(token, None) save_sessions(self.sessions) return self.reply(302, b"", "text/plain", [ ("Location", "/"), ("Set-Cookie", f"{COOKIE}=; Path=/; HttpOnly; Max-Age=0"), ]) if __name__ == "__main__": PRIVATE.mkdir(exist_ok=True) server = ThreadingHTTPServer(("127.0.0.1", PORT), Proxy) print(f"aligned proxy: http://127.0.0.1:{PORT} " f"(app {APP}, feedgen {FEEDGEN}, sidecar {SIDECAR})") try: server.serve_forever() except KeyboardInterrupt: pass