import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; const mocks = vi.hoisted(() => ({ session: vi.fn(), auth: vi.fn() })); vi.mock("server-only", () => ({})); vi.mock("@/db", () => ({ getDb: () => ({}) })); vi.mock("next/headers", () => ({ headers: async () => new Headers() })); vi.mock("better-auth", () => ({ betterAuth: mocks.auth })); vi.mock("better-auth/adapters/drizzle", () => ({ drizzleAdapter: () => ({}) })); vi.mock("better-auth/next-js", () => ({ nextCookies: () => ({}) })); vi.mock("better-auth/plugins", () => ({ admin: (options: unknown) => options, captcha: () => ({}) })); beforeEach(() => { vi.resetModules(); vi.stubEnv("NODE_ENV", "development"); vi.stubEnv("DATABASE_URL", "postgresql://test.invalid/test"); vi.stubEnv("BETTER_AUTH_URL", "https://guide.example.test"); vi.stubEnv("BETTER_AUTH_SECRET", "a-test-secret-with-more-than-32-characters"); mocks.auth.mockReturnValue({ api: { getSession: mocks.session } }); mocks.session.mockResolvedValue(null); }); afterEach(() => vi.unstubAllEnvs()); describe("actual administrator session boundary", () => { it("does not grant access when the old demo flag is enabled", async () => { vi.stubEnv("BUZZ_DEMO_MODE", "true"); const { getAdminSession, requireAdmin } = await import("./server"); expect(await getAdminSession()).toBeNull(); await expect(requireAdmin()).rejects.toMatchObject({ status: 401 }); }); it("rejects unprivileged users and revoked sessions", async () => { const { requireAdmin } = await import("./server"); const user = { id: "admin", email: "admin@test.invalid", emailVerified: true, role: "admin" }; mocks.session.mockResolvedValue({ user, session: { id: "session" } }); await expect(requireAdmin()).resolves.toMatchObject({ user: { id: "admin" } }); mocks.session.mockResolvedValue({ user: { ...user, role: "user" }, session: { id: "session" } }); await expect(requireAdmin()).rejects.toMatchObject({ status: 401 }); mocks.session.mockResolvedValue(null); await expect(requireAdmin()).rejects.toMatchObject({ status: 401 }); }); it("defaults accounts to user and requires strong new passwords", async () => { (await import("./server")).getAuth(); const options = mocks.auth.mock.calls.at(-1)![0]; expect(options.emailAndPassword).toMatchObject({ disableSignUp: true, minPasswordLength: 12 }); expect(options.plugins).toContainEqual({ defaultRole: "user" }); expect(options.rateLimit.customStorage.consume).toBeTypeOf("function"); expect(options.databaseHooks).toBeUndefined(); }); });