~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
security: enforce rel=noopener noreferrer via pre-commit hook (#4144)
LearningCircuit6726fd953046
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 0643aed9f9..c9a6eccc84 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -169,6 +169,14 @@ repos:exclude: ^tests/description: "Ensure no external CDN URLs or external resources are referencedin the codebase"+ - id: check-target-blank-rel+ name: Check external target=_blank links have rel=noopener noreferrer+ entry: .pre-commit-hooks/check-target-blank-rel.py+ language: script+ files: \.(html|js|jsx|ts|tsx|mjs)$+ exclude: ^(tests?/|vendor/|.*/vendor/)+ description: "Prevent tabnabbing and Referer leakage on external+ target=_blank links"- id: check-css-class-prefixname: Check CSS class names have ldr- prefixentry: .pre-commit-hooks/check-css-class-prefix.pydiff --git a/.pre-commit-hooks/check-target-blank-rel.py b/.pre-commit-hooks/check-target-blank-rel.pynew file mode 100755index 0000000000..d329765a43--- /dev/null+++ b/.pre-commit-hooks/check-target-blank-rel.py@@ -0,0 +1,157 @@+#!/usr/bin/env python3+"""+Pre-commit hook to enforce rel="noopener noreferrer" on every+<a target="_blank"> that points at an external (cross-origin) URL.++Without rel="noopener", the opened page can access window.opener and+perform tabnabbing attacks. Without rel="noreferrer", the Referer header+leaks the LDR URL to the destination.++Same-origin anchors (href starting with "/" or "#" or a Jinja url_for)+are skipped — there is no cross-origin tabnabbing risk on those.+"""++from __future__ import annotations++import re+import sys+from pathlib import Path++# Match <a ...> opening tags, tolerating multi-line attribute lists: the+# negated class [^>] already spans newlines, so a tag whose attributes wrap+# across lines is captured up to its first ">". IGNORECASE also matches+# <A ...>. Known limitation: a ">" inside a quoted attribute value (e.g.+# title="a > b") truncates the match early; our anchors don't contain one.+ANCHOR_RE = re.compile(r"<a\b([^>]*?)>", re.IGNORECASE)++ATTR_RE = re.compile(+ r"""([A-Za-z_:][-A-Za-z0-9_:.]*) # attribute name+ \s*=\s*+ (?: "([^"]*)" | '([^']*)' | (\S+) ) # quoted or bare value+ """,+ re.VERBOSE,+)+++def is_external_href(href: str) -> bool:+ """Return True iff the href can be statically proven to be cross-origin.++ Returns True only for hrefs beginning with http://, https://, or a+ scheme-relative //host (the scheme comparison is case-insensitive).+ Everything else is treated as internal: same-origin paths (/, ?, #),+ pseudo-schemes (mailto:, tel:, javascript:, data:), Jinja {{ }}/{% %}+ and JS ${ } expressions we cannot resolve statically, and bare+ scheme-less hosts (e.g. "example.com") which browsers resolve as+ relative paths. We only flag what we can prove is external.+ """+ h = href.strip()+ if not h:+ return False+ # Jinja/template expressions — can't tell statically, skip+ if h.startswith("{{") or h.startswith("{%"):+ return False+ # JS template literal — also can't tell, skip+ if h.startswith("${"):+ return False+ # URL schemes are case-insensitive; compare against a lowercased copy.+ hl = h.lower()+ if hl.startswith("http://") or hl.startswith("https://"):+ return True+ if hl.startswith("//"):+ return True+ # mailto:, tel:, javascript:, data: — not http navigation+ if ":" in h.split("/", 1)[0]:+ return False+ # Same-origin paths (/, ?, #).+ if h.startswith(("/", "?", "#")):+ return False+ # Bare scheme-less host (e.g. "example.com"): browsers treat this as a+ # relative path and we cannot prove it is external, so skip it.+ return False+++def parse_attrs(attr_blob: str) -> dict[str, str]:+ """Parse anchor attributes into a name -> value dict (lowercased keys)."""+ out: dict[str, str] = {}+ for m in ATTR_RE.finditer(attr_blob):+ name = m.group(1).lower()+ value = m.group(2) or m.group(3) or m.group(4) or ""+ out[name] = value+ return out+++def check_file(filepath: Path) -> list[tuple[int, str]]:+ """Return list of (line_number, snippet) violations for filepath."""+ try:+ text = filepath.read_text(encoding="utf-8")+ except (UnicodeDecodeError, OSError):+ return []++ violations: list[tuple[int, str]] = []++ for match in ANCHOR_RE.finditer(text):+ attr_blob = match.group(1)+ attrs = parse_attrs(attr_blob)++ target = attrs.get("target", "").lower()+ if target != "_blank":+ continue++ href = attrs.get("href", "")+ if not is_external_href(href):+ continue++ rel = attrs.get("rel", "").lower()+ rel_tokens = set(rel.split())+ if "noopener" in rel_tokens and "noreferrer" in rel_tokens:+ continue++ # Find the line number of the match start+ line_num = text.count("\n", 0, match.start()) + 1+ snippet = match.group(0).strip().replace("\n", " ")+ if len(snippet) > 140:+ snippet = snippet[:137] + "..."+ violations.append((line_num, snippet))++ return violations+++def main() -> int:+ files = [Path(f) for f in sys.argv[1:]]++ skip_parts = {"vendor", "node_modules", ".venv", "venv", "__pycache__"}++ all_violations: list[tuple[Path, list[tuple[int, str]]]] = []+ for filepath in files:+ if any(part in skip_parts for part in filepath.parts):+ continue+ vs = check_file(filepath)+ if vs:+ all_violations.append((filepath, vs))++ if not all_violations:+ return 0++ print('\nExternal <a target="_blank"> missing rel="noopener noreferrer":\n')+ print(+ "Without noopener, the opened page can access window.opener "+ "(tabnabbing).\nWithout noreferrer, the Referer header leaks the "+ "LDR URL to the destination.\n"+ )+ for filepath, vs in all_violations:+ print(f" {filepath}")+ for line_num, snippet in vs:+ print(f" line {line_num}: {snippet}")+ print()++ print(+ 'Fix: add rel="noopener noreferrer" to each flagged anchor. '+ "Internal same-origin\n"+ "links (href starts with /, #, ?, or a Jinja url_for) are "+ "skipped automatically."+ )+ return 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/src/local_deep_research/web/static/js/components/details.js b/src/local_deep_research/web/static/js/components/details.jsindex 7510350ee5..1bdefe8c61 100644--- a/src/local_deep_research/web/static/js/components/details.js+++ b/src/local_deep_research/web/static/js/components/details.js@@ -151,7 +151,7 @@const resourceHtml = data.resources.map(resource => `<div style="padding: 0.75rem; border-bottom: 1px solid var(--border-color);"><div style="font-weight: 500; margin-bottom: 0.25rem;">${escapeHtml(resource.title)}</div>- <a href="${escapeAttr(resource.url)}" target="_blank" style="color: var(--primary-color); text-decoration: none; font-size: 0.875rem; word-break: break-all;">+ <a href="${escapeAttr(resource.url)}" target="_blank" rel="noopener noreferrer" style="color: var(--primary-color); text-decoration: none; font-size: 0.875rem; word-break: break-all;">${escapeHtml(resource.url)}</a>${resource.preview ? `<div style="color: var(--text-secondary); font-size: 0.875rem; margin-top: 0.5rem;">${escapeHtml(resource.preview)}</div>` : ''}diff --git a/src/local_deep_research/web/templates/pages/journal_quality.html b/src/local_deep_research/web/templates/pages/journal_quality.htmlindex d402c5c02c..aaafc831e4 100644--- a/src/local_deep_research/web/templates/pages/journal_quality.html+++ b/src/local_deep_research/web/templates/pages/journal_quality.html@@ -149,10 +149,10 @@</div><div style="font-size: 0.78rem; color: var(--text-secondary); line-height: 1.45; margin-bottom: 0.75rem;">Journal quality scoring is built on freely-licensed bibliographic data from- <a href="https://openalex.org" target="_blank" rel="noopener" style="color: var(--accent-primary); text-decoration: none;">OpenAlex</a> (CC0 — sources & institutions),- <a href="https://doaj.org" target="_blank" rel="noopener" style="color: var(--accent-primary); text-decoration: none;">DOAJ</a> (CC0 — open-access verification),- <a href="https://github.com/JabRef/abbrv.jabref.org" target="_blank" rel="noopener" style="color: var(--accent-primary); text-decoration: none;">JabRef abbreviations</a> (CC0), and- <a href="https://github.com/stop-predatory-journals/stop-predatory-journals.github.io" target="_blank" rel="noopener" style="color: var(--accent-primary); text-decoration: none;">Stop Predatory Journals</a> (MIT).+ <a href="https://openalex.org" target="_blank" rel="noopener noreferrer" style="color: var(--accent-primary); text-decoration: none;">OpenAlex</a> (CC0 — sources & institutions),+ <a href="https://doaj.org" target="_blank" rel="noopener noreferrer" style="color: var(--accent-primary); text-decoration: none;">DOAJ</a> (CC0 — open-access verification),+ <a href="https://github.com/JabRef/abbrv.jabref.org" target="_blank" rel="noopener noreferrer" style="color: var(--accent-primary); text-decoration: none;">JabRef abbreviations</a> (CC0), and+ <a href="https://github.com/stop-predatory-journals/stop-predatory-journals.github.io" target="_blank" rel="noopener noreferrer" style="color: var(--accent-primary); text-decoration: none;">Stop Predatory Journals</a> (MIT).Every dataset is fetched directly from the upstream provider on demand — please consider supporting them if you find this useful.</div><div id="ldr-sources-grid" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 0.6rem;">@@ -257,7 +257,7 @@<ol style="color: var(--text-secondary); line-height: 1.7; padding-left: 1.25rem;"><li><strong>Tier 0 — Local cache.</strong> Already scored in your per-user DB? Return instantly.</li><li><strong>Tier 1 — Predatory blacklist.</strong> Match against- <a href="https://github.com/stop-predatory-journals/stop-predatory-journals.github.io" target="_blank" rel="noopener" style="color: var(--accent-primary);">Stop Predatory Journals</a>+ <a href="https://github.com/stop-predatory-journals/stop-predatory-journals.github.io" target="_blank" rel="noopener noreferrer" style="color: var(--accent-primary);">Stop Predatory Journals</a>(~2.5K entries). A hit forces score 1 and the result is dropped from your search.</li><li><strong>Tier 2 — OpenAlex sources.</strong> ~280K journals + conferences with h-index, 2-yr meancitedness, citation count, publisher, ISSN. Quality is derived from h-index thresholds@@ -359,7 +359,7 @@<p style="color: var(--text-secondary); font-size: 0.85rem; margin-top: 1rem; margin-bottom: 0;">Full documentation:<a href="https://github.com/LearningCircuit/local-deep-research/blob/main/docs/journal-quality.md"- target="_blank" rel="noopener" style="color: var(--accent-primary);">+ target="_blank" rel="noopener noreferrer" style="color: var(--accent-primary);">docs/journal-quality.md on GitHub</a></p>@@ -692,17 +692,17 @@ function renderSourcesBanner(sources) {const pillIcon = ok ? '✓' : '✗';const pillLabel = ok ? 'Downloaded' : 'Not downloaded';const datasetLink = s.dataset_url- ? `<a href="${safeHref(s.dataset_url)}" target="_blank" rel="noopener" style="color: var(--accent-primary); text-decoration: none;" title="Direct link to the upstream dataset/dump"><i class="fas fa-database" style="margin-right: 0.2rem;"></i>Dataset</a>`+ ? `<a href="${safeHref(s.dataset_url)}" target="_blank" rel="noopener noreferrer" style="color: var(--accent-primary); text-decoration: none;" title="Direct link to the upstream dataset/dump"><i class="fas fa-database" style="margin-right: 0.2rem;"></i>Dataset</a>`: '';return `<div style="padding: 0.6rem 0.75rem; background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 0.5rem;"><div style="display: flex; align-items: center; justify-content: space-between; gap: 0.5rem; margin-bottom: 0.3rem;">- <a href="${safeHref(s.url)}" target="_blank" rel="noopener" style="font-weight: 600; color: var(--text-primary); text-decoration: none; font-size: 0.85rem;">${escHtml(s.name)}</a>+ <a href="${safeHref(s.url)}" target="_blank" rel="noopener noreferrer" style="font-weight: 600; color: var(--text-primary); text-decoration: none; font-size: 0.85rem;">${escHtml(s.name)}</a><span style="display: inline-flex; align-items: center; gap: 0.2rem; padding: 0.15rem 0.45rem; border-radius: 999px; background: ${pillBg}; color: ${pillColor}; font-size: 0.7rem; font-weight: 600; white-space: nowrap;">${pillIcon} ${pillLabel}</span></div><div style="font-size: 0.72rem; color: var(--text-secondary); line-height: 1.35; margin-bottom: 0.3rem;">${escHtml(s.description || '')}</div><div style="display: flex; gap: 0.75rem; font-size: 0.7rem;">- <a href="${safeHref(s.license_url)}" target="_blank" rel="noopener" style="color: var(--accent-primary); text-decoration: none;">License: ${escHtml(s.license)}</a>+ <a href="${safeHref(s.license_url)}" target="_blank" rel="noopener noreferrer" style="color: var(--accent-primary); text-decoration: none;">License: ${escHtml(s.license)}</a>${datasetLink}</div></div>diff --git a/tests/hooks/test_check_target_blank_rel.py b/tests/hooks/test_check_target_blank_rel.pynew file mode 100644index 0000000000..c62bc0b3c7--- /dev/null+++ b/tests/hooks/test_check_target_blank_rel.py@@ -0,0 +1,225 @@+"""+Tests for the check-target-blank-rel pre-commit hook.++The hook (added in PR #4144) flags any external ``<a target="_blank">`` that+is missing ``rel="noopener noreferrer"`` — without ``noopener`` the opened+page can reach back via ``window.opener`` (tabnabbing), and without+``noreferrer`` the Referer header leaks the LDR URL to the destination.++These tests lock in the externality classification, the both-tokens-required+rel check, multi-line/quoting robustness, the case-insensitive scheme match+(PR #4144 follow-up), and the deliberate blind spots (dynamic ``${...}`` /+Jinja hrefs and bare scheme-less hosts are treated as internal).+"""++import subprocess+import sys+import tempfile+from pathlib import Path++import pytest+++HOOK_SCRIPT = (+ Path(__file__).parent.parent.parent+ / ".pre-commit-hooks"+ / "check-target-blank-rel.py"+)+++def _run_hook(+ content: str, filename: str = "x.html"+) -> subprocess.CompletedProcess:+ """Write content to a temp file and run the hook against it."""+ with tempfile.TemporaryDirectory() as d:+ path = Path(d) / filename+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(content)+ return subprocess.run(+ [sys.executable, str(HOOK_SCRIPT), str(path)],+ capture_output=True,+ text=True,+ )+++class TestFlagsExternalMissingRel:+ """External new-tab anchors missing either rel token must be flagged."""++ def test_external_no_rel_is_flagged(self):+ result = _run_hook(+ '<a href="https://example.com" target="_blank">x</a>\n'+ )+ assert result.returncode == 1+ assert "noopener noreferrer" in result.stdout++ def test_external_noopener_only_is_flagged(self):+ """`rel="noopener"` alone still leaks the Referer — must fail."""+ result = _run_hook(+ '<a href="https://example.com" target="_blank" '+ 'rel="noopener">x</a>\n'+ )+ assert result.returncode == 1++ def test_external_noreferrer_only_is_flagged(self):+ result = _run_hook(+ '<a href="https://example.com" target="_blank" '+ 'rel="noreferrer">x</a>\n'+ )+ assert result.returncode == 1++ def test_http_external_is_flagged(self):+ result = _run_hook(+ '<a href="http://example.com" target="_blank">x</a>\n'+ )+ assert result.returncode == 1++ def test_protocol_relative_external_is_flagged(self):+ result = _run_hook('<a href="//example.com" target="_blank">x</a>\n')+ assert result.returncode == 1++ def test_literal_scheme_prefix_before_template_expr_is_flagged(self):+ """`https://${host}` begins with a literal scheme → provably external."""+ result = _run_hook(+ '<a href="https://${host}/p" target="_blank">x</a>\n', "x.js"+ )+ assert result.returncode == 1+++class TestCompliantAnchorsPass:+ """Correctly-protected external anchors must pass regardless of style."""++ def test_both_tokens_present_passes(self):+ result = _run_hook(+ '<a href="https://example.com" target="_blank" '+ 'rel="noopener noreferrer">x</a>\n'+ )+ assert result.returncode == 0++ def test_reversed_token_order_passes(self):+ result = _run_hook(+ '<a href="https://example.com" target="_blank" '+ 'rel="noreferrer noopener">x</a>\n'+ )+ assert result.returncode == 0++ def test_uppercase_rel_tokens_pass(self):+ result = _run_hook(+ '<a href="https://example.com" target="_blank" '+ 'rel="NOOPENER NOREFERRER">x</a>\n'+ )+ assert result.returncode == 0++ def test_extra_rel_tokens_pass(self):+ result = _run_hook(+ '<a href="https://example.com" target="_blank" '+ 'rel="nofollow noopener noreferrer">x</a>\n'+ )+ assert result.returncode == 0+++class TestInternalHrefsSkipped:+ """Same-origin / unresolvable hrefs are not a cross-origin risk → pass."""++ @pytest.mark.parametrize(+ "href",+ [+ "/library/document/1/pdf",+ "#section",+ "?tab=settings",+ "{{ url_for('main.index') }}",+ "{% if x %}/a{% endif %}",+ "mailto:[email protected]",+ "tel:+123",+ "javascript:void(0)",+ ],+ )+ def test_internal_href_with_blank_target_passes(self, href: str):+ result = _run_hook(f'<a href="{href}" target="_blank">x</a>\n')+ assert result.returncode == 0, result.stdout++ def test_js_template_literal_href_is_skipped(self):+ """`${...}` hrefs can't be resolved statically — deliberate blind spot."""+ result = _run_hook(+ '<a href="${escapeAttr(resource.url)}" target="_blank">x</a>\n',+ "x.js",+ )+ assert result.returncode == 0++ def test_bare_scheme_less_host_treated_internal(self):+ """Documents the known limitation: `example.com` (no scheme) is treated+ as a relative path / internal, so it is NOT flagged."""+ result = _run_hook('<a href="example.com" target="_blank">x</a>\n')+ assert result.returncode == 0++ def test_anchor_without_blank_target_is_ignored(self):+ result = _run_hook('<a href="https://example.com">x</a>\n')+ assert result.returncode == 0+++class TestSchemeCaseInsensitive:+ """PR #4144 follow-up: uppercase URL schemes must not evade the check."""++ @pytest.mark.parametrize(+ "href",+ ["HTTPS://example.com", "HTTP://example.com", "HtTpS://example.com"],+ )+ def test_uppercase_scheme_external_is_flagged(self, href: str):+ result = _run_hook(f'<a href="{href}" target="_blank">x</a>\n')+ assert result.returncode == 1, result.stdout+++class TestParsingRobustness:+ """Attribute order, quoting, casing, and multi-line tags all parse."""++ def test_target_before_href_is_flagged(self):+ result = _run_hook(+ '<a target="_blank" href="https://example.com">x</a>\n'+ )+ assert result.returncode == 1++ def test_single_quoted_attrs_are_flagged(self):+ result = _run_hook(+ "<a href='https://example.com' target='_blank'>x</a>\n"+ )+ assert result.returncode == 1++ def test_mixed_case_blank_target_is_flagged(self):+ result = _run_hook(+ '<a href="https://example.com" TARGET="_BLANK">x</a>\n'+ )+ assert result.returncode == 1++ def test_multiline_tag_missing_rel_is_flagged(self):+ """Multi-line attribute lists must still be parsed (no DOTALL needed)."""+ result = _run_hook(+ '<a href="https://example.com"\n'+ ' target="_blank"\n'+ ' class="x">link</a>\n'+ )+ assert result.returncode == 1++ def test_multiline_tag_with_rel_passes(self):+ result = _run_hook(+ '<a href="https://example.com"\n'+ ' target="_blank"\n'+ ' rel="noopener noreferrer">link</a>\n'+ )+ assert result.returncode == 0+++class TestExitCodes:+ """No anchors / no violations → clean exit."""++ def test_no_anchors_passes(self):+ result = _run_hook("<div>no anchors here</div>\n")+ assert result.returncode == 0++ def test_multiple_violations_reported(self):+ content = (+ '<a href="https://a.com" target="_blank">a</a>\n'+ '<a href="https://b.com" target="_blank" rel="noopener">b</a>\n'+ )+ result = _run_hook(content)+ assert result.returncode == 1+ assert "line 1" in result.stdout+ assert "line 2" in result.stdout