interplane.Get Omega
Read in your language

aienos.com

Source of www.aienos.com, served from my own hardware

Brought by drakestapleton

branch main Branches Tags History

aienos.com / scripts / allen / allen_projects.py

204 lines · 9673 bytes Raw Blame History
1"""The build loop in the public gateway: homes, save, publish, gallery, and Drake's approve list.
2
3allen_chat.py calls into this module from a few hook lines; it holds no GitHub credential.
4Save and publish items go into the same write-only spool as issues and are filed by
5omega-projects-pusher (allen_build.py documents the item shapes).
6
7Public routes (/allen/api/...):
8 POST projects/handle {"name"} remembered visitor (X-Allen-Key): the stable handle
9 <name>-<8 hex>, remembered in the visitor Cortex as
10 "Builder handle: ..."; anonymous: a one-time handle
11 anon-<10 hex> and its claim code, shown once and never stored.
12 GET projects/me the caller's handle: from the visitor Cortex, or from the
13 claim code in X-Allen-Claim; null when there is none.
14 POST projects/save item one commit on u/<handle> (viewable on GitHub at once)
15 POST projects/publish item a pull request to main for Drake's approval
16 GET gallery merged projects ("Built with Aien")
17Ownership is checked here, server side, for every save and publish: a remembered handle
18must match HMAC(secret, vid) for the caller's own key, an anon- handle must match the
19caller's claim code. Model output cannot set either header.
20
21Console (Drake, tailnet only): a "Projects waiting for you" section listing open publish
22requests with links to review and approve on GitHub, a Decline button (the pusher comments
23and closes the pull request) and a Refresh button (the pusher rewrites the index).
24"""
25
26import html
27import os
28import secrets
29
30import allen_build as build
31import allen_spool as spool
32
33NOTE = "Builder handle: "
34
35
36def init(app, buckets):
37 """Called from App.__init__ with the gateway's token-bucket class."""
38 app.build_save_rate = buckets(10, 60)
39 app.build_publish_rate = buckets(3, 1200)
40 app.build_handle_rate = buckets(5, 600)
41
42
43def _secret(h):
44 return h.app.visitor_secret
45
46
47def _claim(h):
48 c = h.headers.get("X-Allen-Claim", "").strip()
49 return c if build.CLAIM.match(c) else None
50
51
52def get(h, route):
53 """Public GET routes; True when handled."""
54 if route == "projects/me":
55 return _me(h) or True
56 if route == "gallery":
57 idx = build.read_index(h.app.args.spool_status) if h.app.args.spool_status else build.read_index("/nonexistent")
58 h.send_json(200, {"updated": idx.get("updated"), "gallery": idx["gallery"],
59 "repo": build.REPO_URL})
60 return True
61 return False
62
63
64def post(h, route):
65 """Public POST routes; True when handled."""
66 if route == "projects/handle":
67 return _handle(h) or True
68 if route in ("projects/save", "projects/publish"):
69 return _drop(h, route.split("/")[1]) or True
70 return False
71
72
73def _me(h):
74 app, secret = h.app, _secret(h)
75 if not secret:
76 return h.send_json(503, {"error": "unavailable", "message": "Homes are not available right now."})
77 claim = _claim(h)
78 if claim:
79 return h.send_json(200, {"handle": build.handle_for_claim(secret, claim), "anonymous": True})
80 vid = app.vid(h)
81 handle = None
82 if vid and app.memory:
83 for note in app.memory.recall(vid, 40):
84 if note.startswith(NOTE):
85 cand = note[len(NOTE):].split()[0] if note[len(NOTE):].split() else ""
86 if build.owns(secret, cand, vid=vid):
87 handle = cand
88 break
89 return h.send_json(200, {"handle": handle, "anonymous": vid is None})
90
91
92def _handle(h):
93 app, secret = h.app, _secret(h)
94 if not secret:
95 return h.send_json(503, {"error": "unavailable", "message": "Homes are not available right now."})
96 req = h.read_json()
97 if req is None:
98 return None
99 retry = app.build_handle_rate.take(app.client_key(h))
100 if retry:
101 return h.refuse(429, "rate", "Too many requests. Try again shortly.", retry)
102 vid = app.vid(h)
103 if vid is None:
104 claim = build.new_claim()
105 app.stats.add("build_handle_anon")
106 return h.send_json(200, {"handle": build.handle_for_claim(secret, claim), "claim": claim, "anonymous": True,
107 "message": "Keep this claim code: it is shown once and is the only way to "
108 "save to this home again."})
109 name = req.get("name") if isinstance(req, dict) else None
110 try:
111 handle = build.handle_for_vid(secret, vid, name if isinstance(name, str) else "")
112 except build.Invalid as e:
113 return h.send_json(422, {"error": "invalid", "message": str(e)})
114 remembered = bool(app.memory and app.memory.replace_note(vid, NOTE, handle, max_chars=80))
115 app.stats.add("build_handle")
116 return h.send_json(200, {"handle": handle, "anonymous": False, "remembered": remembered,
117 "home": "%s/tree/u/%s/projects/%s" % (build.REPO_URL, handle, handle)})
118
119
120def _drop(h, kind):
121 app, secret = h.app, _secret(h)
122 app.stats.add("build_%s_requests" % kind)
123 if not app.args.spool_in or not secret:
124 return h.send_json(404, {"error": "not_found"})
125 req = h.read_json()
126 if req is None:
127 return None
128 if not isinstance(req, dict):
129 return h.send_json(422, {"error": "invalid", "message": "Send a JSON object."})
130 req = dict(req, v=1, kind=kind)
131 if not build.owns(secret, req.get("handle"), vid=app.vid(h), claim=_claim(h)):
132 app.stats.add("build_not_owner")
133 return h.send_json(403, {"error": "not_owner",
134 "message": "That home belongs to someone else, or your key or claim code is missing."})
135 try:
136 item = build.validate(req)
137 except build.Invalid as e:
138 app.stats.add("build_invalid")
139 return h.send_json(422, {"error": "invalid", "message": str(e)})
140 iid = spool.item_id(item)
141 st = spool.read_status(app.args.spool_status, iid)
142 if st is None and os.path.exists(os.path.join(app.args.spool_in, iid + ".json")):
143 st = {"id": iid, "state": "queued", "url": None, "reason": None}
144 if st is not None:
145 return h.send_json(200, dict(st, duplicate=True, status="/allen/api/status/" + iid))
146 rate = app.build_save_rate if kind == "save" else app.build_publish_rate
147 retry = rate.take(app.client_key(h))
148 if retry:
149 return h.refuse(429, "rate", "You have saved several times already. Try again shortly.", retry)
150 iid, _ = spool.write_item(app.args.spool_in, item)
151 app.stats.add("build_" + kind)
152 branch = "u/" + item["handle"] if kind == "save" else "p/%s/%s" % (item["handle"], item["project"])
153 return h.send_json(200, {"id": iid, "state": "queued", "url": None, "reason": None, "duplicate": False,
154 "status": "/allen/api/status/" + iid, "branch": branch,
155 "view": "%s/tree/%s/%s" % (build.REPO_URL, branch, build.project_dir(item))})
156
157
158# ---------------------------------------------------------------- Drake's console
159
160def console_html(c, csrf):
161 """The approve/decline list for the console dashboard."""
162 app = c.app
163 idx = build.read_index(app.args.spool_status) if app.args.spool_status else build.read_index("/nonexistent")
164 esc = html.escape
165 rows = []
166 for o in idx["open"]:
167 url = o.get("url", "")
168 if not (isinstance(url, str) and url.startswith(build.REPO_URL + "/pull/")):
169 continue
170 rows.append("<tr><td><a href='%s'>#%d</a></td><td>%s</td><td>%s/%s</td>"
171 "<td><a href='%s/files'>Review and approve on GitHub</a></td>"
172 "<td><form class=inline method=post action=/projects/decline>%s"
173 "<input type=hidden name=pr value='%d'><input type=text name=reason maxlength=1000 "
174 "placeholder='Reason (shown on the pull request)'><button>Decline</button></form></td></tr>" % (
175 esc(url, quote=True), o["number"], esc(o.get("title", "")), esc(o.get("handle", "")),
176 esc(o.get("project", "")), esc(url, quote=True), c.csrf_field(csrf), o["number"]))
177 table = ("<table><tr><th>Request</th><th>Title</th><th>Home</th><th>Approve</th><th>Decline</th></tr>%s</table>"
178 % "".join(rows)) if rows else "<p>No projects are waiting.</p>"
179 return ("<section><h2>Projects waiting for you</h2>%s<p>Index updated %s &middot; %d in the gallery.</p>"
180 "<form method=post action=/projects/refresh>%s<button>Refresh from GitHub</button></form></section>") % (
181 table, esc(str(idx.get("updated") or "never")), len(idx["gallery"]), c.csrf_field(csrf))
182
183
184def console_post(c, path, form):
185 """Console POST routes after login and CSRF checks; True when handled."""
186 app = c.app
187 if path not in ("/projects/decline", "/projects/refresh"):
188 return False
189 if not app.args.spool_in:
190 c.send_body(404, b"no spool configured\n", "text/plain")
191 return True
192 if path == "/projects/decline":
193 try:
194 item = build.validate({"v": 1, "kind": "decline", "pr": int(form.get("pr", "")),
195 "reason": " ".join(form.get("reason", "").split())})
196 except (ValueError, build.Invalid) as e:
197 c.send_body(422, ("cannot decline: %s\n" % e).encode(), "text/plain")
198 return True
199 else:
200 item = {"v": 1, "kind": "refresh", "nonce": secrets.token_hex(8)}
201 spool.write_item(app.args.spool_in, item)
202 app.stats.add("console_" + item["kind"])
203 c.redirect("/")
204 return True