refactor: 统一ID类型为Long并优化代码安全性和性能
修复用户删除接口的ID类型从Integer改为Long 移除未使用的Bouncy Castle依赖 添加dompurify依赖增强XSS防护 修复SQL表定义中的bigintBIGINT语法错误 优化图片预览接口的安全检查和错误处理 添加Vditor渲染引擎预加载和图片懒加载 统一分组和文件接口的ID类型为Long 增强前端用户状态管理,添加token过期检查 优化Markdown内容渲染流程和图片URL处理
This commit is contained in:
28
biji-qianduan/package-lock.json
generated
28
biji-qianduan/package-lock.json
generated
@@ -10,6 +10,7 @@
|
||||
"dependencies": {
|
||||
"@kangc/v-md-editor": "^2.2.4",
|
||||
"codemirror": "^6.0.1",
|
||||
"dompurify": "^3.3.1",
|
||||
"element-plus": "^2.7.6",
|
||||
"highlight.js": "^11.11.1",
|
||||
"html2canvas": "^1.4.1",
|
||||
@@ -2585,10 +2586,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/dompurify": {
|
||||
"version": "3.1.6",
|
||||
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.1.6.tgz",
|
||||
"integrity": "sha512-cTOAhc36AalkjtBpfG6O8JimdTMWNXjiePT2xQH/ppBGi/4uIpmj8eKyIkMJErXWARyINV/sB38yf8JCLF5pbQ==",
|
||||
"license": "(MPL-2.0 OR Apache-2.0)"
|
||||
"version": "3.3.1",
|
||||
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.3.1.tgz",
|
||||
"integrity": "sha512-qkdCKzLNtrgPFP1Vo+98FRzJnBRGe4ffyCea9IwHB1fyxPOeNTHpLKYGd4Uk9xvNoH0ZoOjwZxNptyMwqrId1Q==",
|
||||
"license": "(MPL-2.0 OR Apache-2.0)",
|
||||
"optionalDependencies": {
|
||||
"@types/trusted-types": "^2.0.7"
|
||||
}
|
||||
},
|
||||
"node_modules/element-plus": {
|
||||
"version": "2.10.4",
|
||||
@@ -3414,16 +3418,6 @@
|
||||
"html2canvas": "^1.0.0-rc.5"
|
||||
}
|
||||
},
|
||||
"node_modules/jspdf/node_modules/dompurify": {
|
||||
"version": "3.2.6",
|
||||
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.2.6.tgz",
|
||||
"integrity": "sha512-/2GogDQlohXPZe6D6NOgQvXLPSYBqIWMnZ8zzOhn09REE4eyAzb+Hed3jhoM9OkuaJ8P6ZGTTVWQKAi8ieIzfQ==",
|
||||
"license": "(MPL-2.0 OR Apache-2.0)",
|
||||
"optional": true,
|
||||
"optionalDependencies": {
|
||||
"@types/trusted-types": "^2.0.7"
|
||||
}
|
||||
},
|
||||
"node_modules/katex": {
|
||||
"version": "0.13.24",
|
||||
"resolved": "https://registry.npmjs.org/katex/-/katex-0.13.24.tgz",
|
||||
@@ -3705,6 +3699,12 @@
|
||||
"web-worker": "^1.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/mermaid/node_modules/dompurify": {
|
||||
"version": "3.1.6",
|
||||
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.1.6.tgz",
|
||||
"integrity": "sha512-cTOAhc36AalkjtBpfG6O8JimdTMWNXjiePT2xQH/ppBGi/4uIpmj8eKyIkMJErXWARyINV/sB38yf8JCLF5pbQ==",
|
||||
"license": "(MPL-2.0 OR Apache-2.0)"
|
||||
},
|
||||
"node_modules/mermaid/node_modules/katex": {
|
||||
"version": "0.16.22",
|
||||
"resolved": "https://registry.npmjs.org/katex/-/katex-0.16.22.tgz",
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
"dependencies": {
|
||||
"@kangc/v-md-editor": "^2.2.4",
|
||||
"codemirror": "^6.0.1",
|
||||
"dompurify": "^3.3.1",
|
||||
"element-plus": "^2.7.6",
|
||||
"highlight.js": "^11.11.1",
|
||||
"html2canvas": "^1.4.1",
|
||||
@@ -24,7 +25,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.0.5",
|
||||
"vite": "^5.3.1",
|
||||
"terser": "^5.31.3"
|
||||
"terser": "^5.31.3",
|
||||
"vite": "^5.3.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,8 @@ import axiosApi from '@/utils/axios.js'
|
||||
|
||||
|
||||
|
||||
// 修复:使用 encodeURIComponent 编码 URL 参数,防止注入
|
||||
export const groupingId = (data) => axiosApi.get(`/api/markdown/grouping/${encodeURIComponent(data)}`)
|
||||
// 根据分组ID获取Markdown文件列表
|
||||
export const groupingId = (groupingId) => axiosApi.get(`/api/markdown/grouping/${encodeURIComponent(groupingId)}`)
|
||||
// 获取所有分组
|
||||
export const groupingAll = (data) => {
|
||||
if (data) {
|
||||
@@ -71,16 +71,17 @@ export const register = (data) => {
|
||||
const formData = new FormData()
|
||||
formData.append('username', data.username)
|
||||
formData.append('password', data.password)
|
||||
formData.append('email', data.email || '') // 修复:添加 email 参数
|
||||
formData.append('registrationCode', data.registrationCode)
|
||||
return axiosApi.post('/api/user/register', formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data'
|
||||
}
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
// 更新分组名称
|
||||
// 修复:使用与后端 Grouping 实体类匹配的字段名
|
||||
export const updateGroupingName = (id, newName) => {
|
||||
return axiosApi.put(`/api/groupings/${id}`, { grouping: newName });
|
||||
}
|
||||
@@ -106,20 +107,6 @@ export const getRecentFiles = (limit = 16) => axiosApi.get(`/api/markdown/recent
|
||||
|
||||
|
||||
|
||||
// MD5哈希
|
||||
export const MD5 = (data, file) => {
|
||||
const formData = new FormData()
|
||||
if (data) formData.append('input', data)
|
||||
if (file) formData.append('file', file)
|
||||
return axiosApi.post('/api/common/md5', formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data'
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -130,11 +130,12 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, ref, nextTick, watch, computed, onBeforeUnmount } from 'vue';
|
||||
import { onMounted, ref, nextTick, watch, computed, onBeforeUnmount, watchEffect, provide } from 'vue';
|
||||
import { ElMessage, ElMessageBox } from 'element-plus';
|
||||
import Vditor from 'vditor';
|
||||
import 'vditor/dist/index.css';
|
||||
import { escapeHtml } from '@/utils/security';
|
||||
import DOMPurify from 'dompurify';
|
||||
import {
|
||||
groupingAll,
|
||||
markdownList,
|
||||
@@ -197,6 +198,11 @@ const showSystemSettingsDialog = ref(false);
|
||||
const showUpdatePasswordDialog = ref(false);
|
||||
const showPrivacyDialog = ref(false);
|
||||
|
||||
// Vditor 渲染引擎就绪状态
|
||||
const vditorReady = ref(false);
|
||||
// 提供给子组件使用
|
||||
provide('vditorReady', vditorReady);
|
||||
|
||||
// Data for dialogs
|
||||
const itemToRename = ref(null);
|
||||
const fileToImport = ref(null);
|
||||
@@ -369,8 +375,10 @@ const previewFile = async (file) => {
|
||||
selectedFile.value = null;
|
||||
return;
|
||||
}
|
||||
// 重置渲染缓存,确保每次打开笔记都重新渲染
|
||||
lastRenderedKey = null;
|
||||
// 先立即显示预览页(加载状态),让用户感知到响应
|
||||
selectedFile.value = { ...file, content: '', isLoading: true };
|
||||
selectedFile.value = { ...file, content: '', isLoading: true, isRendering: false };
|
||||
showEditor.value = false;
|
||||
|
||||
// 异步加载内容
|
||||
@@ -378,7 +386,9 @@ const previewFile = async (file) => {
|
||||
const content = await Preview(file.id) || '';
|
||||
// 内容加载完成后更新
|
||||
if (selectedFile.value && selectedFile.value.id === file.id) {
|
||||
selectedFile.value = { ...file, content, isLoading: false };
|
||||
// 如果 Vditor 渲染引擎未就绪,显示渲染中状态
|
||||
const isRendering = !vditorReady.value;
|
||||
selectedFile.value = { ...file, content, isLoading: false, isRendering };
|
||||
}
|
||||
} catch (error) {
|
||||
// 错误已在 axios 拦截器中显示,这里不再重复显示
|
||||
@@ -507,9 +517,13 @@ const handleExport = async (format) => {
|
||||
const blob = new Blob([content], { type: 'text/markdown;charset=utf-8' });
|
||||
downloadBlob(blob, `${title}.md`);
|
||||
} else if (format === 'html') {
|
||||
// 修复:对title进行HTML转义,防止XSS
|
||||
// 修复:对title进行HTML转义,使用DOMPurify清理内容防止XSS
|
||||
const escapedTitle = escapeHtml(title);
|
||||
const fullHtml = `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><title>${escapedTitle}</title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.1.0/github-markdown.min.css"><style>body{box-sizing:border-box;min-width:200px;max-width:980px;margin:0 auto;padding:45px;}</style></head><body class="markdown-body"><h1>${escapedTitle}</h1>${previewElement.innerHTML}</body></html>`;
|
||||
const sanitizedContent = DOMPurify.sanitize(previewElement.innerHTML, {
|
||||
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'code', 'pre', 'ul', 'ol', 'li', 'blockquote', 'img', 'br', 'hr', 'table', 'thead', 'tbody', 'tr', 'th', 'td'],
|
||||
ALLOWED_ATTR: ['href', 'title', 'class', 'src', 'alt', 'width', 'height']
|
||||
});
|
||||
const fullHtml = `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><title>${escapedTitle}</title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.1.0/github-markdown.min.css"><style>body{box-sizing:border-box;min-width:200px;max-width:980px;margin:0 auto;padding:45px;}</style></head><body class="markdown-body"><h1>${escapedTitle}</h1>${sanitizedContent}</body></html>`;
|
||||
const blob = new Blob([fullHtml], { type: 'text/html;charset=utf-8' });
|
||||
downloadBlob(blob, `${escapedTitle}.html`);
|
||||
} else if (format === 'pdf') {
|
||||
@@ -555,8 +569,33 @@ onMounted(async () => {
|
||||
await fetchGroupings();
|
||||
await resetToHomeView();
|
||||
window.addEventListener('resize', handleResize);
|
||||
|
||||
// 预加载 Vditor 渲染引擎(lute.min.js),避免第一次点击笔记时等待下载
|
||||
preloadVditor();
|
||||
});
|
||||
|
||||
// 预加载 Vditor 渲染引擎
|
||||
const preloadVditor = () => {
|
||||
// 创建一个隐藏的容器用于预加载
|
||||
const preloadContainer = document.createElement('div');
|
||||
preloadContainer.style.cssText = 'position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden;';
|
||||
document.body.appendChild(preloadContainer);
|
||||
|
||||
// 调用 Vditor.preview 会触发 lute.min.js 的下载
|
||||
Vditor.preview(preloadContainer, '# 预加载', {
|
||||
mode: 'light',
|
||||
after: () => {
|
||||
// 渲染引擎加载完成
|
||||
vditorReady.value = true;
|
||||
// 清理预加载容器
|
||||
if (preloadContainer.parentNode) {
|
||||
preloadContainer.parentNode.removeChild(preloadContainer);
|
||||
}
|
||||
console.log('Vditor 渲染引擎已就绪');
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('resize', handleResize);
|
||||
});
|
||||
@@ -571,26 +610,91 @@ const handleResize = () => {
|
||||
// Vditor 渲染优化
|
||||
let lastRenderedKey = null;
|
||||
|
||||
watch([selectedFile, showEditor], ([newFile, newShowEditor]) => {
|
||||
if (newFile && !newShowEditor) {
|
||||
// 使用文件ID+内容长度作为渲染标识,内容变化时重新渲染
|
||||
const renderKey = `${newFile.id}-${newFile.content?.length || 0}`;
|
||||
if (lastRenderedKey === renderKey) return;
|
||||
|
||||
// 使用 requestAnimationFrame 确保流畅渲染
|
||||
requestAnimationFrame(() => {
|
||||
const previewElement = document.querySelector('.markdown-preview');
|
||||
if (previewElement) {
|
||||
const contentToRender = (newFile.isPrivate === 1 && !userStore.isLoggedIn) ? privateNoteContent : newFile.content;
|
||||
Vditor.preview(previewElement, contentToRender || '', {
|
||||
mode: 'light',
|
||||
hljs: { enable: true, style: 'github' }
|
||||
});
|
||||
lastRenderedKey = renderKey;
|
||||
}
|
||||
});
|
||||
// 处理 Markdown 内容中的图片 URL,将相对路径转换为完整路径
|
||||
const processImageUrls = (content) => {
|
||||
if (!content) return '';
|
||||
const baseUrl = import.meta.env.VITE_API_BASE_URL || '';
|
||||
if (!baseUrl) return content;
|
||||
|
||||
// 匹配 Markdown 图片语法 
|
||||
return content.replace(
|
||||
/!\[([^\]]*)\]\((\/api\/images\/preview\/[^)]+)\)/g,
|
||||
(_match, alt, relativeUrl) => {
|
||||
// 确保 URL 格式正确
|
||||
const fullUrl = baseUrl.endsWith('/') && relativeUrl.startsWith('/')
|
||||
? baseUrl + relativeUrl.substring(1)
|
||||
: baseUrl + relativeUrl;
|
||||
return ``;
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
// 渲染 Markdown 内容的函数
|
||||
const renderMarkdown = async (file) => {
|
||||
if (!file || showEditor.value) return;
|
||||
|
||||
// 使用文件ID+内容长度作为渲染标识,内容变化时重新渲染
|
||||
const renderKey = `${file.id}-${file.content?.length || 0}`;
|
||||
if (lastRenderedKey === renderKey) return;
|
||||
|
||||
// 如果正在加载中,等待加载完成再渲染
|
||||
if (file.isLoading) {
|
||||
return;
|
||||
}
|
||||
}, { deep: true });
|
||||
|
||||
// 等待 DOM 更新完成
|
||||
await nextTick();
|
||||
|
||||
// 使用 requestAnimationFrame 确保浏览器已完成布局和绘制
|
||||
requestAnimationFrame(() => {
|
||||
const previewElement = document.querySelector('.markdown-preview');
|
||||
if (previewElement) {
|
||||
let contentToRender = (file.isPrivate === 1 && !userStore.isLoggedIn) ? privateNoteContent : file.content;
|
||||
// 处理图片 URL
|
||||
contentToRender = processImageUrls(contentToRender);
|
||||
// 先清空内容,避免闪烁
|
||||
previewElement.innerHTML = '';
|
||||
Vditor.preview(previewElement, contentToRender || '', {
|
||||
mode: 'light',
|
||||
hljs: { enable: true, style: 'github' },
|
||||
after: () => {
|
||||
// 渲染完成后,如果文件有 isRendering 标记,移除它
|
||||
if (selectedFile.value && selectedFile.value.isRendering) {
|
||||
selectedFile.value = { ...selectedFile.value, isRendering: false };
|
||||
}
|
||||
// 为图片添加懒加载属性
|
||||
const images = previewElement.querySelectorAll('img');
|
||||
images.forEach(img => {
|
||||
if (!img.hasAttribute('loading')) {
|
||||
img.setAttribute('loading', 'lazy');
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
lastRenderedKey = renderKey;
|
||||
} else {
|
||||
// 如果元素不存在,100ms 后重试
|
||||
setTimeout(() => renderMarkdown(file), 100);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// 监听选中文件变化,自动渲染
|
||||
watch(() => selectedFile.value, (newFile) => {
|
||||
if (newFile && !showEditor.value) {
|
||||
renderMarkdown(newFile);
|
||||
} else if (!newFile) {
|
||||
// 用户返回列表页,重置渲染缓存
|
||||
lastRenderedKey = null;
|
||||
}
|
||||
}, { deep: true, immediate: true });
|
||||
|
||||
// 监听编辑器状态变化
|
||||
watch(showEditor, (isEditor) => {
|
||||
if (!isEditor && selectedFile.value) {
|
||||
renderMarkdown(selectedFile.value);
|
||||
}
|
||||
});
|
||||
|
||||
</script>
|
||||
|
||||
|
||||
@@ -32,9 +32,9 @@ const vditor = ref(null);
|
||||
const currentId = ref(null);
|
||||
const isInitialized = ref(false);
|
||||
const saveStatus = ref('');
|
||||
let saveTimeout = null;
|
||||
let lastSavedContent = ref('');
|
||||
let isSaving = ref(false);
|
||||
const saveTimeout = ref(null); // 修复:使用 ref 替代 let,确保响应式追踪
|
||||
const lastSavedContent = ref('');
|
||||
const isSaving = ref(false);
|
||||
// 维护当前最新的笔记数据
|
||||
const currentData = ref({ ...props.editData });
|
||||
|
||||
@@ -63,9 +63,9 @@ const initVditor = () => {
|
||||
input: (value) => {
|
||||
if (!isInitialized.value) return;
|
||||
|
||||
clearTimeout(saveTimeout);
|
||||
clearTimeout(saveTimeout.value);
|
||||
saveStatus.value = '正在输入...';
|
||||
saveTimeout = setTimeout(() => {
|
||||
saveTimeout.value = setTimeout(() => {
|
||||
if (!isSaving.value && value !== lastSavedContent.value) {
|
||||
save(value);
|
||||
}
|
||||
@@ -78,9 +78,14 @@ const initVditor = () => {
|
||||
if (!file) return;
|
||||
|
||||
uploadImage(file).then(res => {
|
||||
const url = res.url;
|
||||
// 后端返回相对路径,拼接成完整 URL
|
||||
const relativeUrl = res.url;
|
||||
const baseUrl = import.meta.env.VITE_API_BASE_URL || '';
|
||||
vditor.value.insertValue(``);
|
||||
// 确保 URL 格式正确,避免双斜杠
|
||||
const fullUrl = baseUrl.endsWith('/') && relativeUrl.startsWith('/')
|
||||
? baseUrl + relativeUrl.substring(1)
|
||||
: baseUrl + relativeUrl;
|
||||
vditor.value.insertValue(``);
|
||||
}).catch((error) => {
|
||||
// 错误已在 axios 拦截器中显示,这里不再重复显示
|
||||
console.error('图片上传失败:', error);
|
||||
@@ -185,7 +190,11 @@ onMounted(() => {
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
clearTimeout(saveTimeout);
|
||||
// 修复:确保清理定时器
|
||||
if (saveTimeout.value) {
|
||||
clearTimeout(saveTimeout.value);
|
||||
saveTimeout.value = null;
|
||||
}
|
||||
if (vditor.value) {
|
||||
vditor.value.destroy();
|
||||
vditor.value = null;
|
||||
|
||||
@@ -46,6 +46,11 @@
|
||||
<el-icon class="loading-icon is-loading"><Loading /></el-icon>
|
||||
<span class="loading-text">内容加载中...</span>
|
||||
</div>
|
||||
<!-- 渲染状态遮罩 -->
|
||||
<div v-else-if="file.isRendering" class="content-loading">
|
||||
<el-icon class="loading-icon is-loading"><Loading /></el-icon>
|
||||
<span class="loading-text">正在渲染...</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ export const useUserStore = defineStore('user', {
|
||||
state: () => ({
|
||||
token: '',
|
||||
userInfo: null,
|
||||
tokenExpiry: null, // 添加 Token 过期时间
|
||||
}),
|
||||
actions: {
|
||||
async login(username, password) {
|
||||
@@ -12,6 +13,9 @@ export const useUserStore = defineStore('user', {
|
||||
const response = await loginApi({ username, password });
|
||||
if (response && response.token) {
|
||||
this.token = response.token;
|
||||
// 解析 JWT 获取过期时间
|
||||
const payload = JSON.parse(atob(response.token.split('.')[1]));
|
||||
this.tokenExpiry = payload.exp * 1000; // 转换为毫秒
|
||||
if (response.userInfo) {
|
||||
this.userInfo = response.userInfo;
|
||||
}
|
||||
@@ -26,10 +30,16 @@ export const useUserStore = defineStore('user', {
|
||||
logout() {
|
||||
this.token = '';
|
||||
this.userInfo = null;
|
||||
this.tokenExpiry = null;
|
||||
},
|
||||
// 检查 Token 是否过期
|
||||
isTokenExpired() {
|
||||
if (!this.tokenExpiry) return true;
|
||||
return Date.now() >= this.tokenExpiry;
|
||||
},
|
||||
},
|
||||
getters: {
|
||||
isLoggedIn: (state) => !!state.token,
|
||||
isLoggedIn: (state) => !!state.token && Date.now() < (state.tokenExpiry || 0),
|
||||
// 添加:判断是否为管理员
|
||||
isAdmin: (state) => state.userInfo?.role === 'ADMIN',
|
||||
},
|
||||
@@ -38,7 +48,7 @@ export const useUserStore = defineStore('user', {
|
||||
strategies: [
|
||||
{
|
||||
key: 'user-store',
|
||||
storage: sessionStorage,
|
||||
storage: sessionStorage, // 使用 sessionStorage,比 localStorage 更安全
|
||||
}
|
||||
],
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user