server.js 9.1 KB

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