diff --git a/frontend/src/components/doc-content.vue b/frontend/src/components/doc-content.vue index 49f68912..0b2652dc 100644 --- a/frontend/src/components/doc-content.vue +++ b/frontend/src/components/doc-content.vue @@ -812,7 +812,10 @@ const runMarkdownPostRenderPipeline = async () => { if (!renderRoot) { return; } - await hydrateProtectedFileImages(renderRoot, undefined, props.kbId); + await hydrateProtectedFileImages( + renderRoot, + props.kbId ? { mode: 'knowledgeBase', kbId: props.kbId } : undefined, + ); const images = renderRoot?.querySelectorAll?.('img.markdown-image') as NodeListOf | undefined; if (images) { images.forEach(async item => { diff --git a/frontend/src/utils/protectedFileAccess.test.ts b/frontend/src/utils/protectedFileAccess.test.ts new file mode 100644 index 00000000..f5bd1c55 --- /dev/null +++ b/frontend/src/utils/protectedFileAccess.test.ts @@ -0,0 +1,82 @@ +import assert from 'node:assert/strict' +import test from 'node:test' + +import { + buildProtectedFileRequest, + isProtectedFileProxyPath, + isProviderFileURL, + resolveProtectedFileAccess, + setDefaultProtectedFileAccess, + type ProtectedFileAccessContext, +} from './protectedFileAccess.ts' + +const RESOURCE = 'resource://AbCdEfGhIjKlMnOpQrStUv' + +test.afterEach(() => { + setDefaultProtectedFileAccess(null) +}) + +test('tenant access routes through the tenant-scoped proxy', () => { + const request = buildProtectedFileRequest(RESOURCE, { mode: 'tenant' }) + + assert.equal(request?.url, `/files?file_path=${encodeURIComponent(RESOURCE)}`) +}) + +test('embed access routes through the channel-scoped proxy with the Embed header', () => { + const request = buildProtectedFileRequest(RESOURCE, { + mode: 'embed', + channelId: 'ch-1', + token: 'tok-1', + }) + + assert.equal(request?.url, `/api/v1/embed/ch-1/files?file_path=${encodeURIComponent(RESOURCE)}`) + assert.equal(request?.headers.Authorization, 'Embed tok-1') +}) + +test('knowledge-base access routes through the KB-scoped proxy', () => { + const request = buildProtectedFileRequest(RESOURCE, { mode: 'knowledgeBase', kbId: 'kb 1' }) + + assert.equal( + request?.url, + `/api/v1/knowledge-bases/kb%201/files?file_path=${encodeURIComponent(RESOURCE)}`, + ) +}) + +test('an embed context without a token yields no request instead of an unauthenticated one', () => { + const request = buildProtectedFileRequest(RESOURCE, { mode: 'embed', channelId: 'ch-1', token: '' }) + + assert.equal(request, null) +}) + +test('non-storage sources are not proxied', () => { + assert.equal(buildProtectedFileRequest('https://example.com/a.png', { mode: 'tenant' }), null) + assert.equal(isProviderFileURL('https://example.com/a.png'), false) + assert.equal(isProviderFileURL('storage://backend-1/local://42/a.png'), true) +}) + +test('the registered embed plane wins over a component-level knowledge-base scope', () => { + // An embed visitor holds no Bearer token, so the KB proxy would answer 401. + setDefaultProtectedFileAccess({ mode: 'embed', channelId: 'ch-1', token: 'tok-1' }) + + const access = resolveProtectedFileAccess({ mode: 'knowledgeBase', kbId: 'kb-1' }) + + assert.deepEqual(access, { mode: 'embed', channelId: 'ch-1', token: 'tok-1' }) +}) + +test('a component scope refines the default tenant plane', () => { + const override: ProtectedFileAccessContext = { mode: 'knowledgeBase', kbId: 'kb-1' } + + assert.deepEqual(resolveProtectedFileAccess(override), override) + assert.deepEqual(resolveProtectedFileAccess(), { mode: 'tenant' }) + assert.deepEqual( + resolveProtectedFileAccess({ mode: 'knowledgeBase', kbId: ' ' }), + { mode: 'tenant' }, + ) +}) + +test('all three file proxies are recognized as protected proxy paths', () => { + assert.equal(isProtectedFileProxyPath('/files'), true) + assert.equal(isProtectedFileProxyPath('/api/v1/knowledge-bases/kb-1/files'), true) + assert.equal(isProtectedFileProxyPath('/api/v1/embed/ch-1/files'), true) + assert.equal(isProtectedFileProxyPath('/api/v1/embed/ch-1/config'), false) +}) diff --git a/frontend/src/utils/protectedFileAccess.ts b/frontend/src/utils/protectedFileAccess.ts new file mode 100644 index 00000000..ccab611c --- /dev/null +++ b/frontend/src/utils/protectedFileAccess.ts @@ -0,0 +1,158 @@ +/** + * 受保护文件(provider:// / resource:// 等)的访问上下文。 + * + * 后端按访问主体拆了三条文件代理,鉴权模型互不相同: + * - `/files` → 登录态 Bearer + X-Tenant-ID + * - `/api/v1/knowledge-bases/:id/files` → 知识库访问权限(跨租户共享库) + * - `/api/v1/embed/:channel_id/files` → 嵌入访客的 Embed token + * + * 选哪条代理取决于当前请求的鉴权平面,而不是取决于哪个组件在渲染图片。 + * 这里把该决策收敛成单一真相源,渲染组件只需声明作用域,不再各自拼 URL。 + */ + +export const PROVIDER_SCHEME_PATTERN = 'resource|local|minio|cos|tos|s3|oss|ks3|obs'; + +const PROVIDER_FILE_SCHEME_RE = new RegExp(`^(${PROVIDER_SCHEME_PATTERN}):\\/\\/\\S+$`, 'i'); +const STORAGE_BACKEND_FILE_SCHEME_RE = new RegExp( + `^storage:\\/\\/[0-9A-Za-z_-]+\\/(${PROVIDER_SCHEME_PATTERN}):\\/\\/\\S+$`, + 'i', +); + +const KB_FILE_PROXY_PATH_RE = /^\/api\/v1\/knowledge-bases\/[^/]+\/files$/; +const EMBED_FILE_PROXY_PATH_RE = /^\/api\/v1\/embed\/[^/]+\/files$/; + +export type ProtectedFileAccessContext = + /** 登录态用户:Bearer + 选中租户。 */ + | { mode: 'tenant' } + /** 嵌入访客:只持有 Embed token,无 Bearer、无租户上下文。 */ + | { mode: 'embed'; channelId: string; token: string } + /** 知识库作用域:登录态用户读取共享库中归属其他租户的对象。 */ + | { mode: 'knowledgeBase'; kbId: string }; + +export interface ProtectedFileRequest { + url: string; + headers: Record; +} + +const TENANT_ACCESS: ProtectedFileAccessContext = { mode: 'tenant' }; + +interface ProtectedFileAccessState { + current: ProtectedFileAccessContext; +} + +// 与 blob 缓存同样挂在 window 上:Vite 热更新会替换模块但不会重建文档, +// 模块级变量会丢失嵌入应用启动时注册的上下文。 +const accessState: ProtectedFileAccessState = (() => { + const fresh = (): ProtectedFileAccessState => ({ current: TENANT_ACCESS }); + if (typeof window === 'undefined') return fresh(); + const scope = window as typeof window & { + __weknoraProtectedFileAccessV1__?: ProtectedFileAccessState; + }; + scope.__weknoraProtectedFileAccessV1__ ||= fresh(); + return scope.__weknoraProtectedFileAccessV1__; +})(); + +/** + * 注册当前文档的默认访问上下文。由应用入口调用一次(嵌入应用在拿到 + * channelId/token 后注册),此后所有受保护文件请求自动走对应代理。 + */ +export function setDefaultProtectedFileAccess( + access: ProtectedFileAccessContext | null, +): void { + accessState.current = access ?? TENANT_ACCESS; +} + +export function getDefaultProtectedFileAccess(): ProtectedFileAccessContext { + return accessState.current; +} + +/** + * 合并默认上下文与组件传入的作用域。 + * + * 默认上下文携带的是鉴权平面(嵌入访客 vs 登录态用户),组件级 override 只能 + * 在同一平面内细化作用域。嵌入访客没有 Bearer,若让 `knowledgeBase` override + * 覆盖 embed 平面,请求会落到需要登录态的代理上并返回 401。 + */ +export function resolveProtectedFileAccess( + override?: ProtectedFileAccessContext | null, +): ProtectedFileAccessContext { + const fallback = accessState.current; + if (fallback.mode === 'embed') return fallback; + if (!override) return fallback; + if (override.mode === 'knowledgeBase' && !override.kbId.trim()) return fallback; + return override; +} + +/** 是否为需要经代理拉取的存储路径(provider:// 或 storage:///provider://)。 */ +export function isProviderFileURL(url: string): boolean { + const trimmed = url.trim(); + return PROVIDER_FILE_SCHEME_RE.test(trimmed) || STORAGE_BACKEND_FILE_SCHEME_RE.test(trimmed); +} + +/** 是否为三条受保护文件代理之一的路径。 */ +export function isProtectedFileProxyPath(pathname: string): boolean { + return ( + pathname === '/files' + || KB_FILE_PROXY_PATH_RE.test(pathname) + || EMBED_FILE_PROXY_PATH_RE.test(pathname) + ); +} + +function tenantRequestHeaders(): Record { + const headers: Record = {}; + try { + const token = (localStorage.getItem('weknora_token') || '').trim(); + if (token) { + headers['Authorization'] = `Bearer ${token}`; + } + + const selectedTenantId = (localStorage.getItem('weknora_selected_tenant_id') || '').trim(); + if (selectedTenantId) { + // Always attach when a selected tenant is set. Same rationale as + // utils/request.ts / api/chat/streame.ts: the + // "selectedTenantId === defaultTenantId → skip" short-circuit + // silently drops the header whenever any code path writes the + // active tenant into weknora_tenant, leaving authenticated file + // fetches landing on the home tenant. + headers['X-Tenant-ID'] = selectedTenantId; + } + } catch { + // ignore localStorage read errors + } + return headers; +} + +/** + * 为一个存储路径构造代理请求。返回 null 表示当前上下文无法发起该请求 + * (非存储路径,或嵌入上下文尚未拿到 token),调用方应跳过并稍后重试。 + */ +export function buildProtectedFileRequest( + sourceURL: string, + access: ProtectedFileAccessContext, +): ProtectedFileRequest | null { + const filePath = sourceURL.trim(); + if (!isProviderFileURL(filePath)) return null; + + const query = new URLSearchParams({ file_path: filePath }).toString(); + + if (access.mode === 'embed') { + const channelId = access.channelId.trim(); + const token = access.token.trim(); + // 嵌入访客只有 Embed token 这一种凭据;缺失时退回 /files 只会得到 401, + // 不如跳过等待 bootstrap 完成后的下一次水合。 + if (!channelId || !token) return null; + return { + url: `/api/v1/embed/${encodeURIComponent(channelId)}/files?${query}`, + headers: { Authorization: `Embed ${token}` }, + }; + } + + if (access.mode === 'knowledgeBase') { + return { + url: `/api/v1/knowledge-bases/${encodeURIComponent(access.kbId.trim())}/files?${query}`, + headers: tenantRequestHeaders(), + }; + } + + return { url: `/files?${query}`, headers: tenantRequestHeaders() }; +} diff --git a/frontend/src/utils/security.ts b/frontend/src/utils/security.ts index 797fc8cc..224a67ce 100644 --- a/frontend/src/utils/security.ts +++ b/frontend/src/utils/security.ts @@ -10,14 +10,16 @@ import { markdownDomPurifyConfig, markdownDomPurifySecurityHooks, } from './markdownDomPurify.ts'; +import { + buildProtectedFileRequest, + isProtectedFileProxyPath, + isProviderFileURL, + PROVIDER_SCHEME_PATTERN, + resolveProtectedFileAccess, + type ProtectedFileAccessContext, +} from './protectedFileAccess.ts'; const PROVIDER_IMAGE_PLACEHOLDER = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=='; -const PROVIDER_SCHEME_PATTERN = 'resource|local|minio|cos|tos|s3|oss|ks3|obs'; -const PROVIDER_FILE_SCHEME_RE = new RegExp(`^(${PROVIDER_SCHEME_PATTERN}):\\/\\/\\S+$`, 'i'); -const STORAGE_BACKEND_FILE_SCHEME_RE = new RegExp( - `^storage:\\/\\/[0-9A-Za-z_-]+\\/(${PROVIDER_SCHEME_PATTERN}):\\/\\/\\S+$`, - 'i', -); const PROVIDER_IMG_SRC_RE = new RegExp( `]*?)\\ssrc=(["'])(${PROVIDER_SCHEME_PATTERN}):(?:\\/\\/|//|//)([^"']+)\\2([^>]*)>`, 'gi', @@ -190,11 +192,6 @@ function decodeProviderURL(raw: string): string { .replace(/"/g, '"'); } -function isProviderFileURL(url: string): boolean { - const trimmed = url.trim(); - return PROVIDER_FILE_SCHEME_RE.test(trimmed) || STORAGE_BACKEND_FILE_SCHEME_RE.test(trimmed); -} - function providerSourceFromImageSrc(src: string): string | null { const decodedSrc = decodeProviderURL(src); if (isProviderFileURL(decodedSrc)) { @@ -204,10 +201,7 @@ function providerSourceFromImageSrc(src: string): string | null { try { const baseURL = typeof window !== 'undefined' ? window.location.origin : 'http://localhost'; const url = new URL(decodedSrc, baseURL); - const isFileProxy = - url.pathname === '/files' || - /^\/api\/v1\/embed\/[^/]+\/files$/.test(url.pathname); - if (!isFileProxy) { + if (!isProtectedFileProxyPath(url.pathname)) { return null; } @@ -416,30 +410,6 @@ const protectedFileFailureCache = protectedFileCacheState.failures; const protectedFileInflight = protectedFileCacheState.inflight; const PROTECTED_FILE_RETRY_COOLDOWN_MS = 5000; -function getProtectedFileRequestHeaders(): Record { - const headers: Record = {}; - try { - const token = (localStorage.getItem('weknora_token') || '').trim(); - if (token) { - headers['Authorization'] = `Bearer ${token}`; - } - - const selectedTenantId = (localStorage.getItem('weknora_selected_tenant_id') || '').trim(); - if (selectedTenantId) { - // Always attach when a selected tenant is set. Same rationale as - // utils/request.ts / api/chat/streame.ts: the - // "selectedTenantId === defaultTenantId → skip" short-circuit - // silently drops the header whenever any code path writes the - // active tenant into weknora_tenant, leaving authenticated file - // fetches landing on the home tenant. - headers['X-Tenant-ID'] = selectedTenantId; - } - } catch { - // ignore localStorage read errors - } - return headers; -} - /** * 将 Markdown 里通过 /files 代理的图片,改为用带鉴权 Header 的 fetch 拉取后再显示。 * 用于避免在 URL 中暴露 token。 @@ -489,10 +459,17 @@ function applyHydratedProtectedImage(root: ParentNode, sourceURL: string, blobUR }); } +/** + * 将内容里的受保护图片(resource:// 等)通过对应的文件代理带鉴权拉取, + * 再以 blob URL 替换显示。 + * + * 走哪条代理由 {@link resolveProtectedFileAccess} 决定:应用入口注册的默认 + * 上下文(如嵌入应用的 Embed 平面)优先,组件只在同一鉴权平面内用 + * `access` 细化作用域(如知识库)。 + */ export async function hydrateProtectedFileImages( root: ParentNode | null | undefined, - embed?: { channelId: string; token: string }, - kbId?: string, + access?: ProtectedFileAccessContext, ): Promise { if (!root || typeof window === 'undefined') { return; @@ -505,11 +482,7 @@ export async function hydrateProtectedFileImages( return; } - // Embed visitors carry no Bearer/tenant context; route through the - // embed-scoped file proxy (auth via the Embed header, tenant from the channel). - const headers = embed - ? { Authorization: `Embed ${embed.token}` } - : getProtectedFileRequestHeaders(); + const resolvedAccess = resolveProtectedFileAccess(access); await Promise.all(Array.from(images).map(async (img) => { const normalizedSourceURL = normalizeProtectedImageElement(img); @@ -528,30 +501,15 @@ export async function hydrateProtectedFileImages( } img.dataset.authHydrated = '1'; - const isProviderScheme = isProviderFileURL(sourceURL); - // When a KB context is known, route through the KB-scoped proxy. It is - // authorized via RequireKBAccess (own / org-shared / agent-visible) and - // serves objects owned by the KB's source tenant — so images in a shared - // KB (local:///...) load for the borrowing tenant, which the - // tenant-scoped /files route rejects as a cross-tenant path. - const fileProxyBase = embed - ? `/api/v1/embed/${embed.channelId}/files` - : kbId - ? `/api/v1/knowledge-bases/${encodeURIComponent(kbId)}/files` - : '/files'; - const requestURL = isProviderScheme - ? `${fileProxyBase}?${new URLSearchParams({ file_path: sourceURL }).toString()}` - : sourceURL; - - const isProxyRequest = - requestURL.includes('file_path=') && - (requestURL.startsWith('/files?') || - /^\/api\/v1\/knowledge-bases\/[^/]+\/files\?/.test(requestURL) || - /^\/api\/v1\/embed\/[^/]+\/files\?/.test(requestURL)); - if (!isProxyRequest) { + // A null request means this source cannot be fetched under the current + // access context (not a storage path, or the embed token has not arrived + // yet). Leave the placeholder so a later pass can retry. + const request = buildProtectedFileRequest(sourceURL, resolvedAccess); + if (!request) { img.dataset.authHydrated = '0'; return; } + const { url: requestURL, headers } = request; const cachedBlobURL = protectedFileBlobCache.get(requestURL); if (cachedBlobURL) { diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vue index 4005004d..069fb676 100644 --- a/frontend/src/views/chat/components/AgentStreamDisplay.vue +++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue @@ -507,6 +507,7 @@ import { useAuthStore } from '@/stores/auth'; import { useI18n } from 'vue-i18n'; import i18n from '@/i18n'; import { hydrateProtectedFileImages, clearProtectedFileFailureCache, sanitizeMarkdownHTML } from '@/utils/security'; +import type { ProtectedFileAccessContext } from '@/utils/protectedFileAccess'; import { unwrapFinalAnswerWrappers, thinkingEqualsAnswer } from '@/utils/finalAnswer'; import { getAgentToolIconName } from '@/utils/agent-tool-icons'; import { getQueryText, getWikiPageText } from '@/utils/agent-tool-display'; @@ -718,7 +719,7 @@ const wikiDrawerContent = computed(() => { watch(wikiDrawerContent, async () => { await nextTick(); if (wikiDrawerBodyRef.value) { - await hydrateProtectedFileImages(wikiDrawerBodyRef.value); + await hydrateProtectedFileImages(wikiDrawerBodyRef.value, protectedFileAccess.value); } }); @@ -817,6 +818,15 @@ const showRequestInfo = computed( () => !props.embeddedMode && !!(props.session?.request_id || props.session?.id), ); +// Agent answers embed exported charts and knowledge-base images as +// `resource://` handles. An embed visitor has no Bearer token, so they must be +// fetched through the channel-scoped proxy rather than the tenant one. +const protectedFileAccess = computed(() => + props.embeddedMode && props.embedChannelId && props.embedToken + ? { mode: 'embed', channelId: props.embedChannelId, token: props.embedToken } + : undefined, +); + const { float: citationFloat, rebind: rebindCitations, @@ -1224,7 +1234,7 @@ watch(eventStream, (stream) => { activeThinkingVersion.value++; nextTick(async () => { - await hydrateProtectedFileImages(rootElement.value); + await hydrateProtectedFileImages(rootElement.value, protectedFileAccess.value); await enhanceMarkdownContainer(rootElement.value); // Auto-scroll thinking detail content to bottom during streaming if (newActiveIds.size > 0 && rootElement.value) { @@ -1401,7 +1411,7 @@ watch(answerFullyRendered, (ready) => { // suppressed by the missing-source cache. clearProtectedFileFailureCache(); nextTick(async () => { - await hydrateProtectedFileImages(rootElement.value); + await hydrateProtectedFileImages(rootElement.value, protectedFileAccess.value); }); }, { immediate: true }); @@ -1871,7 +1881,7 @@ const toggleIntermediateSteps = () => { showIntermediateSteps.value = !showIntermediateSteps.value; nextTick(async () => { if (rootElement.value) { - await hydrateProtectedFileImages(rootElement.value); + await hydrateProtectedFileImages(rootElement.value, protectedFileAccess.value); } }); }; @@ -2191,7 +2201,7 @@ onMounted(() => { (root as any).__citationKeydown__ = keydownListener; root.addEventListener('keydown', keydownListener, true); rebindCitations(); - await hydrateProtectedFileImages(rootElement.value); + await hydrateProtectedFileImages(rootElement.value, protectedFileAccess.value); }); }); @@ -2215,7 +2225,7 @@ onUpdated(() => { // and idempotent: blob results are cached per URL, in-flight fetches are // de-duped, and failures back off for a cooldown — so a not-yet-ready file // simply retries later (and the answerFullyRendered pass is the backstop). - await hydrateProtectedFileImages(rootElement.value); + await hydrateProtectedFileImages(rootElement.value, protectedFileAccess.value); }); }); diff --git a/frontend/src/views/embed/EmbedBotMessage.vue b/frontend/src/views/embed/EmbedBotMessage.vue index 0c33ff03..812fed37 100644 --- a/frontend/src/views/embed/EmbedBotMessage.vue +++ b/frontend/src/views/embed/EmbedBotMessage.vue @@ -48,6 +48,7 @@ import { isValidImageURL, hydrateProtectedFileImages, } from '@/utils/security' +import type { ProtectedFileAccessContext } from '@/utils/protectedFileAccess' import { createChatMarkdownRenderer, renderChatMarkdown, @@ -171,11 +172,11 @@ const hasActualContent = computed(() => { }) const hydrateImages = async () => { - const embedCtx = + const embedAccess: ProtectedFileAccessContext | undefined = props.embedChannelId && props.embedToken - ? { channelId: props.embedChannelId, token: props.embedToken } + ? { mode: 'embed', channelId: props.embedChannelId, token: props.embedToken } : undefined - await hydrateProtectedFileImages(parentMd.value, embedCtx) + await hydrateProtectedFileImages(parentMd.value, embedAccess) } const renderMermaidDiagrams = async () => { diff --git a/frontend/src/views/embed/EmbedPage.vue b/frontend/src/views/embed/EmbedPage.vue index 268c1cad..627a2913 100644 --- a/frontend/src/views/embed/EmbedPage.vue +++ b/frontend/src/views/embed/EmbedPage.vue @@ -53,11 +53,12 @@