chore: trust host header e validação centralizada de domínios

This commit is contained in:
Esdras Renan 2025-10-16 20:55:48 -03:00
parent c424febf1f
commit 508ffe5022
5 changed files with 173 additions and 205 deletions

View file

@ -1,5 +1,7 @@
import { NextRequest, NextResponse } from "next/server"
import { getCookieCache } from "better-auth/cookies"
import { NextRequest, NextResponse } from "next/server"
import { isAllowedHost } from "@/config/allowed-hosts"
// Rotas públicas explícitas (não autenticadas)
// Permite handshake de máquina sem sessão prévia para criar a sessão de máquina.
@ -9,8 +11,16 @@ const ADMIN_ONLY_PATHS = [/^\/admin(?:$|\/)/]
const APP_HOME = "/dashboard"
export async function middleware(request: NextRequest) {
if (process.env.NODE_ENV === "production" && !isAllowedHost(request.headers.get("host"))) {
return new NextResponse("Invalid Host header", { status: 403 })
}
const { pathname, search } = request.nextUrl
if (pathname.startsWith("/api")) {
return NextResponse.next()
}
if (PUBLIC_PATHS.some((pattern) => pattern.test(pathname))) return NextResponse.next()
const session = await getCookieCache(request)
@ -70,7 +80,7 @@ export async function middleware(request: NextRequest) {
export const config = {
runtime: "nodejs",
// Evita executar para assets e imagens estáticas
matcher: ["/((?!api|_next/static|_next/image|favicon.ico|icon.png).*)"],
matcher: ["/((?!_next/static|_next/image|favicon.ico|icon.png).*)"],
}
async function attemptSessionRefresh(request: NextRequest): Promise<NextResponse | null> {