~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: flag dynamic target=_blank links in check-target-blank-rel hook (#4626)
LearningCircuit019e9ef745c0
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex c9a6eccc84..e3586db586 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -173,7 +173,7 @@ repos:name: Check external target=_blank links have rel=noopener noreferrerentry: .pre-commit-hooks/check-target-blank-rel.pylanguage: script- files: \.(html|js|jsx|ts|tsx|mjs)$+ files: \.(html|js|jsx|ts|tsx|mjs|jinja2|jinja)$exclude: ^(tests?/|vendor/|.*/vendor/)description: "Prevent tabnabbing and Referer leakage on externaltarget=_blank links"diff --git a/.pre-commit-hooks/check-target-blank-rel.py b/.pre-commit-hooks/check-target-blank-rel.pyindex d329765a43..877a17c32c 100755--- a/.pre-commit-hooks/check-target-blank-rel.py+++ b/.pre-commit-hooks/check-target-blank-rel.py@@ -7,8 +7,13 @@ Without rel="noopener", the opened page can access window.opener andperform tabnabbing attacks. Without rel="noreferrer", the Referer headerleaks 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.+The check is "flag unless proven internal": a new-tab link must carry the+rel unless we can statically prove it stays same-origin. This intentionally+also covers dynamic hrefs — JS ${...} and Jinja {{ ... }} expressions that+are not url_for() — since those are exactly where past regressions lived.+Provably same-origin anchors (href starting with "/", "#", "?", a Jinja+url_for, or a non-HTTP pseudo-scheme such as mailto:) are skipped — there is+no cross-origin tabnabbing risk on those."""from __future__ import annotations@@ -33,41 +38,48 @@ ATTR_RE = re.compile()-def is_external_href(href: str) -> bool:- """Return True iff the href can be statically proven to be cross-origin.+# Jinja url_for() always resolves to a same-origin path, e.g.+# {{ url_for('x') }} or {{- url_for(...) }}.+URL_FOR_RE = re.compile(r"\{\{-?\s*url_for\b", re.IGNORECASE)- 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.+# Non-HTTP pseudo-schemes that are not new-tab navigation / tabnabbing vectors.+SAFE_SCHEMES = ("mailto:", "tel:", "sms:", "javascript:", "data:")+++def requires_rel(href: str) -> bool:+ """Return True unless the href is provably same-origin / non-navigational.++ Deliberately "flag unless proven internal": a new-tab link should carry+ rel="noopener noreferrer" unless we can PROVE it stays same-origin. This+ covers dynamic links — JS ${...} and Jinja {{ ... }} expressions that are+ not url_for() — which an "only flag provably-external" check would miss+ (and which is exactly where past regressions lived).++ Provably internal (returns False): empty; a same-origin absolute path+ "/..." (but not protocol-relative "//host"); a "#fragment" or "?query"; a+ Jinja {{ url_for(...) }}; and a non-HTTP pseudo-scheme (mailto:, tel:,+ sms:, javascript:, data:). Everything else — http(s)://, //host, a bare+ host like "example.com", or an unresolved ${...} / {{ ... }} expression —+ returns True so the rel is required."""h = href.strip()if not h:return False- # Jinja/template expressions — can't tell statically, skip- if h.startswith("{{") or h.startswith("{%"):+ # Same-origin absolute path (but NOT protocol-relative //host).+ if h.startswith("/") and not h.startswith("//"):return False- # JS template literal — also can't tell, skip- if h.startswith("${"):+ # Fragment or query against the current document.+ 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]:+ # Jinja url_for() always resolves to a same-origin path.+ if URL_FOR_RE.match(h):return False- # Same-origin paths (/, ?, #).- if h.startswith(("/", "?", "#")):+ # Non-HTTP pseudo-schemes are not new-tab navigation.+ if h.lower().startswith(SAFE_SCHEMES):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+ # Anything else (http(s)://, //host, bare host, or an unresolved+ # ${...} / {{ ... }} expression) cannot be proven same-origin — flag it.+ return Truedef parse_attrs(attr_blob: str) -> dict[str, str]:@@ -98,7 +110,7 @@ def check_file(filepath: Path) -> list[tuple[int, str]]:continuehref = attrs.get("href", "")- if not is_external_href(href):+ if not requires_rel(href):continuerel = attrs.get("rel", "").lower()@@ -146,9 +158,10 @@ def main() -> int: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."+ "Provably same-origin\n"+ "links (href starts with /, #, ?, a Jinja url_for, or a mailto:/tel: "+ "scheme)\nare skipped automatically. For a dynamic href that is "+ 'genuinely internal,\nprefer a leading "/" so the check can prove it.')return 1diff --git a/tests/hooks/test_check_target_blank_rel.py b/tests/hooks/test_check_target_blank_rel.pyindex c62bc0b3c7..8ebd433bb0 100644--- a/tests/hooks/test_check_target_blank_rel.py+++ b/tests/hooks/test_check_target_blank_rel.py@@ -1,15 +1,18 @@"""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+The hook flags any ``<a target="_blank">`` that is not provably same-origin+and is missing ``rel="noopener noreferrer"`` — without ``noopener`` the openedpage 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).+The hook uses a "flag unless proven internal" policy: a new-tab link must+carry the rel unless we can statically prove it stays same-origin. That means+dynamic hrefs (JS ``${...}`` and Jinja ``{{ ... }}`` that are not+``url_for()``) and bare scheme-less hosts ARE flagged — those are exactly the+shapes where past regressions lived. Provably same-origin hrefs (leading+``/``, ``#``, ``?``, a Jinja ``url_for``, or a ``mailto:``/``tel:`` scheme)+are skipped."""import subprocess@@ -42,8 +45,8 @@ def _run_hook()-class TestFlagsExternalMissingRel:- """External new-tab anchors missing either rel token must be flagged."""+class TestFlagsStaticExternalMissingRel:+ """Static external new-tab anchors missing either rel token are flagged."""def test_external_no_rel_is_flagged(self):result = _run_hook(@@ -77,8 +80,38 @@ class TestFlagsExternalMissingRel:result = _run_hook('<a href="//example.com" target="_blank">x</a>\n')assert result.returncode == 1++class TestFlagsDynamicMissingRel:+ """The point of the flip: hrefs not provably internal are flagged too."""++ def test_js_template_literal_href_is_flagged(self):+ """`${...}` is not provably same-origin — it must carry rel."""+ result = _run_hook(+ '<a href="${escapeAttr(resource.url)}" target="_blank">x</a>\n',+ "x.js",+ )+ assert result.returncode == 1++ def test_jinja_expression_href_is_flagged(self):+ """A non-url_for `{{ ... }}` (e.g. an external source URL) needs rel."""+ result = _run_hook(+ '<a href="{{ document.original_url }}" target="_blank">x</a>\n'+ )+ assert result.returncode == 1++ def test_jinja_statement_wrapped_href_is_flagged(self):+ """`{% if %}...{% endif %}` could resolve external — not provable."""+ result = _run_hook(+ '<a href="{% if x %}https://a{% else %}/b{% endif %}" '+ 'target="_blank">x</a>\n'+ )+ assert result.returncode == 1++ def test_bare_scheme_less_host_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")@@ -86,7 +119,7 @@ class TestFlagsExternalMissingRel:class TestCompliantAnchorsPass:- """Correctly-protected external anchors must pass regardless of style."""+ """Correctly-protected anchors pass regardless of static/dynamic href."""def test_both_tokens_present_passes(self):result = _run_hook(@@ -116,18 +149,27 @@ class TestCompliantAnchorsPass:)assert result.returncode == 0+ def test_dynamic_href_with_rel_passes(self):+ """A `${...}` href is fine once it carries the rel."""+ result = _run_hook(+ '<a href="${u}" target="_blank" rel="noopener noreferrer">x</a>\n',+ "x.js",+ )+ assert result.returncode == 0+-class TestInternalHrefsSkipped:- """Same-origin / unresolvable hrefs are not a cross-origin risk → pass."""+class TestProvablyInternalSkipped:+ """Provably same-origin hrefs are skipped even without rel."""@pytest.mark.parametrize("href",["/library/document/1/pdf",+ "/progress/${encodeURIComponent(id)}", # dynamic but same-origin"#section","?tab=settings","{{ url_for('main.index') }}",- "{% if x %}/a{% endif %}",+ "{{- url_for('main.index') }}","mailto:[email protected]","tel:+123","javascript:void(0)",@@ -137,27 +179,13 @@ class TestInternalHrefsSkipped: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 == 0class TestSchemeCaseInsensitive:- """PR #4144 follow-up: uppercase URL schemes must not evade the check."""+ """Uppercase URL schemes must not evade the check."""@pytest.mark.parametrize("href",