fix(frontend): keep target="_blank" on sanitized markdown links (#3818)

* md预览链接 a 增加target

* fix(security): keep target on links in document preview sanitizer

documentPreviewDomPurifyConfig spread the base config and then replaced
ADD_ATTR with the image attributes only, dropping the 'target' entry
this PR adds, so links in document previews still lost target="_blank".
Extend the base ADD_ATTR instead, and lock both configs with tests.

* fix(security): drop author-supplied target before sanitizing links

ADD_ATTR now allows target globally so the hook-added target="_blank"
survives, but that also kept author values on elements the hook never
rewrites (SVG <a>, <area>, protocol-relative / uppercase / leading-space
hrefs in sanitizeHTML and document preview), e.g. target="_blank"
rel="opener" or target="_top". Strip target in beforeSanitizeElements
so only the hook's _blank, always paired with rel="noopener noreferrer",
can appear.

---------

Co-authored-by: wizardchen <wizardchen@tencent.com>
main
rill 2026-10-08 14:02:22 +08:00 committed by GitHub
parent 11aa00f85f
commit 9a2cd20063
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 71 additions and 3 deletions

View File

@ -2,6 +2,7 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import {
domPurifyAllowedUriRegexp,
domPurifySecurityHooks,
markdownDomPurifyConfig,
markdownDomPurifySecurityHooks,
} from './markdownDomPurify.ts';
@ -17,6 +18,50 @@ test('ALLOWED_URI_REGEXP allows s3:// and rejects javascript:', () => {
assert.doesNotMatch('javascript:alert(1)', re);
});
test('markdownDomPurifyConfig keeps hook-added target attribute', () => {
// USE_PROFILES replaces ALLOWED_ATTR, so target must come from ADD_ATTR.
assert.ok(markdownDomPurifyConfig.ADD_ATTR.includes('target'));
});
test('author-supplied target never survives; only the hook adds _blank with noopener', () => {
// ADD_ATTR allows target globally, so the before hook must drop any
// author value. SVG <a> (lowercase tagName), <area> and non-"http" hrefs
// never reach the after hook's rewrite and would otherwise keep it.
const cases = [
{ tagName: 'a', href: 'https://evil.example' },
{ tagName: 'AREA', href: 'https://evil.example' },
{ tagName: 'A', href: '//evil.example' },
{ tagName: 'A', href: 'HTTPS://evil.example' },
{ tagName: 'A', href: ' https://evil.example' },
{ tagName: 'A', href: '/relative' },
{ tagName: 'DIV', href: null },
];
const hookSets = {
base: domPurifySecurityHooks,
markdown: markdownDomPurifySecurityHooks,
};
for (const [name, hooks] of Object.entries(hookSets)) {
for (const { tagName, href } of cases) {
const attributes = new Map([['target', '_top'], ['rel', 'opener']]);
if (href !== null) attributes.set('href', href);
const el = {
tagName,
getAttribute: (n) => attributes.get(n) ?? null,
setAttribute: (n, v) => attributes.set(n, v),
hasAttribute: (n) => attributes.has(n),
removeAttribute: (n) => attributes.delete(n),
};
hooks.beforeSanitizeElements(el);
hooks.afterSanitizeElements(el);
const label = `${name} ${tagName} ${JSON.stringify(href)}`;
if (attributes.has('target')) {
assert.equal(attributes.get('target'), '_blank', label);
assert.equal(attributes.get('rel'), 'noopener noreferrer', label);
}
}
}
});
test('chat markdown links always open in a new tab', () => {
const attributes = new Map([['href', '/platform/knowledge-bases/kb-1']]);
const anchor = {

View File

@ -32,6 +32,12 @@ export const domPurifySecurityHooks = {
element.removeAttribute(attr);
}
});
// target is allowed only so the afterSanitizeElements hook can add
// target="_blank" together with rel="noopener noreferrer"; never keep an
// author-supplied value (SVG <a>, <area>, non-http hrefs skip the hook).
if (element.hasAttribute('target')) {
element.removeAttribute('target');
}
},
afterSanitizeElements: (currentNode: Node) => {
if (!('tagName' in currentNode) || !('getAttribute' in currentNode)) return;
@ -102,5 +108,9 @@ export const markdownDomPurifyConfig = {
'mathvariant', 'encoding', 'aria-hidden',
],
USE_PROFILES: { html: true, svg: true, mathMl: true },
// USE_PROFILES 会整体替换 ALLOWED_ATTR,而 html profile 默认不含 target,
// 导致 afterSanitizeElements hook 加上的 target="_blank" 在随后的
// _sanitizeAttributes 中被剥离。用 ADD_ATTR 在 profile 之上追加该属性。
ADD_ATTR: ['target'],
...domPurifySecurityOptions,
};

View File

@ -1,7 +1,7 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { protectProviderImageSrcInHTML } from './security.ts'
import { documentPreviewDomPurifyConfig, protectProviderImageSrcInHTML } from './security.ts'
test('protectProviderImageSrcInHTML uses a placeholder src for provider images', () => {
const html = '<p><img alt="preview" src="local://10000/exports/a.jpg"></p>'
@ -36,3 +36,11 @@ test('protectProviderImageSrcInHTML uses a placeholder src for resource referenc
/data-protected-src="resource:\/\/AbCdEfGhIjKlMnOpQrStUv"/,
)
})
test('document preview sanitizer keeps target on links alongside image attributes', () => {
// USE_PROFILES replaces ALLOWED_ATTR, so target must come from ADD_ATTR or
// the hook-added target="_blank" is stripped again.
for (const attr of ['target', 'loading', 'decoding', 'fetchpriority']) {
assert.ok(documentPreviewDomPurifyConfig.ADD_ATTR.includes(attr), attr)
}
})

View File

@ -93,6 +93,10 @@ const DOMPurifyConfig = {
'mathvariant', 'encoding', 'aria-hidden'
],
USE_PROFILES: { html: true, svg: true, mathMl: true },
// USE_PROFILES 会整体替换 ALLOWED_ATTR,而 html profile 默认不含 target,
// 导致 afterSanitizeElements hook 加上的 target="_blank" 在随后的
// _sanitizeAttributes 中被剥离。用 ADD_ATTR 在 profile 之上追加该属性。
ADD_ATTR: ['target'],
...domPurifySecurityOptions,
};
@ -129,9 +133,10 @@ export function applyDocumentPreviewImageAttributes(currentNode: Node): void {
element.setAttribute('fetchpriority', 'low');
}
const documentPreviewDomPurifyConfig = {
export const documentPreviewDomPurifyConfig = {
...DOMPurifyConfig,
ADD_ATTR: [...DOCUMENT_PREVIEW_IMAGE_ATTRS],
// 在基础 ADD_ATTR 上追加,而不是覆盖,否则链接的 target="_blank" 又会被剥掉。
ADD_ATTR: [...DOMPurifyConfig.ADD_ATTR, ...DOCUMENT_PREVIEW_IMAGE_ATTRS],
};
const documentPreviewSecurityHooks: SecurityHooks = {