local-file-operation-mcp
Version: 
本地文件操作 MCP 服务器:安全的读写、编辑、搜索、比较、哈希、权限、压缩、监控、命令与任务管理工具集。
62 lines (54 loc) • 1.43 kB
JavaScript
/**
 * 安全验证模块
 * 提供路径和命令的安全检查功能
 */
const path = require('path');
const os = require('os');
class SecurityValidator {
  constructor() {
    this.userHome = os.homedir();
  }
  isPathAllowed(filePath, workingDirectory = null) {
    try {
      // 解析为绝对路径:优先工作目录;否则相对用户主目录;绝对路径保持不变
      let absPath;
      if (path.isAbsolute(filePath)) {
        absPath = path.resolve(filePath);
      } else if (workingDirectory) {
        absPath = path.resolve(workingDirectory, filePath);
      } else {
        absPath = path.resolve(this.userHome, filePath);
      }
      
      // 仅允许用户主目录及其子目录
      const normalizedHome = path.resolve(this.userHome);
      if (absPath.startsWith(normalizedHome + path.sep) || absPath === normalizedHome) {
        return true;
      }
      return false;
    } catch (error) {
      return false;
    }
  }
  isDangerousCommand(command) {
    const dangerousCommands = [
      'rm -rf',
      'sudo',
      'su',
      'chmod 777',
      'chown',
      'passwd',
      'format',
      'del',
      'format c:',
      'shutdown',
      'reboot',
      'halt',
      'init 0',
      'init 6'
    ];
    
    return dangerousCommands.some(dangerous => 
      command.toLowerCase().includes(dangerous.toLowerCase())
    );
  }
}
module.exports = SecurityValidator;