Coverage for app / services / knowledge / html_preview.py: 100%
21 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2A website page snapshot's HTML, made safe to show.
4The raw HTML of a crawled page is somebody else's markup, captured verbatim —
5scripts, trackers, forms, meta refreshes and all. The preview shows it without
6trusting any of that, in three independent layers so that no one failure
7exposes the viewer:
91. **Here: an allow-list sanitiser** (``nh3``, the Rust ``ammonia`` crate).
10 Only text structure survives — headings, paragraphs, lists, tables,
11 emphasis, code, quotes. Scripts, styles, frames, forms, SVG and every event
12 handler are removed with their content; images keep only ``data:``
13 sources; links keep only in-page ``#anchors``. The output has no way to
14 run code or to fetch anything.
152. **fe-core: a sandboxed frame.** The preview is rendered from ``srcdoc`` in
16 an ``<iframe sandbox="">``: an opaque origin with no scripts, forms,
17 popups, or navigation of the app, and no access to its cookies or DOM.
183. **fe-core: a CSP forbidding all network access.** ``default-src 'none'``
19 heads the preview document, so even markup that slipped past (1) cannot
20 load a tracker, a font or a stylesheet.
22The site's own look is not reproduced: its stylesheets were never captured,
23and fetching them live would both leak the viewer to the site and show the
24page as it is now rather than as it was. The preview shows what the page
25*said* and how it was structured, in a neutral style.
27The raw HTML stays available as a download (``/html``), never rendered.
28"""
30from __future__ import annotations
32from dataclasses import dataclass
34import nh3
36#: The text structure a page's content lives in.
37ALLOWED_TAGS: frozenset[str] = frozenset(
38 {
39 "a", "abbr", "address", "article", "aside", "b", "bdi", "bdo",
40 "blockquote", "br", "caption", "cite", "code", "col", "colgroup",
41 "dd", "del", "details", "dfn", "div", "dl", "dt", "em", "figcaption",
42 "figure", "footer", "h1", "h2", "h3", "h4", "h5", "h6", "header",
43 "hr", "i", "img", "ins", "kbd", "li", "main", "mark", "nav", "ol",
44 "p", "pre", "q", "rp", "rt", "ruby", "s", "samp", "section", "small",
45 "span", "strong", "sub", "summary", "sup", "table", "tbody", "td",
46 "tfoot", "th", "thead", "time", "tr", "u", "ul", "var", "wbr",
47 }
48) # fmt: skip
50#: Removed *with* their content — text inside them is not page content (a
51#: script's source, a stylesheet, the <title> already shown as the heading) or
52#: is a whole embedded document.
53DROPPED_WITH_CONTENT: frozenset[str] = frozenset(
54 {
55 "script", "style", "title", "head", "template", "noscript", "iframe",
56 "frame", "frameset", "object", "embed", "applet", "svg", "math",
57 "canvas", "audio", "video", "picture", "source", "select", "option",
58 "textarea", "form",
59 }
60) # fmt: skip
62ALLOWED_ATTRIBUTES: dict[str, set[str]] = {
63 "*": {"id", "class", "title", "lang", "dir"},
64 "a": {"href"},
65 "img": {"src", "alt", "width", "height"},
66 "td": {"colspan", "rowspan", "headers"},
67 "th": {"colspan", "rowspan", "headers", "scope"},
68 "col": {"span"},
69 "colgroup": {"span"},
70 "ol": {"start", "reversed", "type"},
71 "time": {"datetime"},
72 "details": {"open"},
73 "abbr": {"title"},
74}
76#: The browser renders the preview; past this it is truncated rather than
77#: handed a multi-megabyte document to lay out.
78MAX_PREVIEW_CHARS = 2_000_000
81def _attribute_filter(tag: str, attribute: str, value: str) -> str | None:
82 """Keep only attributes that cannot reach the network or navigate.
84 A link's ``href`` would let a click load the live site into the frame —
85 and a navigated frame no longer carries the preview's CSP. In-page
86 anchors are kept so a long page's table of contents still works.
87 """
88 if tag == "a" and attribute == "href":
89 return value if value.startswith("#") else None
90 if tag == "img" and attribute == "src":
91 return value if value.startswith("data:image/") else None
92 return value
95@dataclass(frozen=True)
96class SanitizedPreview:
97 html: str
98 truncated: bool
101def sanitize_snapshot(raw_html: str) -> SanitizedPreview:
102 """Reduce a captured page to inert, network-free HTML."""
103 cleaned = nh3.clean(
104 raw_html,
105 tags=set(ALLOWED_TAGS),
106 clean_content_tags=set(DROPPED_WITH_CONTENT),
107 attributes=ALLOWED_ATTRIBUTES,
108 attribute_filter=_attribute_filter,
109 url_schemes={"data"},
110 link_rel=None,
111 strip_comments=True,
112 )
113 truncated = len(cleaned) > MAX_PREVIEW_CHARS
114 return SanitizedPreview(
115 html=cleaned[:MAX_PREVIEW_CHARS] if truncated else cleaned,
116 truncated=truncated,
117 )