okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-027-web: the served web chat page for 0.2.75d9f47922

main
5.2 KiB107 linesraw
1"""Chat math on the served page (serve/web/math.js, math-adapter.js, vendor/katex): opt-in, offline, no scripts from the model."""
2from __future__ import annotations
3
4import hashlib
5import json
6import re
7import shutil
8import subprocess
9import unittest
10import urllib.error
11import urllib.request
12from pathlib import Path
13
14from serve.frontend import ChatTemplate
15from serve.server import ByteTokenizer, MockEngine, Service, serve
16
17WEB = Path(__file__).parent / "web"
18KATEX = WEB / "vendor" / "katex"
19
20
21@unittest.skipUnless(shutil.which("node"), "node is not installed")
22class MathInNode(unittest.TestCase):
23    def test_delimiters_escaping_drawing_and_hostile_formulas(self):
24        r = subprocess.run([shutil.which("node"), str(Path(__file__).with_name("test_web_math.js"))],
25                           capture_output=True, text=True, timeout=120)
26        self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
27
28
29class Vendored(unittest.TestCase):
30    def test_the_files_are_the_ones_in_provenance(self):
31        prov = json.loads((KATEX / "PROVENANCE.json").read_text(encoding="utf-8"))
32        self.assertEqual((prov["package"], prov["version"], prov["license"]), ("katex", "0.19.0", "MIT"))
33        self.assertTrue(prov["integrity"].startswith("sha512-"))
34        on_disk = {p.relative_to(KATEX).as_posix() for p in KATEX.rglob("*") if p.is_file() and p.name != "PROVENANCE.json"}
35        self.assertEqual(on_disk, set(prov["sha256"]), "a file was added or removed without PROVENANCE.json")
36        for name, digest in prov["sha256"].items():
37            with self.subTest(name=name):
38                self.assertEqual(hashlib.sha256((KATEX / name).read_bytes()).hexdigest(), digest)
39        self.assertTrue((KATEX / "LICENSE").read_text(encoding="utf-8").startswith("The MIT License"))
40
41    def test_it_works_offline(self):
42        css = (KATEX / "dist" / "katex.min.css").read_text(encoding="utf-8")
43        fonts = set(re.findall(r"url\(fonts/([\w-]+\.woff2)\)", css))
44        self.assertEqual(len(fonts), 20)
45        for font in fonts:
46            self.assertTrue((KATEX / "dist" / "fonts" / font).is_file(), font)
47        # no address outside this server in anything that loads on the page
48        for f in (WEB / "math.js", WEB / "math-adapter.js", KATEX / "dist" / "katex.min.css"):
49            self.assertNotRegex(f.read_text(encoding="utf-8"), r"https?://(?!www\.w3\.org)", f.name)
50        self.assertNotIn("@import", css)
51
52    def test_the_page_loads_nothing_until_math_is_on(self):
53        html = (WEB / "index.html").read_text(encoding="utf-8")
54        js = (WEB / "app.js").read_text(encoding="utf-8")
55        self.assertIn('src="web/math.js"', html)
56        self.assertIn('src="web/math-adapter.js"', html)
57        self.assertNotIn("katex", html.lower().replace("math-adapter", ""), "KaTeX is not named in the page: the adapter loads it")
58        self.assertIn("math: false", js, "off by default")
59        self.assertIn('id="s-math"', html)
60        self.assertIn('aria-checked="false"', re.search(r'<button[^>]*id="s-math"[^>]*>', html).group(0))
61        adapter = re.sub(r"^\s*//.*$", "", (WEB / "math-adapter.js").read_text(encoding="utf-8"), flags=re.M)   # the code, not its comments
62        self.assertIn("trust: false", adapter)
63        self.assertNotIn("innerHTML", adapter)
64        self.assertNotIn("renderToString", adapter, "KaTeX builds DOM nodes; no HTML string goes into the page")
65
66
67class Served(unittest.TestCase):
68    @classmethod
69    def setUpClass(cls):
70        tok = ByteTokenizer()
71        cls.svc = Service(MockEngine(tok, "ok"), tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja"))
72        cls.httpd = serve(cls.svc, port=0)
73        cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}"
74
75    @classmethod
76    def tearDownClass(cls):
77        cls.httpd.shutdown()
78        cls.httpd.server_close()
79
80    def get(self, path):
81        try:
82            with urllib.request.urlopen(self.base + path, timeout=10) as r:
83                return r.status, r.headers.get("Content-Type", ""), r.read()
84        except urllib.error.HTTPError as e:
85            return e.code, e.headers.get("Content-Type", ""), e.read()
86
87    def test_scripts_style_and_fonts_are_served(self):
88        for path, want in (("/web/math.js", "javascript"), ("/web/math-adapter.js", "javascript"),
89                           ("/web/vendor/katex/dist/katex.min.js", "javascript"),
90                           ("/web/vendor/katex/dist/katex.min.css", "text/css"),
91                           ("/web/vendor/katex/dist/fonts/KaTeX_Main-Regular.woff2", "font/woff2")):
92            with self.subTest(path=path):
93                code, ctype, body = self.get(path)
94                self.assertEqual(code, 200)
95                self.assertIn(want, ctype)
96                self.assertTrue(body)
97
98    def test_nothing_else_below_vendor(self):
99        for path in ("/web/vendor/katex/PROVENANCE.json", "/web/vendor/katex/LICENSE", "/web/vendor/katex/dist/fonts/x.ttf",
100                     "/web/vendor/katex/../../app.js", "/web/vendor/", "/web/vendor/katex/dist/fonts",
101                     "/web/vendor/katex/dist/missing.js"):
102            with self.subTest(path=path):
103                self.assertEqual(self.get(path)[0], 404)
104
105
106if __name__ == "__main__":
107    unittest.main()