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.
This commit is contained in:
wizardchen
2026-07-14 18:13:09 +08:00
committed by lyingbug
parent ace84bc757
commit bdd459b071
7 changed files with 155 additions and 42 deletions
@@ -106,10 +106,16 @@
</component> </component>
<div v-if="item.kind === 'document'" class="reference-card__actions"> <div v-if="item.kind === 'document'" class="reference-card__actions">
<button v-if="item.knowledgeBaseId && !embeddedMode" type="button" class="reference-card__action" @click="navigateToDocument(item)"> <a
v-if="item.knowledgeBaseId && !embeddedMode"
class="reference-card__action"
:href="getDocumentHref(item)"
target="_blank"
rel="noopener noreferrer"
>
<t-icon name="jump" size="14px" /> <t-icon name="jump" size="14px" />
<span>{{ t('chat.navigateToDocument') }}</span> <span>{{ t('chat.navigateToDocument') }}</span>
</button> </a>
</div> </div>
</article> </article>
</section> </section>
@@ -250,14 +256,14 @@ function toggleDocumentSnippet(item: ReferenceListItem, event?: MouseEvent) {
expandedKeys.add(item.key) expandedKeys.add(item.key)
} }
function navigateToDocument(item: ReferenceListItem) { function getDocumentHref(item: ReferenceListItem) {
if (!item.knowledgeBaseId) return if (!item.knowledgeBaseId) return ''
const query: Record<string, string> = {} const query: Record<string, string> = {}
if (item.knowledgeId) query.knowledge_id = item.knowledgeId if (item.knowledgeId) query.knowledge_id = item.knowledgeId
router.push({ return router.resolve({
path: `/platform/knowledge-bases/${item.knowledgeBaseId}`, path: `/platform/knowledge-bases/${item.knowledgeBaseId}`,
query, query,
}) }).href
} }
async function scrollToHighlight() { async function scrollToHighlight() {
@@ -540,6 +546,7 @@ watch(visible, (open) => {
gap: 4px; gap: 4px;
cursor: pointer; cursor: pointer;
padding: 0; padding: 0;
text-decoration: none;
&:hover { &:hover {
color: var(--td-text-color-primary); color: var(--td-text-color-primary);
@@ -3,6 +3,7 @@ import test from 'node:test';
import { import {
domPurifyAllowedUriRegexp, domPurifyAllowedUriRegexp,
markdownDomPurifyConfig, markdownDomPurifyConfig,
markdownDomPurifySecurityHooks,
} from './markdownDomPurify.ts'; } from './markdownDomPurify.ts';
test('markdownDomPurifyConfig FORBID_TAGS includes script', () => { 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.match('s3://bucket/key', re);
assert.doesNotMatch('javascript:alert(1)', 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');
});
+31 -14
View File
@@ -20,27 +20,45 @@ export const domPurifySecurityOptions = {
/** Shared DOMPurify hooks: strip scripts/event attrs; noopener links; alt on images. */ /** Shared DOMPurify hooks: strip scripts/event attrs; noopener links; alt on images. */
export const domPurifySecurityHooks = { export const domPurifySecurityHooks = {
beforeSanitizeElements: (currentNode: Element) => { beforeSanitizeElements: (currentNode: Node) => {
if (currentNode.tagName === 'SCRIPT') { if (!('tagName' in currentNode) || !('hasAttribute' in currentNode)) return;
currentNode.remove(); const element = currentNode as Element;
return null; if (element.tagName === 'SCRIPT') {
element.remove();
return;
} }
domPurifyForbidAttr.forEach((attr) => { domPurifyForbidAttr.forEach((attr) => {
if (currentNode.hasAttribute(attr)) { if (element.hasAttribute(attr)) {
currentNode.removeAttribute(attr); element.removeAttribute(attr);
} }
}); });
}, },
afterSanitizeElements: (currentNode: Element) => { afterSanitizeElements: (currentNode: Node) => {
if (currentNode.tagName === 'A') { if (!('tagName' in currentNode) || !('getAttribute' in currentNode)) return;
const href = currentNode.getAttribute('href'); const element = currentNode as Element;
if (element.tagName === 'A') {
const href = element.getAttribute('href');
if (href && href.startsWith('http')) { if (href && href.startsWith('http')) {
currentNode.setAttribute('rel', 'noopener noreferrer'); element.setAttribute('rel', 'noopener noreferrer');
currentNode.setAttribute('target', '_blank'); element.setAttribute('target', '_blank');
} }
} }
if (currentNode.tagName === 'IMG' && !currentNode.getAttribute('alt')) { if (element.tagName === 'IMG' && !element.getAttribute('alt')) {
currentNode.setAttribute('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 }, USE_PROFILES: { html: true, svg: true, mathMl: true },
...domPurifySecurityOptions, ...domPurifySecurityOptions,
HOOKS: domPurifySecurityHooks,
}; };
+32 -4
View File
@@ -3,16 +3,37 @@
*/ */
import DOMPurify from 'dompurify'; import DOMPurify from 'dompurify';
import type { Config } from 'dompurify'; import type { Config, NodeHook } from 'dompurify';
import { import {
domPurifySecurityHooks, domPurifySecurityHooks,
domPurifySecurityOptions, domPurifySecurityOptions,
markdownDomPurifyConfig, markdownDomPurifyConfig,
markdownDomPurifySecurityHooks,
} from './markdownDomPurify.ts'; } from './markdownDomPurify.ts';
const PROVIDER_IMAGE_PLACEHOLDER = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=='; 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; 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 的安全策略 // 配置 DOMPurify 的安全策略
const DOMPurifyConfig = { const DOMPurifyConfig = {
// 允许的标签 // 允许的标签
@@ -54,7 +75,6 @@ const DOMPurifyConfig = {
], ],
USE_PROFILES: { html: true, svg: true, mathMl: true }, USE_PROFILES: { html: true, svg: true, mathMl: true },
...domPurifySecurityOptions, ...domPurifySecurityOptions,
HOOKS: domPurifySecurityHooks,
}; };
/** /**
@@ -69,7 +89,11 @@ export function sanitizeHTML(html: string): string {
try { try {
const preparedHTML = protectProviderImageSrcInHTML(html); const preparedHTML = protectProviderImageSrcInHTML(html);
return DOMPurify.sanitize(preparedHTML, DOMPurifyConfig as unknown as Config); return sanitizeWithSecurityHooks(
preparedHTML,
DOMPurifyConfig as unknown as Config,
domPurifySecurityHooks,
);
} catch (error) { } catch (error) {
console.error('HTML sanitization failed:', error); console.error('HTML sanitization failed:', error);
// 如果清理失败,返回转义的纯文本 // 如果清理失败,返回转义的纯文本
@@ -85,7 +109,11 @@ export function sanitizeMarkdownHTML(html: string): string {
try { try {
const preparedHTML = protectProviderImageSrcInHTML(html); const preparedHTML = protectProviderImageSrcInHTML(html);
return DOMPurify.sanitize(preparedHTML, markdownDomPurifyConfig as unknown as Config); return sanitizeWithSecurityHooks(
preparedHTML,
markdownDomPurifyConfig as unknown as Config,
markdownDomPurifySecurityHooks,
);
} catch (error) { } catch (error) {
console.error('Markdown HTML sanitization failed:', error); console.error('Markdown HTML sanitization failed:', error);
return escapeHTML(html); return escapeHTML(html);
@@ -442,7 +442,13 @@
|| 1 || 1
}) }}</span> }) }}</span>
</div> </div>
<t-link theme="primary" hover="color" @click="navigateToWikiGraph"> <t-link
theme="primary"
hover="color"
:href="wikiGraphHref"
target="_blank"
rel="noopener noreferrer"
>
<template #prefixIcon><t-icon name="chart-bubble" /></template> <template #prefixIcon><t-icon name="chart-bubble" /></template>
{{ $t('knowledgeEditor.wikiBrowser.viewInGraph') }} {{ $t('knowledgeEditor.wikiBrowser.viewInGraph') }}
</t-link> </t-link>
@@ -698,15 +704,17 @@ const openWikiDrawer = async (kbId: string, slug: string) => {
} }
}; };
const navigateToWikiGraph = () => { const wikiGraphHref = computed(() => {
if (currentWikiKbId.value && wikiDrawerPage.value?.slug) { if (!currentWikiKbId.value || !wikiDrawerPage.value?.slug) return '';
wikiDrawerVisible.value = false; return router.resolve({
try { path: `/platform/knowledge-bases/${currentWikiKbId.value}`,
router.push(`/platform/knowledge-bases/${currentWikiKbId.value}?tab=graph&slug=${encodeURIComponent(wikiDrawerPage.value.slug)}`); query: { tab: 'graph', slug: wikiDrawerPage.value.slug },
} catch (error) { }).href;
console.error('Failed to navigate to wiki graph:', error); });
}
} const openRouteInNewTab = (path: string) => {
const href = router.resolve(path).href;
window.open(href, '_blank', 'noopener,noreferrer');
}; };
const handleWikiDrawerClick = (e: MouseEvent) => { const handleWikiDrawerClick = (e: MouseEvent) => {
@@ -1892,7 +1900,7 @@ const onRootClick = (e: Event) => {
} }
if (kbId) { if (kbId) {
try { try {
router.push(`/platform/knowledge-bases/${kbId}`); openRouteInNewTab(`/platform/knowledge-bases/${kbId}`);
} catch (error) { } catch (error) {
console.error('Failed to navigate to knowledge base:', error); console.error('Failed to navigate to knowledge base:', error);
} }
@@ -1964,7 +1972,7 @@ const onRootKeydown = (e: KeyboardEvent) => {
} }
if (kbId) { if (kbId) {
try { try {
router.push(`/platform/knowledge-bases/${kbId}`); openRouteInNewTab(`/platform/knowledge-bases/${kbId}`);
} catch (error) { } catch (error) {
console.error('Failed to navigate to knowledge base:', error); console.error('Failed to navigate to knowledge base:', error);
} }
@@ -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\(/)
})
+12 -6
View File
@@ -30,9 +30,14 @@
</div> </div>
<div class="doc-group-actions" v-if="!embeddedMode && group.knowledgeBaseId" @click.stop> <div class="doc-group-actions" v-if="!embeddedMode && group.knowledgeBaseId" @click.stop>
<t-tooltip :content="$t('chat.navigateToDocument')"> <t-tooltip :content="$t('chat.navigateToDocument')">
<span class="doc-group-navigate" @click="navigateToDocument(group)"> <a
class="doc-group-navigate"
:href="getDocumentHref(group)"
target="_blank"
rel="noopener noreferrer"
>
<t-icon name="jump" size="14px" /> <t-icon name="jump" size="14px" />
</span> </a>
</t-tooltip> </t-tooltip>
</div> </div>
</div> </div>
@@ -165,16 +170,16 @@ const truncateContent = (content, maxLen) => {
return text.slice(0, maxLen) + '...'; return text.slice(0, maxLen) + '...';
}; };
const navigateToDocument = (group) => { const getDocumentHref = (group) => {
if (!group.knowledgeBaseId) return; if (!group.knowledgeBaseId) return '';
const query = {}; const query = {};
if (group.knowledgeId) { if (group.knowledgeId) {
query.knowledge_id = group.knowledgeId; query.knowledge_id = group.knowledgeId;
} }
router.push({ return router.resolve({
path: `/platform/knowledge-bases/${group.knowledgeBaseId}`, path: `/platform/knowledge-bases/${group.knowledgeBaseId}`,
query query
}); }).href;
}; };
const getWebSearchUrl = (item) => { const getWebSearchUrl = (item) => {
@@ -444,6 +449,7 @@ const getWebSearchDisplayText = (item) => {
border-radius: 4px; border-radius: 4px;
color: var(--td-brand-color); color: var(--td-brand-color);
cursor: pointer; cursor: pointer;
text-decoration: none;
transition: all 0.15s ease; transition: all 0.15s ease;
&:hover { &:hover {