Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347#!/usr/bin/env python3"""The aligned.click admin site — the operator surface.
Binds loopback and is reached through the auth proxy at /admin, so the calleris whoever the proxy's X-Forwarded-DID says they are. The gate isprivate/members.json: only the DIDs listed there may open the site or use itswrites; everyone else gets a 403.
GET /admin the admin page GET /api/me who I am, and whether I am an admin GET /api/stats pool statistics GET /api/keywords every keyword with its lifecycle fields POST /api/keywords {"terms"} index new retrieval keywords (admin-only, run in the background) GET /api/topics every topic with its processing state GET /api/topics/<rkey>/exemplars a topic's region anchors
Reads and writes are admin-only. The one write — adding keywords — only widensthe pool; membership (grades, assignments) is never touched from here.
python3 admin/server.py # http://127.0.0.1:8790"""
import jsonimport osimport sysimport threadingimport timeimport urllib.parsefrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom pathlib import Path
ROOT = Path(__file__).parentsys.path.insert(0, str(ROOT.parent))
from feed import store # noqa: E402from admin import members # noqa: E402from shared.log import log # noqa: E402
PORT = int(os.environ.get("ADMIN_PORT", "8790"))
CSP = ("default-src 'none'; script-src 'self' 'unsafe-inline'; " "style-src 'self' 'unsafe-inline'; img-src 'self' data:; " "connect-src 'self'; font-src 'self'; base-uri 'none'; " "frame-ancestors 'none'")
# A body larger than this is a mistake, not a payload.MAX_BODY = 1 << 20
def _int_param(params, name): try: return int((params.get(name) or [None])[0]) except (TypeError, ValueError): return None
class Handler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" server_version = "aligned-admin"
# ---- 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 = self.headers.get("Content-Length") try: length = int(length or 0) except ValueError: length = 0 if length <= 0 or length > MAX_BODY: 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): # noqa: A002 — the console stays pass # quiet; log() handles 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)
def _caller(self): """The logged-in reader — the auth proxy's X-Forwarded-DID. The admin server binds loopback, so only the proxy can reach it; this header is the same trust the app relies on.""" return str(self.headers.get("X-Forwarded-DID") or "").strip()
def _require_admin(self): """403 unless the caller is on the members list. Returns True when allowed, or False after sending the reply.""" did = self._caller() if not members.is_admin(did): self.reply(403, {"error": "not an admin"}) return False return True
# ---- routing ---------------------------------------------------------
@staticmethod def _strip_admin(path: str) -> str: """The proxy forwards the full path, so the admin server receives `/admin/api/...`, not `/api/...`. Strip the mount prefix before routing; direct loopback access (no prefix) is unchanged.""" if path == "/admin": return "/" if path.startswith("/admin/"): return path[len("/admin"):] return path
def do_GET(self): path = self._strip_admin( urllib.parse.unquote(self.path.split("?")[0])) if path == "/": return self.page() if not self._require_admin(): return if path == "/api/me": return self.me() if path == "/api/stats": return self.stats() if path == "/api/keywords": return self.keywords() if path == "/api/topics": return self.topics() if path == "/api/logs": return self.logs() if path == "/api/llm": return self.llm() if path.startswith("/api/topics/") and path.endswith("/exemplars"): rkey = path[len("/api/topics/"):-len("/exemplars")] return self.exemplars(rkey) return self.reply(404, {"error": "not found"})
def do_POST(self): path = self._strip_admin(self.path.split("?")[0]) if not self._require_admin(): return body = self.body() if path == "/api/keywords": return self.add_keywords(body) if path.startswith("/api/keywords/"): return self.keyword_action(path, body) return self.reply(404, {"error": "not found"})
# ---- keywords ---------------------------------------------------------
def keyword_action(self, path, body): """Per-keyword actions: /api/keywords/<kw>/include, /exclude, /delete, /extend. The keyword is URL-encoded in the path.""" rest = path[len("/api/keywords/"):] if "/" not in rest: return self.reply(404, {"error": "not found"}) raw, action = rest.rsplit("/", 1) keyword = urllib.parse.unquote(raw) if not store.get_keyword(keyword): return self.reply(404, {"error": f"no such keyword: {keyword}"}) if action == "include": # Back on the firehose filter. Touch last_seen so a re-included # keyword gets a full prune window instead of being pruned on the # very next housekeeping round. store.update_keyword(keyword, status="indexed", last_seen=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())) log(f"admin {self._caller()}: include {keyword}") return self.reply(200, {"keyword": keyword, "status": "indexed"}) if action == "exclude": # Paused off the filter; its posts stay. Harvest still sees it and # won't re-propose it. store.update_keyword(keyword, status="excluded") log(f"admin {self._caller()}: exclude {keyword}") return self.reply(200, {"keyword": keyword, "status": "excluded"}) if action == "delete": store.delete_keyword(keyword) log(f"admin {self._caller()}: delete {keyword}") return self.reply(200, {"deleted": keyword}) if action == "extend": return self.extend(keyword) return self.reply(404, {"error": "not found"})
def extend(self, keyword): """Harvest the keyword's top extensions and return them for the admin to pick from. Synchronous: it pages through the keyword's recent posts (up to KEYWORD_POST_CAP), which for a common keyword is a few seconds of search API calls.""" try: from feed import keywords as kw exts = kw.extensions(keyword) except Exception as e: # noqa: BLE001 — a verdict, not a traceback return self.reply(400, {"error": f"extend failed: {e}"}) log(f"admin {self._caller()}: extend {keyword} -> {len(exts)} candidate(s)") return self.reply(200, {"keyword": keyword, "extensions": exts})
# ---- pages -----------------------------------------------------------
def page(self): did = self._caller() if not members.is_admin(did): return self.reply(403, "<!doctype html><meta charset=utf-8>" "<title>aligned.click admin</title>" "<style>body{font:16px system-ui;display:flex;" "align-items:center;justify-content:center;" "min-height:100dvh;margin:0;color:#e8e8e8;" "background:#17181c}main{text-align:center}" "p{color:#9aa0a6}a{color:#4e9d85}</style>" "<main><h1>aligned<span style='color:#4e9d85'>." "</span>click admin</h1>" "<p>Not an admin — the people listed in " "private/members.json.</p>" "<p><a href='/'>back to the feed</a></p></main>", "text/html; charset=utf-8") return self.reply(200, (ROOT / "index.html").read_text(), "text/html; charset=utf-8")
# ---- API -------------------------------------------------------------
def me(self): did = self._caller() handle = "" if did: from shared.identity import resolve_handle handle = resolve_handle(did) return self.reply(200, { "did": did, "handle": handle, "admin": members.is_admin(did), })
def stats(self): return self.reply(200, store.pool_stats())
def logs(self): params = urllib.parse.parse_qs( urllib.parse.urlparse(self.path).query) n = _int_param(params, "n") or 200 from shared import log as slog return self.reply(200, {"lines": slog.tail(max(1, min(n, 2000)))})
def llm(self): params = urllib.parse.parse_qs( urllib.parse.urlparse(self.path).query) n = _int_param(params, "n") or 100 topic = (params.get("topic") or [""])[0] return self.reply(200, {"calls": store.recent_llm(max(1, min(n, 500)), topic=topic)})
def keywords(self): out = store.all_keywords() out.sort(key=lambda k: k["keyword"].lower()) return self.reply(200, {"keywords": out})
def topics(self): from shared.identity import resolve_handle assigned = store.assignment_counts() exemplars = store.exemplar_counts() out = [] for t in store.all_topics(): rkey = t["rkey"] progress = store.progress_for(rkey) out.append({ "rkey": rkey, "did": t.get("did", ""), "handle": resolve_handle(t.get("did", "")) if t.get("did") else "", "text": t["text"], "distance": t.get("distance", 0), "status": t.get("status", ""), "processed": bool(t.get("processed")), "created": t.get("created", ""), "posts": assigned.get(rkey, 0), "exemplars": exemplars.get(rkey, 0), "progress": progress[-1]["msg"] if progress else "", }) out.sort(key=lambda t: t["created"], reverse=True) return self.reply(200, {"topics": out})
def exemplars(self, rkey): t = store.get_topic(rkey) if not t: return self.reply(404, {"error": "no such topic"}) items = [] for e in store.exemplars_for(rkey): items.append({"text": e["text"], "dim": int(len(e["embedding"]))}) return self.reply(200, {"topic": rkey, "exemplars": items})
def add_keywords(self, body): raw = body.get("terms") or body.get("keywords") if isinstance(raw, str): terms = [t.strip() for t in raw.split(",") if t.strip()] elif isinstance(raw, list): terms = [str(t).strip() for t in raw if str(t).strip()] else: return self.reply(400, {"error": "no terms"}) if not terms: return self.reply(400, {"error": "no terms"}) if len(terms) > 12: return self.reply(400, {"error": "at most 12 terms at once"}) for t in terms: if len(t) > 40: return self.reply(400, {"error": f"term too long: {t[:40]}…"}) # Indexing searches, embeds, and pools — minutes for a few terms. Run # it off the request thread; the keywords table picks the results up # (the store's short table TTL makes them visible within seconds). from feed import keywords as kw def run(): try: kw.index_keywords(terms, provenance="admin", progress=lambda m: log(m)) except Exception as e: # noqa: BLE001 log(f"index_keywords {terms} failed: {e}") threading.Thread(target=run, daemon=True).start() log(f"admin {self._caller()}: indexing {terms}") return self.reply(202, { "terms": terms, "note": "indexing started in the background — the terms will " "appear in the table as they are searched and pooled.", })
if __name__ == "__main__": store.ensure() server = ThreadingHTTPServer(("127.0.0.1", PORT), Handler) print(f"aligned admin: http://127.0.0.1:{PORT} (via proxy /admin)", file=sys.stderr) try: server.serve_forever() except KeyboardInterrupt: pass