refactor: simplify image handling in _resolve_images function

- Removed the image storage handling from the `_resolve_images` function, which now only decodes images and returns them as inline bytes.
- Updated the function's docstring to clarify that image persistence is managed by the Go App, and the return value for `image_dir_path` is always empty.
- Adjusted related gRPC and protobuf files to remove the `ConvertToPDF` method and its associated types, streamlining the API.
- Enhanced security measures in the frontend by implementing a placeholder for provider images and ensuring proper hydration of protected file images.

These changes improve the clarity and efficiency of image processing and API interactions within the application.
This commit is contained in:
wizardchen
2026-03-03 21:30:27 +08:00
committed by lyingbug
parent 894d2c060a
commit 4192cfd072
26 changed files with 835 additions and 897 deletions
+136 -6
View File
@@ -4,6 +4,8 @@
import DOMPurify from 'dompurify';
const PROVIDER_IMAGE_PLACEHOLDER = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
// 配置 DOMPurify 的安全策略
const DOMPurifyConfig = {
// 允许的标签
@@ -21,7 +23,7 @@ const DOMPurifyConfig = {
],
// 允许的属性
ALLOWED_ATTR: [
'href', 'title', 'alt', 'src', 'class', 'id', 'style',
'href', 'title', 'alt', 'src', 'class', 'id', 'style', 'data-protected-src',
'target', 'rel', 'width', 'height',
// Mermaid SVG 支持的属性
'd', 'fill', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin',
@@ -39,7 +41,7 @@ const DOMPurifyConfig = {
'display', 'pointer-events', 'cursor', 'data-emit', 'direction'
],
// 允许的协议
ALLOWED_URI_REGEXP: /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i,
ALLOWED_URI_REGEXP: /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|(?:local|minio|cos|tos):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i,
// 禁止的标签和属性
FORBID_TAGS: ['script', 'object', 'embed', 'form', 'input', 'button'],
FORBID_ATTR: ['onerror', 'onload', 'onclick', 'onmouseover', 'onfocus', 'onblur'],
@@ -99,7 +101,8 @@ export function sanitizeHTML(html: string): string {
}
try {
return DOMPurify.sanitize(html, DOMPurifyConfig);
const preparedHTML = protectProviderImageSrcInHTML(html);
return DOMPurify.sanitize(preparedHTML, DOMPurifyConfig);
} catch (error) {
console.error('HTML sanitization failed:', error);
// 如果清理失败,返回转义的纯文本
@@ -107,6 +110,24 @@ export function sanitizeHTML(html: string): string {
}
}
function protectProviderImageSrcInHTML(html: string): string {
if (!html) return html;
const decodeProviderURL = (raw: string): string =>
raw
.replace(///gi, '/')
.replace(///g, '/')
.replace(/&/g, '&')
.replace(/"/g, '"');
return html.replace(
/<img\b([^>]*?)\ssrc=(["'])(local|minio|cos|tos):(?:\/\/|&#x2f;&#x2f;|&#47;&#47;)([^"']+)\2([^>]*)>/gi,
(_m, before, quote, provider, restPathRaw, after) => {
const restPath = decodeProviderURL(restPathRaw);
const protectedSrc = `${provider}://${restPath}`;
return `<img${before} src=${quote}${PROVIDER_IMAGE_PLACEHOLDER}${quote} data-protected-src=${quote}${protectedSrc}${quote}${after}>`;
},
);
}
/**
* 转义 HTML 特殊字符
* @param text 需要转义的文本
@@ -140,14 +161,23 @@ export function isValidURL(url: string): boolean {
if (!url || typeof url !== 'string') {
return false;
}
const trimmed = url.trim();
if (!trimmed) {
return false;
}
// 允许以 / 开头的站内相对路径(如本地存储 /files/images/xxx.jpg)
if (url.startsWith('/') && !url.startsWith('//')) {
if (trimmed.startsWith('/') && !trimmed.startsWith('//')) {
return true;
}
// 允许 provider:// 形式,由前端后续鉴权拉取并替换为 blob URL
if (/^(local|minio|cos|tos):\/\/\S+$/i.test(trimmed)) {
return true;
}
try {
const urlObj = new URL(url);
const urlObj = new URL(trimmed);
return ['http:', 'https:'].includes(urlObj.protocol);
} catch {
return false;
@@ -220,9 +250,109 @@ export function createSafeImage(src: string, alt: string = '', title: string = '
return '';
}
const safeSrc = escapeHTML(src);
// src is validated by isValidImageURL; keep URL structure unchanged.
// Only escape quotes to avoid breaking attributes.
const safeSrc = src.replace(/"/g, '&quot;');
const safeAlt = escapeHTML(alt);
const safeTitle = escapeHTML(title);
return `<img src="${safeSrc}" alt="${safeAlt}" title="${safeTitle}" class="markdown-image" style="max-width: 100%; height: auto;">`;
}
const protectedFileBlobCache = new Map<string, string>();
function getProtectedFileRequestHeaders(): Record<string, string> {
const headers: Record<string, string> = {};
try {
const token = (localStorage.getItem('weknora_token') || '').trim();
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
const selectedTenantId = (localStorage.getItem('weknora_selected_tenant_id') || '').trim();
const tenantRaw = localStorage.getItem('weknora_tenant');
if (selectedTenantId) {
try {
const tenant = tenantRaw ? JSON.parse(tenantRaw) : null;
const defaultTenantId = tenant?.id ? String(tenant.id) : '';
if (selectedTenantId !== defaultTenantId) {
headers['X-Tenant-ID'] = selectedTenantId;
}
} catch {
// ignore tenant parse error and skip X-Tenant-ID
}
}
} catch {
// ignore localStorage read errors
}
return headers;
}
/**
* 将 Markdown 里通过 /files 代理的图片,改为用带鉴权 Header 的 fetch 拉取后再显示。
* 用于避免在 URL 中暴露 token。
*/
export async function hydrateProtectedFileImages(root: ParentNode | null | undefined): Promise<void> {
if (!root || typeof window === 'undefined') {
return;
}
const images = root.querySelectorAll<HTMLImageElement>(
'img[data-protected-src], img[src^="local://"], img[src^="minio://"], img[src^="cos://"], img[src^="tos://"]',
);
if (!images.length) {
return;
}
const headers = getProtectedFileRequestHeaders();
await Promise.all(Array.from(images).map(async (img) => {
const protectedSrc = (img.getAttribute('data-protected-src') || '').trim();
const src = (img.getAttribute('src') || '').trim();
const sourceURL = protectedSrc || src;
if (!sourceURL) {
return;
}
if (img.dataset.authHydrated === '1') {
return;
}
img.dataset.authHydrated = '1';
const isProviderScheme = /^(local|minio|cos|tos):\/\//.test(sourceURL);
const requestURL = isProviderScheme
? `/files?${new URLSearchParams({ file_path: sourceURL }).toString()}`
: sourceURL;
if (!requestURL.startsWith('/files?') || !requestURL.includes('file_path=')) {
img.dataset.authHydrated = '0';
return;
}
const cachedBlobURL = protectedFileBlobCache.get(requestURL);
if (cachedBlobURL) {
img.src = cachedBlobURL;
return;
}
try {
const resp = await fetch(requestURL, {
method: 'GET',
headers,
credentials: 'include',
});
if (!resp.ok) {
throw new Error(`HTTP ${resp.status}`);
}
const blob = await resp.blob();
const blobURL = URL.createObjectURL(blob);
protectedFileBlobCache.set(requestURL, blobURL);
img.src = blobURL;
if (protectedSrc) {
img.removeAttribute('data-protected-src');
}
} catch (error) {
console.warn('[security] hydrateProtectedFileImages failed:', error);
img.dataset.authHydrated = '0';
}
}));
}