import type { NextRequest } from "next/server"; import { NextResponse } from "next/server"; const SESSION_COOKIE = "inven_session"; function decodeBase64Url(value: string) { const normalized = value.replace(/-/g, "+").replace(/_/g, "/"); const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "="); return atob(padded); } async function hasValidSession(request: NextRequest) { const raw = request.cookies.get(SESSION_COOKIE)?.value; if (!raw) { return false; } const [base] = raw.split("."); if (!base) { return false; } try { const payload = JSON.parse(decodeBase64Url(base)) as { expiresAt?: number }; return typeof payload.expiresAt === "number" && payload.expiresAt > Date.now(); } catch { return false; } } export async function proxy(request: NextRequest) { const { pathname } = request.nextUrl; const isPublic = pathname === "/login" || pathname.startsWith("/_next") || pathname.startsWith("/favicon") || pathname === "/api/health"; const authenticated = await hasValidSession(request); if (!authenticated && !isPublic) { const url = request.nextUrl.clone(); url.pathname = "/login"; return NextResponse.redirect(url); } if (authenticated && pathname === "/login") { const url = request.nextUrl.clone(); url.pathname = "/"; return NextResponse.redirect(url); } return NextResponse.next(); } export const config = { matcher: ["/((?!.*\\..*).*)"] };