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 / test-site-routes.py

161 lines · 7581 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Read-only HTTP oracle for the pre-cutover sitemap and generated internal links.
3
4This is verification tooling, never part of page generation. The original sitemap
5is a captured independent input, not regenerated from the candidate registry.
6"""
7import argparse
8from html.parser import HTMLParser
9import json
10from pathlib import Path
11import re
12import sys
13import urllib.error
14import urllib.parse
15import urllib.request
16import xml.etree.ElementTree as ET
17
18CANONICAL = "https://www.aienos.com"
19# Routes the hub edge serves outside dist/: the Hive board. www.aienos.com/forge/ is no longer one of
20# them: since 2026-11-10 it only redirects to interplane.io, so a page linking /forge/ is a broken link.
21EDGE = {"/hive/board/", "/hive/live.json"}
22
23
24class Document(HTMLParser):
25 def __init__(self):
26 super().__init__(convert_charrefs=True)
27 self.links = []
28 self.ids = set()
29 self.canonical = None
30 self.refresh = None
31
32 def handle_starttag(self, tag, attrs):
33 a = dict(attrs)
34 if "id" in a:
35 self.ids.add(a["id"])
36 if tag == "a" and "name" in a:
37 self.ids.add(a["name"])
38 if tag == "link" and a.get("rel", "").lower() == "canonical":
39 self.canonical = a.get("href")
40 if tag == "meta" and a.get("http-equiv", "").lower() == "refresh":
41 content = a.get("content", "")
42 # A delay alone reloads the same page (the live /hive/board/ does
43 # this every 15 s); it redirects nowhere.
44 if re.fullmatch(r"\s*\d+(?:\.\d+)?\s*;?\s*", content):
45 return
46 match = re.fullmatch(r"\s*\d+(?:\.\d+)?\s*;\s*url\s*=\s*(.*?)\s*", content, re.I)
47 if not match:
48 raise ValueError("malformed meta refresh")
49 self.refresh = match[1].strip("\"'")
50 for key in ("href", "src", "poster"):
51 if a.get(key):
52 self.links.append(a[key])
53 if a.get("srcset"):
54 self.links.extend(item.strip().split()[0] for item in a["srcset"].split(",") if item.strip())
55
56
57def same_site(url):
58 return urllib.parse.urlsplit(url).hostname in {"aienos.com", "www.aienos.com"}
59
60
61def main():
62 parser = argparse.ArgumentParser(description=__doc__)
63 parser.add_argument("--base", required=True, help="Origin serving candidate output")
64 parser.add_argument("--dist", required=True, type=Path)
65 parser.add_argument("--old-sitemap", required=True, type=Path)
66 parser.add_argument("--edge-base", help="Explicit existing edge origin for edge-only routes")
67 parser.add_argument("--report", required=True, type=Path)
68 args = parser.parse_args()
69 base = args.base.rstrip("/")
70 parsed = ET.parse(args.old_sitemap)
71 old = [n.text for n in parsed.findall(".//{http://www.sitemaps.org/schemas/sitemap/0.9}loc")]
72 if not old or any(not u or not same_site(u) for u in old) or len(old) != len(set(old)):
73 parser.error("old sitemap must contain distinct canonical-site URLs")
74 report = {"base": base, "old_sitemap": str(args.old_sitemap), "old_count": len(old), "old_urls": [], "links": [], "failures": []}
75 cache = {}
76
77 def fetch(path, fragment="", trail=()):
78 key = path
79 if key in trail or len(trail) >= 10:
80 raise ValueError("redirect cycle or excessive redirects: " + path)
81 if key not in cache:
82 origin = args.edge_base.rstrip("/") if path.split("?", 1)[0] in EDGE and args.edge_base else base
83 url = origin + path
84 request = urllib.request.Request(url, headers={"User-Agent": "aienos-cutover-readonly-oracle", "Cache-Control": "no-cache"})
85 with urllib.request.urlopen(request, timeout=30) as response:
86 status = response.status
87 final = response.url
88 if status != 200:
89 raise ValueError(f"{url}: HTTP {status}")
90 if urllib.parse.urlsplit(final).netloc != urllib.parse.urlsplit(origin).netloc:
91 raise ValueError(f"unexpected cross-origin HTTP redirect: {final}")
92 body = response.read()
93 mime = response.headers.get_content_type()
94 doc = None
95 if mime == "text/html":
96 doc = Document()
97 doc.feed(body.decode("utf-8"))
98 doc.close()
99 cache[key] = {"path": path, "status": status, "final": final, "bytes": len(body), "document": doc}
100 row = cache[key]
101 doc = row["document"]
102 if doc and doc.refresh:
103 refresh = urllib.parse.urljoin(CANONICAL + path, doc.refresh)
104 canonical = urllib.parse.urljoin(CANONICAL + path, doc.canonical or "")
105 if not doc.canonical or canonical != refresh or not same_site(refresh):
106 raise ValueError(f"{path}: refresh lacks matching same-site canonical")
107 dest = urllib.parse.urlsplit(refresh)
108 fetch(dest.path + ("?" + dest.query if dest.query else ""), dest.fragment, trail + (key,))
109 elif fragment and doc and fragment not in doc.ids:
110 raise ValueError(f"{path}: missing fragment #{fragment}")
111 return {k: v for k, v in row.items() if k != "document"}
112
113 for url in old:
114 p = urllib.parse.urlsplit(url)
115 try:
116 report["old_urls"].append(fetch(p.path, p.fragment))
117 except (ValueError, OSError, UnicodeError) as exc:
118 report["failures"].append({"source": "old-sitemap", "url": url, "error": str(exc)})
119
120 html_files = sorted(args.dist.rglob("*.html"))
121 if not html_files:
122 report["failures"].append({"source": "candidate", "error": "no generated HTML"})
123 seen = set()
124 for file in html_files:
125 rel = file.relative_to(args.dist).as_posix()
126 route = "/" + (rel[:-10] if rel.endswith("index.html") else rel)
127 doc = Document()
128 try:
129 doc.feed(file.read_text(encoding="utf-8"))
130 doc.close()
131 except (ValueError, UnicodeError) as exc:
132 report["failures"].append({"source": route, "error": str(exc)})
133 continue
134 for href in doc.links:
135 dest = urllib.parse.urlsplit(urllib.parse.urljoin(CANONICAL + route, href))
136 if dest.scheme not in {"http", "https"} or not same_site(dest.geturl()):
137 continue
138 # APIs are runtime services, not static document links or resources.
139 if dest.path.startswith("/allen/api/"):
140 continue
141 path = dest.path + ("?" + dest.query if dest.query else "")
142 key = (path, dest.fragment)
143 if key in seen:
144 continue
145 seen.add(key)
146 try:
147 report["links"].append(fetch(path, dest.fragment))
148 except (ValueError, OSError, UnicodeError) as exc:
149 report["failures"].append({"source": route, "url": href, "error": str(exc)})
150 report["checked_old"] = len(report["old_urls"])
151 report["checked_internal"] = len(report["links"])
152 report["failure_count"] = len(report["failures"])
153 report["verdict"] = "FAIL" if report["failures"] else "PASS"
154 args.report.parent.mkdir(parents=True, exist_ok=True)
155 args.report.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
156 print(f"SITE-ROUTES {report['verdict']} old={report['checked_old']}/{report['old_count']} internal={report['checked_internal']} failures={report['failure_count']}")
157 return 1 if report["failures"] else 0
158
159
160if __name__ == "__main__":
161 sys.exit(main())