Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienos.com/blob/main/scripts/allen/allen_spool.py # aienos.com Source of www.aienos.com, served from my own hardware Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienos.com / scripts / allen / allen_spool.py` 246 lines ยท 11421 bytes Raw Blame History 1 """Validation and spool format shared by allen-chat (writer) and omega-projects-pusher (reader). 2 3 The gateway holds no GitHub credential. It validates a visitor-confirmed item 4 and drops it into a spool directory it can only write into; the pusher, a 5 separate unit and the only holder of GitHub write ability, validates the same 6 item again before filing anything. An item is one JSON file named .json, 7 where id is derived from the content, so identical submissions collapse into 8 one item (dedupe). Status comes back as status/.json written by the pusher. 9 10 Item, version 1: 11 {"v":1, "kind":"issue", "template":"feature"|"question"|"bug", 12 "title":str, "body":str, "area":str} 13 Projects are save/publish items with their own rules and routes: allen_build.py. 14 Status: {"id":..., "state":"queued"|"filed"|"rejected"|"failed", "url":str|null, "reason":str|null} 15 queued = not filed yet; filed = url set; rejected = content broke a rule (fixable); 16 failed = GitHub did not take it after N attempts or the daily cap was hit (offer the relay). 17 """ 18 19 import hashlib 20 import json 21 import os 22 import re 23 import secrets 24 25 TEMPLATES = ("feature", "question", "bug") 26 SLUG = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$") 27 AREA = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$") 28 ID = re.compile(r"\A[0-9a-f]{20}\Z") 29 30 SECRET_SHAPES = [ 31 re.compile(p) for p in ( 32 r"gh[pousr]_[A-Za-z0-9]{20,}", r"github_pat_[A-Za-z0-9_]{20,}", 33 r"\bsk-[A-Za-z0-9_-]{20,}", r"\bsk-ant-[A-Za-z0-9_-]{10,}", 34 r"\bAKIA[0-9A-Z]{16}\b", r"\bAIza[0-9A-Za-z_-]{30,}", 35 r"xox[abprs]-[A-Za-z0-9-]{10,}", r"-----BEGIN [A-Z ]*PRIVATE KEY-----", 36 r"\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.", 37 r"(?i)\b(api[_-]?key|secret|passw(or)?d|access[_-]?token|auth[_-]?token)\b\s*[:=]\s*['\"]?[^\s'\"]{12,}", 38 ) 39 ] 40 # Anything that would make a published page load or send something elsewhere. 41 EXTERNAL = [ 42 re.compile(p, re.I) for p in ( 43 r"]*\bsrc\s*=", r"]*http-equiv", r"\b(src|href|action|formaction|poster|data)\s*=\s*['\"]?\s*(https?:)?//", 45 r"url\(\s*['\"]?\s*(https?:)?//", r"@import\b", r"\bfetch\s*\(", r"XMLHttpRequest", r"WebSocket", 46 r"EventSource", r"sendBeacon", r"\bimport\s*\(", r"\bimportScripts\b", r"\bwindow\.open\b", 47 ) 48 ] 49 # Bounded by the RFC 5321 limits (local part 64, domain 253, label 63): every start 50 # position scans at most ~380 characters, so the search is linear in the text length 51 # (CodeQL py/polynomial-redos). A longer local part still matches on its last 64 chars. 52 EMAIL = re.compile(r"[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,253}\.[A-Za-z]{2,63}") 53 PHONE = re.compile(r"(? TRANSCRIPT_MSGS: 175 raise Invalid("transcript is limited to %d messages" % TRANSCRIPT_MSGS) 176 out, total = [], 0 177 for m in t: 178 if not isinstance(m, dict) or set(m) != {"role", "content"} or m.get("role") not in ("user", "assistant"): 179 raise Invalid("each transcript message has a role (user or assistant) and a content") 180 c = _text(m["content"], "transcript message", 0, RELAY_MESSAGE) 181 total += len(c) 182 out.append({"role": m["role"], "content": c}) 183 if total > TRANSCRIPT_CHARS: 184 raise Invalid("transcript is limited to %d characters" % TRANSCRIPT_CHARS) 185 return out 186 187 188 def validate_relay(req): 189 """{"message", "name", "contact", "transcript"} -> canonical relay fields or Invalid.""" 190 if not isinstance(req, dict): 191 raise Invalid("send a JSON object") 192 extra = set(req) - {"message", "name", "contact", "transcript"} 193 if extra: 194 raise Invalid("unknown fields: " + ", ".join(sorted(extra))[:200]) 195 message = _text(req.get("message"), "message", 1, RELAY_MESSAGE).strip() 196 if not message: 197 raise Invalid("message is empty") 198 name = req.get("name") or "" 199 contact = req.get("contact") or "" 200 return {"message": message, 201 "name": _text(name, "name", 0, RELAY_FIELD, line=True).strip(), 202 "contact": _text(contact, "contact", 0, RELAY_FIELD, line=True).strip(), 203 "transcript": validate_transcript(req.get("transcript"))} 204 205 206 def validate_relay_record(rec): 207 """A relay drop file as the gateway writes it; the mailer re-checks every field.""" 208 if not isinstance(rec, dict) or rec.get("v") != 1 or rec.get("type") != "relay": 209 raise Invalid("not a version 1 relay record") 210 if set(rec) != {"v", "type", "id", "received", "conv", "message", "name", "contact", "transcript"}: 211 raise Invalid("relay record fields do not match") 212 if not isinstance(rec["id"], str) or not RELAY_ID.fullmatch(rec["id"]): 213 raise Invalid("bad relay id") 214 if not isinstance(rec["received"], str) or not RECEIVED.fullmatch(rec["received"]): 215 raise Invalid("bad received time") 216 if not isinstance(rec["conv"], str) or not (rec["conv"] == "" or CONV.fullmatch(rec["conv"])): 217 raise Invalid("bad conversation id") 218 item = validate_relay({k: rec[k] for k in ("message", "name", "contact", "transcript")}) 219 return dict(item, v=1, type="relay", id=rec["id"], received=rec["received"], conv=rec["conv"]) 220 221 222 def validate_say(req): 223 """{"text"} the visitor types while Drake is there.""" 224 if not isinstance(req, dict) or set(req) != {"text"}: 225 raise Invalid("say takes only text") 226 text = _text(req["text"], "text", 1, RELAY_MESSAGE).strip() 227 if not text: 228 raise Invalid("text is empty") 229 return text 230 231 232 def validate_summary(req): 233 """{"summary", "consent"} for POST project-summary: the visitor's own short project summary, 234 text only (no code or file fields), no secrets, emails or phone numbers.""" 235 if not isinstance(req, dict) or set(req) - {"summary", "consent"}: 236 raise Invalid("project-summary takes only summary and consent") 237 s = req.get("summary") 238 if not isinstance(s, str): 239 raise Invalid("summary must be text") 240 s = s.strip() 241 if not s or len(s.encode("utf-8")) > 1000: 242 raise Invalid("summary must be 1 to 1000 bytes") 243 _text(s, "summary", 1, 1000) 244 if EMAIL.search(s) or PHONE.search(s): 245 raise Invalid("summary must not contain an email address or a phone number") 246 return s