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_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
3The gateway holds no GitHub credential. It validates a visitor-confirmed item
4and drops it into a spool directory it can only write into; the pusher, a
5separate unit and the only holder of GitHub write ability, validates the same
6item again before filing anything. An item is one JSON file named <id>.json,
7where id is derived from the content, so identical submissions collapse into
8one item (dedupe). Status comes back as status/<id>.json written by the pusher.
9
10Item, 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.
14Status: {"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
19import hashlib
20import json
21import os
22import re
23import secrets
24
25TEMPLATES = ("feature", "question", "bug")
26SLUG = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$")
27AREA = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$")
28ID = re.compile(r"\A[0-9a-f]{20}\Z")
29
30SECRET_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.
41EXTERNAL = [
42 re.compile(p, re.I) for p in (
43 r"<script\b[^>]*\bsrc\s*=", r"<link\b", r"<iframe\b", r"<object\b", r"<embed\b", r"<base\b",
44 r"<meta\b[^>]*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.
52EMAIL = re.compile(r"[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,253}\.[A-Za-z]{2,63}")
53PHONE = re.compile(r"(?<![\w.])\+?\d[\d ().-]{7,}\d(?!\w|\.\d)")
54
55
56class Invalid(ValueError):
57 pass
58
59
60def _text(value, name, lo, hi, line=False):
61 if not isinstance(value, str):
62 raise Invalid("%s must be text" % name)
63 if not lo <= len(value) <= hi:
64 raise Invalid("%s must be %d to %d characters" % (name, lo, hi))
65 bad = "\n\r" if line else ""
66 for ch in value:
67 o = ord(ch)
68 if ((o < 32 and ch not in "\n\t\r") or o == 127 or ch in bad or 0xD800 <= o <= 0xDFFF
69 or 0xFDD0 <= o <= 0xFDEF or (o & 0xFFFE) == 0xFFFE or o == 0xFFFD):
70 raise Invalid("%s contains a control or binary character" % name)
71 for pat in SECRET_SHAPES:
72 if pat.search(value):
73 raise Invalid("%s looks like it contains a secret (key, token or password); remove it" % name)
74 return value
75
76
77def scrub(text):
78 """Remove email addresses and phone numbers before anything is published."""
79 return PHONE.sub("[phone removed]", EMAIL.sub("[email removed]", text))
80
81
82def validate(item, areas=None):
83 """Return the canonical item or raise Invalid. `areas`: known public repo names."""
84 if not isinstance(item, dict) or item.get("v") != 1:
85 raise Invalid("unknown item version")
86 kind = item.get("kind")
87 if kind == "issue":
88 if set(item) != {"v", "kind", "template", "title", "body", "area"}:
89 raise Invalid("issue fields are template, title, body and area")
90 if item["template"] not in TEMPLATES:
91 raise Invalid("template must be feature, question or bug")
92 area = item["area"]
93 if not isinstance(area, str) or not AREA.match(area):
94 raise Invalid("area must be a repository name")
95 if areas is not None and area not in areas and area != "unknown":
96 area = "unknown"
97 return {"v": 1, "kind": "issue", "template": item["template"],
98 "title": _text(item["title"], "title", 8, 120, line=True).strip(),
99 "body": _text(item["body"], "body", 20, 6000), "area": area}
100 raise Invalid("kind must be issue (projects go through projects/save and projects/publish)")
101
102
103def item_id(item):
104 canon = json.dumps(item, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
105 return hashlib.sha256(canon).hexdigest()[:20]
106
107
108def write_item(spool_in, item):
109 """Atomically place a validated item; returns (id, created)."""
110 iid = item_id(item)
111 final = os.path.join(spool_in, iid + ".json")
112 if os.path.exists(final):
113 return iid, False
114 tmp = os.path.join(spool_in, ".tmp-%s-%s" % (iid, secrets.token_hex(4)))
115 # 0640: the spool directory's setgid group lets the pusher read it; the writer cannot list the dir.
116 fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o640)
117 with os.fdopen(fd, "w", encoding="utf-8") as f:
118 json.dump(item, f, ensure_ascii=False, sort_keys=True)
119 f.flush()
120 os.fsync(f.fileno())
121 os.rename(tmp, final)
122 return iid, True
123
124
125def spool_file(directory, iid):
126 """directory/iid.json for a well-formed id, or None; the real path must stay in directory."""
127 if not ID.fullmatch(iid or ""):
128 return None
129 root = os.path.realpath(directory)
130 path = os.path.realpath(os.path.join(root, iid + ".json"))
131 return path if path.startswith(root + os.sep) else None
132
133
134def read_status(spool_status, iid):
135 path = spool_file(spool_status, iid)
136 if path is None:
137 return None
138 try:
139 with open(path, encoding="utf-8") as f:
140 st = json.load(f)
141 except (OSError, ValueError):
142 return None
143 url = st.get("url")
144 if url is not None and not (isinstance(url, str) and re.match(
145 r"^https://github\.com/aien-dev/omega-projects/(issues/\d+|pull/\d+|commit/[0-9a-f]{40})$", url)):
146 url = None
147 return {"id": iid, "state": st.get("state") if st.get("state") in ("queued", "filed", "rejected", "failed")
148 else "queued", "url": url, "reason": st.get("reason") if isinstance(st.get("reason"), str) else None}
149
150
151# Reaching Drake: relay messages (gateway writes, allen-relay mailer reads) and live text.
152RELAY_MESSAGE = 4000
153RELAY_FIELD = 200
154TRANSCRIPT_MSGS = 24
155TRANSCRIPT_CHARS = 16000
156RELAY_ID = re.compile(r"\Ar_[0-9a-f]{16}\Z")
157# Live-session bearer. The page draws 32 hex (128 bits). A tab opened on the
158# previous page, and a relay file queued before this gateway is deployed, still
159# carry 16 hex. Both are accepted until 2026-12-02
160# (https://github.com/aien-dev/aienos.com/issues/196). Anything else is refused.
161# 32 is first so a path match cannot stop at the first 16 of a longer id.
162# \Z, not $: a trailing newline must not pass. ASCII digits only.
163CONV_BODY = r"[0-9a-f]{32}|[0-9a-f]{16}"
164CONV = re.compile(r"\A(?:%s)\Z" % CONV_BODY)
165RECEIVED = re.compile(r"\A[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z\Z")
166
167
168def validate_transcript(t):
169 """A conversation the visitor chose to include: [] or up to 24 user/assistant messages."""
170 if t is None:
171 return []
172 if not isinstance(t, list):
173 raise Invalid("transcript must be a list of messages")
174 if len(t) > 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
188def 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
206def 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
222def 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
232def 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