import { describe, it, expect } from "vitest"; import { NextRequest } from "next/server"; import { middleware, config } from "./middleware"; const PROTECTED_PAGE = "/dashboard"; // harden-portal-requests (F29): the middleware refuses cross-site API writes before any route handler runs. function req(method: string, path: string, headers: Record): NextRequest { return new NextRequest(new URL(path, "https://portal.test"), { method, headers }); } describe("middleware: API writes", () => { it("answers 403 to a same-site POST", async () => { const res = await middleware(req("POST", "/api/member/change-password", { "sec-fetch-site": "same-site" })); expect(res.status).toBe(403); expect(await res.json()).toEqual({ success: false, message: "Forbidden" }); }); it("answers 403 to a foreign Origin without fetch metadata", async () => { const res = await middleware(req("DELETE", "/api/anything/1", { origin: "https://evil.example", host: "portal.test" })); expect(res.status).toBe(403); }); it("lets a same-origin POST through to the handler", async () => { const res = await middleware(req("POST", "/api/anything", { "sec-fetch-site": "same-origin" })); expect(res.status).toBe(200); expect(res.headers.get("x-middleware-next")).toBe("1"); }); it("lets a non-browser POST (no Sec-Fetch-Site, no Origin) through", async () => { const res = await middleware(req("POST", "/api/anything", { "content-type": "application/json" })); expect(res.headers.get("x-middleware-next")).toBe("1"); }); it("still sends a signed-out visitor on a member page to login", async () => { const res = await middleware(req("GET", PROTECTED_PAGE, {})); expect(res.status).toBeGreaterThanOrEqual(300); expect(res.status).toBeLessThan(400); expect(res.headers.get("location")).toContain("/login"); }); it("does not apply the page guard to API routes", async () => { const res = await middleware(req("GET", "/api/anything", { "sec-fetch-site": "cross-site" })); expect(res.headers.get("x-middleware-next")).toBe("1"); }); it("runs on API routes", async () => { const matchers = ([] as string[]).concat(config.matcher); expect(matchers.some(m => new RegExp(`^${m.replace(":path*", ".*")}$`).test("/api/member/change-password"))).toBe(true); }); });