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