refactor: 统一ID类型为Long并优化代码安全性和性能

修复用户删除接口的ID类型从Integer改为Long
移除未使用的Bouncy Castle依赖
添加dompurify依赖增强XSS防护
修复SQL表定义中的bigintBIGINT语法错误
优化图片预览接口的安全检查和错误处理
添加Vditor渲染引擎预加载和图片懒加载
统一分组和文件接口的ID类型为Long
增强前端用户状态管理,添加token过期检查
优化Markdown内容渲染流程和图片URL处理
This commit is contained in:
ikmkj
2026-03-04 16:27:42 +08:00
parent 25b52f87aa
commit 90626e73d9
23 changed files with 304 additions and 143 deletions

View File

@@ -126,13 +126,6 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId> <artifactId>spring-boot-starter-validation</artifactId>
</dependency> </dependency>
<!-- Bouncy Castle 加密库 -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk18on</artifactId>
<version>1.76</version>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@@ -84,4 +84,16 @@ public class GlobalExceptionHandler {
log.error("Unexpected error at {} - Error type: {}", request.getRequestURI(), e.getClass().getSimpleName()); log.error("Unexpected error at {} - Error type: {}", request.getRequestURI(), e.getClass().getSimpleName());
return R.fail(ResultCode.FAILED.getCode(), "系统繁忙,请稍后再试"); return R.fail(ResultCode.FAILED.getCode(), "系统繁忙,请稍后再试");
} }
// 修复:处理 IllegalStateExceptiongetWriter() 已调用等问题)
@ExceptionHandler(IllegalStateException.class)
public R<Void> handleIllegalStateException(IllegalStateException e, HttpServletRequest request) {
log.warn("Illegal state at {}: {}", request.getRequestURI(), e.getMessage());
// 如果是图片预览相关请求,可能是响应已经提交
if (request.getRequestURI().contains("/api/images/preview")) {
// 响应可能已经提交,直接返回 null避免再次写入响应
return null;
}
return R.fail(ResultCode.FAILED.getCode(), "请求处理失败");
}
} }

View File

@@ -52,11 +52,9 @@ public class GroupingController {
@PreAuthorize("hasRole('ADMIN')") @PreAuthorize("hasRole('ADMIN')")
@PutMapping("/{id}") @PutMapping("/{id}")
public R<Grouping> updateGrouping( public R<Grouping> updateGrouping(
@PathVariable String id, @PathVariable Long id,
@RequestBody Grouping grouping) { @RequestBody Grouping grouping) {
grouping.setId(id);
long l = Long.parseLong(id);
grouping.setId(l);
Grouping updated = groupingService.updateGrouping(grouping); Grouping updated = groupingService.updateGrouping(grouping);
return R.success(updated); return R.success(updated);
} }
@@ -64,9 +62,8 @@ public class GroupingController {
@Operation(summary = "删除分组") @Operation(summary = "删除分组")
@PreAuthorize("hasRole('ADMIN')") @PreAuthorize("hasRole('ADMIN')")
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public R<Void> deleteGrouping(@PathVariable String id) { public R<Void> deleteGrouping(@PathVariable Long id) {
Long idLong = Long.parseLong(id); groupingService.deleteGrouping(id);
groupingService.deleteGrouping(idLong);
return R.success(); return R.success();
} }
} }

View File

