import type { NextRequest } from "next/server"; import { NextResponse } from "next/server"; function unauthorized() { return new NextResponse("Authentication required", { status: 401, headers: { "WWW-Authenticate": 'Basic realm="IPv6 Admin"', }, }); } export function middleware(request: NextRequest) { const user = process.env.ADMIN_BASIC_AUTH_USER; const pass = process.env.ADMIN_BASIC_AUTH_PASS; if (!user || !pass) { return NextResponse.next(); } const auth = request.headers.get("authorization"); if (!auth?.startsWith("Basic ")) { return unauthorized(); } let decoded: string; try { decoded = atob(auth.slice(6)); } catch { return unauthorized(); } const colon = decoded.indexOf(":"); const u = colon >= 0 ? decoded.slice(0, colon) : ""; const p = colon >= 0 ? decoded.slice(colon + 1) : ""; if (u !== user || p !== pass) { return new NextResponse("Unauthorized", { status: 401 }); } return NextResponse.next(); } export const config = { matcher: ["/admin", "/admin/:path*"], };