import { NextRequest, NextResponse } from "next/server"; import { getSessionCookie } from "better-auth/cookies"; const PUBLIC_PATHS = ["/login", "/signup", "/verify-email", "/forgot-password", "/reset-password", "/api/auth", "/r/", "/u/", "/s/", "/docs", "/api/v1/openapi.json", "/api/webhooks", "/api/v1/invites/", "/api/internal/"]; const ADMIN_PATHS = ["/admin"]; export async function proxy(request: NextRequest) { const { pathname } = request.nextUrl; const isPublic = PUBLIC_PATHS.some((p) => pathname.startsWith(p)); const isAdmin = ADMIN_PATHS.some((p) => pathname.startsWith(p)); const isApi = pathname.startsWith("/api/v1"); if (isPublic) return NextResponse.next(); // API-key clients authenticate via `Authorization: Bearer ek_...`, not a // session cookie — they'd otherwise be rejected here before ever reaching // requireSessionOrApiKey (lib/api-auth.ts), which is the only place that // actually verifies the key. Defer to it instead of requiring a cookie. const authHeader = request.headers.get("authorization"); const hasApiKeyHeader = isApi && authHeader?.startsWith("Bearer ek_"); const sessionCookie = getSessionCookie(request); if (!sessionCookie && !hasApiKeyHeader) { if (isApi) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } return NextResponse.redirect(new URL("/login", request.url)); } if (isAdmin) { // Role check happens inside admin pages — middleware only checks auth // Full role verification requires DB lookup, done server-side in admin layout } return NextResponse.next(); } export default proxy; export const config = { matcher: [ "/((?!_next/static|_next/image|favicon.ico|icon.svg|icon-192.svg|icon-512.svg|manifest.webmanifest|sw.js|public/).*)", ], };