Implement proper rate limiting for HF Spaces proxy environment
Browse filesInstead of disabling rate limiting, configure it properly for
Hugging Face Spaces:
- Higher limits due to shared proxy infrastructure
- Custom key generator using multiple headers
- Skip validation to avoid proxy configuration errors
- Maintain security while working with HF infrastructure
- server/index.ts +25 -3
server/index.ts
CHANGED
@@ -71,8 +71,20 @@ app.use(helmet({
|
|
71 |
|
72 |
// Rate limiting configuration for production (HF Spaces) vs development
|
73 |
const rateLimitConfig = process.env.NODE_ENV === 'production' ? {
|
74 |
-
// For HF Spaces -
|
75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
} : {
|
77 |
// For development - normal rate limiting
|
78 |
windowMs: 15 * 60 * 1000, // 15 minutes
|
@@ -87,7 +99,17 @@ const rateLimitConfig = process.env.NODE_ENV === 'production' ? {
|
|
87 |
const limiter = rateLimit(rateLimitConfig);
|
88 |
|
89 |
export const strictLimiter = process.env.NODE_ENV === 'production' ?
|
90 |
-
rateLimit({
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
91 |
rateLimit({
|
92 |
windowMs: 1 * 60 * 1000, // 1 minute
|
93 |
max: 10, // limit each IP to 10 requests per minute for sensitive endpoints
|
|
|
71 |
|
72 |
// Rate limiting configuration for production (HF Spaces) vs development
|
73 |
const rateLimitConfig = process.env.NODE_ENV === 'production' ? {
|
74 |
+
// For HF Spaces - configure for proxy environment
|
75 |
+
windowMs: 15 * 60 * 1000, // 15 minutes
|
76 |
+
max: 1000, // Higher limit since we can't reliably identify individual users
|
77 |
+
message: {
|
78 |
+
error: "Too many requests, please try again later."
|
79 |
+
},
|
80 |
+
standardHeaders: true,
|
81 |
+
legacyHeaders: false,
|
82 |
+
// Use a combination of headers for better user identification in proxy environment
|
83 |
+
keyGenerator: (req) => {
|
84 |
+
return req.ip + '|' + (req.headers['x-forwarded-for'] || req.headers['cf-connecting-ip'] || req.connection.remoteAddress);
|
85 |
+
},
|
86 |
+
// Skip validation that was causing the errors
|
87 |
+
validate: false,
|
88 |
} : {
|
89 |
// For development - normal rate limiting
|
90 |
windowMs: 15 * 60 * 1000, // 15 minutes
|
|
|
99 |
const limiter = rateLimit(rateLimitConfig);
|
100 |
|
101 |
export const strictLimiter = process.env.NODE_ENV === 'production' ?
|
102 |
+
rateLimit({
|
103 |
+
windowMs: 5 * 60 * 1000, // 5 minutes
|
104 |
+
max: 50, // More generous limit for production
|
105 |
+
message: {
|
106 |
+
error: "Too many requests, please try again later."
|
107 |
+
},
|
108 |
+
keyGenerator: (req) => {
|
109 |
+
return req.ip + '|' + (req.headers['x-forwarded-for'] || req.headers['cf-connecting-ip'] || req.connection.remoteAddress);
|
110 |
+
},
|
111 |
+
validate: false,
|
112 |
+
}) :
|
113 |
rateLimit({
|
114 |
windowMs: 1 * 60 * 1000, // 1 minute
|
115 |
max: 10, // limit each IP to 10 requests per minute for sensitive endpoints
|