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.7 KiB81 linesraw
1// serve/web/preview.js - the preview of an ```svg or ```html block in an answer (PR #1628 by thoives).
2//
3// A block is shown in an <iframe srcdoc> that is cut off from the page:
4//   - sandbox="" : an opaque origin, so no access to the page's DOM, storage, cookies or the server; no scripts, no forms,
5//     no popups, no navigation of the page, no downloads;
6//   - a CSP in the frame's own document: default-src 'none' (no network, no fonts, no frames, no media), styles inline and
7//     pictures as data: only, no <base>, no form target;
8//   - the page's own header CSP frame-src 'none' (serve/server.py) stops the frame from navigating away to a web page
9//     (a link, or <meta refresh>), which no sandbox flag can.
10// An svg is shown as an <img> with a data: URL where it parses as XML: an image runs no scripts and loads nothing, and it
11// animates in every browser. The user can run ONE html block with scripts, after a warning, never remembered: the frame then
12// has sandbox="allow-scripts" (still an opaque origin, still no network), and the CSP allows its inline script.
13//
14// This file builds strings and frames only; app.js decides when. Nothing in it touches the page's own DOM.
15"use strict";
16(function (root) {
17  // no allow-same-origin: that would give the frame the page's origin and with it the page itself
18  const SANDBOX = {static: "", scripts: "allow-scripts"};
19  const csp = (scripts) => "default-src 'none'; " + (scripts ? "script-src 'unsafe-inline'; " : "") +
20    "style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'";
21  const metaCsp = (scripts) => `<meta http-equiv="Content-Security-Policy" content="${csp(scripts)}">`;
22  const SVG_NS = "http://www.w3.org/2000/svg";
23
24  // theme = {dark: bool, ink: "#rrggbb"}: the frame carries the page's colours, so it is transparent on the page's surface
25  const safeInk = (ink) => (/^[#\w(),.\s%-]{1,40}$/.test(ink || "") ? ink : "CanvasText");
26  const themeCss = (theme) => `html{color-scheme:${theme && theme.dark ? "dark" : "light"};color:${safeInk(theme && theme.ink)}}`;
27  const frameHead = (css, scripts, theme) => `<!doctype html><html><head>${metaCsp(scripts)}<style>${themeCss(theme)}html,body{background:transparent;margin:0;height:100%}${css}</style></head><body>`;
28
29  // a plain svg as an <img> with a data: URL, or null when it is not well-formed XML (then the inline svg is used)
30  function svgImage(s, theme, env = root) {
31    try {
32      const doc = new env.DOMParser().parseFromString(/^<svg\b[^>]*\sxmlns\s*=/i.test(s) ? s : s.replace(/^<svg\b/i, `<svg xmlns="${SVG_NS}"`), "image/svg+xml");
33      const r = doc.documentElement;
34      if (doc.querySelector("parsererror") || r.namespaceURI !== SVG_NS || r.localName !== "svg") return null;
35      const st = doc.createElementNS(SVG_NS, "style");              // an image has no page around it: give currentColor the page's ink
36      st.textContent = `svg{color:${safeInk(theme && theme.ink)}}`;
37      r.insertBefore(st, r.firstChild);
38      const fill = !r.hasAttribute("width") && !r.hasAttribute("height");
39      return `<img alt="" ${fill ? 'style="width:100%;height:100%;object-fit:contain" ' : ""}src="data:image/svg+xml;charset=utf-8,${encodeURIComponent(new env.XMLSerializer().serializeToString(doc))}">`;
40    } catch (e) { return null; }
41  }
42
43  // the document for a block, or null when the block is not a previewable svg or html (lang is the fence's language)
44  function previewDoc(lang, code, scripts, theme, env) {
45    let s = String(code).trim();
46    if (/^svg\b/i.test(lang) && /^<svg[\s>]/i.test(s)) {
47      const img = scripts ? null : svgImage(s, theme, env);
48      return frameHead("body{display:flex;align-items:center;justify-content:center}" + (img ? "img" : "svg") + "{max-width:100%;max-height:100%}", scripts, theme) +
49             (img || s) + "</body></html>";
50    }
51    if (/^html?$/i.test(lang) && /^<[/a-z!]/i.test(s)) {
52      s = s.replace(/<meta\b[^>]*\bhttp-equiv\s*=\s*["']?\s*refresh\b[^>]*>/gi, "");   // a page that redirects itself would leave the sandbox's document
53      // a complete document: our CSP and theme come first, then the page without its doctype (its own html and head tags merge
54      // into ours, and its own CSS still wins); nothing of the page can run before the CSP is in force
55      if (/^<!doctype\s+html/i.test(s)) return `<!doctype html><html><head>${metaCsp(scripts)}<style>${themeCss(theme)}</style></head>` + s.replace(/^<!doctype[^>]*>/i, "");
56      return frameHead("", scripts, theme) + s + "</body></html>";               // a fragment: wrap in a minimal document
57    }
58    return null;
59  }
60  const kindOf = (lang) => (/^svg\b/i.test(lang) ? "svg" : "page");
61  // cheap: can this block be previewed at all (the same test as previewDoc, without building anything)
62  const canPreview = (lang, code) => {
63    const s = String(code).trim();
64    return (/^svg\b/i.test(lang) && /^<svg[\s>]/i.test(s)) || (/^html?$/i.test(lang) && /^<[/a-z!]/i.test(s));
65  };
66
67  // a new frame holding the document (the sandbox attribute only counts when a frame is created, so a frame is never reused)
68  function makeFrame(doc, {scripts = false, title = "", lang = ""} = {}, env = root) {
69    const f = env.document.createElement("iframe");
70    f.setAttribute("sandbox", scripts ? SANDBOX.scripts : SANDBOX.static);
71    f.setAttribute("referrerpolicy", "no-referrer");
72    f.setAttribute("allow", "");
73    f.title = title; f.dataset.lang = lang;
74    if (doc) { f.dataset.opened = "1"; if (scripts) f.dataset.scripts = "1"; f.srcdoc = doc; }
75    return f;
76  }
77
78  const api = {SANDBOX, csp, metaCsp, previewDoc, svgImage, kindOf, canPreview, makeFrame, themeCss};
79  root.StrataPreview = api;
80  if (typeof module !== "undefined" && module.exports) module.exports = api;
81})(typeof globalThis !== "undefined" ? globalThis : this);