| 49 | } |
| 50 | |
| 51 | setupMiddleware() { |
| 52 | // 安全中间件 |
| 53 | this.app.use(helmet({ |
| 54 | contentSecurityPolicy: { |
| 55 | directives: { |
| 56 | defaultSrc: ["'self'"], |
| 57 | styleSrc: ["'self'", "'unsafe-inline'"], |
| 58 | scriptSrc: ["'self'", "'unsafe-inline'"], |
| 59 | imgSrc: ["'self'", "data:", "https:"], |
| 60 | connectSrc: [ |
| 61 | "'self'", |
| 62 | // 🔧 生产环境:允许连接到当前域名 |
| 63 | "ws:", "wss:", |
| 64 | "http:", "https:" |
| 65 | ] |
| 66 | } |
| 67 | } |
| 68 | })); |
| 69 | |
| 70 | // CORS配置 - 支持生产环境 |
| 71 | this.app.use(cors({ |
| 72 | origin: (origin, callback) => { |
| 73 | // 允许无origin的请求(如移动应用、Postman等) |
| 74 | if (!origin) return callback(null, true); |
| 75 | |
| 76 | // 开发环境:允许localhost |
| 77 | if (origin.includes('localhost') || origin.includes('127.0.0.1')) { |
| 78 | return callback(null, true); |
| 79 | } |
| 80 | |
| 81 | // 生产环境:允许所有HTTPS域名 |
| 82 | const url = new URL(origin); |
| 83 | if (url.protocol === 'https:') { |
| 84 | console.log('🌐 允许HTTPS跨域访问:', origin); |
| 85 | return callback(null, true); |
| 86 | } |
| 87 | |
| 88 | // 允许HTTP(用于测试) |
| 89 | if (url.protocol === 'http:' && process.env.NODE_ENV !== 'production') { |
| 90 | console.log('🌐 允许HTTP跨域访问(非生产环境):', origin); |
| 91 | return callback(null, true); |
| 92 | } |
| 93 | |
| 94 | console.log('🚫 拒绝跨域访问:', origin); |
| 95 | callback(new Error('CORS策略不允许此来源')); |
| 96 | }, |
| 97 | credentials: true |
| 98 | })); |
| 99 | |
| 100 | // 压缩响应 |
| 101 | this.app.use(compression()); |
| 102 | |
| 103 | // 速率限制 |
| 104 | const limiter = rateLimit({ |
| 105 | windowMs: 15 * 60 * 1000, // 15分钟 |
| 106 | max: 1000, // 每个IP最多1000次请求 |
| 107 | message: { |
| 108 | error: '请求过于频繁,请稍后再试' |