@@ -81,43 +81,48 @@ public class ImageController {
@Operation(summary = "在线预览", description = "浏览器直接打开文件流") @Operation(summary = "在线预览", description = "浏览器直接打开文件流")
@GetMapping("/preview/{url}") @GetMapping("/preview/{url}")
public void preview(@PathVariable String url, HttpServletResponse resp) throws IOException { public void preview(@PathVariable String url, HttpServletResponse resp) throws IOException {
// 修复:使用 try-with-resources 确保 PrintWriter 关闭 // 注意:不能同时调用 resp.getWriter() 和 resp.getOutputStream()
try (PrintWriter writer = resp.getWriter()) {
if (StrUtil.isBlank(url)) { if (StrUtil.isBlank(url)) {
resp.setStatus(404); resp.setStatus(404);
writer.write("{\"code\":404,\"msg\":\"文件不存在\",\"data\":null}"); resp.setContentType("application/json;charset=UTF-8");
return; resp.getWriter().write("{\"code\":404,\"msg\":\"文件不存在\",\"data\":null}");
} return;
}
String sanitizedUrl = sanitizeFileName(url);
if (sanitizedUrl == null) { String sanitizedUrl = sanitizeFileName(url);
resp.setStatus(403); if (sanitizedUrl == null) {
writer.write("{\"code\":403,\"msg\":\"非法文件路径\",\"data\":null}"); resp.setStatus(403);
return; resp.setContentType("application/json;charset=UTF-8");
} resp.getWriter().write("{\"code\":403,\"msg\":\"非法文件路径\",\"data\":null}");
return;
Path basePath = Paths.get(rootPath).normalize().toAbsolutePath(); }
Path filePath = basePath.resolve(sanitizedUrl).normalize();
Path basePath = Paths.get(rootPath).normalize().toAbsolutePath();
if (!filePath.startsWith(basePath)) { Path filePath = basePath.resolve(sanitizedUrl).normalize();
resp.setStatus(403);
writer.write("{\"code\":403,\"msg\":\"非法文件路径\",\"data\":null}"); if (!filePath.startsWith(basePath)) {
return; resp.setStatus(403);
} resp.setContentType("application/json;charset=UTF-8");
resp.getWriter().write("{\"code\":403,\"msg\":\"非法文件路径\",\"data\":null}");
File file = filePath.toFile(); return;
if (!file.exists() || !file.isFile()) { }
resp.setStatus(404);
writer.write("{\"code\":404,\"msg\":\"文件不存在\",\"data\":null}"); File file = filePath.toFile();
return; if (!file.exists() || !file.isFile()) {
} resp.setStatus(404);
resp.setContentType("application/json;charset=UTF-8");
String contentTypeFromFileExtension = getContentTypeFromFileExtension(url); resp.getWriter().write("{\"code\":404,\"msg\":\"文件不存在\",\"data\":null}");
resp.setContentType(contentTypeFromFileExtension); return;
resp.setContentLengthLong(file.length()); }
try (FileInputStream in = new FileInputStream(file)) {
StreamUtils.copy(in, resp.getOutputStream()); String contentTypeFromFileExtension = getContentTypeFromFileExtension(url);
} resp.setContentType(contentTypeFromFileExtension);
resp.setContentLengthLong(file.length());
// 文件流直接输出,不使用 try-with-resources 包装整个方法
try (FileInputStream in = new FileInputStream(file)) {
StreamUtils.copy(in, resp.getOutputStream());
resp.getOutputStream().flush();
} }
} }
@@ -125,7 +130,9 @@ public class ImageController {
if (StrUtil.isBlank(fileName)) { if (StrUtil.isBlank(fileName)) {
return null; return null;
} }
if (fileName.contains("..") || fileName.contains("/") || fileName.contains("\\") || fileName.contains(":")) { // 修复:使用白名单验证文件名格式(只允许 UUID 格式)
// 例如550e8400-e29b-41d4-a716-446655440000.jpg
if (!fileName.matches("^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\\.[a-zA-Z0-9]+$")) {
return null; return null;
} }
return fileName; return fileName;
@@ -162,6 +169,7 @@ public class ImageController {
} }
String extension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase(); String extension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
// 使用更安全的 MIME 类型映射,只允许图片类型
switch (extension) { switch (extension) {
case "jpg": case "jpg":
case "jpeg": case "jpeg":
@@ -177,8 +185,27 @@ public class ImageController {
case "svg": case "svg":
return "image/svg+xml"; return "image/svg+xml";
default: default:
// 对于未知的扩展名,返回通用的二进制流类型,避免执行风险
return "application/octet-stream"; return "application/octet-stream";
} }
} }
/**
* 验证文件是否为允许的图片类型
* @param contentType 文件内容类型
* @return 是否允许
*/
private boolean isAllowedImageType(String contentType) {
if (StrUtil.isBlank(contentType)) {
return false;
}
// 只允许标准的图片 MIME 类型
return contentType.equals("image/jpeg") ||
contentType.equals("image/png") ||
contentType.equals("image/gif") ||
contentType.equals("image/bmp") ||
contentType.equals("image/webp") ||
contentType.equals("image/svg+xml");
}
} }

