Harden dashboard security surfaces

This commit is contained in:
Codex
2026-04-25 03:00:13 +00:00
parent 28dfa3074c
commit 5fc2ea78de
11 changed files with 323 additions and 172 deletions
+35 -7
View File
@@ -22,35 +22,63 @@ function isAssetPath(pathname: string) {
return pathname.startsWith("/_next/") || pathname.startsWith("/public/")
}
function withSecurityHeaders(response: NextResponse) {
response.headers.set("x-content-type-options", "nosniff")
response.headers.set("x-frame-options", "DENY")
response.headers.set("referrer-policy", "same-origin")
response.headers.set("permissions-policy", "camera=(), microphone=(), geolocation=()")
return response
}
function isStateChangingMethod(method: string) {
return !["GET", "HEAD", "OPTIONS"].includes(method.toUpperCase())
}
function hasTrustedOrigin(request: NextRequest) {
const origin = request.headers.get("origin")
if (!origin) return true
try {
return new URL(origin).origin === request.nextUrl.origin
} catch {
return false
}
}
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl
const settings = getAuthSettings()
if (isStateChangingMethod(request.method) && !hasTrustedOrigin(request)) {
return withSecurityHeaders(NextResponse.json({ ok: false, error: "Untrusted request origin" }, { status: 403 }))
}
if (settings.disabled || isAssetPath(pathname)) {
if (pathname === "/login") {
return NextResponse.redirect(new URL("/", request.url))
return withSecurityHeaders(NextResponse.redirect(new URL("/", request.url)))
}
return NextResponse.next()
return withSecurityHeaders(NextResponse.next())
}
if (isPublicPath(pathname)) {
if (pathname === "/login" && await verifySessionCookieValue(request.cookies.get(settings.cookieName)?.value)) {
return NextResponse.redirect(new URL("/", request.url))
return withSecurityHeaders(NextResponse.redirect(new URL("/", request.url)))
}
return NextResponse.next()
return withSecurityHeaders(NextResponse.next())
}
const authenticated = await verifySessionCookieValue(request.cookies.get(settings.cookieName)?.value)
if (authenticated) {
return NextResponse.next()
return withSecurityHeaders(NextResponse.next())
}
if (pathname.startsWith("/api/")) {
return NextResponse.json({ ok: false, error: "Authentication required" }, { status: 401 })
return withSecurityHeaders(NextResponse.json({ ok: false, error: "Authentication required" }, { status: 401 }))
}
const loginUrl = new URL("/login", request.url)
loginUrl.searchParams.set("next", `${pathname}${request.nextUrl.search}`)
return NextResponse.redirect(loginUrl)
return withSecurityHeaders(NextResponse.redirect(loginUrl))
}
export const config = {