From ee7be33fa150e923f5800c646687f3ea5e38927b Mon Sep 17 00:00:00 2001 From: shamoon <4887959+shamoon@users.noreply.github.com> Date: Mon, 27 Jan 2025 00:45:51 -0800 Subject: [PATCH] Security: support host header validation --- src/middleware.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 src/middleware.js diff --git a/src/middleware.js b/src/middleware.js new file mode 100644 index 00000000..7b7b088d --- /dev/null +++ b/src/middleware.js @@ -0,0 +1,17 @@ +import { NextResponse } from "next/server"; + +export function middleware(req) { + // Check the Host header, if HOMEPAGE_ALLOWED_HOSTS is set + const host = req.headers.get("host"); + const allowedHosts = process.env.HOMEPAGE_ALLOWED_HOSTS + ? process.env.HOMEPAGE_ALLOWED_HOSTS.split(",").concat(["localhost:3000"]) + : []; + if (allowedHosts.length && !(host || allowedHosts.includes(host))) { + return new NextResponse("Invalid Host header", { status: 400 }); + } + return NextResponse.next(); +} + +export const config = { + matcher: "/api/:path*", +};