import { NextResponse, type NextRequest } from "next/server"; /** * Edge-light routing guard: redirects unauthenticated visitors away from /app and /admin * based on the presence of the session cookie. Real verification happens server-side in * `requireUser()`; this only avoids a flash of protected UI. */ export function proxy(req: NextRequest) { const { pathname } = req.nextUrl; const hasSession = req.cookies.getAll().some((c) => /polyllm.*session_token/.test(c.name)); if ((pathname.startsWith("/app") || pathname.startsWith("/admin")) && !hasSession) { const url = req.nextUrl.clone(); url.pathname = "/login"; url.searchParams.set("next", pathname); return NextResponse.redirect(url); } if ((pathname === "/login" || pathname === "/signup") && hasSession) { // A stale/revoked session cookie: `requireUser()` sent the visitor here with ?expired=1. // Clear the cookies and show the login page instead of bouncing back to /app forever. if (req.nextUrl.searchParams.has("expired")) { const res = NextResponse.next(); for (const c of req.cookies.getAll()) if (/polyllm.*session/.test(c.name)) res.cookies.delete(c.name); return res; } const url = req.nextUrl.clone(); url.pathname = "/app/chat"; url.search = ""; return NextResponse.redirect(url); } return NextResponse.next(); } export const config = { matcher: ["/app/:path*", "/admin/:path*", "/login", "/signup"], };