import { NextRequest, NextResponse } from "next/server"; import { getToken } from "next-auth/jwt"; export async function proxy(request: NextRequest) { const pathname = request.nextUrl.pathname; // ── ADMIN GUARD ────────────────────────────────────────────────────────── if (pathname.startsWith("/admin")) { // Allow the login page and NextAuth API routes through without session check if ( pathname === "/admin/login" || pathname.startsWith("/api/auth") ) { return NextResponse.next(); } const token = await getToken({ req: request, secret: process.env.NEXTAUTH_SECRET, }); if (!token) { const loginUrl = new URL("/admin/login", request.url); loginUrl.searchParams.set("callbackUrl", pathname); return NextResponse.redirect(loginUrl); } return NextResponse.next(); } // ── CLIENT TOKEN GUARD ─────────────────────────────────────────────────── if (pathname.startsWith("/c/")) { const tokenMatch = pathname.match(/^\/c\/([a-zA-Z0-9_-]+)/); if (!tokenMatch) { return NextResponse.rewrite(new URL("/not-found", request.url)); } const clientToken = tokenMatch[1]; try { // Call internal Node.js API route — Edge middleware cannot use postgres-js directly // postgres-js requires Node.js net/tls which are unavailable in the Edge runtime const validateUrl = new URL( `/api/internal/validate-token?token=${encodeURIComponent(clientToken)}`, request.url ); const res = await fetch(validateUrl.toString()); if (!res.ok) { return NextResponse.rewrite(new URL("/not-found", request.url)); } return NextResponse.next(); } catch { return NextResponse.rewrite(new URL("/not-found", request.url)); } } return NextResponse.next(); } export const config = { matcher: ["/admin/:path*", "/c/:path*"], };