okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
5d9f47922
main
1// Chat math (serve/web/math.js + math-adapter.js + the vendored KaTeX), run in Node. 2// node serve/test_web_math.js (serve/test_web_math.py runs it too and skips when node is missing) 3// 4// 1. where a formula starts and ends (prices, code, links, half-written formulas); 5// 2. the Markdown step: the model's text is escaped, a formula's source only ever reaches the page escaped; 6// 3. drawing: a stub adapter and a stub DOM (order, cache, stale answers, errors, size limit); 7// 4. safety: the REAL vendored KaTeX with the adapter's options, fed hostile formulas. 8"use strict" ; 9const assert = require ( "node:assert/strict" ); 10const path = require ( "node:path" ); 11 12const web = path . join ( __dirname , "web" ); 13const math = require ( path . join ( web , "math.js" )); 14const { split} = math ; 15const esc = ( s ) => String ( s ). replace ( / [ &<>"' ] / g , ( c ) => ({ "&" :"&" , "<" :"<" , ">" :">" , '"' :""" , "'" :"'" }[ c ])); 16const unesc = ( s ) => s . replace ( / & ( amp | lt | gt | quot | #39 ) ; / g , ( m , k ) => ({ amp :"&" , lt :"<" , gt :">" , quot :'"' , "#39" :"'" }[ k ])); 17const sources = ( text ) => split ( text ). filter (( p ) => p . source !== undefined ). map (( p ) => [ p . source , p . display ]); 18 19const cases = { 20split_delimiters () { 21assert . deepEqual ( sources ( "a $x^2$ b" ), [[ "x^2" , false ]]); 22assert . deepEqual ( sources ( "a \\(x+1\\) b" ), [[ "x+1" , false ]]); 23assert . deepEqual ( sources ( "a $$\\int_0^1 f$$ b" ), [[ "\\int_0^1 f" , true ]]); 24assert . deepEqual ( sources ( "a \\[\\sum_i i\\] b" ), [[ "\\sum_i i" , true ]]); 25assert . deepEqual ( sources ( "$$\nx = 1\n$$" ), [[ "\nx = 1\n" , true ]], "display math may span lines" ); 26assert . deepEqual ( sources ( "$a$ and $b$" ), [[ "a" , false ], [ "b" , false ]]); 27// the text around a formula is kept whole 28assert . equal ( split ( "a $x$ b" ). map (( p ) => p . raw ). join ( "" ), "a $x$ b" ); 29}, 30split_not_math () { 31for ( const text of [ "It costs $5." , "$5 and $10" , "from $5 to $10 each" , "$ 5 $" , "a $ b" , "price: $1,000" , "cost $5 USD, $6 EUR" , 32"no formula here" , "\\$x\\$" , "a \\( unfinished" , "100$" ]) { 33assert . deepEqual ( sources ( text ), [], text ); 34} 35assert . deepEqual ( sources ( "`$x$` and ```\n$$y$$\n```" ), [], "code is code" ); 36assert . deepEqual ( sources ( "```js\nlet a = '$x$'\n```\n$z$" ), [[ "z" , false ]], "a closed fence ends" ); 37assert . deepEqual ( sources ( "~~~\n\\(a\\)\n~~~" ), [], "tilde fences too" ); 38assert . deepEqual ( sources ( "[x](https://example.com/$a$/b) $c$" ), [[ "c" , false ]], "a link target is not math" ); 39}, 40split_streaming () { 41const parts = split ( "see $$x^2 + " ); 42assert . equal ( parts . length , 2 ); 43assert . equal ( parts [ 1 ]. incomplete , true , "a formula still being written is plain text" ); 44assert . equal ( parts [ 1 ]. source , undefined ); 45assert . equal ( split ( "```\n$$never closed" ). filter (( p ) => p . source !== undefined ). length , 0 , "an open fence swallows the rest" ); 46}, 47markdown_escapes_everything () { 48const fmt = ( t ) => `<p> ${ esc ( t )} </p>` ; 49const html = math . markdown ( "hi <b>there</b> $x<y>\"'$ and <script>alert(1)</script>" , fmt ); 50assert . ok ( html . includes ( "<b>there</b>" ) && html . includes ( "<script>" ), "the model's own tags are escaped" ); 51assert . ok ( ! /<script | <b> / . test ( html ), html ); 52// the source sits in one attribute, URL-encoded, and as escaped text 53const m = / data-math=" ([ ^ " ] * ) " / . exec ( html ); 54assert . ok ( m , html ); 55assert . equal ( decodeURIComponent ( unesc ( m [ 1 ])), "x<y>\"'" , "the attribute (as the browser reads it) holds the source" ); 56assert . ok ( ! m [ 1 ]. includes ( "<" ) && ! m [ 1 ]. includes ( '"' )); 57assert . ok ( html . includes ( "$x<y>"'$" ), "the visible fallback is the escaped source" ); 58// an attribute break-out in the source stays in the attribute 59const evil = math . markdown ( '$x" onmouseover="alert(1)$' , fmt ); 60assert . equal (( evil . match ( / <span / g ) || []). length , 1 ); 61const tag = / <span ([ ^ > ] * ) > / . exec ( evil )[ 1 ]; 62assert . deepEqual ([ ...tag . matchAll ( / (?: ^ | \s )([ \w - ] + ) =" / g )]. map (( x ) => x [ 1 ]), [ "class" , "data-math" , "data-display" ], "no attribute of the model's" ); 63}, 64markdown_keeps_source_text () { 65const text = "a $x$ and \\(y\\)" ; 66const seen = []; 67math . markdown ( text , ( t ) => { seen . push ( t ); return t ; }); 68assert . equal ( text , "a $x$ and \\(y\\)" , "strings are values, but the function must also not need a copy" ); 69assert . ok ( ! /\$x\$ | \\\(y\\\) / . test ( seen [ 0 ]), "the Markdown step sees placeholders, not formulas" ); 70// a message that contains the placeholder word itself is not confused 71const html = math . markdown ( "STRATAMATHPLACEHOLDER0END and $x$" , ( t ) => t ); 72assert . ok ( html . startsWith ( "STRATAMATHPLACEHOLDER0END and <span" ), html ); 73}, 74async hydrate_with_a_stub_adapter () { 75const calls = []; 76class Slot { 77constructor ( source , display ) { this . dataset = { math :encodeURIComponent ( source ), display :display ?"1" :"0" }; this . children = []; this . title = "" ; } 78replaceChildren ( c ) { this . children = [ c ]; } 79} 80const box = ( slots ) => ({ querySelectorAll :() => slots , contains :( s ) => slots . includes ( s )}); 81const mk = ( tag ) => ({ tag, cloneNode () { return { tag, cloned :true }; }}); 82globalThis . StrataMathAdapter = { 83async initialize () { calls . push ( "init" ); }, 84async render ( source , { display}) { 85calls . push ( "render " + source ); 86if ( source === "bad" ) return { ok :false , reason :"invalid" }; 87return { ok :true , element :mk ( source )}; 88}, 89}; 90math . reset (); 91const a = new Slot ( "x" , false ), b = new Slot ( "bad" , false ), c = new Slot ( "x" , true ); 92const container = box ([ a , b , c ]); 93math . hydrate ( container ); 94await new Promise (( r ) => setTimeout ( r , 20 )); 95assert . deepEqual ( calls , [ "init" , "render x" , "render bad" , "render x" ], "one at a time, started once" ); 96assert . equal ( a . children [ 0 ]. tag , "x" ); assert . equal ( c . children [ 0 ]. tag , "x" ); 97assert . equal ( b . dataset . mathError , "invalid" ); assert . ok ( b . children . length === 0 , "a bad formula stays source text" ); 98assert . match ( b . title , / invalid / ); 99// drawn before: placed at once (no flicker while an answer streams), without another render 100const again = new Slot ( "x" , false ); 101math . hydrate ( box ([ again ])); 102assert . equal ( again . children [ 0 ]. tag , "x" , "placed synchronously from the cache" ); 103assert . equal ( calls . length , 4 ); 104// an answer that was replaced while a formula was drawn does not get the old drawing 105const old = new Slot ( "slow" , false ); 106const stale = box ([ old ]); 107globalThis . StrataMathAdapter . render = async ( s ) => { await new Promise (( r ) => setTimeout ( r , 15 )); return { ok :true , element :mk ( s )}; }; 108math . hydrate ( stale ); 109math . hydrate ( box ([])); // a different container is a different generation; the same container is bumped below 110stale . _mathGeneration ++ ; 111await new Promise (( r ) => setTimeout ( r , 40 )); 112assert . equal ( old . children . length , 0 , "stale generation ignored" ); 113// a formula over 16 KiB is not drawn, and no adapter means source text 114assert . deepEqual ( await math . result ( "x" . repeat ( 20000 ), false ), { ok :false , reason :"limit" }); 115math . reset (); delete globalThis . StrataMathAdapter ; 116assert . deepEqual ( await math . result ( "y" , false ), { ok :false , reason :"unavailable" }); 117math . reset (); globalThis . StrataMathAdapter = { initialize :async () => { throw new Error ( "no engine" ); }, render :async () => ({ ok :true })}; 118assert . deepEqual ( await math . result ( "z" , false ), { ok :false , reason :"unavailable" }, "an engine that cannot start leaves the source" ); 119delete globalThis . StrataMathAdapter ; 120}, 121katex_options_are_the_safe_ones () { 122const { OPTIONS } = require ( path . join ( web , "math-adapter.js" )); 123assert . equal ( OPTIONS . trust , false , "no \\href, \\url, \\includegraphics, \\htmlClass ..." ); 124assert . equal ( OPTIONS . throwOnError , true , "an error returns the source, not a red error box" ); 125assert . ok ( OPTIONS . maxExpand <= 1000 && OPTIONS . maxSize <= 20 , "macro loops and huge sizes are cut" ); 126}, 127katex_hostile_input () { 128const katex = require ( path . join ( web , "vendor" , "katex" , "dist" , "katex.min.js" )); 129const { OPTIONS } = require ( path . join ( web , "math-adapter.js" )); 130const draw = ( src , display = false ) => katex . renderToString ( src , { ...OPTIONS , displayMode :display , macros :{}}); 131// with trust off these commands are not run: KaTeX draws the command's name in red, as text. There is no link, picture, 132// style, id, class or data attribute of the model's making in the result. 133const mathml = ( h ) => h . replace ( / <annotation [ ^ > ] * > [ \s\S ] * ?<\/annotation> / g , "" ); 134for ( const [ src , name ] of [[ "\\href{javascript:alert(1)}{click}" , "\\href" ], [ "\\url{javascript:alert(1)}" , "\\url" ], 135[ "\\href{https://example.com}{x}" , "\\href" ], [ "\\includegraphics{https://example.com/p.png}" , "\\includegraphics" ], 136[ "\\htmlClass{evil}{b}" , "\\htmlClass" ], [ "\\htmlId{evil}{b}" , "\\htmlId" ], 137[ "\\htmlStyle{color:red}{b}" , "\\htmlStyle" ], [ "\\htmlData{evil=1}{b}" , "\\htmlData" ]]) { 138const html = mathml ( draw ( src )); 139assert . ok ( html . includes ( `<mtext> ${ name } </mtext>` ), src + " is drawn as its own name: " + html . slice ( 0 , 200 )); 140assert . ok ( ! /<a\b | <img\b | href= | src= | javascript: | evil | id=" | data-evil | color:red / i . test ( html ), src + " -> " + html ); 141} 142for ( const src of [ "<img src=x onerror=alert(1)>" , "\\text{<script>alert(1)</script>}" , "a < b > c \\& d \" '" , 143"\\text{</span><img src=x onerror=alert(1)>}" , "\\mathrm{javascript:alert(1)}" , "x_{<svg onload=alert(1)>}" ]) { 144const html = draw ( src ); 145// the output may contain the text, but only as text: no tag the model wrote exists 146assert . ok ( ! /< ( img | script | svg | iframe | a ) \b / i . test ( html . replace ( / <annotation [ ^ > ] * > [ \s\S ] * ?<\/annotation> / g , "" )), src + " -> " + html ); 147const tags = ( html . match ( / < [ a - zA - Z ][ ^ > ] * > / g ) || []). join ( " " ); 148assert . ok ( ! /\son\w + \s * = | javascript: | \ssrc\s * = | \shref\s * = / i . test ( tags ), "no event handler, link or source in any tag: " + src ); 149} 150// the TeX source is kept in an <annotation> as escaped text, never as markup 151const kept = draw ( "<img src=x onerror=alert(1)>" ); 152assert . ok ( ! kept . includes ( "<img" ), kept ); 153// limits 154assert . throws (() => draw ( "\\def\\a{\\a\\a}\\a" ), / expansion | Too many / i , "a macro loop is cut" ); 155const rule = mathml ( draw ( "\\rule{100em}{100em}" )); 156assert . ok ( rule . includes ( "20em" ) && ! rule . includes ( "100em" ), "a huge rule is cut to maxSize" ); 157// macros are not shared between formulas 158draw ( "\\gdef\\foo{1}\\foo" ); 159assert . throws (() => draw ( "\\foo" ), / Undefined control sequence / ); 160// and a good formula still draws 161assert . match ( draw ( "\\frac{a}{b} + \\sqrt{x}" ), / class="katex" / ); 162}, 163}; 164 165( async () => { 166const name = process . argv [ 2 ]; 167const run = name ?[[ name , cases [ name ]]] :Object . entries ( cases ); 168if ( name && ! cases [ name ]) throw new Error ( "unknown test " + name ); 169for ( const [ n , fn ] of run ) { await fn (); console . log ( "ok " + n ); } 170})(). catch (( e ) => { console . error ( e ); process . exitCode = 1 ; });