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