"""The chat's svg/html preview: sandboxed, no network, no way to the page (serve/web/preview.js)."""
from __future__ import annotations
import os
import re
import shutil
import subprocess
import unittest
import urllib.request
from pathlib import Path
from serve.frontend import ChatTemplate
from serve.server import PAGE_CSP, ByteTokenizer, MockEngine, Service, serve
ROOT = Path(__file__).resolve().parents[1]
WEB = Path(__file__).parent / "web"
@unittest.skipUnless(shutil.which("node"), "node is not installed")
class PreviewInNode(unittest.TestCase):
def test_documents_frames_and_flags(self):
r = subprocess.run([shutil.which("node"), str(Path(__file__).with_name("test_web_preview.js"))],
capture_output=True, text=True, timeout=60)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
class ThePageSource(unittest.TestCase):
def test_no_way_for_a_frame_to_reach_the_page(self):
scripts = {p.name: p.read_text(encoding="utf-8") for p in WEB.glob("*.js")}
for name, src in scripts.items():
with self.subTest(name=name):
self.assertNotIn("allow-same-origin", src.replace("no allow-same-origin", ""), "a frame with the page's origin is the page")
self.assertNotRegex(src, r"allow-(top-navigation|popups|forms|modals|downloads)")
# the page never listens for what a frame posts to it
self.assertNotRegex(scripts["app.js"], r"addEventListener\(\s*[\"']message[\"']")
self.assertNotRegex(scripts["app.js"], r"\bonmessage\b")
# every iframe starts closed, and is only ever made by preview.js
for tag in re.findall(r"