Skip to content

Commit fc3f155

Browse files
tobenotcursoragent
andauthored
Implement comprehensive CORS solution with config, middleware, and testing (#4)
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
1 parent 555aa32 commit fc3f155

File tree

12 files changed

+1173
-28
lines changed

12 files changed

+1173
-28
lines changed

.env.example

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,27 @@
11
# 数据库配置
22
DATABASE_URL="postgresql://username:password@localhost:5432/database_name"
33

4-
# JWT密钥
5-
# 请使用一个长而随机的字符串,例如从 https://www.uuidgenerator.net/ 生成
4+
# JWT配置
65
JWT_SECRET="your-super-secret-jwt-key-here"
76

8-
# Resend邮件服务API密钥
7+
# 邮件配置
98
RESEND_API_KEY="your-resend-api-key-here"
9+
EMAIL_FROM="noreply@sendmail.tobenot.top"
1010

1111
# 服务器配置
1212
PORT=3000
1313
HOST=localhost
14+
NODE_ENV=development
1415

15-
# 前端URL配置
16+
# 前端配置
1617
FRONTEND_LOCAL_URL="http://localhost:5174"
1718
FRONTEND_PRODUCTION_URL="https://tobenot.top/Basic-Web-Game/#/demo-with-backend"
1819

19-
# 后端URL配置
20+
# 后端配置
2021
BACKEND_LOCAL_URL="http://localhost:3000"
21-
BACKEND_PRODUCTION_URL="https://api.tobenot.top"
22-
23-
# 邮件配置
24-
EMAIL_FROM="noreply@sendmail.tobenot.top"
25-
26-
# 环境配置
27-
NODE_ENV="development"
22+
BACKEND_PRODUCTION_URL="https://bwb.tobenot.top"
2823

29-
# 兼容旧版本的PUBLIC_URL(可选)
30-
PUBLIC_URL="http://localhost:3000"
24+
# CORS配置
25+
CORS_ENABLED=true
26+
CORS_MAX_AGE=86400
27+
CORS_ADDITIONAL_ORIGINS="https://your-additional-domain.com,https://another-domain.com"

CORS_GUIDE.md

Lines changed: 269 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,269 @@
1+
# 🔧 CORS配置指南
2+
3+
## 概述
4+
5+
我们实现了一个更强大、更灵活的CORS解决方案,相比之前的简单配置,新方案提供了:
6+
7+
-**集中管理**: 所有CORS逻辑都在专门的中间件中处理
8+
-**环境感知**: 根据环境自动调整CORS策略
9+
-**详细日志**: 完整的CORS请求日志和调试信息
10+
-**灵活配置**: 通过环境变量轻松配置
11+
-**测试工具**: 内置的CORS测试和调试工具
12+
13+
## 🏗️ 架构设计
14+
15+
### 文件结构
16+
```
17+
src/
18+
├── config/
19+
│ └── cors.ts # CORS配置管理
20+
├── middleware/
21+
│ ├── cors.ts # CORS中间件实现
22+
│ └── index.ts # 中间件导出
23+
├── routers/
24+
│ └── cors-debug.ts # CORS调试API
25+
├── utils/
26+
│ └── cors-test.ts # CORS测试工具
27+
└── server.ts # 主服务器文件
28+
```
29+
30+
### 核心组件
31+
32+
1. **CORS配置管理器** (`src/config/cors.ts`)
33+
- 集中管理所有CORS相关配置
34+
- 支持环境变量覆盖
35+
- 提供类型安全的配置接口
36+
37+
2. **CORS中间件** (`src/middleware/cors.ts`)
38+
- 处理预检请求 (OPTIONS)
39+
- 验证源白名单
40+
- 设置正确的CORS响应头
41+
42+
3. **调试工具** (`src/utils/cors-test.ts`)
43+
- 命令行CORS测试
44+
- 配置验证
45+
- 常见源测试
46+
47+
4. **调试API** (`src/routers/cors-debug.ts`)
48+
- RESTful API端点
49+
- 实时CORS配置查询
50+
- 源验证测试
51+
52+
## ⚙️ 配置选项
53+
54+
### 环境变量
55+
56+
| 变量名 | 默认值 | 说明 |
57+
|--------|--------|------|
58+
| `CORS_ENABLED` | `true` | 是否启用CORS中间件 |
59+
| `CORS_MAX_AGE` | `86400` | 预检请求缓存时间(秒) |
60+
| `CORS_ADDITIONAL_ORIGINS` | - | 额外的允许源(逗号分隔) |
61+
62+
### 配置示例
63+
64+
```bash
65+
# .env
66+
CORS_ENABLED=true
67+
CORS_MAX_AGE=86400
68+
CORS_ADDITIONAL_ORIGINS=https://myapp.com,https://admin.myapp.com
69+
```
70+
71+
## 🧪 测试和调试
72+
73+
### 1. 命令行测试
74+
75+
启动服务器时,会自动运行CORS配置测试:
76+
77+
```bash
78+
npm run dev
79+
```
80+
81+
输出示例:
82+
```
83+
🔧 CORS配置详情:
84+
==================================================
85+
启用状态: ✅ 启用
86+
环境: development
87+
最大缓存时间: 86400秒
88+
允许的方法: GET, HEAD, PUT, PATCH, POST, DELETE, OPTIONS
89+
允许的头部: Content-Type, Authorization, x-trpc-source, X-Requested-With, Accept, Origin
90+
支持凭据: 是
91+
允许的源:
92+
1. http://localhost:5174
93+
2. http://localhost:3000
94+
3. https://tobenot.top/Basic-Web-Game/#/demo-with-backend
95+
4. https://bwb.tobenot.top
96+
==================================================
97+
```
98+
99+
### 2. 浏览器测试
100+
101+
访问 `http://localhost:3000/cors-test.html` 使用可视化测试工具。
102+
103+
### 3. API测试
104+
105+
使用tRPC客户端测试:
106+
107+
```typescript
108+
// 获取CORS配置
109+
const config = await trpc.corsDebug.getConfig.query();
110+
111+
// 测试特定源
112+
const result = await trpc.corsDebug.testOrigin.query({
113+
origin: 'http://localhost:3000'
114+
});
115+
116+
// 健康检查
117+
const health = await trpc.corsDebug.health.query();
118+
```
119+
120+
## 🔍 常见问题解决
121+
122+
### 1. CORS错误排查
123+
124+
如果遇到CORS错误,请检查:
125+
126+
1. **源是否在白名单中**
127+
```bash
128+
# 查看当前允许的源
129+
curl http://localhost:3000/api/trpc/corsDebug.getConfig
130+
```
131+
132+
2. **环境变量是否正确**
133+
```bash
134+
# 检查环境变量
135+
echo $CORS_ENABLED
136+
echo $CORS_ADDITIONAL_ORIGINS
137+
```
138+
139+
3. **服务器日志**
140+
```bash
141+
# 查看CORS相关日志
142+
npm run dev | grep "CORS"
143+
```
144+
145+
### 2. 添加新的允许源
146+
147+
方法1:通过环境变量
148+
```bash
149+
export CORS_ADDITIONAL_ORIGINS="https://newdomain.com,https://app.newdomain.com"
150+
```
151+
152+
方法2:修改配置文件
153+
```typescript
154+
// src/config/cors.ts
155+
const baseOrigins = [
156+
// ... 现有源
157+
'https://newdomain.com',
158+
'https://app.newdomain.com',
159+
];
160+
```
161+
162+
### 3. 禁用CORS(不推荐)
163+
164+
```bash
165+
export CORS_ENABLED=false
166+
```
167+
168+
## 🚀 性能优化
169+
170+
### 1. 预检请求缓存
171+
172+
设置合适的 `CORS_MAX_AGE` 值:
173+
- 开发环境:`3600`(1小时)
174+
- 生产环境:`86400`(24小时)
175+
176+
### 2. 源白名单优化
177+
178+
- 生产环境只允许HTTPS源
179+
- 定期清理不再使用的源
180+
- 使用通配符时要谨慎
181+
182+
## 🔒 安全考虑
183+
184+
### 1. 源验证
185+
186+
- 严格验证Origin头
187+
- 不允许通配符 `*`
188+
- 生产环境只允许HTTPS
189+
190+
### 2. 凭据处理
191+
192+
- 设置 `credentials: true` 时要特别小心
193+
- 确保源白名单是可信的
194+
- 考虑使用 `SameSite` cookie属性
195+
196+
### 3. 头部限制
197+
198+
只允许必要的头部:
199+
```typescript
200+
allowedHeaders: [
201+
'Content-Type',
202+
'Authorization',
203+
'x-trpc-source'
204+
]
205+
```
206+
207+
## 📊 监控和日志
208+
209+
### 1. 日志格式
210+
211+
```
212+
🔍 CORS检查 - Origin: http://localhost:3000
213+
🔍 允许的源: ['http://localhost:3000', 'https://tobenot.top']
214+
🔍 源是否允许: true
215+
```
216+
217+
### 2. 错误日志
218+
219+
```
220+
❌ CORS拒绝 - Origin: https://malicious-site.com
221+
🔍 处理OPTIONS预检请求
222+
❌ 源不在白名单中,拒绝请求
223+
```
224+
225+
## 🔄 迁移指南
226+
227+
### 从旧配置迁移
228+
229+
1. **备份当前配置**
230+
```bash
231+
cp .env .env.backup
232+
```
233+
234+
2. **更新环境变量**
235+
```bash
236+
# 添加新的CORS配置
237+
echo "CORS_ENABLED=true" >> .env
238+
echo "CORS_MAX_AGE=86400" >> .env
239+
```
240+
241+
3. **测试新配置**
242+
```bash
243+
npm run dev
244+
# 访问 http://localhost:3000/cors-test.html
245+
```
246+
247+
4. **验证功能**
248+
- 测试所有前端应用
249+
- 检查API调用是否正常
250+
- 验证预检请求
251+
252+
## 📚 参考资源
253+
254+
- [MDN CORS文档](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)
255+
- [Fastify CORS插件](https://github.com/fastify/fastify-cors)
256+
- [tRPC CORS最佳实践](https://trpc.io/docs/server/cors)
257+
258+
## 🤝 贡献
259+
260+
如果你发现CORS相关的问题或有改进建议,请:
261+
262+
1. 使用测试工具复现问题
263+
2. 查看服务器日志
264+
3. 提交详细的错误报告
265+
4. 包含环境信息和配置
266+
267+
---
268+
269+
**注意**: 这个CORS解决方案专门为Fastify + tRPC架构设计,如果你使用其他框架,可能需要相应调整。

0 commit comments

Comments
 (0)