2026-03-23 16:16:45 -05:00
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-23 16:39:03 -05:00
|
|
|
const [base] = raw.split(".");
|
|
|
|
|
if (!base) {
|
2026-03-23 16:16:45 -05:00
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const payload = JSON.parse(decodeBase64Url(base)) as { expiresAt?: number };
|
|
|
|
|
return typeof payload.expiresAt === "number" && payload.expiresAt > Date.now();
|
|
|
|
|
} catch {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-23 16:28:35 -05:00
|
|
|
export async function proxy(request: NextRequest) {
|
2026-03-23 16:16:45 -05:00
|
|
|
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: ["/((?!.*\\..*).*)"]
|
|
|
|
|
};
|