~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(themes): escape JSON embedded in inline scripts (#7102)
LearningCircuit8c14873a5b9d
diff --git a/changelog.d/+theme-inline-json-escaping.security.md b/changelog.d/+theme-inline-json-escaping.security.mdnew file mode 100644index 0000000000..13c0d91dc6--- /dev/null+++ b/changelog.d/+theme-inline-json-escaping.security.md@@ -0,0 +1 @@+Escape theme IDs and metadata for inline script output so HTML-sensitive theme text cannot terminate the script element.diff --git a/src/local_deep_research/web/templates/base.html b/src/local_deep_research/web/templates/base.htmlindex 2564b08093..f1a5e5aad0 100644--- a/src/local_deep_research/web/templates/base.html+++ b/src/local_deep_research/web/templates/base.html@@ -14,9 +14,9 @@<script>(function() {// Auto-detected from CSS - no need to manually update this list- var validThemes = {{ get_themes_json()|safe }};+ var validThemes = {{ get_themes_json() }};// Store theme metadata for JavaScript (used by theme.js)- window.LDR_THEME_METADATA = {{ get_theme_metadata()|safe }};+ window.LDR_THEME_METADATA = {{ get_theme_metadata() }};var userId = {{ session.username|default("anonymous", true)|tojson }};var storageKey = 'ldr-theme-' + userId;diff --git a/src/local_deep_research/web/themes/__init__.py b/src/local_deep_research/web/themes/__init__.pyindex 8195aa972b..ad42e33278 100644--- a/src/local_deep_research/web/themes/__init__.py+++ b/src/local_deep_research/web/themes/__init__.py@@ -20,9 +20,9 @@ Usage:css = theme_registry.get_combined_css()"""-import jsonfrom pathlib import Path+from jinja2.utils import htmlsafe_json_dumpsfrom loguru import loggerfrom markupsafe import Markup@@ -135,7 +135,7 @@ class ThemeRegistry:Returns:Markup-safe JSON array string"""- return Markup(json.dumps(self.get_theme_ids()))+ return htmlsafe_json_dumps(self.get_theme_ids())def get_metadata_json(self) -> Markup:"""Get full theme metadata as JSON for JavaScript.@@ -146,7 +146,9 @@ class ThemeRegistry:metadata = {}for theme_id, theme in self.themes.items():metadata[theme_id] = theme.to_dict()- return Markup(json.dumps(metadata))+ # JSON is embedded in a script element. Escape HTML delimiters even+ # though today's metadata comes from package-shipped theme files.+ return htmlsafe_json_dumps(metadata)def get_settings_options(self) -> list[dict]:"""Generate options list for settings UI.diff --git a/tests/js/services/theme-bootstrap-runtime.test.js b/tests/js/services/theme-bootstrap-runtime.test.jsindex d133560668..4be074edfa 100644--- a/tests/js/services/theme-bootstrap-runtime.test.js+++ b/tests/js/services/theme-bootstrap-runtime.test.js@@ -9,8 +9,8 @@ const metadata = Object.fromEntries(['system', 'light', 'hashed', 'sepia'].map(id => [id, { label: id }]));// Supply only the server-rendered values; execute the checked-in browser logic.const bootstrap = template.match(/<script>([\s\S]*?)<\/script>/)[1]- .replace('{{ get_themes_json()|safe }}', JSON.stringify(Object.keys(metadata)))- .replace('{{ get_theme_metadata()|safe }}', JSON.stringify(metadata))+ .replace('{{ get_themes_json() }}', JSON.stringify(Object.keys(metadata)))+ .replace('{{ get_theme_metadata() }}', JSON.stringify(metadata)).replace('{{ session.username|default("anonymous", true)|tojson }}', JSON.stringify('reader'));// This source comes from our template above, never from user-controlled input.diff --git a/tests/security/test_injection_and_template_safety.py b/tests/security/test_injection_and_template_safety.pyindex 21cc6359d0..693cb81601 100644--- a/tests/security/test_injection_and_template_safety.py+++ b/tests/security/test_injection_and_template_safety.py@@ -654,8 +654,6 @@ def test_escape_exception_scanner_is_quiet_on_escaped_output():# Every autoescape opt-out in web/templates, with the verdict on# whether user content can reach it. See the dedicated tests below.ESCAPE_EXCEPTION_CENSUS = {- # Package-shipped theme JSON. Not reachable by user content.- ("base.html", "|safe"): 2,# Callers pass string literals only; enforced below.("components/help_macros.html", "|safe"): 1,}@@ -673,7 +671,7 @@ def test_autoescape_opt_outs_are_exactly_the_reviewed_set():# ----------------------------------------------------------------------# The theme-JSON globals (the ``|safe`` sites in base.html)+# The theme-JSON globals embedded in base.html# ---------------------------------------------------------------------@@ -704,7 +702,7 @@ def test_flask_theme_helper_was_replaced_not_dropped():registered.add(key.value)for name in ("get_themes_json", "get_theme_metadata"):assert name in registered, (- f"base.html renders {name}() with |safe but the port does "+ f"base.html renders {name}() but the port does ""not register it as a template global")@@ -750,12 +748,7 @@ def test_theme_json_globals_return_markup_from_package_files_only():def test_shipped_theme_json_cannot_break_out_of_the_script_block():- """No shipped theme carries HTML-significant characters.-- ``get_theme_metadata()`` is ``Markup(json.dumps(...))``, and- ``json.dumps`` does not escape ``<``. Containment therefore rests- entirely on the theme files' own content, so assert that content.- """+ """Shipped theme metadata is JSON with no HTML-significant characters."""from local_deep_research.web import themes as themes_modulefor payload in (@@ -765,40 +758,45 @@ def test_shipped_theme_json_cannot_break_out_of_the_script_block():assert json.loads(payload) is not Nonefor char in ("<", ">", "&"):assert char not in payload, (- f"a shipped theme contains {char!r}; rendered through "- "|safe that escapes the inline <script> block"+ f"theme JSON contains unescaped {char!r}")-def test_theme_json_encoding_is_content_dependent_not_escaping():- """Pin the latent gap so a future theme source cannot reopen it.[email protected]("payload", [BREAKOUT_HTML, "<>&'\" café", "</ScRiPt>"])+def test_theme_json_escapes_metadata_before_inline_render(monkeypatch, payload):+ """Real helpers and the base template preserve data without HTML breakout."""+ from local_deep_research.web import themes as themes_module- Rendered exactly as ``base.html`` line 18 does. If theme metadata- ever becomes user-supplied (an uploaded or plugin theme), this- demonstrates the breakout that would follow, and this test is the- thing that has to change.- """- env = Environment(autoescape=True) # autoescape on, as the app- template = env.from_string("<script>window.M = {{ meta|safe }};</script>")- # noqa S704: reproducing production's Markup(json.dumps(...)) is- # the entire point of this test.- hostile = Markup( # noqa: S704- json.dumps({"evil": {"label": BREAKOUT_HTML}})- )- rendered = template.render(meta=hostile)- assert BREAKOUT_HTML in rendered, (- "json.dumps() + |safe passes HTML through unescaped — this is "- "the mechanism the test above constrains by content"+ theme = themes_module.ThemeMetadata(+ id=payload, label=payload, icon="fa-star", group="other")- # ...whereas |tojson would have neutralised the same payload.- safe_template = env.from_string(- "<script>window.M = {{ meta|tojson }};</script>"+ monkeypatch.setattr(+ themes_module.theme_registry._loader,+ "load_all_themes",+ lambda: {payload: theme},)- safe_rendered = safe_template.render(- meta={"evil": {"label": BREAKOUT_HTML}}+ ids = themes_module.get_themes_json()+ metadata = themes_module.get_theme_metadata()+ assert json.loads(ids) == [payload]+ assert json.loads(metadata) == {payload: theme.to_dict()}+ assert isinstance(ids, Markup) and isinstance(metadata, Markup)+ for value in (ids, metadata):+ assert all(char not in value for char in "<>&'")++ source = (TEMPLATES / "base.html").read_text(encoding="utf-8")+ script = re.search(r"<script>.*?</script>", source, re.DOTALL).group()+ rendered = (+ Environment(autoescape=True)+ .from_string(script)+ .render(+ get_themes_json=themes_module.get_themes_json,+ get_theme_metadata=themes_module.get_theme_metadata,+ session={"username": "alice"},+ ))- assert BREAKOUT_HTML not in safe_rendered- assert "\\u003c/script\\u003e" in safe_rendered+ assert rendered.lower().count("</script>") == 1+ assert "<" not in rendered # JSON must not become HTML entities.+ assert str(ids) in rendered and str(metadata) in rendered# ---------------------------------------------------------------------