rate limiting and api security enhancements

This commit is contained in:
2024-09-10 13:47:16 +02:00
parent 88991c9de0
commit 158a8ca0bb
4 changed files with 195 additions and 0 deletions

View File

@@ -1,6 +1,7 @@
import type { NextApiRequest, NextApiResponse } from 'next'
import sqlite3 from 'sqlite3'
import path from 'path'
import { rateLimit, getRateLimitHeaders } from '../../../lib/rate-limiter'
type CheckResponse = {
is_problematic: boolean
@@ -54,6 +55,19 @@ export default async function handler(
return res.status(405).json({ error: 'Method not allowed' })
}
// Rate limiting
const clientIp = req.headers['x-forwarded-for'] || req.connection?.remoteAddress || 'unknown'
const rateLimitResult = rateLimit(clientIp.toString())
const headers = getRateLimitHeaders(rateLimitResult)
Object.entries(headers).forEach(([key, value]) => {
res.setHeader(key, value)
})
if (!rateLimitResult.allowed) {
return res.status(429).json({ error: 'Too many requests' })
}
const { url } = req.query
if (!url || typeof url !== 'string') {