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
7.5 KiB104 linesraw
1// The svg/html preview (serve/web/preview.js), run in Node. The real browser behaviour (what a sandboxed frame can and
2// cannot reach) is tested in tools/webtest/browser_test.mjs; here the documents and frames that are built are checked.
3//   node serve/test_web_preview.js      (serve/test_web_preview.py runs it too and skips when node is missing)
4"use strict";
5const assert = require("node:assert/strict");
6const path = require("node:path");
7const P = require(path.join(__dirname, "web", "preview.js"));
8
9const light = {dark: false, ink: "#221e1f"}, dark = {dark: true, ink: "#eef1f3"};
10const cspOf = (doc) => /Content-Security-Policy" content="([^"]*)"/.exec(doc)[1];
11const noImage = {DOMParser: undefined};          // no DOMParser: the inline svg path
12
13const cases = {
14  can_preview() {
15    assert.ok(P.canPreview("svg", "<svg></svg>") && P.canPreview("SVG", "  <svg xmlns='x'/>"));
16    assert.ok(P.canPreview("html", "<p>x</p>") && P.canPreview("htm", "<!doctype html>") && P.canPreview("HTML", "</p>"));
17    assert.ok(!P.canPreview("python", "<svg></svg>") && !P.canPreview("html", "plain words") && !P.canPreview("svg", "<p>not svg</p>"));
18    assert.ok(!P.canPreview("", "<p>x</p>") && !P.canPreview("svgx", "<svg>"), "the fence's language decides");
19  },
20  sandbox_flags_are_minimal() {
21    assert.equal(P.SANDBOX.static, "", "no flags: no scripts, forms, popups, downloads, modals or navigation");
22    assert.equal(P.SANDBOX.scripts, "allow-scripts", "scripts only");
23    for (const v of Object.values(P.SANDBOX)) assert.ok(!/same-origin|top-navigation|popups|forms|modals|downloads|storage|pointer-lock|presentation/.test(v));
24  },
25  csp_has_no_network() {
26    const off = P.csp(false), on = P.csp(true);
27    for (const c of [off, on]) {
28      assert.match(c, /^default-src 'none'; /, "everything is off unless listed");
29      assert.ok(!/connect-src|frame-src|font-src|media-src|object-src|https?:|\*/.test(c), "no network source: " + c);
30      assert.match(c, /img-src data:/); assert.match(c, /base-uri 'none'/); assert.match(c, /form-action 'none'/);
31    }
32    assert.ok(!off.includes("script-src"), "off: scripts fall back to default-src 'none'");
33    assert.match(on, /script-src 'unsafe-inline'/, "on: the block's own inline script, and no source");
34    assert.ok(!/script-src[^;]*(https?:|\*|'self'|data:)/.test(on));
35  },
36  html_documents() {
37    const frag = P.previewDoc("html", "<p>hi</p>", false, light);
38    assert.ok(frag.startsWith("<!doctype html><html><head><meta http-equiv=\"Content-Security-Policy\""), "the CSP comes first: nothing of the page runs before it");
39    assert.ok(frag.includes("<p>hi</p>") && frag.endsWith("</body></html>"));
40    assert.match(frag, /color-scheme:light/);
41    const full = P.previewDoc("html", "<!DOCTYPE html><html><head><title>t</title></head><body><b>x</b></body></html>", false, dark);
42    assert.ok(full.indexOf("Content-Security-Policy") < full.indexOf("<title>"), "our CSP is before the page's head");
43    assert.equal((full.match(/<!doctype/gi) || []).length, 1, "one doctype");
44    assert.match(full, /color-scheme:dark/);
45    assert.equal(cspOf(full), P.csp(false));
46    assert.equal(cspOf(P.previewDoc("html", "<p>x</p>", true, light)), P.csp(true));
47    assert.equal(P.previewDoc("html", "just words", false, light), null);
48    assert.equal(P.previewDoc("python", "<p>x</p>", false, light), null);
49  },
50  a_page_cannot_redirect_itself() {
51    for (const meta of ['<meta http-equiv="refresh" content="0;url=http://evil.example/">', "<meta http-equiv=refresh content='0; url=http://evil.example'>",
52                        '<META HTTP-EQUIV = "Refresh" CONTENT="1;URL=http://evil.example">', '<meta content="0;url=http://evil.example" http-equiv="refresh">']) {
53      const doc = P.previewDoc("html", `<!doctype html><html><head>${meta}</head><body>x</body></html>`, false, light);
54      assert.ok(!/refresh/i.test(doc.replace(/Content-Security-Policy[^>]*>/, "")), meta + " -> " + doc);
55      assert.ok(!/<meta\b[^>]*refresh/i.test(P.previewDoc("html", `<p>x</p>${meta}`, true, light)), "also in a fragment and with scripts");
56    }
57  },
58  svg_documents() {
59    const doc = P.previewDoc("svg", '<svg width="10" height="10"><circle r="4"/></svg>', false, light, noImage);
60    assert.ok(doc.includes("<svg width=\"10\"") && doc.includes("display:flex"), "an svg that cannot be an image is inline");
61    assert.equal(cspOf(doc), P.csp(false), "inline svg: scripts and handlers are still blocked by the CSP");
62    assert.equal(P.previewDoc("svg", "<p>no</p>", false, light), null);
63    // as an image: with a parser, the svg goes in as a data: URL, with the page's ink as currentColor
64    const env = {
65      DOMParser: class { parseFromString(s) {
66        const style = {textContent: ""}, root = {namespaceURI: "http://www.w3.org/2000/svg", localName: "svg", firstChild: null,
67          insertBefore(n) { this.style = n; }, hasAttribute: () => false};
68        return {documentElement: root, querySelector: () => null, createElementNS: () => style, src: s};
69      } },
70      XMLSerializer: class { serializeToString(d) { return "<svg>" + (d.documentElement.style ? d.documentElement.style.textContent : "") + "</svg>"; } },
71    };
72    const img = P.previewDoc("svg", '<svg><script>x</script></svg>', false, {dark: false, ink: "#123456"}, env);
73    assert.match(img, /<img alt="" style="width:100%;height:100%;object-fit:contain" src="data:image\/svg\+xml;charset=utf-8,/);
74    assert.ok(decodeURIComponent(/src="data:image\/svg\+xml;charset=utf-8,([^"]*)"/.exec(img)[1]).includes("svg{color:#123456}"));
75    assert.ok(!img.includes("<svg><script>"), "the svg is not in the document, only its encoded image");
76    // with scripts requested for an svg, the markup is inline (an image cannot run anything)
77    assert.ok(P.previewDoc("svg", "<svg></svg>", true, light, env).includes("<body><svg></svg>"));
78  },
79  the_theme_cannot_inject() {
80    const evil = {dark: false, ink: "red;}</style><script>parent.x=1</script><style>"};
81    assert.ok(!P.previewDoc("html", "<p>x</p>", false, evil).includes("<script>parent.x"), "the ink goes into CSS only after a check");
82    assert.match(P.previewDoc("html", "<p>x</p>", false, evil), /color:CanvasText/);
83    assert.match(P.previewDoc("html", "<p>x</p>", false, {dark: true, ink: "rgb(1, 2, 3)"}), /color:rgb\(1, 2, 3\)/);
84  },
85  frames_are_built_cut_off() {
86    class Frame { constructor() { this.attrs = {}; this.dataset = {}; } setAttribute(k, v) { this.attrs[k] = v; } }
87    const env = {document: {createElement: (t) => { assert.equal(t, "iframe"); return new Frame(); }}};
88    const f = P.makeFrame("<p>x</p>", {scripts: false, title: "Page preview", lang: "html"}, env);
89    assert.deepEqual(f.attrs, {sandbox: "", referrerpolicy: "no-referrer", allow: ""});
90    assert.equal(f.srcdoc, "<p>x</p>"); assert.equal(f.dataset.opened, "1"); assert.equal(f.dataset.scripts, undefined);
91    const run = P.makeFrame("<p>x</p>", {scripts: true}, env);
92    assert.equal(run.attrs.sandbox, "allow-scripts"); assert.equal(run.dataset.scripts, "1");
93    const blank = P.makeFrame(null, {}, env);
94    assert.equal(blank.srcdoc, undefined); assert.equal(blank.dataset.opened, undefined, "an empty frame holds nothing");
95    assert.equal(blank.attrs.sandbox, "", "a blank frame is as closed as a static one");
96  },
97};
98
99(async () => {
100  const name = process.argv[2];
101  const run = name ? [[name, cases[name]]] : Object.entries(cases);
102  if (name && !cases[name]) throw new Error("unknown test " + name);
103  for (const [n, fn] of run) { await fn(); console.log("ok " + n); }
104})().catch((e) => { console.error(e); process.exitCode = 1; });