#!/usr/bin/env python3 """The aligned.click web product — the public surface. Serves app/index.html plus the product's reads and its one write: GET / the product page GET /shared/… the one copy of atproto-wc + theme GET /api/feeds the main feed GET /api/topics every topic, grouped mine/liked/rest GET /api/topic/ one topic and its fitted posts GET /api/me who the proxy thinks the reader is POST /api/request {"text"} create a topic from the literal answer POST /api/vote {"uri"} +1 a post: a vote record in the voter's repo POST /api/engage like/repost a post: a standard atproto record (app.bsky.feed.like / .repost) in the voter's repo, toggled on/off POST /api/fit a member's fit/no-fit verdict on a post in a topic — private ground truth for the judge, not an atproto record, toggled on/off Posts are not served here. The page draws each pick as an element, which renders the post live from whichever PDS hosts its author — the same split the reader used, for the same reason. python3 app/server.py # http://127.0.0.1:8782 Reading is public. Writing is a record in the writer's own repo — a request record or a vote record — so the truth lives on atproto and this store is only its cache: the auth proxy passes the logged-in reader as the X-Forwarded-DID header, and this server writes through the OAuth sidecar as them. A topic appears in the store the moment its request is written (greyed out until its pass is done) — the firehose only pools posts, never topics. """ import argparse import json import os import sys import threading import time import urllib.parse from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path ROOT = Path(__file__).parent sys.path.insert(0, str(ROOT.parent)) from feed import store, topics # noqa: E402 from admin import members # noqa: E402 from shared.log import log # noqa: E402 PORT = int(os.environ.get("ALIGNED_PORT", "8782")) SHARED = ROOT / "shared" CONTENT_TYPES = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".json": "application/json; charset=utf-8", ".svg": "image/svg+xml", } CSP = ("default-src 'none'; script-src 'self' 'unsafe-inline'; " "style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; " "connect-src 'self' https:; font-src 'self'; base-uri 'none'; " "frame-ancestors 'none'") def _int_param(params, name): try: return int((params.get(name) or [None])[0]) except (TypeError, ValueError): return None def _enrich_handles(posts): """Give every post's fitting topics their creator's handle. DIDs resolve through the public directory once each and are cached.""" from shared.identity import resolve_handle seen: dict[str, str] = {} for p in posts: for t in p.get("topics") or []: d = t.get("did") or "" if d not in seen: seen[d] = resolve_handle(d) t["handle"] = seen[d] return posts class Handler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" server_version = "aligned-app" # ---- plumbing ------------------------------------------------------- def reply(self, status, body=b"", content_type="application/json; charset=utf-8"): 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("Content-Security-Policy", CSP) self.send_header("Referrer-Policy", "no-referrer") self.send_header("X-Content-Type-Options", "nosniff") self.end_headers() if self.command != "HEAD": self.wfile.write(body) def body(self): length = int(self.headers.get("Content-Length") or 0) if not length: return {} try: return json.loads(self.rfile.read(length)) except json.JSONDecodeError: return {} def send_error(self, code, message=None, explain=None): # noqa: A003 self.reply(code, {"error": message or "error"}) def log_message(self, format, *args): # the console stays quiet; log() pass # handles the request lines def log_request(self, status): try: line = f"{self.command} {self.path} -> {status}" except Exception: # noqa: BLE001 line = f"{self.command} {self.path}" log(line) # ---- routing --------------------------------------------------------- def do_GET(self): path = urllib.parse.unquote(self.path.split("?")[0]) if path == "/": return self.reply(200, (ROOT / "index.html").read_text(), "text/html; charset=utf-8") if path.startswith("/shared/"): return self.serve_static(path[len("/shared/"):]) if path == "/api/feeds": return self.feeds() if path == "/api/topics": return self.topics() if path == "/api/me": return self.me() if path.startswith("/api/topic/"): return self.topic(path[len("/api/topic/"):]) return self.reply(404, {"error": "not found"}) def do_POST(self): body = self.body() if self.path == "/api/request": return self.create_request(body) if self.path == "/api/vote": return self.vote(body) if self.path == "/api/engage": return self.engage(body) if self.path == "/api/fit": return self.fit(body) return self.reply(404, {"error": "not found"}) def do_DELETE(self): path = urllib.parse.unquote(self.path.split("?")[0]) if path.startswith("/api/topic/"): return self.delete_topic(path[len("/api/topic/"):]) return self.reply(404, {"error": "not found"}) # ---- API ------------------------------------------------------------- def _caller(self): """The logged-in reader — the auth proxy's X-Forwarded-DID. There is no dev mode: a reader is whoever the proxy's OAuth session says they are, and nothing lets a caller claim to be anyone else.""" return str(self.headers.get("X-Forwarded-DID") or "").strip() def feeds(self): params = urllib.parse.parse_qs( urllib.parse.urlparse(self.path).query) min_grade = _int_param(params, "min_grade") min_fit = _int_param(params, "min_fit") offset = max(_int_param(params, "offset") or 0, 0) limit = max(_int_param(params, "limit") or 10, 1) did = self._caller() main = store.main_feed(limit, min_grade=min_grade, min_fit=min_fit, did=did, offset=offset) _enrich_handles(main) self._annotate_engagement(main, did) has_more = len(main) == limit return self.reply(200, { "main": main, "offset": offset + len(main), "hasMore": has_more, }) def topics(self): """Every feed, annotated for the left pane: `mine` (the caller created it), `liked` (the caller +1'd a post in it), `processed` (background pass done), the latest status line for one still processing, and the creator's handle for the title sentence.""" did = self._caller() voted = set(store.voted_uris(did)) if did else set() from shared.identity import resolve_handle handles: dict[str, str] = {} out = [] for t in store.all_topics(): rkey = t["rkey"] creator = t.get("did", "") if creator not in handles: handles[creator] = resolve_handle(creator) if creator else "" uri = f"at://{creator}/click.aligned.feed.request/{rkey}" if creator else "" uris = set(store.fitted_uris(topic=rkey)) processed = bool(t.get("processed")) status = "" if not processed: progress = store.progress_for(rkey) if progress: status = progress[-1]["msg"] out.append({ "rkey": rkey, "text": t["text"], "did": creator, "uri": uri, "handle": handles[creator], "mine": bool(did) and creator == did, "liked": bool(did) and uri in voted, "processed": processed, "status": status, "posts": len(uris), "created": t.get("created", ""), }) # Mine first, then liked, then the rest. Within a group the newest # come first; a topic still processing is fresh, so it lands at the # top of "your feeds" and greys out with its status line beneath. def group(t): if t["mine"]: return 0 if t["liked"]: return 1 return 2 out.sort(key=lambda t: (group(t), t["created"]), reverse=True) out.sort(key=group) return self.reply(200, {"topics": out}) def topic(self, rkey): rkey = rkey.split("?")[0] params = urllib.parse.parse_qs( urllib.parse.urlparse(self.path).query) min_fit = _int_param(params, "min_fit") offset = max(_int_param(params, "offset") or 0, 0) limit = max(_int_param(params, "limit") or 10, 1) did = self._caller() t = store.get_topic(rkey) if not t: return self.reply(404, {"error": "no such topic"}) uris = store.fitted_uris(topic=rkey, min_score=min_fit) votes = store.vote_counts(uris) voted = set(store.voted_uris(did)) if did else set() verdicts = (store.feedback_for(rkey, did) if did and members.is_member(did) else {}) posts = [] for u in uris: p = store.get_post(u) if p: p.pop("embedding", None) p["fit"] = store.score_for(u, rkey) p["votes"] = votes.get(u, 0) p["voted"] = u in voted p["fitVerdict"] = verdicts.get(u) posts.append(p) posts.sort(key=lambda p: p.get("createdAt") or "", reverse=True) window = posts[offset:offset + limit] self._annotate_engagement(window, did) from shared.identity import resolve_handle creator = t.get("did", "") uri = f"at://{creator}/click.aligned.feed.request/{rkey}" if creator else "" topic_votes = store.vote_counts([uri]).get(uri, 0) if uri else 0 topic_voted = uri in set(store.voted_uris(did)) if uri and did else False return self.reply(200, { "topic": {"rkey": rkey, "did": creator, "handle": resolve_handle(creator) if creator else "", "uri": uri, "text": t["text"], "distance": t.get("distance", 0), "processed": bool(t.get("processed")), "votes": topic_votes, "voted": topic_voted}, "posts": window, "offset": offset + len(window), "hasMore": len(window) == limit, }) def delete_topic(self, rkey): """Remove a topic — only its own creator can. The request record is deleted from the creator's repo too: the truth lives on atproto, and the store row is its cache.""" rkey = rkey.split("?")[0] did = self._caller() t = store.get_topic(rkey) if not t: return self.reply(404, {"error": "no such topic"}) if not did or t.get("did") != did: return self.reply(403, {"error": "you can only delete your own " "topics"}) if t.get("did"): try: from auth import records records.delete("click.aligned.feed.request", rkey, did) except Exception as e: # noqa: BLE001 — a verdict, not a traceback return self.reply(400, {"error": str(e)}) store.delete_topic(rkey) return self.reply(200, {"deleted": rkey}) def me(self): did = self.headers.get("X-Forwarded-DID", "") handle = "" if did: from shared.identity import resolve_handle handle = resolve_handle(did) return self.reply(200, { "did": did, "handle": handle, "loggedIn": bool(did), "member": bool(did) and members.is_member(did), }) def fit(self, body): """A member's fit/no-fit verdict on one post inside a topic — the ground truth the judge will learn from. Stored privately (not an atproto record); the same verdict again clears it.""" uri = str(body.get("uri") or "").strip() topic = str(body.get("topic") or "").strip() label = str(body.get("label") or "").strip() did = self._caller() if not did: return self.reply(401, {"error": "log in to judge fit"}) if not members.is_member(did): return self.reply(403, {"error": "members only"}) if not uri.startswith("at://"): return self.reply(400, {"error": "no post uri"}) if not store.get_topic(topic): return self.reply(404, {"error": "no such topic"}) if label not in ("fit", "no-fit"): return self.reply(400, {"error": "label must be 'fit' or 'no-fit'"}) verdict = store.set_feedback(uri, topic, did, label) return self.reply(200, {"uri": uri, "topic": topic, "verdict": verdict}) def vote(self, body): uri = str(body.get("uri") or "").strip() did = self._caller() if not did: return self.reply(401, {"error": "log in to +1 posts"}) if not uri: return self.reply(400, {"error": "no post uri"}) # The +1 is a record in the voter's own repo — the truth is on # atproto; the votes table is only its cache. A record write is the # authenticated act, so a failed write is a failed vote, not something # to paper over with a cache row. try: from auth import records records.create("click.aligned.feed.vote", { "$type": "click.aligned.feed.vote", "post": uri, "createdAt": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), }, did) except Exception as e: # noqa: BLE001 — a verdict, not a traceback return self.reply(400, {"error": str(e)}) store.vote(uri, did) count = store.vote_counts([uri]).get(uri, 0) return self.reply(200, {"uri": uri, "count": count, "voted": True}) def engage(self, body): """Like or repost a post — a toggle. The action is a standard atproto record (app.bsky.feed.like / app.bsky.feed.repost) written to the reader's own repo through the sidecar, so it shows up on Bluesky itself; the store is not involved. The post's CID comes from the author's PDS at click time — our posts table keeps no CID. Clicking again removes the record (listRecords finds the one we wrote).""" uri = str(body.get("uri") or "").strip() kind = str(body.get("kind") or "").strip().lower() did = self._caller() if not did: return self.reply(401, {"error": "log in to like and repost"}) if kind not in ("like", "repost"): return self.reply(400, {"error": "kind must be 'like' or 'repost'"}) if not uri.startswith("at://"): return self.reply(400, {"error": "no post uri"}) collection = f"app.bsky.feed.{kind}" try: from auth import bsky, records repo = uri[5:].split("/", 1)[0] rkey = uri.rsplit("/", 1)[-1] got = bsky.get("com.atproto.repo.getRecord", { "repo": repo, "collection": "app.bsky.feed.post", "rkey": rkey, }, did) cid = got.get("cid") if not cid: return self.reply(400, {"error": "could not resolve the post"}) existing = self._my_record(collection, uri, did) if existing: records.delete(collection, existing, did) return self.reply(200, {"uri": uri, "kind": kind, "engaged": False}) records.create(collection, { "$type": collection, "subject": {"uri": uri, "cid": cid}, "createdAt": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), }, did) return self.reply(200, {"uri": uri, "kind": kind, "engaged": True}) except Exception as e: # noqa: BLE001 — a verdict, not a traceback return self.reply(400, {"error": str(e)}) def _my_record(self, collection, uri, did): """The rkey of the reader's own record in `collection` whose subject is `uri`, or None. The truth is on atproto; we look it up live rather than keeping a mirror table.""" from auth import bsky page = bsky.get("com.atproto.repo.listRecords", { "repo": did, "collection": collection, "limit": 100, }, did) for rec in page.get("records", []): subject = (rec.get("value") or {}).get("subject") or {} if subject.get("uri") == uri: return rec["uri"].rsplit("/", 1)[-1] return None def _engagement(self, did): """{(kind): {post uri}} — the posts this reader has liked / reposted, read live from their repo. Used to light the buttons in the feed.""" out = {"like": set(), "repost": set()} if not did: return out from auth import bsky for kind in out: page = bsky.get("com.atproto.repo.listRecords", { "repo": did, "collection": f"app.bsky.feed.{kind}", "limit": 100, }, did) for rec in page.get("records", []): subject = (rec.get("value") or {}).get("subject") or {} if subject.get("uri"): out[kind].add(subject["uri"]) return out def _annotate_engagement(self, posts, did): """Light the like/repost buttons: which of these posts has this reader already engaged with. A live atproto read, so no mirror table; a failure (offline sidecar, new account) leaves the buttons dark.""" if not did or not posts: return try: mine = self._engagement(did) except Exception: # noqa: BLE001 — dark buttons, not a broken feed return for p in posts: p["liked"] = p["uri"] in mine["like"] p["reposted"] = p["uri"] in mine["repost"] def create_request(self, body): text = str(body.get("text") or "").strip() if not text: return self.reply(400, {"error": "the request is empty — say what " "kind of posts you want to see more of."}) # The reader is whoever the proxy's OAuth session says they are — # there is no dev mode, so a request always writes a record to that # reader's own repo. The topic appears in the store immediately — # greyed out in the left pane until its background pass is done — # like a post appearing on bsky.app the moment it's created. It is # not the firehose's job to notice request records anymore (the # worker only pools posts); the app creates the topic here, then the # worker's housekeeping picks the unprocessed topic up and runs its # pass. did = self._caller() if not did: return self.reply(401, {"error": "log in to add a topic"}) try: from auth import records out = records.create("click.aligned.feed.request", { "$type": "click.aligned.feed.request", "topic": text, "createdAt": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), }, did) except Exception as e: # noqa: BLE001 — a verdict, not a traceback return self.reply(400, {"error": str(e)}) rkey = out["uri"].rsplit("/", 1)[-1] try: topics.start_topic(rkey, did, text) except Exception as e: # noqa: BLE001 — a verdict, not a traceback return self.reply(400, {"error": str(e)}) return self.reply(200, { "rkey": rkey, "text": text, "note": "topic created. The worker is harvesting keywords, widening " "the pool, and judging candidates in its region — posts " "appear as it works. Progress streams below.", }) # ---- static ----------------------------------------------------------- def serve_static(self, rel): target = (SHARED / rel).resolve() try: target.relative_to(SHARED.resolve()) except ValueError: return self.reply(404, {"error": "not found"}) if not target.is_file(): return self.reply(404, {"error": "not found"}) ctype = CONTENT_TYPES.get(target.suffix, "application/octet-stream") return self.reply(200, target.read_bytes(), ctype) def sweep_unprocessed() -> None: """Process topics that were created but never got their background pass — created before the app started them inline, or whose pass failed. Running this here is the dev-mode counterpart of the worker's housekeeping; in production the worker is the one that picks them up. Also gives every active topic its exemplar anchor if it lacks one.""" for t in store.unprocessed_topics(): try: topics.process_topic(t["rkey"]) log(f"processed stranded topic {t['rkey']}: \"{t['text'][:40]}\"") except Exception as e: # noqa: BLE001 log(f"process_topic {t['rkey']} failed: {e}") for t in store.all_topics(): try: if topics.ensure_exemplars(t["rkey"]): log(f"wrote exemplars for {t['rkey']}: \"{t['text'][:40]}\"") except Exception as e: # noqa: BLE001 log(f"ensure_exemplars {t['rkey']} failed: {e}") def main() -> None: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--port", type=int, default=PORT, help="port to serve on (default %(default)s)") args = parser.parse_args() server = ThreadingHTTPServer(("127.0.0.1", args.port), Handler) threading.Thread(target=sweep_unprocessed, daemon=True).start() print(f"aligned at http://127.0.0.1:{args.port}", file=sys.stderr) try: server.serve_forever() except KeyboardInterrupt: pass if __name__ == "__main__": main()