~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(security): harden DOMPurify tabnabbing hook registration and target matching (#6592)
LearningCircuitdb6d85d5bf12
diff --git a/changelog.d/6592.security.md b/changelog.d/6592.security.mdnew file mode 100644index 0000000000..0944d26486--- /dev/null+++ b/changelog.d/6592.security.md@@ -0,0 +1 @@+The renderer's tabnabbing defense (adding rel=noopener noreferrer during sanitization on `<a>` elements, including SVG `<a>`, and on `<area>` and `<form>` elements whose target can open a new browsing context) now registers lazily and idempotently per sanitizer instance instead of only at script-load time, so it no longer depends on the sanitizer library being bound before the protection script loads, and a replaced sanitizer instance also gets it. It previously covered only `<a>`; `<area>` and `<form>` targets are now covered too. The hook now matches targets case-insensitively and covers named and non-standard targets, not only an exact lowercase `_blank`; only the exact `_self`, `_parent` and `_top` keywords and an empty target are exempt. It reads and writes the element through the DOM prototype, so a form control named or id'd `tagName`, `getAttribute` or `setAttribute` can no longer switch it off, and it merges into an existing rel (keeping other tokens such as `nofollow`, dropping `opener`) instead of replacing it. The markdown renderer also ensures the hook before it sanitizes, so links and forms embedded as raw HTML inside markdown gain the same rel as markdown-syntax links. A sanitizer instance without hook support is now reported once via SafeLogger when it is available, instead of being skipped silently.diff --git a/src/local_deep_research/web/static/js/pages/news.js b/src/local_deep_research/web/static/js/pages/news.jsindex 2e44effe79..4aa8d4fd1f 100644--- a/src/local_deep_research/web/static/js/pages/news.js+++ b/src/local_deep_research/web/static/js/pages/news.js@@ -10,10 +10,11 @@ function safeRenderHTML(container, htmlString) {if (!container) return;- // DOMPurify is loaded via app.js as a <script type="module"> in base.html.- // Module scripts execute after all defer scripts, so DOMPurify may not yet- // be available when this defer script first runs. Fall back to textContent- // (which is always XSS-safe) until DOMPurify is ready.+ // DOMPurify is bound by app.js, a <script type="module"> in base.html.+ // Non-async module scripts and defer classic scripts execute in document+ // order, so it is normally bound before this script runs; if the bundle+ // failed to load or was reordered, fall back to textContent (which is+ // always XSS-safe) instead of assigning unsanitized HTML.if (!window.DOMPurify) {SafeLogger.warn('DOMPurify not yet loaded — rendering as plain text (safe fallback)');while (container.firstChild) {diff --git a/src/local_deep_research/web/static/js/security/xss-protection.js b/src/local_deep_research/web/static/js/security/xss-protection.jsindex 1b3bd90432..b47f43a40c 100644--- a/src/local_deep_research/web/static/js/security/xss-protection.js+++ b/src/local_deep_research/web/static/js/security/xss-protection.js@@ -33,23 +33,138 @@(function() {'use strict';- // Check if DOMPurify is available dynamically (loaded via app.js/Vite module)- // Must be a function since Vite modules are deferred and load after this script+ // Check if DOMPurify is available dynamically (bound by app.js/Vite module).+ // Evaluated per call rather than once, so no helper depends on the+ // relative load order of this script and the module that binds it.function hasDOMPurify() {return typeof DOMPurify !== 'undefined';}- // Configure DOMPurify hooks to prevent tabnabbing attacks- // This must be done at module load time, before any sanitization occurs- if (hasDOMPurify()) {- DOMPurify.addHook('afterSanitizeAttributes', function(node) {- // Enforce rel="noopener noreferrer" on all links with target="_blank"- // This prevents the opened page from accessing window.opener- if (node.tagName === 'A' && node.getAttribute('target') === '_blank') {- node.setAttribute('rel', 'noopener noreferrer');+ // Browsing-context keywords that never open a new browsing context.+ // Any other non-empty target (_blank, a named window, or an unknown+ // keyword) can, so it gets the forced rel.+ const SAME_CONTEXT_TARGETS = new Set(['_self', '_parent', '_top']);++ // Elements whose `target` can navigate a new browsing context and whose+ // `rel` accepts noopener/noreferrer: <a> (HTML, and SVG <a>, whose+ // lowercase tagName is upper-cased below), <area>, and <form>.+ const NEW_CONTEXT_TAGS = new Set(['A', 'AREA', 'FORM']);++ // Element accessors taken from Element.prototype rather than read off+ // the node. On a <form>, a descendant control named or id'd `tagName`,+ // `getAttribute` or `setAttribute` shadows the same-named instance+ // property (HTMLFormElement's [LegacyOverrideBuiltIns] named+ // properties), and DOMPurify's clobbering check does not cover all of+ // them, so the hook must never trust a property looked up on the node.+ // Captured at load when Element exists, otherwise on first use.+ let _elementApi = null;+ function _getElementApi() {+ if (_elementApi) {+ return _elementApi;+ }+ if (typeof Element !== 'function' || !Element.prototype) {+ return null;+ }+ const proto = Element.prototype;+ const tagNameDesc = Object.getOwnPropertyDescriptor(proto, 'tagName');+ if (!tagNameDesc || typeof tagNameDesc.get !== 'function' ||+ typeof proto.getAttribute !== 'function' ||+ typeof proto.setAttribute !== 'function') {+ return null;+ }+ _elementApi = {+ ElementCtor: Element,+ getTagName: tagNameDesc.get,+ getAttr: proto.getAttribute,+ setAttr: proto.setAttribute,+ };+ return _elementApi;+ }+ _getElementApi();++ // Merge the forced keywords into an existing rel instead of replacing+ // it: keep every other token (e.g. nofollow, ugc) once, drop `opener`+ // (it would re-grant window.opener), and append noopener noreferrer.+ function _mergeRel(existing) {+ const kept = [];+ const seen = new Set();+ String(existing === null || existing === undefined ? '' : existing)+ .split(/[\t\n\f\r ]+/)+ .forEach(function(token) {+ const lower = token.toLowerCase();+ if (token === '' || lower === 'opener' ||+ lower === 'noopener' || lower === 'noreferrer' ||+ seen.has(lower)) {+ return;+ }+ seen.add(lower);+ kept.push(token);+ });+ kept.push('noopener', 'noreferrer');+ return kept.join(' ');+ }++ // Configure DOMPurify hooks to prevent tabnabbing attacks.+ // Registration is lazy and idempotent per DOMPurify instance. The+ // load-time call below registers when DOMPurify is already bound, but+ // correctness does not rest on it: every sanitize path whose config+ // keeps `target` (this module's, and renderMarkdown via the exported+ // ensure) ensures the hook first, so a DOMPurify bound (or replaced)+ // after this script loads is covered too. Direct DOMPurify.sanitize+ // callers elsewhere keep no `target` attribute, so need no hook.+ const _hookedPurifiers = new WeakSet();+ let _warnedNoAddHook = false;+ function _ensureTabnabbingHook() {+ if (!hasDOMPurify()) {+ return;+ }+ const purifier = DOMPurify;+ if (!purifier || _hookedPurifiers.has(purifier)) {+ return;+ }+ if (typeof purifier.addHook !== 'function') {+ // Report once via SafeLogger when it is available: sanitizing+ // still works, but links that open a new browsing context will+ // not get the forced rel.+ if (!_warnedNoAddHook && typeof SafeLogger !== 'undefined' &&+ SafeLogger && typeof SafeLogger.warn === 'function') {+ _warnedNoAddHook = true;+ SafeLogger.warn('DOMPurify has no addHook; tabnabbing rel hook not registered');+ }+ return;+ }+ purifier.addHook('afterSanitizeAttributes', function(node) {+ // Enforce rel noopener noreferrer on every link or form that+ // can open a new browsing context, so the opened page cannot+ // reach window.opener (tabnabbing) or receive the Referer.+ // Every read and write goes through the prototype accessors+ // above, never through a property looked up on the node.+ const api = _getElementApi();+ if (!api || !(node instanceof api.ElementCtor)) {+ return;+ }+ const tag = String(api.getTagName.call(node)).toUpperCase();+ if (!NEW_CONTEXT_TAGS.has(tag)) {+ return;+ }+ const target = api.getAttr.call(node, 'target');+ if (target === null) {+ return;+ }+ // Only the exact keywords are exempt (ASCII case-insensitive,+ // not trimmed here): anything else gets the forced rel, and an+ // extra rel on a same-context navigation is harmless. DOMPurify+ // trims attribute values before this hook runs, so a padded+ // " _top " arrives as "_top"; the no-trim rule only matters for+ // callers that hand the hook untrimmed values.+ const normalized = String(target).toLowerCase();+ if (normalized !== '' && !SAME_CONTEXT_TARGETS.has(normalized)) {+ api.setAttr.call(node, 'rel', _mergeRel(api.getAttr.call(node, 'rel')));}});+ _hookedPurifiers.add(purifier);}+ _ensureTabnabbingHook();/*** HTML entity encoding map for XSS prevention@@ -143,6 +258,7 @@ function safeSetInnerHTML(element, content, allowHtmlTags = false) {if (allowHtmlTags && hasDOMPurify()) {// Use DOMPurify for secure HTML sanitization+ _ensureTabnabbingHook();const sanitized = DOMPurify.sanitize(contentString, SANITIZE_CONFIG);// bearer:disable javascript_lang_dangerous_insert_html// eslint-disable-next-line no-unsanitized/property -- audited 2026-03-28: content already sanitized by DOMPurify.sanitize() above@@ -204,6 +320,7 @@ function safeCreateElement(tagName, text = '', attributes = {}, classNames = [])}// Let DOMPurify sanitize attributes (on*, javascript:/data: URIs, etc.)+ _ensureTabnabbingHook();const clean = DOMPurify.sanitize(element.outerHTML, {ALLOWED_TAGS: [normalizedTag],RETURN_DOM_FRAGMENT: true,@@ -288,6 +405,7 @@ function sanitizeHtml(dirty, config = {}) {if (hasDOMPurify()) {const finalConfig = { ...SANITIZE_CONFIG, ...config };+ _ensureTabnabbingHook();return DOMPurify.sanitize(String(dirty), finalConfig);}// Fallback: escape all HTML if DOMPurify is not available@@ -340,6 +458,7 @@ function sanitizeUserInput(input, options = {}) {// Export to global scopewindow.XSSProtection = {escapeHtml,+ ensureTabnabbingHook: _ensureTabnabbingHook,escapeHtmlAttribute,safeSetInnerHTML,safeCreateElement,diff --git a/src/local_deep_research/web/static/js/services/ui.js b/src/local_deep_research/web/static/js/services/ui.jsindex ce4e4d5320..f3800ea165 100644--- a/src/local_deep_research/web/static/js/services/ui.js+++ b/src/local_deep_research/web/static/js/services/ui.js@@ -305,6 +305,11 @@ function renderMarkdown(markdown) {const processedHtml = processSpecialMarkdown(html);// Sanitize to prevent XSS from markdown content+ // Raw <a target="_blank"> HTML embedded in markdown bypasses+ // the marked renderer's rel hook; ensure the shared tabnabbing+ // hook is registered before sanitizing (idempotent, and a+ // no-op when XSSProtection has not loaded).+ window.XSSProtection?.ensureTabnabbingHook?.();const sanitized = typeof DOMPurify !== 'undefined'? DOMPurify.sanitize(processedHtml, {ADD_TAGS: ['semantics', 'annotation'],diff --git a/tests/js/security/render-markdown-tabnabbing.test.js b/tests/js/security/render-markdown-tabnabbing.test.jsnew file mode 100644index 0000000000..39dfa75031--- /dev/null+++ b/tests/js/security/render-markdown-tabnabbing.test.js@@ -0,0 +1,232 @@+/**+ * Tabnabbing contracts for raw-HTML anchors inside rendered markdown.+ *+ * ``renderMarkdown``'s marked renderer adds ``rel="noopener+ * noreferrer"`` to **markdown-syntax** links, but raw ``<a+ * target="_blank">`` HTML embedded in markdown passes through marked's+ * HTML passthrough untouched by that renderer hook. Those anchors get+ * their rel from xss-protection.js's ``afterSanitizeAttributes`` hook,+ * so ``renderMarkdown`` ensures that hook is registered before it+ * sanitizes (``XSSProtection.ensureTabnabbingHook``).+ *+ * These contracts pin, under the adverse order where DOMPurify binds+ * after both scripts loaded: a raw-HTML ``target="_blank"`` anchor,+ * ``<area>`` or ``<form>`` in markdown keeps its target through+ * renderMarkdown's ``ADD_ATTR`` and gains the rel through the hook,+ * registration stays single across renders, and the marked-missing+ * fallback escapes raw anchors into inert text. Every test reloads both+ * modules and late-binds a fresh DOMPurify, so each test's first render+ * is the first sanitize that instance sees: moving the ensure after the+ * sanitize call fails every rel assertion, not only the first test's.+ */++// Browsers expose a <form>'s controls as named properties that shadow+// same-named built-ins on the form instance ([LegacyOverrideBuiltIns]);+// happy-dom does not, so the stand-in emulates it while the hooks run.+const FORM_SHADOWABLE = ['tagName', 'getAttribute', 'setAttribute'];+const FORM_CONTROLS = 'input,button,select,textarea,fieldset,output,object';++const withFormNamedProps = (el, fn) => {+ const shadowed = [];+ if (el.localName === 'form') {+ const controls = Array.from(el.querySelectorAll(FORM_CONTROLS));+ FORM_SHADOWABLE.forEach((prop) => {+ const control = controls.find((c) =>+ c.getAttribute('name') === prop || c.getAttribute('id') === prop+ );+ if (control) {+ Object.defineProperty(el, prop, {+ configurable: true,+ get: () => control,+ });+ shadowed.push(prop);+ }+ });+ }+ try {+ fn();+ } finally {+ shadowed.forEach((prop) => delete el[prop]);+ }+ return shadowed.length;+};++describe('renderMarkdown ensures the tabnabbing hook', () => {+ let registeredHooks;+ let purifier;+ let shadowedCount;++ // Subset of DOMPurify's default ALLOWED_ATTR; like the real list it+ // has no `target`, so `target` only survives through the caller's+ // ADD_ATTR (renderMarkdown passes ['target', 'rel']).+ const DEFAULT_ALLOWED_ATTR = [+ 'href', 'title', 'class', 'id', 'rel', 'action', 'method', 'name',+ 'alt', 'shape', 'coords',+ ];++ const lateBind = () => {+ registeredHooks = {};+ shadowedCount = 0;+ purifier = {+ addHook: (name, cb) => {+ registeredHooks[name] ||= [];+ registeredHooks[name].push(cb);+ },+ sanitize: (dirty, config = {}) => {+ const template = document.createElement('template');+ // eslint-disable-next-line no-unsanitized/property -- test harness stand-in: fixture is this file's own input+ template.innerHTML = String(dirty);+ const allowedAttr = new Set([+ ...(config.ALLOWED_ATTR || DEFAULT_ALLOWED_ATTR),+ ...(config.ADD_ATTR || []),+ ].map((x) => String(x).toLowerCase()));+ // Like DOMPurify: filter each element's attributes, then run+ // the afterSanitizeAttributes hooks on it.+ template.content.querySelectorAll('*').forEach((el) => {+ Array.from(el.attributes).forEach((attr) => {+ if (!allowedAttr.has(attr.name.toLowerCase())) {+ el.removeAttribute(attr.name);+ }+ });+ shadowedCount += withFormNamedProps(el, () => {+ (registeredHooks.afterSanitizeAttributes || []).forEach(+ (cb) => cb(el)+ );+ });+ });+ return template.innerHTML;+ },+ };+ globalThis.DOMPurify = purifier;+ };++ const parseOut = (out) => {+ const template = document.createElement('template');+ // eslint-disable-next-line no-unsanitized/property -- test harness: output under test+ template.innerHTML = out;+ return template.content;+ };++ beforeEach(async () => {+ // Adverse order, per test: neither marked, nor DOMPurify, nor+ // (therefore) the hook exist when the modules load.+ delete globalThis.DOMPurify;+ globalThis.marked = undefined;+ vi.resetModules();+ await import('@js/security/xss-protection.js');+ await import('@js/services/ui.js');++ // ...then the real-world stack binds afterwards.+ // eslint-disable-next-line require-atomic-updates -- deliberate late binding of the deferred-module global+ globalThis.marked = {+ Renderer: class {+ link() {+ return '<a href="#">x</a>';+ }+ },+ setOptions() {},+ parse: (md) => String(md),+ };+ lateBind();+ });++ afterEach(() => {+ delete globalThis.DOMPurify;+ delete globalThis.marked;+ delete window.XSSProtection;+ delete window.ui;+ ['escapeHtml', 'escapeHtmlAttribute', 'safeSetInnerHTML',+ 'safeCreateElement', 'safeSetTextContent', 'createSafeAlertElement',+ 'sanitizeUserInput', 'sanitizeHtml', 'safeUpdateButton',+ 'createSafeLoadingOverlay', 'safeSetStyles', 'showSafeAlert'+ ].forEach((name) => delete window[name]);+ });++ it('a raw-HTML target=_blank anchor in markdown gains rel', () => {+ const out = window.ui.renderMarkdown(+ 'text <a href="https://example.test" target="_blank">raw link</a> more'+ );+ const template = document.createElement('template');+ // eslint-disable-next-line no-unsanitized/property -- test harness: output under test+ template.innerHTML = out;+ const anchor = template.content.querySelector('a[target="_blank"]');+ expect(anchor).not.toBeNull();+ expect(anchor.getAttribute('rel')).toBe('noopener noreferrer');+ });++ it('target survives the ADD_ATTR config that DOMPurify defaults would strip', () => {+ const out = window.ui.renderMarkdown(+ '<a href="https://example.test" target="popup">named</a>'+ );+ const anchor = parseOut(out).querySelector('a');+ expect(anchor.getAttribute('target')).toBe('popup');+ expect(anchor.getAttribute('rel')).toBe('noopener noreferrer');+ });++ it.each([+ ['area', '<map name="m"><area href="https://example.test" target="_blank"></map>'],+ ['form', '<form action="https://example.test" target="_blank"></form>'],+ ])('a raw-HTML <%s target=_blank> in markdown gains rel', (tag, markdown) => {+ const el = parseOut(window.ui.renderMarkdown(markdown)).querySelector(tag);+ expect(el).not.toBeNull();+ expect(el.getAttribute('target')).toBe('_blank');+ expect(el.getAttribute('rel')).toBe('noopener noreferrer');+ });++ it.each([+ ['name', 'tagName'], ['id', 'tagName'],+ ['name', 'getAttribute'], ['id', 'getAttribute'],+ ['name', 'setAttribute'], ['id', 'setAttribute'],+ ])('a raw-HTML <form> whose control %s=%j shadows the built-in still gains rel', (attr, prop) => {+ const form = document.createElement('form');+ form.setAttribute('action', 'https://evil.test');+ form.setAttribute('target', 'popup');+ const control = document.createElement('input');+ control.setAttribute(attr, prop);+ const button = document.createElement('button');+ button.textContent = 'go';+ form.append(control, button);++ const el = parseOut(window.ui.renderMarkdown(form.outerHTML))+ .querySelector('form');++ // The emulated override was live while the hook ran...+ expect(shadowedCount).toBe(1);+ // ...and the hook still set rel through Element.prototype.+ expect(el).not.toBeNull();+ expect(el.getAttribute('target')).toBe('popup');+ expect(el.getAttribute('rel')).toBe('noopener noreferrer');+ });++ it('an existing rel is merged: other tokens kept, opener dropped', () => {+ const anchor = parseOut(window.ui.renderMarkdown(+ '<a href="https://example.test" target="_blank" rel="nofollow ugc opener">r</a>'+ )).querySelector('a');+ const tokens = anchor.getAttribute('rel').split(/\s+/);+ expect(tokens).toEqual(+ expect.arrayContaining(['nofollow', 'ugc', 'noopener', 'noreferrer'])+ );+ expect(tokens).toHaveLength(4);+ expect(tokens).not.toContain('opener');+ });++ it('registration stays single across repeated renders', () => {+ for (let i = 0; i < 3; i++) {+ window.ui.renderMarkdown('# heading\n\n[a](https://x.test)');+ }+ expect(+ (registeredHooks.afterSanitizeAttributes || []).length+ ).toBe(1);+ });++ it('the marked-missing fallback escapes raw anchors into inert text', () => {+ globalThis.marked = undefined;+ const markdown =+ 'x <a href="https://example.test" target="_blank">raw</a>';+ const out = window.ui.renderMarkdown(markdown);+ const doc = new window.DOMParser().parseFromString(out, 'text/html');+ // No live anchor survives: the raw HTML is shown verbatim as text.+ expect(doc.querySelector('a')).toBeNull();+ expect(doc.querySelector('pre').textContent).toBe(markdown);+ });+});diff --git a/tests/js/security/xss-protection-late-dompurify.test.js b/tests/js/security/xss-protection-late-dompurify.test.jsnew file mode 100644index 0000000000..b76515683a--- /dev/null+++ b/tests/js/security/xss-protection-late-dompurify.test.js@@ -0,0 +1,383 @@+/**+ * Late-DOMPurify contracts for the tabnabbing hook.+ *+ * ``xss-protection.js`` registers an ``afterSanitizeAttributes`` hook that+ * forces ``rel="noopener noreferrer"`` on ``<a>`` (including SVG ``<a>``),+ * ``<area>`` and ``<form>`` elements whose target can open a new browsing+ * context. In the shipped base.html the app.js module (which binds+ * DOMPurify) executes before this deferred classic script, so the load-time+ * registration succeeds; the runtime suite pins that favorable order.+ *+ * These contracts pin the adverse order: the module loads with no DOMPurify+ * in scope and the sanitizer binds afterwards. Each sanitize entry point is+ * exercised on a freshly evaluated module as the FIRST sanitize call, so each+ * one must register the hook on its own rather than inherit a registration+ * made by an earlier test. The hook is also bound to the DOMPurify instance,+ * so a replaced instance must get it too. The hook reads and writes through+ * Element.prototype, so a <form> control that shadows a built-in on the+ * form instance cannot switch it off, and it merges into an existing rel+ * rather than replacing it.+ */++const EXPORTED_GLOBALS = [+ 'XSSProtection', 'escapeHtml', 'escapeHtmlAttribute', 'safeSetInnerHTML',+ 'safeCreateElement', 'safeSetTextContent', 'createSafeAlertElement',+ 'sanitizeUserInput', 'sanitizeHtml', 'safeUpdateButton',+ 'createSafeLoadingOverlay', 'safeSetStyles', 'showSafeAlert',+];++/**+ * Subset of DOMPurify's default ALLOWED_ATTR that these fixtures use. Like+ * the real default list it does NOT contain `target`, so a config without+ * ALLOWED_ATTR/ADD_ATTR naming `target` strips it, as production does.+ */+const DEFAULT_ALLOWED_ATTR = [+ 'href', 'title', 'class', 'id', 'rel', 'action', 'method', 'name',+ 'alt', 'shape', 'coords',+];++/**+ * Built-ins a descendant form control can shadow on its <form> instance.+ * Browsers expose a form's controls as named properties that override+ * same-named built-ins ([LegacyOverrideBuiltIns]); happy-dom does not, so+ * the stand-in below emulates it while the hooks run.+ */+const FORM_SHADOWABLE = ['tagName', 'getAttribute', 'setAttribute'];+const FORM_CONTROLS = 'input,button,select,textarea,fieldset,output,object';++/**+ * Run `fn` with `el`'s shadowable built-ins overridden, as a browser does+ * for a <form> holding a control named or id'd like one. Returns how many+ * properties were shadowed so a test can prove the emulation engaged.+ */+const withFormNamedProps = (el, fn) => {+ const shadowed = [];+ if (el.localName === 'form') {+ const controls = Array.from(el.querySelectorAll(FORM_CONTROLS));+ FORM_SHADOWABLE.forEach((prop) => {+ const control = controls.find((c) =>+ c.getAttribute('name') === prop || c.getAttribute('id') === prop+ );+ if (control) {+ Object.defineProperty(el, prop, {+ configurable: true,+ get: () => control,+ });+ shadowed.push(prop);+ }+ });+ }+ try {+ fn();+ } finally {+ shadowed.forEach((prop) => delete el[prop]);+ }+ return shadowed.length;+};++/**+ * Minimal DOMPurify stand-in that honours the parts of the config the+ * sanitize paths under test rely on: ALLOWED_TAGS / FORBID_TAGS (dropped+ * elements keep their content), ALLOWED_ATTR (else the default list above)+ * plus ADD_ATTR, and RETURN_DOM_FRAGMENT. Like DOMPurify it runs the+ * afterSanitizeAttributes hooks on every surviving element after its+ * attributes were filtered, with a browser form's named-property+ * shadowing emulated (`shadowedCount` counts the shadowed properties).+ */+const makePurifier = () => {+ const hooks = {};+ const stats = { shadowedCount: 0 };+ const lower = (list) => (list || []).map((x) => String(x).toLowerCase());+ const purifier = {+ addHook: (name, cb) => {+ hooks[name] ||= [];+ hooks[name].push(cb);+ },+ sanitize: (dirty, config = {}) => {+ const template = document.createElement('template');+ // eslint-disable-next-line no-unsanitized/property -- test harness stand-in: the input is this file's own fixture+ template.innerHTML = String(dirty);+ const allowedTags = config.ALLOWED_TAGS+ ? new Set(lower(config.ALLOWED_TAGS))+ : null;+ const forbiddenTags = new Set(lower(config.FORBID_TAGS));+ const allowedAttr = new Set([+ ...lower(config.ALLOWED_ATTR || DEFAULT_ALLOWED_ATTR),+ ...lower(config.ADD_ATTR),+ ]);+ Array.from(template.content.querySelectorAll('*')).forEach((el) => {+ const name = String(el.localName).toLowerCase();+ if ((allowedTags && !allowedTags.has(name)) ||+ forbiddenTags.has(name)) {+ el.replaceWith(...Array.from(el.childNodes));+ return;+ }+ Array.from(el.attributes).forEach((attr) => {+ if (!allowedAttr.has(attr.name.toLowerCase())) {+ el.removeAttribute(attr.name);+ }+ });+ stats.shadowedCount += withFormNamedProps(el, () => {+ (hooks.afterSanitizeAttributes || []).forEach((cb) => cb(el));+ });+ });+ if (config.RETURN_DOM_FRAGMENT) {+ return template.content;+ }+ return template.innerHTML;+ },+ };+ return { purifier, hooks, stats };+};++const hookCount = (hooks) => (hooks.afterSanitizeAttributes || []).length;++const firstAnchor = (html) =>+ new window.DOMParser().parseFromString(html, 'text/html').querySelector('a');++const anchorHtmlWithTarget = (target) => {+ const a = document.createElement('a');+ a.setAttribute('href', 'https://example.test');+ a.setAttribute('target', target);+ a.textContent = 'x';+ return a.outerHTML;+};++// <area> and <form> also navigate via `target` and accept rel keywords.+const elementHtmlWithTarget = (tag, target) => {+ const el = document.createElement(tag);+ el.setAttribute(tag === 'form' ? 'action' : 'href', 'https://example.test');+ el.setAttribute('target', target);+ return el.outerHTML;+};++const firstElement = (html, tag) =>+ new window.DOMParser().parseFromString(html, 'text/html').querySelector(tag);++/**+ * Evaluate a fresh copy of xss-protection.js with NO DOMPurify in scope,+ * then bind a stand-in afterwards, as a late-binding page would.+ */+const loadThenLateBind = async () => {+ delete globalThis.DOMPurify;+ vi.resetModules();+ await import('@js/security/xss-protection.js');+ const late = makePurifier();+ // eslint-disable-next-line require-atomic-updates -- deliberate late binding of the deferred-module global+ globalThis.DOMPurify = late.purifier;+ return late;+};++describe('tabnabbing hook under late-bound DOMPurify', () => {+ afterEach(() => {+ delete globalThis.DOMPurify;+ EXPORTED_GLOBALS.forEach((name) => delete window[name]);+ });++ it('safeSetInnerHTML registers the hook on its first call', async () => {+ const { hooks } = await loadThenLateBind();+ expect(hookCount(hooks)).toBe(0);++ const el = document.createElement('div');+ window.safeSetInnerHTML(el, anchorHtmlWithTarget('_blank'), true);++ expect(hookCount(hooks)).toBe(1);+ expect(el.querySelector('a').getAttribute('rel')).toBe(+ 'noopener noreferrer'+ );+ });++ it('sanitizeHtml registers the hook on its first call', async () => {+ const { hooks } = await loadThenLateBind();+ expect(hookCount(hooks)).toBe(0);++ const out = window.sanitizeHtml(anchorHtmlWithTarget('_blank'));++ expect(hookCount(hooks)).toBe(1);+ expect(firstAnchor(out).getAttribute('rel')).toBe(+ 'noopener noreferrer'+ );+ });++ it('safeCreateElement registers the hook on its first call', async () => {+ const { hooks } = await loadThenLateBind();+ expect(hookCount(hooks)).toBe(0);++ // Its config (ALLOWED_TAGS only) keeps DOMPurify's default attribute+ // list, which has no `target`, so production strips the target and+ // the hook has nothing to act on; only the registration is pinned.+ const anchor = window.safeCreateElement('a', 'x', {+ href: 'https://example.test',+ });++ expect(hookCount(hooks)).toBe(1);+ expect(anchor.tagName).toBe('A');+ });++ it('the exported ensure registers without any sanitize call', async () => {+ const { hooks } = await loadThenLateBind();+ window.XSSProtection.ensureTabnabbingHook();+ expect(hookCount(hooks)).toBe(1);+ });++ it('registration is idempotent across sanitize calls', async () => {+ const { hooks } = await loadThenLateBind();+ for (let i = 0; i < 3; i++) {+ window.sanitizeHtml('<p>again</p>');+ }+ window.XSSProtection.ensureTabnabbingHook();+ expect(hookCount(hooks)).toBe(1);+ });++ it('a replaced DOMPurify instance gets the hook too', async () => {+ const first = await loadThenLateBind();+ window.sanitizeHtml('<p>warm</p>');+ expect(hookCount(first.hooks)).toBe(1);++ const second = makePurifier();+ globalThis.DOMPurify = second.purifier;+ const out = window.sanitizeHtml(anchorHtmlWithTarget('_blank'));+ expect(hookCount(second.hooks)).toBe(1);+ expect(firstAnchor(out).getAttribute('rel')).toBe(+ 'noopener noreferrer'+ );++ // Switching back must not register a duplicate on the first one.+ globalThis.DOMPurify = first.purifier;+ window.sanitizeHtml('<p>again</p>');+ expect(hookCount(first.hooks)).toBe(1);+ });++ it('a DOMPurify without addHook is tolerated and warned about once', async () => {+ delete globalThis.DOMPurify;+ vi.resetModules();+ await import('@js/security/xss-protection.js');+ const warn = vi.spyOn(globalThis.SafeLogger, 'warn');+ try {+ globalThis.DOMPurify = { sanitize: (dirty) => String(dirty) };++ expect(() => window.sanitizeHtml('<p>x</p>')).not.toThrow();+ window.sanitizeHtml('<p>y</p>');+ window.XSSProtection.ensureTabnabbingHook();++ const hookWarnings = warn.mock.calls.filter((args) =>+ String(args[0]).includes('addHook')+ );+ expect(hookWarnings).toHaveLength(1);+ } finally {+ warn.mockRestore();+ }+ });++ it('a SafeLogger without a warn function does not break sanitizing', async () => {+ delete globalThis.DOMPurify;+ vi.resetModules();+ await import('@js/security/xss-protection.js');+ const savedLogger = globalThis.SafeLogger;+ try {+ globalThis.SafeLogger = {};+ globalThis.DOMPurify = { sanitize: (dirty) => String(dirty) };+ expect(() => window.sanitizeHtml('<p>x</p>')).not.toThrow();+ } finally {+ globalThis.SafeLogger = savedLogger;+ }+ });++ it.each([+ '_blank', '_BLANK', ' _blank ', 'popup', '_new',+ // Padded keywords are not the keyword: " _top " names a new window.+ ' _top ', '_self ',+ ])('target %j can open a new context and gains rel', async (target) => {+ await loadThenLateBind();+ const out = window.sanitizeHtml(anchorHtmlWithTarget(target));+ expect(firstAnchor(out).getAttribute('rel')).toBe(+ 'noopener noreferrer'+ );+ });++ it.each([+ '_self', '_SELF', '_parent', '_top', '',+ ])('target %j stays in the same context and is left alone', async (target) => {+ await loadThenLateBind();+ const out = window.sanitizeHtml(anchorHtmlWithTarget(target));+ expect(firstAnchor(out).hasAttribute('rel')).toBe(false);+ });++ it.each([+ ['area', '_blank'], ['area', 'popup'],+ ['form', '_blank'], ['form', 'popup'],+ ])('<%s target=%j> can open a new context and gains rel', async (tag, target) => {+ await loadThenLateBind();+ const out = window.sanitizeHtml(elementHtmlWithTarget(tag, target), {+ ALLOWED_TAGS: [tag],+ FORBID_TAGS: [],+ });+ const el = firstElement(out, tag);+ expect(el).not.toBeNull();+ expect(el.getAttribute('rel')).toBe('noopener noreferrer');+ });++ it.each(['area', 'form'])('<%s target=_self> is left alone', async (tag) => {+ await loadThenLateBind();+ const out = window.sanitizeHtml(elementHtmlWithTarget(tag, '_self'), {+ ALLOWED_TAGS: [tag],+ FORBID_TAGS: [],+ });+ expect(firstElement(out, tag).hasAttribute('rel')).toBe(false);+ });++ it('an SVG <a target=_blank> (lowercase tagName) gains rel', async () => {+ await loadThenLateBind();+ const out = window.sanitizeHtml(+ '<svg><a href="https://example.test" target="_blank">x</a></svg>',+ { ALLOWED_TAGS: ['svg', 'a'] }+ );+ const anchor = firstElement(out, 'svg a');+ expect(anchor).not.toBeNull();+ expect(anchor.tagName).toBe('a');+ expect(anchor.getAttribute('rel')).toBe('noopener noreferrer');+ });++ it.each([+ ['name', 'tagName'], ['id', 'tagName'],+ ['name', 'getAttribute'], ['id', 'getAttribute'],+ ['name', 'setAttribute'], ['id', 'setAttribute'],+ ])('a <form> whose control %s=%j shadows the built-in still gains rel', async (attr, prop) => {+ const { stats } = await loadThenLateBind();+ const form = document.createElement('form');+ form.setAttribute('action', 'https://example.test');+ form.setAttribute('target', 'popup');+ const control = document.createElement('input');+ control.setAttribute(attr, prop);+ form.appendChild(control);++ const out = window.sanitizeHtml(form.outerHTML, {+ ALLOWED_TAGS: ['form', 'input'],+ ALLOWED_ATTR: ['action', 'target', 'rel', 'name', 'id'],+ FORBID_TAGS: [],+ });++ // The emulated override was live while the hook ran...+ expect(stats.shadowedCount).toBe(1);+ // ...and the hook read and wrote through Element.prototype anyway.+ const el = firstElement(out, 'form');+ expect(el).not.toBeNull();+ expect(el.getAttribute('rel')).toBe('noopener noreferrer');+ });++ it('existing rel tokens are kept, opener is dropped, forced ones added once', async () => {+ await loadThenLateBind();+ const a = document.createElement('a');+ a.setAttribute('href', 'https://example.test');+ a.setAttribute('target', '_blank');+ a.setAttribute('rel', 'nofollow UGC opener NoOpener nofollow');+ a.textContent = 'x';++ const out = window.sanitizeHtml(a.outerHTML);+ const rel = firstAnchor(out).getAttribute('rel');+ const tokens = rel.split(/\s+/);++ expect(tokens).toEqual(['nofollow', 'UGC', 'noopener', 'noreferrer']);+ expect(tokens.map((t) => t.toLowerCase())).not.toContain('opener');+ });+});diff --git a/tests/security/test_client_side_xss_sinks.py b/tests/security/test_client_side_xss_sinks.pyindex 78c4e42703..838922001e 100644--- a/tests/security/test_client_side_xss_sinks.py+++ b/tests/security/test_client_side_xss_sinks.py@@ -875,30 +875,98 @@ def test_no_cross_origin_blank_anchor_ships_without_noopener():assert offenders == []-def test_dompurify_tabnabbing_hook_registration_is_load_order_bound():- """The hook that enforces ``rel`` on sanitised links is conditional.-- ``xss-protection.js`` registers its ``afterSanitizeAttributes`` hook- inside ``if (hasDOMPurify())`` evaluated once at script-evaluation- time — while the file's own comment on ``hasDOMPurify`` says the- check "must be a function since Vite modules are deferred and load- after this script". Both cannot be true: if the comment is right the- hook never registers. Nothing else in the tree depends on it today- (report links get their ``rel`` from the ``marked`` renderer- wrapper, and snippet links carry no ``target``), so this pins the- contradiction rather than asserting an outcome no static read can- settle.+def test_dompurify_tabnabbing_hook_registration_is_lazy_and_idempotent():+ """Static shape of the tabnabbing hook registration in xss-protection.js.++ The hook must not be registered only inside a one-shot load-time+ ``if (hasDOMPurify()) { DOMPurify.addHook(...) }`` guard: a DOMPurify+ bound after the script loads would then never get it. Instead a+ lazy ensure, idempotent per DOMPurify instance, runs at load time and+ before each of the module's own sanitize calls, and is exported for+ other sanitizing callers (renderMarkdown in services/ui.js). Every+ sanitize path whose config lets ``target`` through (SANITIZE_CONFIG in+ xss-protection.js, renderMarkdown's ``ADD_ATTR``) ensures the hook+ first, so correctness does not depend on the load-time call or on+ script order. The remaining direct ``DOMPurify.sanitize`` callers+ (safeSetHTML in ui.js, news.js, pdf.js, semantic_search.js) keep+ DOMPurify's default attribute list or an explicit one, neither of which+ contains ``target``, so no link they emit can open a new browsing+ context and they need no hook. Behaviour is pinned by+ tests/js/security/xss-protection-late-dompurify.test.js and+ render-markdown-tabnabbing.test.js; this only guards the static shape,+ including that the hook reads and writes the node only through the+ captured Element.prototype accessors (a <form> control can shadow the+ instance's own) and that renderMarkdown calls the ensure before it+ sanitizes with ``target`` in ``ADD_ATTR``. Comments are stripped first+ so a commented-out call cannot satisfy it."""- text = (STATIC_JS / "security" / "xss-protection.js").read_text(- encoding="utf-8"+ text = _strip_js_comments(+ (STATIC_JS / "security" / "xss-protection.js").read_text(+ encoding="utf-8"+ )+ )+ # No load-order-bound registration, however it is formatted.+ assert not re.search(+ r"if\s*\(\s*hasDOMPurify\s*\(\s*\)\s*\)\s*\{\s*DOMPurify\s*\.\s*addHook\s*\(",+ text,+ )+ # A lazy ensure exists, is called at load time and before sanitizing,+ # and is exported for other callers.+ assert re.search(r"function\s+_ensureTabnabbingHook\s*\(", text)+ assert len(re.findall(r"\b_ensureTabnabbingHook\s*\(\s*\)\s*;", text)) >= 4+ assert re.search(+ r"ensureTabnabbingHook\s*:\s*_ensureTabnabbingHook\b", text+ )+ # The hook never trusts a property looked up on the node: a <form>+ # control named or id'd like a built-in shadows it on the instance.+ hook_start = text.index("addHook('afterSanitizeAttributes'")+ hook = text[hook_start : text.index("_hookedPurifiers.add(", hook_start)]+ assert not re.search(r"\bnode\s*(\.|\[)", hook), hook+ assert re.search(+ r"\.setAttr\.call\(\s*node\s*,\s*['\"]rel['\"]\s*,\s*_mergeRel\(",+ hook,+ )+ assert re.search(r"\.getTagName\.call\(\s*node\s*\)", hook)+ assert re.search(+ r"\.getAttr\.call\(\s*node\s*,\s*['\"]target['\"]\s*\)", hook+ )+ ui = _strip_js_comments(+ (STATIC_JS / "services" / "ui.js").read_text(encoding="utf-8")+ )+ body = _render_markdown_body(ui)+ # renderMarkdown's config is the only one outside xss-protection.js+ # that keeps ``target``. Removing ``target`` from it is a deliberate+ # change that must update this test, so it fails rather than skips.+ sanitize = re.search(r"DOMPurify\.sanitize\s*\(", body)+ assert sanitize, "renderMarkdown no longer calls DOMPurify.sanitize"+ add_attr = re.search(r"ADD_ATTR\s*:\s*\[([^\]]*)\]", body[sanitize.end() :])+ assert add_attr, "renderMarkdown's sanitize config lost its ADD_ATTR"+ assert re.search(r"['\"]target['\"]", add_attr.group(1))+ # The ensure is an actual call, in renderMarkdown, before that sanitize.+ ensure = re.search(+ r"window\.XSSProtection\s*\?\.\s*ensureTabnabbingHook\s*\?\.\s*\(\s*\)\s*;",+ body,)- assert "if (hasDOMPurify()) {\n DOMPurify.addHook(" in text- assert "Must be a function since Vite modules are deferred" in text- assert "node.setAttribute('rel', 'noopener noreferrer');" in text- # The bundle that defines DOMPurify is a module; the guard is not.- base = (TEMPLATES / "base.html").read_text(encoding="utf-8")- assert "{{ vite_asset('js/app.js') }}" in base- assert 'defer src="/static/js/security/xss-protection.js"' in base+ assert ensure, "renderMarkdown does not call ensureTabnabbingHook"+ assert ensure.end() <= sanitize.start()+++def _strip_js_comments(text: str) -> str:+ """Drop ``/* ... */`` blocks and whole-line ``//`` comments.++ Naive: it does not track string or regex literals, so it only removes+ comments that start a line (after indentation) and block comments.+ That is enough to stop a commented-out call satisfying a pin.+ """+ text = re.sub(r"/\*.*?\*/", "", text, flags=re.DOTALL)+ return re.sub(r"(?m)^[ \t]*//.*$", "", text)+++def _render_markdown_body(text: str) -> str:+ """The body of ``renderMarkdown``, up to its column-0 closing brace."""+ start = text.index("function renderMarkdown(")+ end = text.index("\n}", start)+ return text[start:end]# ---------------------------------------------------------------------diff --git a/tests/web/test_js_fetch_parity.py b/tests/web/test_js_fetch_parity.pyindex 5d3d786df0..4959eeea6d 100644--- a/tests/web/test_js_fetch_parity.py+++ b/tests/web/test_js_fetch_parity.py@@ -973,7 +973,7 @@ LIVE_CASES = (# That is a separate defect (unguarded lookup) and out of scope here;# what matters for *this* test is that 500 means the body passed# validation and the handler ran.- js_ref="pages/news.js:1425",+ js_ref="pages/news.js:1426",method="POST",url=f"/news/api/feedback/{NOPE_UUID}",good={"vote": "up"},