From bdd459b071cbba56992108b96cb4038662115155 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Tue, 14 Jul 2026 18:13:09 +0800 Subject: [PATCH] fix(frontend): open chat reference links in new tabs Prevent in-chat navigation from replacing the active conversation by opening knowledge-base and citation links in a new tab with noopener/noreferrer, and apply the same policy to sanitized markdown links. --- .../src/components/ChatReferencesDrawer.vue | 19 +++++--- frontend/src/utils/markdownDomPurify.test.mjs | 17 +++++++ frontend/src/utils/markdownDomPurify.ts | 45 +++++++++++++------ frontend/src/utils/security.ts | 36 +++++++++++++-- .../chat/components/AgentStreamDisplay.vue | 32 ++++++++----- .../chat/components/chatLinksNewTab.test.mjs | 30 +++++++++++++ .../src/views/chat/components/docInfo.vue | 18 +++++--- 7 files changed, 155 insertions(+), 42 deletions(-) create mode 100644 frontend/src/views/chat/components/chatLinksNewTab.test.mjs diff --git a/frontend/src/components/ChatReferencesDrawer.vue b/frontend/src/components/ChatReferencesDrawer.vue index b2f55dbf..82b3c39e 100644 --- a/frontend/src/components/ChatReferencesDrawer.vue +++ b/frontend/src/components/ChatReferencesDrawer.vue @@ -106,10 +106,16 @@
- +
@@ -250,14 +256,14 @@ function toggleDocumentSnippet(item: ReferenceListItem, event?: MouseEvent) { expandedKeys.add(item.key) } -function navigateToDocument(item: ReferenceListItem) { - if (!item.knowledgeBaseId) return +function getDocumentHref(item: ReferenceListItem) { + if (!item.knowledgeBaseId) return '' const query: Record = {} if (item.knowledgeId) query.knowledge_id = item.knowledgeId - router.push({ + return router.resolve({ path: `/platform/knowledge-bases/${item.knowledgeBaseId}`, query, - }) + }).href } async function scrollToHighlight() { @@ -540,6 +546,7 @@ watch(visible, (open) => { gap: 4px; cursor: pointer; padding: 0; + text-decoration: none; &:hover { color: var(--td-text-color-primary); diff --git a/frontend/src/utils/markdownDomPurify.test.mjs b/frontend/src/utils/markdownDomPurify.test.mjs index 5b3c23e5..5eebc4b5 100644 --- a/frontend/src/utils/markdownDomPurify.test.mjs +++ b/frontend/src/utils/markdownDomPurify.test.mjs @@ -3,6 +3,7 @@ import test from 'node:test'; import { domPurifyAllowedUriRegexp, markdownDomPurifyConfig, + markdownDomPurifySecurityHooks, } from './markdownDomPurify.ts'; test('markdownDomPurifyConfig FORBID_TAGS includes script', () => { @@ -15,3 +16,19 @@ test('ALLOWED_URI_REGEXP allows s3:// and rejects javascript:', () => { assert.match('s3://bucket/key', re); assert.doesNotMatch('javascript:alert(1)', re); }); + +test('chat markdown links always open in a new tab', () => { + const attributes = new Map([['href', '/platform/knowledge-bases/kb-1']]); + const anchor = { + tagName: 'A', + getAttribute: (name) => attributes.get(name) ?? null, + setAttribute: (name, value) => attributes.set(name, value), + hasAttribute: (name) => attributes.has(name), + removeAttribute: (name) => attributes.delete(name), + }; + + markdownDomPurifySecurityHooks.afterSanitizeElements(anchor); + + assert.equal(attributes.get('target'), '_blank'); + assert.equal(attributes.get('rel'), 'noopener noreferrer'); +}); diff --git a/frontend/src/utils/markdownDomPurify.ts b/frontend/src/utils/markdownDomPurify.ts index 078d71c0..80e3be9a 100644 --- a/frontend/src/utils/markdownDomPurify.ts +++ b/frontend/src/utils/markdownDomPurify.ts @@ -20,27 +20,45 @@ export const domPurifySecurityOptions = { /** Shared DOMPurify hooks: strip scripts/event attrs; noopener links; alt on images. */ export const domPurifySecurityHooks = { - beforeSanitizeElements: (currentNode: Element) => { - if (currentNode.tagName === 'SCRIPT') { - currentNode.remove(); - return null; + beforeSanitizeElements: (currentNode: Node) => { + if (!('tagName' in currentNode) || !('hasAttribute' in currentNode)) return; + const element = currentNode as Element; + if (element.tagName === 'SCRIPT') { + element.remove(); + return; } domPurifyForbidAttr.forEach((attr) => { - if (currentNode.hasAttribute(attr)) { - currentNode.removeAttribute(attr); + if (element.hasAttribute(attr)) { + element.removeAttribute(attr); } }); }, - afterSanitizeElements: (currentNode: Element) => { - if (currentNode.tagName === 'A') { - const href = currentNode.getAttribute('href'); + afterSanitizeElements: (currentNode: Node) => { + if (!('tagName' in currentNode) || !('getAttribute' in currentNode)) return; + const element = currentNode as Element; + if (element.tagName === 'A') { + const href = element.getAttribute('href'); if (href && href.startsWith('http')) { - currentNode.setAttribute('rel', 'noopener noreferrer'); - currentNode.setAttribute('target', '_blank'); + element.setAttribute('rel', 'noopener noreferrer'); + element.setAttribute('target', '_blank'); } } - if (currentNode.tagName === 'IMG' && !currentNode.getAttribute('alt')) { - currentNode.setAttribute('alt', ''); + if (element.tagName === 'IMG' && !element.getAttribute('alt')) { + element.setAttribute('alt', ''); + } + }, +}; + +/** Chat markdown links must never replace the conversation page. */ +export const markdownDomPurifySecurityHooks = { + ...domPurifySecurityHooks, + afterSanitizeElements: (currentNode: Node) => { + domPurifySecurityHooks.afterSanitizeElements(currentNode); + if (!('tagName' in currentNode) || !('getAttribute' in currentNode)) return; + const element = currentNode as Element; + if (element.tagName === 'A' && element.getAttribute('href')) { + element.setAttribute('rel', 'noopener noreferrer'); + element.setAttribute('target', '_blank'); } }, }; @@ -79,5 +97,4 @@ export const markdownDomPurifyConfig = { ], USE_PROFILES: { html: true, svg: true, mathMl: true }, ...domPurifySecurityOptions, - HOOKS: domPurifySecurityHooks, }; diff --git a/frontend/src/utils/security.ts b/frontend/src/utils/security.ts index 6e548c7b..d26d6c3b 100644 --- a/frontend/src/utils/security.ts +++ b/frontend/src/utils/security.ts @@ -3,16 +3,37 @@ */ import DOMPurify from 'dompurify'; -import type { Config } from 'dompurify'; +import type { Config, NodeHook } from 'dompurify'; import { domPurifySecurityHooks, domPurifySecurityOptions, markdownDomPurifyConfig, + markdownDomPurifySecurityHooks, } from './markdownDomPurify.ts'; const PROVIDER_IMAGE_PLACEHOLDER = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=='; const PROVIDER_FILE_SCHEME_RE = /^(local|minio|cos|tos|s3|oss|ks3|obs):\/\/\S+$/i; +type SecurityHooks = { + beforeSanitizeElements: NodeHook; + afterSanitizeElements: NodeHook; +}; + +function sanitizeWithSecurityHooks( + html: string, + config: Config, + hooks: SecurityHooks, +): string { + DOMPurify.addHook('beforeSanitizeElements', hooks.beforeSanitizeElements); + DOMPurify.addHook('afterSanitizeElements', hooks.afterSanitizeElements); + try { + return DOMPurify.sanitize(html, config); + } finally { + DOMPurify.removeHook('afterSanitizeElements', hooks.afterSanitizeElements); + DOMPurify.removeHook('beforeSanitizeElements', hooks.beforeSanitizeElements); + } +} + // 配置 DOMPurify 的安全策略 const DOMPurifyConfig = { // 允许的标签 @@ -54,7 +75,6 @@ const DOMPurifyConfig = { ], USE_PROFILES: { html: true, svg: true, mathMl: true }, ...domPurifySecurityOptions, - HOOKS: domPurifySecurityHooks, }; /** @@ -69,7 +89,11 @@ export function sanitizeHTML(html: string): string { try { const preparedHTML = protectProviderImageSrcInHTML(html); - return DOMPurify.sanitize(preparedHTML, DOMPurifyConfig as unknown as Config); + return sanitizeWithSecurityHooks( + preparedHTML, + DOMPurifyConfig as unknown as Config, + domPurifySecurityHooks, + ); } catch (error) { console.error('HTML sanitization failed:', error); // 如果清理失败,返回转义的纯文本 @@ -85,7 +109,11 @@ export function sanitizeMarkdownHTML(html: string): string { try { const preparedHTML = protectProviderImageSrcInHTML(html); - return DOMPurify.sanitize(preparedHTML, markdownDomPurifyConfig as unknown as Config); + return sanitizeWithSecurityHooks( + preparedHTML, + markdownDomPurifyConfig as unknown as Config, + markdownDomPurifySecurityHooks, + ); } catch (error) { console.error('Markdown HTML sanitization failed:', error); return escapeHTML(html); diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vue index da46e6ef..d5f33c49 100644 --- a/frontend/src/views/chat/components/AgentStreamDisplay.vue +++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue @@ -442,7 +442,13 @@ || 1 }) }} - + {{ $t('knowledgeEditor.wikiBrowser.viewInGraph') }} @@ -698,15 +704,17 @@ const openWikiDrawer = async (kbId: string, slug: string) => { } }; -const navigateToWikiGraph = () => { - if (currentWikiKbId.value && wikiDrawerPage.value?.slug) { - wikiDrawerVisible.value = false; - try { - router.push(`/platform/knowledge-bases/${currentWikiKbId.value}?tab=graph&slug=${encodeURIComponent(wikiDrawerPage.value.slug)}`); - } catch (error) { - console.error('Failed to navigate to wiki graph:', error); - } - } +const wikiGraphHref = computed(() => { + if (!currentWikiKbId.value || !wikiDrawerPage.value?.slug) return ''; + return router.resolve({ + path: `/platform/knowledge-bases/${currentWikiKbId.value}`, + query: { tab: 'graph', slug: wikiDrawerPage.value.slug }, + }).href; +}); + +const openRouteInNewTab = (path: string) => { + const href = router.resolve(path).href; + window.open(href, '_blank', 'noopener,noreferrer'); }; const handleWikiDrawerClick = (e: MouseEvent) => { @@ -1892,7 +1900,7 @@ const onRootClick = (e: Event) => { } if (kbId) { try { - router.push(`/platform/knowledge-bases/${kbId}`); + openRouteInNewTab(`/platform/knowledge-bases/${kbId}`); } catch (error) { console.error('Failed to navigate to knowledge base:', error); } @@ -1964,7 +1972,7 @@ const onRootKeydown = (e: KeyboardEvent) => { } if (kbId) { try { - router.push(`/platform/knowledge-bases/${kbId}`); + openRouteInNewTab(`/platform/knowledge-bases/${kbId}`); } catch (error) { console.error('Failed to navigate to knowledge base:', error); } diff --git a/frontend/src/views/chat/components/chatLinksNewTab.test.mjs b/frontend/src/views/chat/components/chatLinksNewTab.test.mjs new file mode 100644 index 00000000..8e6ff3ba --- /dev/null +++ b/frontend/src/views/chat/components/chatLinksNewTab.test.mjs @@ -0,0 +1,30 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import test from 'node:test' + +const referenceDrawer = readFileSync( + new URL('../../../components/ChatReferencesDrawer.vue', import.meta.url), + 'utf8', +) +const legacyReferences = readFileSync(new URL('./docInfo.vue', import.meta.url), 'utf8') +const agentStream = readFileSync(new URL('./AgentStreamDisplay.vue', import.meta.url), 'utf8') + +test('reference document links open in a new tab', () => { + assert.match( + referenceDrawer, + /:href="getDocumentHref\(item\)"[\s\S]*?target="_blank"[\s\S]*?rel="noopener noreferrer"/, + ) + assert.match( + legacyReferences, + /:href="getDocumentHref\(group\)"[\s\S]*?target="_blank"[\s\S]*?rel="noopener noreferrer"/, + ) +}) + +test('wiki drawer navigation and citation fallbacks open in a new tab', () => { + assert.match( + agentStream, + /:href="wikiGraphHref"[\s\S]*?target="_blank"[\s\S]*?rel="noopener noreferrer"/, + ) + assert.match(agentStream, /window\.open\(href, '_blank', 'noopener,noreferrer'\)/) + assert.doesNotMatch(agentStream, /router\.push\(/) +}) diff --git a/frontend/src/views/chat/components/docInfo.vue b/frontend/src/views/chat/components/docInfo.vue index d8fc8a8e..927afa7a 100644 --- a/frontend/src/views/chat/components/docInfo.vue +++ b/frontend/src/views/chat/components/docInfo.vue @@ -30,9 +30,14 @@ @@ -165,16 +170,16 @@ const truncateContent = (content, maxLen) => { return text.slice(0, maxLen) + '...'; }; -const navigateToDocument = (group) => { - if (!group.knowledgeBaseId) return; +const getDocumentHref = (group) => { + if (!group.knowledgeBaseId) return ''; const query = {}; if (group.knowledgeId) { query.knowledge_id = group.knowledgeId; } - router.push({ + return router.resolve({ path: `/platform/knowledge-bases/${group.knowledgeBaseId}`, query - }); + }).href; }; const getWebSearchUrl = (item) => { @@ -444,6 +449,7 @@ const getWebSearchDisplayText = (item) => { border-radius: 4px; color: var(--td-brand-color); cursor: pointer; + text-decoration: none; transition: all 0.15s ease; &:hover {