Refactor: Replace library rate limit with custom Map-based implementation
This commit is contained in:
26
server.js
26
server.js
@@ -30,14 +30,14 @@ async function savePost(post) {
|
|||||||
return posts;
|
return posts;
|
||||||
}
|
}
|
||||||
|
|
||||||
// CaptchaLM Middleware
|
// Custom Rate Limiting
|
||||||
|
const rateLimitMap = new Map();
|
||||||
|
const RATE_LIMIT_WINDOW = 30000; // 30 seconds
|
||||||
|
|
||||||
|
// CaptchaLM Middleware (Rate limit removed)
|
||||||
const { protect, challenge } = createExpressMiddleware({
|
const { protect, challenge } = createExpressMiddleware({
|
||||||
secret: 'ai-twitter-secret-key-123',
|
secret: 'ai-twitter-secret-key-123',
|
||||||
difficulty: 'medium',
|
difficulty: 'medium',
|
||||||
rateLimit: {
|
|
||||||
maxAttempts: 1,
|
|
||||||
windowMs: 30000 // 30 seconds
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// --- API Endpoints ---
|
// --- API Endpoints ---
|
||||||
@@ -55,8 +55,20 @@ app.get('/api/posts', async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// 3. Create Post (Protected - AI Only)
|
// 3. Create Post (Protected - AI Only + Custom Rate Limit)
|
||||||
app.post('/api/posts', protect, async (req, res) => {
|
app.post('/api/posts', protect, async (req, res) => {
|
||||||
|
const ip = req.ip || req.socket.remoteAddress;
|
||||||
|
const lastPostTime = rateLimitMap.get(ip);
|
||||||
|
const now = Date.now();
|
||||||
|
|
||||||
|
if (lastPostTime && (now - lastPostTime < RATE_LIMIT_WINDOW)) {
|
||||||
|
const remaining = Math.ceil((RATE_LIMIT_WINDOW - (now - lastPostTime)) / 1000);
|
||||||
|
return res.status(429).json({
|
||||||
|
error: `Rate limited. Please wait ${remaining}s.`,
|
||||||
|
errorCode: 'RATE_LIMITED'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const { content, agentId = 'Unknown Agent' } = req.body;
|
const { content, agentId = 'Unknown Agent' } = req.body;
|
||||||
|
|
||||||
if (!content) {
|
if (!content) {
|
||||||
@@ -71,6 +83,8 @@ app.post('/api/posts', protect, async (req, res) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
await savePost(newPost);
|
await savePost(newPost);
|
||||||
|
rateLimitMap.set(ip, now); // Update rate limit timestamp
|
||||||
|
|
||||||
console.log(`[New Log] ${agentId}: ${content.substring(0, 50)}...`);
|
console.log(`[New Log] ${agentId}: ${content.substring(0, 50)}...`);
|
||||||
|
|
||||||
res.json({ success: true, post: newPost });
|
res.json({ success: true, post: newPost });
|
||||||
|
|||||||
Reference in New Issue
Block a user