Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(frontend): open chat reference links in new tabs
wizardchenbdd459b071cb
diff --git a/frontend/src/components/ChatReferencesDrawer.vue b/frontend/src/components/ChatReferencesDrawer.vueindex b2f55dbfb..82b3c39e8 100644--- a/frontend/src/components/ChatReferencesDrawer.vue+++ b/frontend/src/components/ChatReferencesDrawer.vue@@ -106,10 +106,16 @@</component><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" /><span>{{ t('chat.navigateToDocument') }}</span>- </button>+ </a></div></article></section>@@ -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<string, string> = {}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.mjsindex 5b3c23e5d..5eebc4b53 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.tsindex 078d71c03..80e3be9ad 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.tsindex 6e548c7b5..d26d6c3b2 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.vueindex da46e6efa..d5f33c495 100644--- a/frontend/src/views/chat/components/AgentStreamDisplay.vue+++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue@@ -442,7 +442,13 @@|| 1}) }}</span></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>{{ $t('knowledgeEditor.wikiBrowser.viewInGraph') }}</t-link>@@ -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.mjsnew file mode 100644index 000000000..8e6ff3ba5--- /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.vueindex d8fc8a8eb..927afa7a3 100644--- a/frontend/src/views/chat/components/docInfo.vue+++ b/frontend/src/views/chat/components/docInfo.vue@@ -30,9 +30,14 @@</div><div class="doc-group-actions" v-if="!embeddedMode && group.knowledgeBaseId" @click.stop><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" />- </span>+ </a></t-tooltip></div></div>@@ -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 {