import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { headers } from "next/headers"; import { skipAuth } from "@/lib/auth-mock"; /** * Dual auth check for API routes: * 1. If NEXT_PUBLIC_SKIP_AUTH=true → allow (dev mode) * 2. If X-API-Key header matches API_KEY env → allow (Gradio server-to-server) * 3. If valid browser session cookie → allow (Next.js UI) * 4. Otherwise → 401 Unauthorized * * Returns null if authorized, or a 401 Response to return early. */ export async function requireAuth(request: NextRequest): Promise { // Dev mode bypass if (skipAuth) return null; // API key auth (for Gradio / external clients) const apiKey = request.headers.get("x-api-key"); const expectedKey = process.env.API_KEY; if (apiKey && expectedKey && apiKey === expectedKey) return null; // Browser session auth (for Next.js UI) try { const session = await auth.api.getSession({ headers: await headers(), }); if (session) return null; } catch { // Session check failed — fall through to 401 } return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); }