Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346#!/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 jsonimport osimport secretsimport sysimport urllib.errorimport urllib.parseimport urllib.requestfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))
ROOT = Path(__file__).parent.parentPRIVATE = 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 = """<style> :root{color-scheme:light dark;--accent:#2f6f5e;--accent-fill:#2f6f5e;--bg:#fff; --fg:#1a1a1a;--muted:#6b7280;--border:#d1d5db;--panel:#f7f8f8} @media(prefers-color-scheme:dark){:root{--accent:#4e9d85;--accent-fill:#2a6353; --bg:#17181c;--fg:#e8e8e8;--muted:#9aa0a6;--border:#2c2d33;--panel:#1f2025}} *{box-sizing:border-box} body{font:16px/1.55 -apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif; display:flex;min-height:100dvh;margin:0;align-items:center;justify-content:center; padding:24px;background:var(--bg);color:var(--fg)} main{width:min(400px,100%)} h1{font-size:19px;margin:0 0 2px;letter-spacing:-0.01em} h1 .dot{color:var(--accent)} .step{font-size:12px;color:var(--muted);margin:0 0 18px;letter-spacing:.02em} h2{font-size:16px;margin:0 0 6px} p{color:var(--muted);font-size:14px;margin:0 0 16px} /* 16px, or Safari zooms the page when a field takes focus and never zooms back. */ input,button,.btn{font:inherit;font-size:16px;width:100%;padding:12px;border-radius:8px; min-height:44px;display:block;text-align:center;text-decoration:none} input{border:1px solid var(--border);background:transparent;color:inherit; margin-bottom:10px;text-align:left} button,.btn.primary{border:0;background:var(--accent-fill);color:#fff;cursor:pointer} .btn.quiet{border:1px solid var(--border);background:var(--panel);color:var(--fg); margin-bottom:8px} .link{background:none;border:0;color:var(--accent);font-size:14px;cursor:pointer; padding:10px 0;min-height:0;width:auto;text-align:left} [hidden]{display:none}</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 = """<!doctype html><meta charset=utf-8><meta name=viewport content="width=device-width, initial-scale=1, viewport-fit=cover"><meta name=theme-color content="#2f6f5e"><title>aligned.click — sign in</title>""" + STYLE + """<main> <h1>aligned<span class=dot>.</span>click</h1>
<section id=s1> <p class=step>Your identity</p> <h2>You sign in with an atproto account</h2> <p>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.</p> <button onclick="go(3)">I have one</button> <p style="margin:14px 0 6px">Otherwise, create one:</p> <a class="btn quiet" href="https://eurosky.tech/accounts" target=_blank rel=noopener>Eurosky — European hosting</a> <a class="btn quiet" href="https://bsky.app" target=_blank rel=noopener>Bluesky</a> <button class=link onclick="go(2)">What is this site? →</button> </section>
<section id=s2 hidden> <p class=step>What is this site?</p> <h2>One feed, shaped by asking</h2> <p>aligned.click is a Bluesky feed. You ask for more of what you want to see — “posts about community gardens” — and that request becomes a region in the embedding space. Posts that fit the region land in the feed under your name.</p> <p>Signing in is how a request is yours: it is published to your own repo as a record, and reads are open to everyone.</p> <button onclick="go(3)">Sign in</button> <button class=link onclick="go(1)">← Back</button> </section>
<section id=s3 hidden> <p class=step>Sign in</p> <h2>Sign in</h2> <p>You are sent to your own server to do it. Nothing here ever sees your password.</p> <form action=/login> <input name=handle placeholder="you.bsky.social" autocapitalize=none autocorrect=off autocomplete=username spellcheck=false> <button>Continue</button> </form> <button class=link onclick="go(1)">← Back</button> </section></main><script>function go(n){[1,2,3].forEach(i=>{document.getElementById("s"+i).hidden=i!==n})}</script>"""
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