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_build.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_build.py` 184 lines ยท 8886 bytes Raw Blame History 1 """The build loop's shared rules: handles, project items and the published index. 2 3 Used by allen-chat (writer, validates and checks ownership) and omega-projects-pusher 4 (reader, validates again before anything reaches GitHub). Stdlib only. 5 6 Homes. Every builder has a home projects/// in aien-dev/omega-projects. 7 remembered visitor: handle = -<8 hex>, the hex being HMAC(server secret, "handle", vid) 8 where vid is the gateway's HMAC of the visitor key; the name is chosen 9 by the visitor (never an email: lowercase letters, digits, hyphens). 10 anonymous visitor: handle = anon-<10 hex>, the hex being HMAC(server secret, "claim", code) 11 for a one-time claim code shown to the visitor once. 12 Only the gateway holds the secret, so only the holder of the visitor key or the claim code 13 can name a handle in a save or publish item; the pusher builds every path from the 14 validated handle and project name, so nothing outside projects/// is written. 15 16 Items, version 1 (spool files, content-addressed exactly like allen_spool items): 17 {"v":1, "kind":"save"|"publish", "handle":h, "project":p, "title":str, 18 "description":str, "files":[{"name":str, "content":str}, ...]} 19 save: one commit on branch u/ (created from main when missing). 20 publish: one commit on branch p// from main and one pull request to 21 main, reused while it is open. Drake approves and merges on GitHub. 22 {"v":1, "kind":"decline", "pr":int, "reason":str} console only: close a publish PR. 23 {"v":1, "kind":"refresh", "nonce":hex} console only: rewrite the index. 24 Index (spool-status/index.json, written by the pusher): 25 {"v":1, "updated":iso, "open":[{number,url,title,handle,project}], 26 "gallery":[{handle,project,title,description,url,page}]} 27 """ 28 29 import hashlib 30 import hmac 31 import json 32 import os 33 import re 34 import secrets 35 36 import allen_spool as spool 37 38 NAME = re.compile(r"^[a-z](?:[a-z0-9]|-(?=[a-z0-9])){1,23}$") 39 HANDLE = re.compile(r"^(?:[a-z](?:[a-z0-9]|-(?=[a-z0-9])){1,23}-[0-9a-f]{8}|anon-[0-9a-f]{10})$") 40 PROJECT = spool.SLUG 41 CLAIM = re.compile(r"^[0-9a-f]{24}$") 42 # Allowlisted text files. No paths, no dotfiles, no binaries; meta.json is written by the pusher. 43 FILENAME = re.compile(r"^(?:index\.html|README\.md|[a-z0-9][a-z0-9_-]{0,39}\.(?:om|js|css|md|txt|patch))$") 44 WEB = (".html", ".js", ".css") 45 PROSE = (".md", ".txt") 46 MAX_FILE = 64 * 1024 47 MAX_TOTAL = 256 * 1024 48 MAX_FILES = 12 49 REPO_URL = "https://github.com/aien-dev/omega-projects" 50 PAGES_URL = "https://aien-dev.github.io/omega-projects" 51 INDEX = "index.json" 52 53 54 Invalid = spool.Invalid # one exception for both modules: _text raises it too 55 56 57 def handle_for_vid(secret, vid, name): 58 if not NAME.match(name or ""): 59 raise Invalid("a name is 2 to 24 lowercase letters, digits or inner hyphens, starting with a letter") 60 tag = hmac.new(secret, b"allen-handle\0" + vid.encode(), hashlib.sha256).hexdigest()[:8] 61 return "%s-%s" % (name, tag) 62 63 64 def handle_for_claim(secret, claim): 65 if not CLAIM.match(claim or ""): 66 raise Invalid("a claim code is 24 hex characters") 67 return "anon-" + hmac.new(secret, b"allen-claim\0" + claim.encode(), hashlib.sha256).hexdigest()[:10] 68 69 70 def new_claim(): 71 return secrets.token_hex(12) 72 73 74 def owns(secret, handle, vid=None, claim=None): 75 """True when the caller (vid from the visitor key, or a claim code) owns the handle.""" 76 if not secret or not isinstance(handle, str) or not HANDLE.match(handle): 77 return False 78 try: 79 if handle.startswith("anon-"): 80 return claim is not None and hmac.compare_digest(handle, handle_for_claim(secret, claim)) 81 if vid is None: 82 return False 83 name = handle.rsplit("-", 1)[0] 84 return hmac.compare_digest(handle, handle_for_vid(secret, vid, name)) 85 except Invalid: 86 return False 87 88 89 def _files(files): 90 if not isinstance(files, list) or not 1 <= len(files) <= MAX_FILES: 91 raise Invalid("a project has 1 to %d files" % MAX_FILES) 92 out, names, total = [], set(), 0 93 for f in files: 94 if not isinstance(f, dict) or set(f) != {"name", "content"}: 95 raise Invalid("each file has a name and a content") 96 name = f["name"] 97 if not isinstance(name, str) or not FILENAME.match(name) or name in names: 98 raise Invalid("file names allowed: index.html, README.md, name.om, name.js, name.css, " 99 "name.md, name.txt, name.patch (lowercase, no folders)") 100 names.add(name) 101 content = f["content"] 102 if not isinstance(content, str): 103 raise Invalid("file content must be text") 104 size = len(content.encode("utf-8")) 105 if size > MAX_FILE: 106 raise Invalid("%s is larger than %d KiB" % (name, MAX_FILE // 1024)) 107 total += size 108 spool._text(content, name, 1, MAX_FILE) # control characters and secret shapes 109 if name.endswith(WEB): 110 for pat in spool.EXTERNAL: 111 if pat.search(content): 112 raise Invalid("%s may not load or send anything from elsewhere (%s)" % (name, pat.pattern[:40])) 113 if not name.endswith(PROSE) and spool.EMAIL.search(content): 114 raise Invalid("%s contains an email address; remove it" % name) 115 out.append({"name": name, "content": content}) 116 if total > MAX_TOTAL: 117 raise Invalid("the project is larger than %d KiB" % (MAX_TOTAL // 1024)) 118 if "README.md" not in names: 119 raise Invalid("a project needs README.md: what it is and who it helps") 120 if not any(n == "index.html" or n.endswith(".om") for n in names): 121 raise Invalid("a project needs index.html or an .om file") 122 out.sort(key=lambda f: f["name"]) 123 return out 124 125 126 def validate(item): 127 """Return the canonical build item or raise Invalid.""" 128 if not isinstance(item, dict) or item.get("v") != 1: 129 raise Invalid("unknown item version") 130 kind = item.get("kind") 131 if kind in ("save", "publish"): 132 if set(item) != {"v", "kind", "handle", "project", "title", "description", "files"}: 133 raise Invalid("%s fields are handle, project, title, description and files" % kind) 134 if not isinstance(item["handle"], str) or not HANDLE.match(item["handle"]): 135 raise Invalid("unknown handle") 136 if not isinstance(item["project"], str) or not PROJECT.match(item["project"]): 137 raise Invalid("a project name is 1 to 40 lowercase letters, digits or inner hyphens") 138 return {"v": 1, "kind": kind, "handle": item["handle"], "project": item["project"], 139 "title": spool._text(item["title"], "title", 3, 80, line=True).strip(), 140 "description": spool._text(item["description"], "description", 10, 2000), 141 "files": _files(item["files"])} 142 if kind == "decline": 143 if set(item) != {"v", "kind", "pr", "reason"} or not isinstance(item["pr"], int) \ 144 or isinstance(item["pr"], bool) or not 1 <= item["pr"] < 10 ** 9: 145 raise Invalid("decline fields are pr and reason") 146 return {"v": 1, "kind": "decline", "pr": item["pr"], 147 "reason": spool._text(item["reason"], "reason", 0, 1000)} 148 if kind == "refresh": 149 if set(item) != {"v", "kind", "nonce"} or not isinstance(item["nonce"], str) \ 150 or not re.fullmatch(r"[0-9a-f]{16}", item["nonce"]): 151 raise Invalid("refresh fields are nonce") 152 return dict(item) 153 raise Invalid("kind must be save, publish, decline or refresh") 154 155 156 def scrubbed(item): 157 """Emails and phone numbers out of prose; code files are refused instead (see _files).""" 158 item = dict(item, title=spool.scrub(item["title"]), description=spool.scrub(item["description"])) 159 item["files"] = [dict(f, content=spool.scrub(f["content"])) if f["name"].endswith(PROSE) else dict(f) 160 for f in item["files"]] 161 return item 162 163 164 def meta(item, iid, day): 165 """meta.json: what the project is, never who the person is.""" 166 return {"v": 1, "handle": item["handle"], "project": item["project"], "title": item["title"], 167 "description": item["description"], "saved": day, "item": iid, "built_with": "Aien", 168 "files": [f["name"] for f in item["files"]]} 169 170 171 def project_dir(item): 172 return "projects/%s/%s" % (item["handle"], item["project"]) 173 174 175 def read_index(status_dir): 176 """The pusher's index, or an empty one.""" 177 try: 178 with open(os.path.join(status_dir, INDEX), encoding="utf-8") as f: 179 d = json.load(f) 180 if isinstance(d, dict) and isinstance(d.get("open"), list) and isinstance(d.get("gallery"), list): 181 return d 182 except (OSError, ValueError): 183 pass 184 return {"v": 1, "updated": None, "open": [], "gallery": []}