fix: protect admin routes and ignore local docs
This commit is contained in:
1 parent
6a08db8dd0
commit
17264dfc06
6 files changed
+37
-413
No files matched your search
@@ -0,0 +1,14 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { shouldRedirectAdminRequest } from "./proxy-access";
|
||||
|
||||
describe("shouldRedirectAdminRequest", () => {
|
||||
it("redirects anonymous and non-staff admin requests before rendering", () => {
|
||||
expect(shouldRedirectAdminRequest("/admin", null)).toBe(true);
|
||||
expect(shouldRedirectAdminRequest("/admin/tickets", { rank: 1 })).toBe(true);
|
||||
});
|
||||
|
||||
it("allows staff admin requests and never affects public routes", () => {
|
||||
expect(shouldRedirectAdminRequest("/admin/permissions", { rank: 7 })).toBe(false);
|
||||
expect(shouldRedirectAdminRequest("/news", null)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
export interface ProxyToken {
|
||||
rank?: unknown;
|
||||
}
|
||||
|
||||
export function shouldRedirectAdminRequest(pathname: string, token: ProxyToken | null): boolean {
|
||||
if (pathname !== "/admin" && !pathname.startsWith("/admin/")) return false;
|
||||
const rank = typeof token?.rank === "number" ? token.rank : Number(token?.rank);
|
||||
return !Number.isInteger(rank) || rank < 7;
|
||||
}
|
||||
+11
-1
@@ -1,10 +1,20 @@
|
||||
import { type NextRequest, NextResponse } from "next/server";
|
||||
import { getToken } from "next-auth/jwt";
|
||||
import { shouldRedirectAdminRequest } from "@/lib/proxy-access";
|
||||
|
||||
// Edge proxy (formerly "middleware"): Prisma can't run here, so we only forward
|
||||
// the request path (so server components / the access guard can read it via
|
||||
// headers()) and normalize the real client IP. The DB-backed banned/maintenance
|
||||
// checks happen in src/lib/access-guard.ts (Node runtime) from the root layout.
|
||||
export function proxy(req: NextRequest) {
|
||||
export async function proxy(req: NextRequest) {
|
||||
if (req.nextUrl.pathname === "/admin" || req.nextUrl.pathname.startsWith("/admin/")) {
|
||||
const secret = process.env.AUTH_SECRET;
|
||||
const token = secret ? await getToken({ req, secret }) : null;
|
||||
if (shouldRedirectAdminRequest(req.nextUrl.pathname, token)) {
|
||||
return NextResponse.redirect(new URL("/login", req.url));
|
||||
}
|
||||
}
|
||||
|
||||
const headers = new Headers(req.headers);
|
||||
headers.set("x-pathname", req.nextUrl.pathname);
|
||||
const ip =
|
||||
|
||||
Reference in new issue
Block a user