Check host on middleware instead

This commit is contained in:
austinkelsay 2024-09-30 19:16:35 -05:00
parent 5235e76855
commit a1f47e0dd3

View File

@ -9,7 +9,6 @@ const BACKEND_STAGING_URL = process.env.BACKEND_STAGING_URL
const ratelimit = new Ratelimit({
redis: kv,
// 5 requests from the same IP in 10 seconds
limiter: Ratelimit.slidingWindow(5, '10 s'),
});
@ -19,9 +18,9 @@ export const config = {
export default async function combinedMiddleware(request) {
const ip = request.ip ?? '127.0.0.1';
const origin = request.headers.get('origin') || '';
const pathname = request.nextUrl.pathname;
const host = request.headers.get('host');
console.log("Host", host)
// Allow access to .well-known paths
if (pathname.startsWith('/.well-known')) {
const { success } = await ratelimit.limit(ip);
@ -30,22 +29,23 @@ export default async function combinedMiddleware(request) {
: NextResponse.redirect(new URL('/blocked', request.url));
}
// Check if the request is coming from allowed origins
const allowedOrigins = [
// Check if the request is coming from allowed hosts
const allowedHosts = [
FRONTEND_HOSTNAME,
FRONTEND_STAGING_HOSTNAME,
BACKEND_URL,
BACKEND_STAGING_URL
new URL(BACKEND_URL).host,
new URL(BACKEND_STAGING_URL).host
].filter(Boolean);
console.log("Allowed hosts", allowedHosts)
if (!allowedOrigins.some(allowed => origin.startsWith(allowed))) {
if (!allowedHosts.includes(host)) {
return new NextResponse(JSON.stringify({ error: 'Forbidden' }), {
status: 403,
headers: { 'Content-Type': 'application/json' }
});
}
// Apply rate limiting for allowed origins
// Apply rate limiting for allowed hosts
const { success } = await ratelimit.limit(ip);
return success
? NextResponse.next()