import { NextResponse, type NextRequest } from "next/server"; import { sessionEnded, type SessionData } from "@/app/lib/sessionCodec"; import { openSession } from "@/app/lib/sessionSeal"; import { sessionCookieName } from "@/app/lib/sessionCookieName"; import { guardDecision, LANDING_FRAME_PATH, PREVIEW_FRAME_PATH } from "@/app/lib/routeGuard"; import { loginUrl } from "@/app/lib/returnTo"; import { isCrossSiteWrite } from "@/app/lib/sameOrigin"; import { bodyLimit } from "@/app/lib/bodyLimit"; import { contentSecurityPolicy, newNonce } from "@/app/lib/contentSecurityPolicy"; export async function middleware(req: NextRequest): Promise { const { pathname } = req.nextUrl; // harden-portal-requests (F29): API routes get only the same-origin write check, never the page guard. if (pathname === "/api" || pathname.startsWith("/api/")) { if (isCrossSiteWrite(req.method, req.headers)) { return NextResponse.json({ success: false, message: "Forbidden" }, { status: 403 }); } // bounded-request-bodies (F40): refuse a body larger than the route allows before any handler buffers it. const declared = Number(req.headers.get("content-length")); if (Number.isFinite(declared) && declared > bodyLimit(pathname)) { return NextResponse.json({ success: false, message: "Payload Too Large" }, { status: 413 }); } return NextResponse.next(); } // sign-session-cookies (F32): only a signed session cookie counts. const session = await openSession(req.cookies.get(sessionCookieName())?.value); // enforce-session-timeouts: a session past its idle limit or cap is no session. return guard(req, session && !sessionEnded(session, Math.floor(Date.now() / 1000)) ? session : null); } function guard(req: NextRequest, session: SessionData | null): NextResponse { const { pathname } = req.nextUrl; const state = session ? { present: true, resetRequired: session.resetPasswordRequired } : null; const redirectTo = guardDecision(pathname, state); if (redirectTo && redirectTo !== pathname) { const url = req.nextUrl.clone(); url.pathname = redirectTo; url.search = ""; // admin-login-return-to: a page (not an API call) remembers where the admin was. if (redirectTo === "/login" && !pathname.startsWith("/api/")) { url.search = new URL(loginUrl(pathname + req.nextUrl.search), url).search; } return NextResponse.redirect(url); } // add-custom-html-block: a Custom HTML frame sends its own sandbox policy; the nonce policy would block its scripts. if (LANDING_FRAME_PATH.test(pathname) || PREVIEW_FRAME_PATH.test(pathname)) return NextResponse.next(); return withScriptPolicy(req); } // portal-script-nonce-csp (F30): a fresh nonce per page. The policy goes on the request too, so Next.js reads the // nonce and puts it on every script it renders. function withScriptPolicy(req: NextRequest): NextResponse { const policy = contentSecurityPolicy(newNonce(), process.env.NODE_ENV === "development"); const headers = new Headers(req.headers); headers.set("Content-Security-Policy", policy); const res = NextResponse.next({ request: { headers } }); res.headers.set("Content-Security-Policy", policy); return res; } export const config = { // Page routes (route guard) and API routes (same-origin write check, F29); skip Next internals and static files. // matcher-and-image-scope (F48): skip only known static extensions, so a dotted page path is still guarded. matcher: ["/api/:path*", "/((?!api|_next/static|_next/image|favicon\\.ico|manifest\\.json|.*\\.(?:png|jpe?g|gif|webp|avif|svg|ico|css|js|map|json|txt|xml|webmanifest|woff2?|ttf|otf)$).*)"], };