Files
buzz-sheet/lib/auth/server.test.ts
T
gunshiz da5de3fa8c
CI / Verify (push) Failing after 57s
CI / Build immutable images and deploy (push) Skipped
feat(auth) : add optional email verification and profile setup
2026-10-08 18:46:04 +07:00

146 lines
9.0 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = { 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: () => ({}),
emailOTP: (options: unknown) => ({ id: "email-otp", options }) }));
const envNames = ["NODE_ENV", "DATABASE_URL", "BETTER_AUTH_URL", "BETTER_AUTH_SECRET", "BUZZ_DEMO_MODE", "RESEND_API_KEY", "TRUSTED_CLIENT_IP_HEADER"] as const;
const testEnv = process.env as Record<string, string | undefined>;
const originalEnv = envNames.map((name) => testEnv[name]);
beforeEach(() => {
vi.resetModules?.();
testEnv.NODE_ENV = "development";
testEnv.DATABASE_URL = "postgresql://test.invalid/test";
testEnv.BETTER_AUTH_URL = "https://guide.example.test";
testEnv.BETTER_AUTH_SECRET = "a-test-secret-with-more-than-32-characters";
mocks.auth.mockReturnValue({ api: { getSession: mocks.session } });
mocks.session.mockResolvedValue(null);
delete testEnv.TRUSTED_CLIENT_IP_HEADER;
});
afterEach(() => {
envNames.forEach((name, index) => {
const value = originalEnv[index];
if (value === undefined) delete testEnv[name];
else testEnv[name] = value;
});
});
describe("actual administrator session boundary", () => {
it("does not grant access when the old demo flag is enabled", async () => {
testEnv.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 six-character new passwords", async () => {
(await import("./server")).getAuth();
const options = mocks.auth.mock.calls.at(-1)![0];
expect(options.emailAndPassword).toMatchObject({ enabled: true, minPasswordLength: 6 });
expect(options.plugins).toContainEqual({ defaultRole: "user" });
expect(options.rateLimit.customStorage.consume).toBeTypeOf("function");
expect(options.databaseHooks).toBeUndefined();
});
it("always enables Guide credentials and registration", async () => {
testEnv.TRUSTED_CLIENT_IP_HEADER = "x-forwarded-for";
(await import("./server")).getAuth();
const options = mocks.auth.mock.calls.at(-1)![0];
expect(options.advanced.ipAddress.ipAddressHeaders).toEqual(["x-forwarded-for"]);
expect(options.emailAndPassword).toMatchObject({ enabled: true });
expect(options.plugins.some((plugin: { id?: string }) => plugin.id === "email-otp")).toBe(true);
expect(options.plugins.some((plugin: { id?: string }) => plugin.id === "generic-oauth")).toBe(false);
expect(options.databaseHooks).toBeUndefined();
});
it("keeps the local Guide session", async () => {
mocks.session.mockResolvedValue({ user: { id: "user-1", email: "[email protected]",
emailVerified: true, role: "admin" }, session: { id: "guide-session" } });
const { getAdminSession, getCustomerSession } = await import("./server");
expect(await getCustomerSession()).toMatchObject({ user: { id: "user-1" } });
expect(await getAdminSession()).toMatchObject({ user: { id: "user-1" } });
});
it("allows an unverified customer session but rejects administrator access", async () => {
mocks.session.mockResolvedValue({ user: { id: "user-1", email: "[email protected]",
emailVerified: false, role: "admin" }, session: { id: "guide-session" } });
const { getAdminSession, getCustomerSession, requireAdmin } = await import("./server");
expect(await getCustomerSession()).toMatchObject({ user: { id: "user-1", emailVerified: false } });
expect(await getAdminSession()).toBeNull();
await expect(requireAdmin()).rejects.toMatchObject({ status: 401 });
});
it("allows unverified sign-in and sends auth links from the configured sender", async () => {
testEnv.RESEND_API_KEY = "test-key";
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(null, { status: 200 }));
try {
(await import("./server")).getAuth();
const options = mocks.auth.mock.calls.at(-1)![0];
expect(options.emailAndPassword).toMatchObject({ requireEmailVerification: false, autoSignIn: true });
expect(options.emailAndPassword.resetPasswordTokenExpiresIn).toBe(3600);
expect(options.emailVerification).toMatchObject({
sendOnSignUp: false, autoSignInAfterVerification: true, expiresIn: 3600,
});
expect(options.user.changeEmail.enabled).toBe(true);
const otp = options.plugins.find((plugin: { id?: string }) => plugin.id === "email-otp");
expect(otp.options).toMatchObject({ sendVerificationOnSignUp: true, storeOTP: "hashed", expiresIn: 300 });
const user = { email: "[email protected]" };
await otp.options.sendVerificationOTP({ email: user.email, otp: "123456", type: "email-verification" });
const otpEmail = JSON.parse(String(fetchMock.mock.calls[0][1]?.body));
expect(otpEmail.subject).toContain("รหัส OTP");
expect(otpEmail.text).toContain("รหัส OTP: 123456");
expect(otpEmail.text).toContain("หมดอายุใน 5 นาที");
expect(otpEmail.text).toContain("อย่าแชร์รหัสนี้กับผู้อื่น");
expect(otpEmail.text).toContain("กรุณาอย่าตอบกลับ");
await options.emailVerification.sendVerificationEmail({ user, url: "https://guide.example.test/verify-email?token=abc" });
await options.user.changeEmail.sendChangeEmailConfirmation({ user, newEmail: "[email protected]",
url: "https://guide.example.test/verify-email?token=change" });
await options.emailAndPassword.sendResetPassword({ user, url: "https://guide.example.test/reset-password/abc" });
expect(fetchMock).toHaveBeenCalledTimes(4);
const emails = fetchMock.mock.calls.map((call) => JSON.parse(String(call[1]?.body)));
expect(emails[1].text).toContain(user.email);
expect(emails[1].text).toContain("ยืนยันอีเมลใหม่");
expect(emails[2].text).toContain(`อีเมลปัจจุบัน: ${user.email}\nอีเมลใหม่: [email protected]`);
expect(emails[2].text).toContain("คุณต้องเปิดลิงก์ในอีเมลใหม่");
expect(emails[3].text).toContain("รหัสผ่านของคุณจะเปลี่ยนเมื่อ");
expect(emails[3].text).toContain("รหัสผ่านเดิมของคุณจะยังใช้งานได้");
for (const email of emails.slice(1)) {
expect(email.text).toContain("หมดอายุใน 1 ชั่วโมง");
expect(email.text).toContain("อย่าแชร์หรือส่งต่อลิงก์นี้");
expect(email.text).toContain("หากคุณไม่ได้");
expect(email.text).toContain("กรุณาอย่าตอบกลับ");
}
for (const call of fetchMock.mock.calls) {
expect(call[0]).toBe("https://api.resend.com/emails");
expect(call[1]?.headers).toMatchObject({ Authorization: "Bearer test-key" });
const body = JSON.parse(String(call[1]?.body));
expect(body).toMatchObject({ from: "Buzz Guide <[email protected]>", to: [user.email] });
expect(body.text).toMatch(/123456|https:\/\/guide\.example\.test\//);
}
} finally { fetchMock.mockRestore(); }
});
it("fails delivery when the provider rejects an auth email", async () => {
testEnv.RESEND_API_KEY = "test-key";
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(null, { status: 403 }));
try {
(await import("./server")).getAuth();
const options = mocks.auth.mock.calls.at(-1)![0];
await expect(options.emailVerification.sendVerificationEmail({
user: { email: "[email protected]" }, url: "https://guide.example.test/verify-email",
})).rejects.toThrow("delivery failed");
} finally { fetchMock.mockRestore(); }
});
});