feat : update
This commit is contained in:
+2
-1
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { createAuthClient } from "better-auth/react";
|
||||
import { emailOTPClient } from "better-auth/client/plugins";
|
||||
|
||||
export const authClient = createAuthClient();
|
||||
export const authClient = createAuthClient({ plugins: [emailOTPClient()] });
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import "server-only";
|
||||
|
||||
const FROM = "Buzz Guide <[email protected]>";
|
||||
|
||||
export async function sendAuthEmail(to: string, subject: string, text: string): Promise<void> {
|
||||
const apiKey = process.env.RESEND_API_KEY;
|
||||
if (!apiKey) throw new Error("RESEND_API_KEY is required for authentication email.");
|
||||
|
||||
const response = await fetch("https://api.resend.com/emails", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ from: FROM, to: [to], subject, text }),
|
||||
});
|
||||
if (!response.ok) throw new Error(`Authentication email delivery failed (${response.status}).`);
|
||||
}
|
||||
@@ -7,7 +7,7 @@ describe("public auth return path", () => {
|
||||
});
|
||||
|
||||
it("rejects external destinations and auth loops", () => {
|
||||
for (const value of ["https://example.com", "//example.com", "/\\example.com", "/login", "/lo%67in", "/register", 4])
|
||||
for (const value of ["https://example.com", "//example.com", "/\\example.com", "/login", "/lo%67in", "/register", "/admin/login", 4])
|
||||
expect(safeAuthReturnPath(value)).toBe("/");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,7 +3,7 @@ export function safeAuthReturnPath(value: unknown): string {
|
||||
try {
|
||||
const url = new URL(value, "https://auth.local");
|
||||
const path = decodeURIComponent(url.pathname);
|
||||
if (url.origin !== "https://auth.local" || ["/login", "/register", "/commission/login"].includes(path))
|
||||
if (url.origin !== "https://auth.local" || ["/login", "/register", "/commission/login", "/admin/login"].includes(path))
|
||||
return "/";
|
||||
return `${url.pathname}${url.search}${url.hash}`;
|
||||
} catch {
|
||||
|
||||
+41
-2
@@ -7,9 +7,10 @@ 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: () => ({}) }));
|
||||
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"] as const;
|
||||
const envNames = ["NODE_ENV", "DATABASE_URL", "BETTER_AUTH_URL", "BETTER_AUTH_SECRET", "BUZZ_DEMO_MODE", "RESEND_API_KEY"] as const;
|
||||
const testEnv = process.env as Record<string, string | undefined>;
|
||||
const originalEnv = envNames.map((name) => testEnv[name]);
|
||||
|
||||
@@ -55,4 +56,42 @@ describe("actual administrator session boundary", () => {
|
||||
expect(options.rateLimit.customStorage.consume).toBeTypeOf("function");
|
||||
expect(options.databaseHooks).toBeUndefined();
|
||||
});
|
||||
it("requires verification 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.requireEmailVerification).toBe(true);
|
||||
expect(options.emailVerification).toMatchObject({ sendOnSignUp: false });
|
||||
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" });
|
||||
const user = { email: "[email protected]" };
|
||||
await otp.options.sendVerificationOTP({ email: user.email, otp: "123456", type: "email-verification" });
|
||||
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);
|
||||
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(); }
|
||||
});
|
||||
});
|
||||
|
||||
+35
-2
@@ -3,7 +3,7 @@ import "server-only";
|
||||
import { betterAuth } from "better-auth";
|
||||
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
||||
import { nextCookies } from "better-auth/next-js";
|
||||
import { admin, captcha } from "better-auth/plugins";
|
||||
import { admin, captcha, emailOTP } from "better-auth/plugins";
|
||||
import { headers } from "next/headers";
|
||||
import { cache } from "react";
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
import { isAuthorizedAdmin, type SessionUserLike } from "./authorization";
|
||||
import { HttpError } from "@/lib/security/http";
|
||||
import { consumeRateLimit } from "@/lib/security/rate-limit";
|
||||
import { sendAuthEmail } from "./email";
|
||||
|
||||
function required(name: string): string {
|
||||
const value = process.env[name];
|
||||
@@ -53,8 +54,27 @@ function createAuth() {
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
disableSignUp: false,
|
||||
requireEmailVerification: true,
|
||||
minPasswordLength: 6,
|
||||
maxPasswordLength: 128,
|
||||
sendResetPassword: async ({ user, url }) => {
|
||||
await sendAuthEmail(user.email, "รีเซ็ตรหัสผ่าน Buzz Guide", `เปิดลิงก์นี้เพื่อรีเซ็ตรหัสผ่าน: ${url}\n\nลิงก์นี้หมดอายุใน 1 ชั่วโมง`);
|
||||
},
|
||||
},
|
||||
user: {
|
||||
changeEmail: {
|
||||
enabled: true,
|
||||
sendChangeEmailConfirmation: async ({ user, newEmail, url }) => {
|
||||
await sendAuthEmail(user.email, "ยืนยันการเปลี่ยนอีเมล Buzz Guide",
|
||||
`เปิดลิงก์นี้เพื่ออนุมัติการเปลี่ยนอีเมลเป็น ${newEmail}: ${url}\n\nลิงก์นี้หมดอายุใน 1 ชั่วโมง`);
|
||||
},
|
||||
},
|
||||
},
|
||||
emailVerification: {
|
||||
sendOnSignUp: false,
|
||||
sendVerificationEmail: async ({ user, url }) => {
|
||||
await sendAuthEmail(user.email, "ยืนยันอีเมล Buzz Guide", `เปิดลิงก์นี้เพื่อยืนยันอีเมล: ${url}\n\nลิงก์นี้หมดอายุใน 1 ชั่วโมง`);
|
||||
},
|
||||
},
|
||||
advanced: {
|
||||
ipAddress: {
|
||||
@@ -65,9 +85,22 @@ function createAuth() {
|
||||
rateLimit: {
|
||||
enabled: true,
|
||||
customStorage: { consume: (key, rule) => consumeRateLimit(`auth:${key}`, rule) },
|
||||
customRules: { "/sign-in/email": { window: 60, max: 10 } },
|
||||
customRules: {
|
||||
"/sign-in/email": { window: 60, max: 10 },
|
||||
"/sign-up/email": { window: 3600, max: 5 },
|
||||
"/send-verification-email": { window: 3600, max: 5 },
|
||||
"/change-email": { window: 3600, max: 5 },
|
||||
"/request-password-reset": { window: 3600, max: 5 },
|
||||
},
|
||||
},
|
||||
plugins: [
|
||||
emailOTP({
|
||||
sendVerificationOnSignUp: true,
|
||||
storeOTP: "hashed",
|
||||
sendVerificationOTP: async ({ email, otp }) => {
|
||||
await sendAuthEmail(email, "รหัสยืนยัน Buzz Guide", `รหัสยืนยันอีเมลของคุณคือ ${otp}\n\nรหัสนี้หมดอายุใน 5 นาที`);
|
||||
},
|
||||
}),
|
||||
...(process.env.NODE_ENV === "development" ? [] : [
|
||||
captcha({
|
||||
provider: "cloudflare-turnstile",
|
||||
|
||||
Reference in New Issue
Block a user