server.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. const express = require('express');
  2. const path = require('path');
  3. const fs = require('fs').promises;
  4. const cors = require('cors');
  5. const app = express();
  6. const PORT = 3000;
  7. // index.md 缓存
  8. let indexCache = null;
  9. let indexCacheTime = 0;
  10. const CACHE_DURATION = 5000; // 5秒缓存
  11. // 路径安全验证函数 - 防止路径遍历攻击
  12. // 注意:此函数仅用于清理单个路径段(如分类名、文件名),不用于完整路径
  13. function sanitizePath(input) {
  14. if (!input || typeof input !== 'string') {
  15. return '';
  16. }
  17. // 安全清理策略:
  18. // 1. 移除路径遍历序列
  19. // 2. 移除开头的斜杠(防止绝对路径)
  20. // 3. 对于单个路径段,不应包含路径分隔符
  21. return input
  22. .replace(/\.\./g, '') // 移除 ..
  23. .replace(/^[\/\\]+/, ''); // 移除开头的 / 和 \
  24. }
  25. // 验证路径是否在允许的目录内
  26. function validatePath(fullPath, baseDir) {
  27. const resolvedPath = path.resolve(fullPath);
  28. const resolvedBaseDir = path.resolve(baseDir);
  29. return resolvedPath.startsWith(resolvedBaseDir);
  30. }
  31. // 中间件
  32. app.use(cors());
  33. app.use(express.json({ limit: '10mb' })); // 增加请求体大小限制到10MB
  34. app.use(express.urlencoded({ limit: '10mb', extended: true }));
  35. app.use(express.static('public'));
  36. // API: 获取图片资源
  37. app.get('/api/image/:category/*', async (req, res) => {
  38. try {
  39. // 对分类名进行处理(移除危险字符但保留中文)
  40. const category = req.params.category.replace(/\.\./g, '');
  41. const imagePath = req.params[0]; // 获取剩余路径部分,如 'assets/test.png'
  42. if (!category || !imagePath) {
  43. return res.status(400).json({ error: '无效的请求路径' });
  44. }
  45. const docsDir = path.join(__dirname, 'docs');
  46. const fullPath = path.join(docsDir, category, imagePath);
  47. // 验证路径安全性
  48. if (!validatePath(fullPath, docsDir)) {
  49. return res.status(403).json({ error: '拒绝访问' });
  50. }
  51. // 检查文件是否存在
  52. try {
  53. await fs.access(fullPath);
  54. } catch (err) {
  55. return res.status(404).json({ error: '图片不存在' });
  56. }
  57. // 发送图片文件
  58. res.sendFile(fullPath);
  59. } catch (error) {
  60. console.error('Error serving image:', error);
  61. res.status(500).json({ error: '无法加载图片' });
  62. }
  63. });
  64. // 获取 index.md 结构(带缓存)
  65. async function getIndexStructure() {
  66. const now = Date.now();
  67. if (indexCache && (now - indexCacheTime < CACHE_DURATION)) {
  68. return indexCache;
  69. }
  70. const indexPath = path.join(__dirname, 'index.md');
  71. const content = await fs.readFile(indexPath, 'utf-8');
  72. indexCache = parseIndexMd(content);
  73. indexCacheTime = now;
  74. return indexCache;
  75. }
  76. // API: 解析 index.md 结构
  77. app.get('/api/structure', async (req, res) => {
  78. try {
  79. const structure = await getIndexStructure();
  80. res.json(structure);
  81. } catch (error) {
  82. res.status(500).json({ error: '无法解析文档结构', details: error.message });
  83. }
  84. });
  85. // API: 获取指定分类的文档列表
  86. app.get('/api/category/:category', async (req, res) => {
  87. try {
  88. const category = sanitizePath(req.params.category);
  89. if (!category) {
  90. return res.status(400).json({ error: '无效的分类名称' });
  91. }
  92. const structure = await getIndexStructure();
  93. const categoryData = structure.find(cat => cat.name === category);
  94. if (!categoryData) {
  95. return res.status(404).json({ error: '分类不存在' });
  96. }
  97. res.json(categoryData);
  98. } catch (error) {
  99. res.status(500).json({ error: '无法获取分类信息', details: error.message });
  100. }
  101. });
  102. // API: 获取指定文档的内容
  103. app.get('/api/doc/:category/:docName', async (req, res) => {
  104. try {
  105. const category = sanitizePath(req.params.category);
  106. const docName = sanitizePath(req.params.docName);
  107. if (!category || !docName) {
  108. return res.status(400).json({ error: '无效的分类或文档名称' });
  109. }
  110. const docsDir = path.join(__dirname, 'docs');
  111. const docPath = path.join(docsDir, category, `${docName}.md`);
  112. // 验证路径是否在 docs 目录内
  113. if (!validatePath(docPath, docsDir)) {
  114. return res.status(403).json({ error: '拒绝访问:无效的路径' });
  115. }
  116. const content = await fs.readFile(docPath, 'utf-8');
  117. res.json({ content, category, docName });
  118. } catch (error) {
  119. res.status(500).json({ error: '无法读取文档', details: error.message });
  120. }
  121. });
  122. // API: 保存文档内容
  123. app.put('/api/doc/:category/:docName', async (req, res) => {
  124. try {
  125. const category = sanitizePath(req.params.category);
  126. const docName = sanitizePath(req.params.docName);
  127. const { content } = req.body;
  128. // 验证输入
  129. if (!category || !docName) {
  130. return res.status(400).json({ error: '无效的分类或文档名称' });
  131. }
  132. if (!content || typeof content !== 'string') {
  133. return res.status(400).json({ error: '无效的文档内容' });
  134. }
  135. const docsDir = path.join(__dirname, 'docs');
  136. const docPath = path.join(docsDir, category, `${docName}.md`);
  137. // 验证路径是否在 docs 目录内
  138. if (!validatePath(docPath, docsDir)) {
  139. return res.status(403).json({ error: '拒绝访问:无效的路径' });
  140. }
  141. // 检查文件是否存在
  142. try {
  143. await fs.access(docPath);
  144. } catch (error) {
  145. return res.status(404).json({ error: '文档不存在' });
  146. }
  147. // 保存文件
  148. await fs.writeFile(docPath, content, 'utf-8');
  149. res.json({
  150. success: true,
  151. message: '文档保存成功',
  152. category,
  153. docName
  154. });
  155. } catch (error) {
  156. console.error('Save document error:', error);
  157. res.status(500).json({ error: '无法保存文档', details: error.message });
  158. }
  159. });
  160. // API: 搜索文档
  161. app.get('/api/search/:category', async (req, res) => {
  162. try {
  163. const category = sanitizePath(req.params.category);
  164. const currentDoc = sanitizePath(req.query.currentDoc);
  165. const { q } = req.query;
  166. if (!category) {
  167. return res.status(400).json({ error: '无效的分类名称' });
  168. }
  169. if (!q || q.trim().length === 0) {
  170. return res.json({ currentDoc: [], otherDocs: [] });
  171. }
  172. const query = q.toLowerCase();
  173. const docsDir = path.join(__dirname, 'docs');
  174. const categoryPath = path.join(docsDir, category);
  175. // 验证路径是否在 docs 目录内
  176. if (!validatePath(categoryPath, docsDir)) {
  177. return res.status(403).json({ error: '拒绝访问:无效的路径' });
  178. }
  179. // 读取分类下的所有文档
  180. const files = await fs.readdir(categoryPath);
  181. const mdFiles = files.filter(file => file.endsWith('.md'));
  182. const currentDocResults = [];
  183. const otherDocsResults = [];
  184. // 搜索每个文档
  185. for (const file of mdFiles) {
  186. const docName = file.replace('.md', '');
  187. const filePath = path.join(categoryPath, file);
  188. const content = await fs.readFile(filePath, 'utf-8');
  189. // 搜索匹配的行
  190. const lines = content.split('\n');
  191. const matches = [];
  192. lines.forEach((line, index) => {
  193. const lowerLine = line.toLowerCase();
  194. if (lowerLine.includes(query)) {
  195. // 获取上下文(前后各50个字符)
  196. const startIndex = Math.max(0, lowerLine.indexOf(query) - 50);
  197. const endIndex = Math.min(line.length, lowerLine.indexOf(query) + query.length + 50);
  198. let snippet = line.substring(startIndex, endIndex);
  199. // 如果不是从头开始,添加省略号
  200. if (startIndex > 0) snippet = '...' + snippet;
  201. if (endIndex < line.length) snippet = snippet + '...';
  202. matches.push({
  203. line: index + 1,
  204. snippet: snippet,
  205. fullLine: line
  206. });
  207. }
  208. });
  209. if (matches.length > 0) {
  210. const result = {
  211. docName,
  212. matchCount: matches.length,
  213. matches: matches.slice(0, 5) // 最多返回5个匹配
  214. };
  215. // 区分当前文档和其他文档
  216. if (docName === currentDoc) {
  217. currentDocResults.push(result);
  218. } else {
  219. otherDocsResults.push(result);
  220. }
  221. }
  222. }
  223. res.json({
  224. query: q,
  225. currentDoc: currentDocResults,
  226. otherDocs: otherDocsResults
  227. });
  228. } catch (error) {
  229. res.status(500).json({ error: '搜索失败', details: error.message });
  230. }
  231. });
  232. // 解析 index.md 的函数
  233. function parseIndexMd(content) {
  234. const lines = content.split('\n');
  235. const structure = [];
  236. let currentCategory = null;
  237. for (const line of lines) {
  238. const trimmedLine = line.trim();
  239. // 匹配分类 [category]
  240. const categoryMatch = trimmedLine.match(/^\[(.+?)\]$/);
  241. if (categoryMatch) {
  242. currentCategory = {
  243. name: categoryMatch[1],
  244. docs: []
  245. };
  246. structure.push(currentCategory);
  247. continue;
  248. }
  249. // 匹配文档项 1: testa.md 或 3.1: testc1.md
  250. const docMatch = trimmedLine.match(/^([\d.]+):\s*(.+?)\.md$/);
  251. if (docMatch && currentCategory) {
  252. const [, number, docName] = docMatch;
  253. const level = (number.match(/\./g) || []).length;
  254. currentCategory.docs.push({
  255. number,
  256. name: docName,
  257. level,
  258. fullName: `${docName}.md`
  259. });
  260. }
  261. }
  262. return structure;
  263. }
  264. // 启动服务器
  265. app.listen(PORT, () => {
  266. console.log(`服务器运行在 http://localhost:${PORT}`);
  267. });