View File

@@ -85,7 +85,7 @@ public class MarkdownController {
@Operation(summary = "根据分组ID获取Markdown文件") @Operation(summary = "根据分组ID获取Markdown文件")
@GetMapping("/grouping/{groupingId}") @GetMapping("/grouping/{groupingId}")
public R<List<MarkdownFileVO>> getFilesByGroupingId(@PathVariable String groupingId) { public R<List<MarkdownFileVO>> getFilesByGroupingId(@PathVariable Long groupingId) {
List<MarkdownFileVO> files = markdownFileService.getFilesByGroupingId(groupingId); List<MarkdownFileVO> files = markdownFileService.getFilesByGroupingId(groupingId);
return R.success(files); return R.success(files);
} }

View File

@@ -112,7 +112,7 @@ public class UserController {
return R.fail("无法获取用户信息,删除失败"); return R.fail("无法获取用户信息,删除失败");
} }
userService.deleteUser(user.getId().intValue()); userService.deleteUser(user.getId());
return R.success("用户删除成功"); return R.success("用户删除成功");
} }

View File

@@ -34,7 +34,7 @@ public interface MarkdownFileMapper extends BaseMapper<MarkdownFile> {
"LEFT JOIN `grouping` g ON mf.grouping_id = g.id " + "LEFT JOIN `grouping` g ON mf.grouping_id = g.id " +
"WHERE mf.grouping_id = #{groupingId} AND mf.is_deleted = 0 " + "WHERE mf.grouping_id = #{groupingId} AND mf.is_deleted = 0 " +
"ORDER BY mf.updated_at DESC") "ORDER BY mf.updated_at DESC")
List<MarkdownFileVO> selectByGroupingIdWithGrouping(@Param("groupingId") String groupingId); List<MarkdownFileVO> selectByGroupingIdWithGrouping(@Param("groupingId") Long groupingId);
/** /**
* 查询已删除的笔记不包含content大字段 * 查询已删除的笔记不包含content大字段

View File

@@ -28,7 +28,7 @@ public interface MarkdownFileService extends IService<MarkdownFile> {
* @param groupingId 分组ID * @param groupingId 分组ID
* @return 文件列表 * @return 文件列表
*/ */
List<MarkdownFileVO> getFilesByGroupingId(String groupingId); List<MarkdownFileVO> getFilesByGroupingId(Long groupingId);
/** /**
* 删除Markdown文件 * 删除Markdown文件

View File

@@ -27,7 +27,7 @@ public interface UserService extends IService<User> {
* 用户删除 * 用户删除
* @param id 用户id * @param id 用户id
*/ */
void deleteUser(Integer id); void deleteUser(Long id);
/** /**
* 查询用户token是否过期 * 查询用户token是否过期

View File

@@ -40,11 +40,15 @@ public class GroupingServiceImpl
@Override @Override
public List<Grouping> getAllGroupings(Long parentId) { public List<Grouping> getAllGroupings(Long parentId) {
if (ObjectUtil.isNull(parentId)){ LambdaQueryWrapper<Grouping> queryWrapper = new LambdaQueryWrapper<>();
return groupingMapper.selectList(null); // 只查询未删除的分组
queryWrapper.eq(Grouping::getIsDeleted, 0);
if (ObjectUtil.isNotNull(parentId)){
queryWrapper.eq(Grouping::getParentId, parentId);
} }
return groupingMapper.selectList(new LambdaQueryWrapper<Grouping>() // 限制最大返回数量,防止内存溢出
.eq(Grouping::getParentId, parentId)); queryWrapper.last("LIMIT 1000");
return groupingMapper.selectList(queryWrapper);
} }
@Override @Override

View File

@@ -103,6 +103,7 @@ public class ImageServiceImpl
Image image = new Image(); Image image = new Image();
image.setOriginalName(originalFilename); image.setOriginalName(originalFilename);
image.setStoredName(storedName); image.setStoredName(storedName);
// 返回相对路径,前端会根据环境自动拼接 baseURL
image.setUrl("/api/images/preview/" + storedName); image.setUrl("/api/images/preview/" + storedName);
image.setSize(file.getSize()); image.setSize(file.getSize());
image.setContentType(contentType); image.setContentType(contentType);

View File

@@ -2,6 +2,7 @@ package com.test.bijihoudaun.service.impl;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
@@ -105,7 +106,7 @@ public class MarkdownFileServiceImpl
@Override @Override
public List<MarkdownFileVO> getFilesByGroupingId(String groupingId) { public List<MarkdownFileVO> getFilesByGroupingId(Long groupingId) {
return markdownFileMapper.selectByGroupingIdWithGrouping(groupingId); return markdownFileMapper.selectByGroupingIdWithGrouping(groupingId);
} }
@@ -130,13 +131,12 @@ public class MarkdownFileServiceImpl
@Override @Override
public List<MarkdownFile> searchByTitle(String keyword) { public List<MarkdownFile> searchByTitle(String keyword) {
// 修复:转义特殊字符防止 SQL 注入 // 修复:使用 LambdaQueryWrapper 避免 SQL 注入风险
if (keyword == null || keyword.trim().isEmpty()) { if (keyword == null || keyword.trim().isEmpty()) {
return List.of(); return List.of();
} }
String escapedKeyword = keyword.replace("%", "\\%").replace("_", "\\_"); LambdaQueryWrapper<MarkdownFile> queryWrapper = new LambdaQueryWrapper<>();
QueryWrapper<MarkdownFile> queryWrapper = new QueryWrapper<>(); queryWrapper.like(MarkdownFile::getTitle, keyword);
queryWrapper.like("title", escapedKeyword);
return this.list(queryWrapper); return this.list(queryWrapper);
} }

View File

@@ -13,7 +13,6 @@ import com.test.bijihoudaun.service.UserService;
import com.test.bijihoudaun.util.JwtTokenUtil; import com.test.bijihoudaun.util.JwtTokenUtil;
import com.test.bijihoudaun.util.LoginLockUtil; import com.test.bijihoudaun.util.LoginLockUtil;
import com.test.bijihoudaun.util.PasswordUtils; import com.test.bijihoudaun.util.PasswordUtils;
import com.test.bijihoudaun.util.UuidV7;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
@@ -126,7 +125,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
} }
@Override @Override
public void deleteUser(Integer id) { public void deleteUser(Long id) {
userMapper.deleteById(id); userMapper.deleteById(id);
} }

View File

@@ -1,6 +1,6 @@
# 服务器配置
server: server:
port: 8084 port: 8084
forward-headers-strategy: framework
spring: spring:
web: web:
@@ -12,13 +12,16 @@ spring:
active: dev active: dev
servlet: servlet:
multipart: multipart:
max-file-size: 10MB # ???????5MB max-file-size: 10MB
max-request-size: 10MB # ???????5MB max-request-size: 10MB
# 文件上传路径
file: file:
upload-dir: uploads upload-dir: uploads
# 内存保护阈值 (MB)
#?? memory:
threshold: 100
## Snowflake ID????? ## Snowflake ID?????
@@ -29,11 +32,20 @@ worker:
datacenter: datacenter:
id: 1 id: 1
# JWT 配置 # JWT 配置
jwt: jwt:
secret: ${JWT_SECRET:V2VsbCwgSSBzdXBwb3NlIHRoYXQgaWYgeW91J3JlIHJlYWRpbmcgdGhpcywgeW91J3JlIHByZXR0eSBjdXJpb3VzLg==} secret: ${JWT_SECRET:V2VsbCwgSSBzdXBwb3NlIHRoYXQgaWYgeW91J3JlIHJlYWRpbmcgdGhpcywgeW91J3JlIHByZXR0eSBjdXJpb3VzLg==}
expiration: 86400 expiration: 86400
header: Authorization header: Authorization
tokenHead: "Bearer " tokenHead: "Bearer "
# 管理员用户名配置
admin:
username: ${ADMIN_USERNAME:admin}
# 日志配置
logging:
level:
com.test.bijihoudaun: INFO
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"

View File

@@ -10,6 +10,7 @@
"dependencies": { "dependencies": {
"@kangc/v-md-editor": "^2.2.4", "@kangc/v-md-editor": "^2.2.4",
"codemirror": "^6.0.1", "codemirror": "^6.0.1",
"dompurify": "^3.3.1",
"element-plus": "^2.7.6", "element-plus": "^2.7.6",
"highlight.js": "^11.11.1", "highlight.js": "^11.11.1",
"html2canvas": "^1.4.1", "html2canvas": "^1.4.1",
@@ -2585,10 +2586,13 @@
} }
}, },
"node_modules/dompurify": { "node_modules/dompurify": {
"version": "3.1.6", "version": "3.3.1",
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.1.6.tgz", "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.3.1.tgz",
"integrity": "sha512-cTOAhc36AalkjtBpfG6O8JimdTMWNXjiePT2xQH/ppBGi/4uIpmj8eKyIkMJErXWARyINV/sB38yf8JCLF5pbQ==", "integrity": "sha512-qkdCKzLNtrgPFP1Vo+98FRzJnBRGe4ffyCea9IwHB1fyxPOeNTHpLKYGd4Uk9xvNoH0ZoOjwZxNptyMwqrId1Q==",
"license": "(MPL-2.0 OR Apache-2.0)" "license": "(MPL-2.0 OR Apache-2.0)",
"optionalDependencies": {
"@types/trusted-types": "^2.0.7"
}
}, },
"node_modules/element-plus": { "node_modules/element-plus": {
"version": "2.10.4", "version": "2.10.4",
@@ -3414,16 +3418,6 @@
"html2canvas": "^1.0.0-rc.5" "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": { "node_modules/katex": {
"version": "0.13.24", "version": "0.13.24",
"resolved": "https://registry.npmjs.org/katex/-/katex-0.13.24.tgz", "resolved": "https://registry.npmjs.org/katex/-/katex-0.13.24.tgz",
@@ -3705,6 +3699,12 @@
"web-worker": "^1.2.0" "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": { "node_modules/mermaid/node_modules/katex": {
"version": "0.16.22", "version": "0.16.22",
"resolved": "https://registry.npmjs.org/katex/-/katex-0.16.22.tgz", "resolved": "https://registry.npmjs.org/katex/-/katex-0.16.22.tgz",

View File

@@ -13,6 +13,7 @@
"dependencies": { "dependencies": {
"@kangc/v-md-editor": "^2.2.4", "@kangc/v-md-editor": "^2.2.4",
"codemirror": "^6.0.1", "codemirror": "^6.0.1",
"dompurify": "^3.3.1",
"element-plus": "^2.7.6", "element-plus": "^2.7.6",
"highlight.js": "^11.11.1", "highlight.js": "^11.11.1",
"html2canvas": "^1.4.1", "html2canvas": "^1.4.1",
@@ -24,7 +25,7 @@
}, },
"devDependencies": { "devDependencies": {
"@vitejs/plugin-vue": "^5.0.5", "@vitejs/plugin-vue": "^5.0.5",
"vite": "^5.3.1", "terser": "^5.31.3",
"terser": "^5.31.3" "vite": "^5.3.1"
} }
} }

View File

@@ -2,8 +2,8 @@ import axiosApi from '@/utils/axios.js'
// 修复:使用 encodeURIComponent 编码 URL 参数,防止注入 // 根据分组ID获取Markdown文件列表
export const groupingId = (data) => axiosApi.get(`/api/markdown/grouping/${encodeURIComponent(data)}`) export const groupingId = (groupingId) => axiosApi.get(`/api/markdown/grouping/${encodeURIComponent(groupingId)}`)
// 获取所有分组 // 获取所有分组
export const groupingAll = (data) => { export const groupingAll = (data) => {
if (data) { if (data) {
@@ -71,16 +71,17 @@ export const register = (data) => {
const formData = new FormData() const formData = new FormData()
formData.append('username', data.username) formData.append('username', data.username)
formData.append('password', data.password) formData.append('password', data.password)
formData.append('email', data.email || '') // 修复:添加 email 参数
formData.append('registrationCode', data.registrationCode) formData.append('registrationCode', data.registrationCode)
return axiosApi.post('/api/user/register', formData, { return axiosApi.post('/api/user/register', formData, {
headers: { headers: {
'Content-Type': 'multipart/form-data' 'Content-Type': 'multipart/form-data'
} }
}) })
} }
// 更新分组名称 // 更新分组名称
// 修复:使用与后端 Grouping 实体类匹配的字段名
export const updateGroupingName = (id, newName) => { export const updateGroupingName = (id, newName) => {
return axiosApi.put(`/api/groupings/${id}`, { grouping: 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'
}
})
}

View File

@@ -130,11 +130,12 @@
</template> </template>
<script setup> <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 { ElMessage, ElMessageBox } from 'element-plus';
import Vditor from 'vditor'; import Vditor from 'vditor';
import 'vditor/dist/index.css'; import 'vditor/dist/index.css';
import { escapeHtml } from '@/utils/security'; import { escapeHtml } from '@/utils/security';
import DOMPurify from 'dompurify';
import { import {
groupingAll, groupingAll,
markdownList, markdownList,
@@ -197,6 +198,11 @@ const showSystemSettingsDialog = ref(false);
const showUpdatePasswordDialog = ref(false); const showUpdatePasswordDialog = ref(false);
const showPrivacyDialog = ref(false); const showPrivacyDialog = ref(false);
// Vditor 渲染引擎就绪状态
const vditorReady = ref(false);
// 提供给子组件使用
provide('vditorReady', vditorReady);
// Data for dialogs // Data for dialogs
const itemToRename = ref(null); const itemToRename = ref(null);
const fileToImport = ref(null); const fileToImport = ref(null);
@@ -369,8 +375,10 @@ const previewFile = async (file) => {
selectedFile.value = null; selectedFile.value = null;
return; return;
} }
// 重置渲染缓存,确保每次打开笔记都重新渲染
lastRenderedKey = null;
// 先立即显示预览页(加载状态),让用户感知到响应 // 先立即显示预览页(加载状态),让用户感知到响应
selectedFile.value = { ...file, content: '', isLoading: true }; selectedFile.value = { ...file, content: '', isLoading: true, isRendering: false };
showEditor.value = false; showEditor.value = false;
// 异步加载内容 // 异步加载内容
@@ -378,7 +386,9 @@ const previewFile = async (file) => {
const content = await Preview(file.id) || ''; const content = await Preview(file.id) || '';
// 内容加载完成后更新 // 内容加载完成后更新
if (selectedFile.value && selectedFile.value.id === 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) { } catch (error) {
// 错误已在 axios 拦截器中显示,这里不再重复显示 // 错误已在 axios 拦截器中显示,这里不再重复显示
@@ -507,9 +517,13 @@ const handleExport = async (format) => {
const blob = new Blob([content], { type: 'text/markdown;charset=utf-8' }); const blob = new Blob([content], { type: 'text/markdown;charset=utf-8' });
downloadBlob(blob, `${title}.md`); downloadBlob(blob, `${title}.md`);
} else if (format === 'html') { } else if (format === 'html') {
// 修复对title进行HTML转义防止XSS // 修复对title进行HTML转义使用DOMPurify清理内容防止XSS
const escapedTitle = escapeHtml(title); 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' }); const blob = new Blob([fullHtml], { type: 'text/html;charset=utf-8' });
downloadBlob(blob, `${escapedTitle}.html`); downloadBlob(blob, `${escapedTitle}.html`);
} else if (format === 'pdf') { } else if (format === 'pdf') {
@@ -555,8 +569,33 @@ onMounted(async () => {
await fetchGroupings(); await fetchGroupings();
await resetToHomeView(); await resetToHomeView();
window.addEventListener('resize', handleResize); 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(() => { onBeforeUnmount(() => {
window.removeEventListener('resize', handleResize); window.removeEventListener('resize', handleResize);
}); });
@@ -571,26 +610,91 @@ const handleResize = () => {
// Vditor 渲染优化 // Vditor 渲染优化
let lastRenderedKey = null; let lastRenderedKey = null;
watch([selectedFile, showEditor], ([newFile, newShowEditor]) => { // 处理 Markdown 内容中的图片 URL将相对路径转换为完整路径
if (newFile && !newShowEditor) { const processImageUrls = (content) => {
// 使用文件ID+内容长度作为渲染标识,内容变化时重新渲染 if (!content) return '';
const renderKey = `${newFile.id}-${newFile.content?.length || 0}`; const baseUrl = import.meta.env.VITE_API_BASE_URL || '';
if (lastRenderedKey === renderKey) return; if (!baseUrl) return content;
// 使用 requestAnimationFrame 确保流畅渲染 // 匹配 Markdown 图片语法 ![alt](/api/images/preview/xxx.png)
requestAnimationFrame(() => { return content.replace(
const previewElement = document.querySelector('.markdown-preview'); /!\[([^\]]*)\]\((\/api\/images\/preview\/[^)]+)\)/g,
if (previewElement) { (_match, alt, relativeUrl) => {
const contentToRender = (newFile.isPrivate === 1 && !userStore.isLoggedIn) ? privateNoteContent : newFile.content; // 确保 URL 格式正确
Vditor.preview(previewElement, contentToRender || '', { const fullUrl = baseUrl.endsWith('/') && relativeUrl.startsWith('/')
mode: 'light', ? baseUrl + relativeUrl.substring(1)
hljs: { enable: true, style: 'github' } : baseUrl + relativeUrl;
}); return `![${alt}](${fullUrl})`;
lastRenderedKey = renderKey; }
} );
}); };
// 渲染 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> </script>

View File

@@ -32,9 +32,9 @@ const vditor = ref(null);
const currentId = ref(null); const currentId = ref(null);
const isInitialized = ref(false); const isInitialized = ref(false);
const saveStatus = ref(''); const saveStatus = ref('');
let saveTimeout = null; const saveTimeout = ref(null); // 修复:使用 ref 替代 let确保响应式追踪
let lastSavedContent = ref(''); const lastSavedContent = ref('');
let isSaving = ref(false); const isSaving = ref(false);
// 维护当前最新的笔记数据 // 维护当前最新的笔记数据
const currentData = ref({ ...props.editData }); const currentData = ref({ ...props.editData });
@@ -63,9 +63,9 @@ const initVditor = () => {
input: (value) => { input: (value) => {
if (!isInitialized.value) return; if (!isInitialized.value) return;
clearTimeout(saveTimeout); clearTimeout(saveTimeout.value);
saveStatus.value = '正在输入...'; saveStatus.value = '正在输入...';
saveTimeout = setTimeout(() => { saveTimeout.value = setTimeout(() => {
if (!isSaving.value && value !== lastSavedContent.value) { if (!isSaving.value && value !== lastSavedContent.value) {
save(value); save(value);
} }
@@ -78,9 +78,14 @@ const initVditor = () => {
if (!file) return; if (!file) return;
uploadImage(file).then(res => { uploadImage(file).then(res => {
const url = res.url; // 后端返回相对路径,拼接成完整 URL
const relativeUrl = res.url;
const baseUrl = import.meta.env.VITE_API_BASE_URL || ''; const baseUrl = import.meta.env.VITE_API_BASE_URL || '';
vditor.value.insertValue(`![${file.name}](${baseUrl}${url})`); // 确保 URL 格式正确,避免双斜杠
const fullUrl = baseUrl.endsWith('/') && relativeUrl.startsWith('/')
? baseUrl + relativeUrl.substring(1)
: baseUrl + relativeUrl;
vditor.value.insertValue(`![${file.name}](${fullUrl})`);
}).catch((error) => { }).catch((error) => {
// 错误已在 axios 拦截器中显示,这里不再重复显示 // 错误已在 axios 拦截器中显示,这里不再重复显示
console.error('图片上传失败:', error); console.error('图片上传失败:', error);
@@ -185,7 +190,11 @@ onMounted(() => {
}); });
onBeforeUnmount(() => { onBeforeUnmount(() => {
clearTimeout(saveTimeout); // 修复:确保清理定时器
if (saveTimeout.value) {
clearTimeout(saveTimeout.value);
saveTimeout.value = null;
}
if (vditor.value) { if (vditor.value) {
vditor.value.destroy(); vditor.value.destroy();
vditor.value = null; vditor.value = null;

View File

@@ -46,6 +46,11 @@
<el-icon class="loading-icon is-loading"><Loading /></el-icon> <el-icon class="loading-icon is-loading"><Loading /></el-icon>
<span class="loading-text">内容加载中...</span> <span class="loading-text">内容加载中...</span>
</div> </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> </div>
</template> </template>

View File

@@ -5,6 +5,7 @@ export const useUserStore = defineStore('user', {
state: () => ({ state: () => ({
token: '', token: '',
userInfo: null, userInfo: null,
tokenExpiry: null, // 添加 Token 过期时间
}), }),
actions: { actions: {
async login(username, password) { async login(username, password) {
@@ -12,6 +13,9 @@ export const useUserStore = defineStore('user', {
const response = await loginApi({ username, password }); const response = await loginApi({ username, password });
if (response && response.token) { if (response && response.token) {
this.token = response.token; this.token = response.token;
// 解析 JWT 获取过期时间
const payload = JSON.parse(atob(response.token.split('.')[1]));
this.tokenExpiry = payload.exp * 1000; // 转换为毫秒
if (response.userInfo) { if (response.userInfo) {
this.userInfo = response.userInfo; this.userInfo = response.userInfo;
} }
@@ -26,10 +30,16 @@ export const useUserStore = defineStore('user', {
logout() { logout() {
this.token = ''; this.token = '';
this.userInfo = null; this.userInfo = null;
this.tokenExpiry = null;
},
// 检查 Token 是否过期
isTokenExpired() {
if (!this.tokenExpiry) return true;
return Date.now() >= this.tokenExpiry;
}, },
}, },
getters: { getters: {
isLoggedIn: (state) => !!state.token, isLoggedIn: (state) => !!state.token && Date.now() < (state.tokenExpiry || 0),
// 添加:判断是否为管理员 // 添加:判断是否为管理员
isAdmin: (state) => state.userInfo?.role === 'ADMIN', isAdmin: (state) => state.userInfo?.role === 'ADMIN',
}, },
@@ -38,7 +48,7 @@ export const useUserStore = defineStore('user', {
strategies: [ strategies: [
{ {
key: 'user-store', key: 'user-store',
storage: sessionStorage, storage: sessionStorage, // 使用 sessionStorage比 localStorage 更安全
} }
], ],
}, },

View File

@@ -6,7 +6,7 @@ SET FOREIGN_KEY_CHECKS = 0;
-- 1. 分组表 -- 1. 分组表
DROP TABLE IF EXISTS `grouping`; DROP TABLE IF EXISTS `grouping`;
CREATE TABLE `grouping` ( CREATE TABLE `grouping` (
`id` bigintBIGINT(20) NOT NULL AUTO_INCREMENT, `id` bigint(20) NOT NULL AUTO_INCREMENT,
`grouping` VARCHAR(255) NOT NULL, `grouping` VARCHAR(255) NOT NULL,
`parentId` BIGINT(20) DEFAULT NULL, `parentId` BIGINT(20) DEFAULT NULL,
`is_deleted` TINYINT(1) DEFAULT 0, `is_deleted` TINYINT(1) DEFAULT 0,

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB