feat : 6 astra improve it
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
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: "[email protected]", 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();
|
||||
});
|
||||
});
|
||||
+18
-24
@@ -5,6 +5,7 @@ import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
||||
import { nextCookies } from "better-auth/next-js";
|
||||
import { admin, captcha } from "better-auth/plugins";
|
||||
import { headers } from "next/headers";
|
||||
import { cache } from "react";
|
||||
|
||||
import { getDb } from "@/db";
|
||||
import {
|
||||
@@ -15,6 +16,8 @@ import {
|
||||
} from "@/db/schema";
|
||||
|
||||
import { isAuthorizedAdmin, type SessionUserLike } from "./authorization";
|
||||
import { HttpError } from "@/lib/security/http";
|
||||
import { consumeRateLimit } from "@/lib/security/rate-limit";
|
||||
|
||||
function required(name: string): string {
|
||||
const value = process.env[name];
|
||||
@@ -50,16 +53,20 @@ function createAuth() {
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
disableSignUp: true,
|
||||
minPasswordLength: 8,
|
||||
minPasswordLength: 12,
|
||||
maxPasswordLength: 128,
|
||||
},
|
||||
databaseHooks: {
|
||||
user: {
|
||||
create: {
|
||||
before: async () => ({ data: { emailVerified: true } }),
|
||||
},
|
||||
advanced: {
|
||||
ipAddress: {
|
||||
ipAddressHeaders: process.env.TRUSTED_CLIENT_IP_HEADER
|
||||
? [process.env.TRUSTED_CLIENT_IP_HEADER] : [],
|
||||
},
|
||||
},
|
||||
rateLimit: {
|
||||
enabled: true,
|
||||
customStorage: { consume: (key, rule) => consumeRateLimit(`auth:${key}`, rule) },
|
||||
customRules: { "/sign-in/email": { window: 60, max: 10 } },
|
||||
},
|
||||
plugins: [
|
||||
...(process.env.NODE_ENV === "development" ? [] : [
|
||||
captcha({
|
||||
@@ -68,7 +75,7 @@ function createAuth() {
|
||||
endpoints: ["/sign-in/email"],
|
||||
}),
|
||||
]),
|
||||
admin({ defaultRole: "admin" }),
|
||||
admin({ defaultRole: "user" }),
|
||||
nextCookies(),
|
||||
],
|
||||
});
|
||||
@@ -87,20 +94,7 @@ export interface AdminSession {
|
||||
session: { id: string };
|
||||
}
|
||||
|
||||
export async function getAdminSession(): Promise<AdminSession | null> {
|
||||
if (process.env.BUZZ_DEMO_MODE === "true") {
|
||||
return {
|
||||
user: {
|
||||
id: "demo-admin",
|
||||
email: "[email protected]",
|
||||
emailVerified: true,
|
||||
role: "admin",
|
||||
name: "Demo Admin",
|
||||
},
|
||||
session: { id: "demo-session" },
|
||||
};
|
||||
}
|
||||
|
||||
export const getAdminSession = cache(async (): Promise<AdminSession | null> => {
|
||||
// Public pages can be prerendered without the runtime auth secret. In that
|
||||
// case the header simply omits the admin link; auth routes still fail loudly
|
||||
// through getAuth() when authentication is actually used.
|
||||
@@ -117,11 +111,11 @@ export async function getAdminSession(): Promise<AdminSession | null> {
|
||||
user: session.user,
|
||||
session: { id: session.session.id },
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
export class AdminAuthorizationError extends Error {
|
||||
export class AdminAuthorizationError extends HttpError {
|
||||
constructor() {
|
||||
super("Admin authorization required.");
|
||||
super(401, "unauthorized");
|
||||
this.name = "AdminAuthorizationError";
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user