server.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. // 路径安全验证函数 - 防止路径遍历攻击
  8. function sanitizePath(input) {
  9. if (!input || typeof input !== 'string') {
  10. return '';
  11. }
  12. // 移除 ../ 和 ..\ 防止路径遍历
  13. // 移除开头的 / 和 \
  14. // 只保留字母、数字、连字符、下划线和点号
  15. return input
  16. .replace(/\.\./g, '')
  17. .replace(/^[\/\\]+/, '')
  18. .replace(/[\/\\]/g, '')
  19. .replace(/[^a-zA-Z0-9\-_.]/g, '');
  20. }
  21. // 验证路径是否在允许的目录内
  22. function validatePath(fullPath, baseDir) {
  23. const resolvedPath = path.resolve(fullPath);
  24. const resolvedBaseDir = path.resolve(baseDir);
  25. return resolvedPath.startsWith(resolvedBaseDir);
  26. }
  27. // 中间件
  28. app.use(cors());
  29. app.use(express.json());
  30. app.use(express.static('public'));
  31. // API: 获取 index.md 内容
  32. app.get('/api/index', async (req, res) => {
  33. try {
  34. const indexPath = path.join(__dirname, 'docs', 'index.md');
  35. const content = await fs.readFile(indexPath, 'utf-8');
  36. res.json({ content });
  37. } catch (error) {
  38. res.status(500).json({ error: '无法读取 index.md', details: error.message });
  39. }
  40. });
  41. // API: 解析 index.md 结构
  42. app.get('/api/structure', async (req, res) => {
  43. try {
  44. const indexPath = path.join(__dirname, 'docs', 'index.md');
  45. const content = await fs.readFile(indexPath, 'utf-8');
  46. // 解析结构
  47. const structure = parseIndexMd(content);
  48. res.json(structure);
  49. } catch (error) {
  50. res.status(500).json({ error: '无法解析文档结构', details: error.message });
  51. }
  52. });
  53. // API: 获取指定分类的文档列表
  54. app.get('/api/category/:category', async (req, res) => {
  55. try {
  56. const category = sanitizePath(req.params.category);
  57. if (!category) {
  58. return res.status(400).json({ error: '无效的分类名称' });
  59. }
  60. const indexPath = path.join(__dirname, 'docs', 'index.md');
  61. const content = await fs.readFile(indexPath, 'utf-8');
  62. // 解析并获取指定分类的文档
  63. const structure = parseIndexMd(content);
  64. const categoryData = structure.find(cat => cat.name === category);
  65. if (!categoryData) {
  66. return res.status(404).json({ error: '分类不存在' });
  67. }
  68. res.json(categoryData);
  69. } catch (error) {
  70. res.status(500).json({ error: '无法获取分类信息', details: error.message });
  71. }
  72. });
  73. // API: 获取指定文档的内容
  74. app.get('/api/doc/:category/:docName', async (req, res) => {
  75. try {
  76. const category = sanitizePath(req.params.category);
  77. const docName = sanitizePath(req.params.docName);
  78. if (!category || !docName) {
  79. return res.status(400).json({ error: '无效的分类或文档名称' });
  80. }
  81. const docsDir = path.join(__dirname, 'docs');
  82. const docPath = path.join(docsDir, category, `${docName}.md`);
  83. // 验证路径是否在 docs 目录内
  84. if (!validatePath(docPath, docsDir)) {
  85. return res.status(403).json({ error: '拒绝访问:无效的路径' });
  86. }
  87. const content = await fs.readFile(docPath, 'utf-8');
  88. res.json({ content, category, docName });
  89. } catch (error) {
  90. res.status(500).json({ error: '无法读取文档', details: error.message });
  91. }
  92. });
  93. // API: 搜索文档
  94. app.get('/api/search/:category', async (req, res) => {
  95. try {
  96. const category = sanitizePath(req.params.category);
  97. const currentDoc = sanitizePath(req.query.currentDoc);
  98. const { q } = req.query;
  99. if (!category) {
  100. return res.status(400).json({ error: '无效的分类名称' });
  101. }
  102. if (!q || q.trim().length === 0) {
  103. return res.json({ currentDoc: [], otherDocs: [] });
  104. }
  105. const query = q.toLowerCase();
  106. const docsDir = path.join(__dirname, 'docs');
  107. const categoryPath = path.join(docsDir, category);
  108. // 验证路径是否在 docs 目录内
  109. if (!validatePath(categoryPath, docsDir)) {
  110. return res.status(403).json({ error: '拒绝访问:无效的路径' });
  111. }
  112. // 读取分类下的所有文档
  113. const files = await fs.readdir(categoryPath);
  114. const mdFiles = files.filter(file => file.endsWith('.md'));
  115. const currentDocResults = [];
  116. const otherDocsResults = [];
  117. // 搜索每个文档
  118. for (const file of mdFiles) {
  119. const docName = file.replace('.md', '');
  120. const filePath = path.join(categoryPath, file);
  121. const content = await fs.readFile(filePath, 'utf-8');
  122. // 搜索匹配的行
  123. const lines = content.split('\n');
  124. const matches = [];
  125. lines.forEach((line, index) => {
  126. const lowerLine = line.toLowerCase();
  127. if (lowerLine.includes(query)) {
  128. // 获取上下文(前后各50个字符)
  129. const startIndex = Math.max(0, lowerLine.indexOf(query) - 50);
  130. const endIndex = Math.min(line.length, lowerLine.indexOf(query) + query.length + 50);
  131. let snippet = line.substring(startIndex, endIndex);
  132. // 如果不是从头开始,添加省略号
  133. if (startIndex > 0) snippet = '...' + snippet;
  134. if (endIndex < line.length) snippet = snippet + '...';
  135. matches.push({
  136. line: index + 1,
  137. snippet: snippet,
  138. fullLine: line
  139. });
  140. }
  141. });
  142. if (matches.length > 0) {
  143. const result = {
  144. docName,
  145. matchCount: matches.length,
  146. matches: matches.slice(0, 5) // 最多返回5个匹配
  147. };
  148. // 区分当前文档和其他文档
  149. if (docName === currentDoc) {
  150. currentDocResults.push(result);
  151. } else {
  152. otherDocsResults.push(result);
  153. }
  154. }
  155. }
  156. res.json({
  157. query: q,
  158. currentDoc: currentDocResults,
  159. otherDocs: otherDocsResults
  160. });
  161. } catch (error) {
  162. res.status(500).json({ error: '搜索失败', details: error.message });
  163. }
  164. });
  165. // 解析 index.md 的函数
  166. function parseIndexMd(content) {
  167. const lines = content.split('\n');
  168. const structure = [];
  169. let currentCategory = null;
  170. for (const line of lines) {
  171. const trimmedLine = line.trim();
  172. // 匹配分类 [category]
  173. const categoryMatch = trimmedLine.match(/^\[(.+?)\]$/);
  174. if (categoryMatch) {
  175. currentCategory = {
  176. name: categoryMatch[1],
  177. docs: []
  178. };
  179. structure.push(currentCategory);
  180. continue;
  181. }
  182. // 匹配文档项 1: testa.md 或 3.1: testc1.md
  183. const docMatch = trimmedLine.match(/^([\d.]+):\s*(.+?)\.md$/);
  184. if (docMatch && currentCategory) {
  185. const [, number, docName] = docMatch;
  186. const level = (number.match(/\./g) || []).length;
  187. currentCategory.docs.push({
  188. number,
  189. name: docName,
  190. level,
  191. fullName: `${docName}.md`
  192. });
  193. }
  194. }
  195. return structure;
  196. }
  197. // 启动服务器
  198. app.listen(PORT, () => {
  199. console.log(`服务器运行在 http://localhost:${PORT}`);
  200. });