feat : update

This commit is contained in:
2026-10-05 18:47:41 +07:00 Unverified
parent d44a2597ba
commit 2f1fe0ab76
14 changed files with 311 additions and 38 deletions
+46 -1
View File
@@ -8,9 +8,10 @@ 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: () => ({}),
genericOAuth: (options: unknown) => ({ id: "generic-oauth", options }),
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"] as const;
const envNames = ["NODE_ENV", "DATABASE_URL", "BETTER_AUTH_URL", "BETTER_AUTH_SECRET", "BUZZ_DEMO_MODE", "RESEND_API_KEY", "SUDLOH_OIDC_CLIENT_ID", "SUDLOH_OIDC_CLIENT_SECRET", "SUDLOH_OIDC_REDIRECT_URI", "SUDLOH_OIDC_ISSUER", "SUDLOH_OIDC_ONLY"] as const;
const testEnv = process.env as Record<string, string | undefined>;
const originalEnv = envNames.map((name) => testEnv[name]);
@@ -22,6 +23,11 @@ beforeEach(() => {
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.SUDLOH_OIDC_CLIENT_ID;
delete testEnv.SUDLOH_OIDC_CLIENT_SECRET;
delete testEnv.SUDLOH_OIDC_REDIRECT_URI;
delete testEnv.SUDLOH_OIDC_ISSUER;
delete testEnv.SUDLOH_OIDC_ONLY;
});
afterEach(() => {
envNames.forEach((name, index) => {
@@ -56,6 +62,45 @@ describe("actual administrator session boundary", () => {
expect(options.rateLimit.customStorage.consume).toBeTypeOf("function");
expect(options.databaseHooks).toBeUndefined();
});
it("adds verified Sudloh sign-in while retaining email sign-in", async () => {
testEnv.SUDLOH_OIDC_CLIENT_ID = "client";
testEnv.SUDLOH_OIDC_CLIENT_SECRET = "secret";
testEnv.SUDLOH_OIDC_REDIRECT_URI = "https://guide.example.test/api/auth/callback/sudloh";
const { getAuth, isSudlohOidcEnabled } = await import("./server");
expect(isSudlohOidcEnabled()).toBe(true);
getAuth();
const options = mocks.auth.mock.calls.at(-1)![0];
expect(options.emailAndPassword).toMatchObject({ enabled: true, disableSignUp: false });
expect(options.account.accountLinking.disableImplicitLinking).toBe(true);
expect(options.account.accountLinking.enabled).not.toBe(false);
expect(options.plugins.some((plugin: { id?: string }) => plugin.id === "email-otp")).toBe(true);
expect(options.plugins.find((plugin: { id?: string }) => plugin.id === "generic-oauth").options.config[0]).toMatchObject({
providerId: "sudloh", authentication: "basic", requireIdTokenVerification: true,
requireEmailVerification: true, disableProviderLogout: true,
scopes: ["openid", "profile", "email"],
redirectURI: "https://guide.example.test/api/auth/callback/sudloh",
});
});
it("disables local sign-in after the OIDC cutover flag is set", async () => {
testEnv.SUDLOH_OIDC_CLIENT_ID = "client";
testEnv.SUDLOH_OIDC_CLIENT_SECRET = "secret";
testEnv.SUDLOH_OIDC_REDIRECT_URI = "https://guide.example.test/api/auth/callback/sudloh";
testEnv.SUDLOH_OIDC_ONLY = "true";
(await import("./server")).getAuth();
const options = mocks.auth.mock.calls.at(-1)![0];
expect(options.emailAndPassword).toMatchObject({ enabled: false, disableSignUp: true });
expect(options.plugins.some((plugin: { id?: string }) => plugin.id === "email-otp")).toBe(false);
});
it("rejects incomplete or mismatched Sudloh client configuration", async () => {
const { getAuth, isSudlohOidcEnabled } = await import("./server");
testEnv.SUDLOH_OIDC_REDIRECT_URI = "https://guide.example.test/api/auth/callback/sudloh";
expect(isSudlohOidcEnabled()).toBe(false);
testEnv.SUDLOH_OIDC_CLIENT_ID = "client";
expect(isSudlohOidcEnabled).toThrow("client ID, client secret, and exact redirect URI");
testEnv.SUDLOH_OIDC_CLIENT_SECRET = "secret";
testEnv.SUDLOH_OIDC_REDIRECT_URI = "https://wrong.example.test/api/auth/callback/sudloh";
expect(getAuth).toThrow("SUDLOH_OIDC_REDIRECT_URI must be");
});
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 }));
+36 -5
View File
@@ -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, emailOTP } from "better-auth/plugins";
import { admin, captcha, emailOTP, genericOAuth } from "better-auth/plugins";
import { headers } from "next/headers";
import { cache } from "react";
@@ -32,7 +32,25 @@ function hasAuthConfiguration(): boolean {
);
}
export function isSudlohOidcEnabled(): boolean {
const clientId = process.env.SUDLOH_OIDC_CLIENT_ID;
const clientSecret = process.env.SUDLOH_OIDC_CLIENT_SECRET;
if (!clientId && !clientSecret) return false;
if (!clientId || !clientSecret || !process.env.SUDLOH_OIDC_REDIRECT_URI) {
throw new Error("Sudloh OIDC requires a client ID, client secret, and exact redirect URI.");
}
return true;
}
function createAuth() {
const oidcEnabled = isSudlohOidcEnabled();
const oidcOnly = oidcEnabled && process.env.SUDLOH_OIDC_ONLY === "true";
if (oidcEnabled) {
const callback = `${required("BETTER_AUTH_URL").replace(/\/$/, "")}/api/auth/callback/sudloh`;
if (process.env.SUDLOH_OIDC_REDIRECT_URI !== callback) {
throw new Error(`SUDLOH_OIDC_REDIRECT_URI must be ${callback}`);
}
}
return betterAuth({
appName: "Buzz Guide",
database: drizzleAdapter(getDb(), {
@@ -52,8 +70,8 @@ function createAuth() {
.filter(Boolean),
secret: required("BETTER_AUTH_SECRET"),
emailAndPassword: {
enabled: true,
disableSignUp: false,
enabled: !oidcOnly,
disableSignUp: oidcOnly,
requireEmailVerification: true,
minPasswordLength: 6,
maxPasswordLength: 128,
@@ -70,6 +88,7 @@ function createAuth() {
},
},
},
account: { accountLinking: { disableImplicitLinking: true } },
emailVerification: {
sendOnSignUp: false,
autoSignInAfterVerification: true,
@@ -95,13 +114,25 @@ function createAuth() {
},
},
plugins: [
emailOTP({
...(oidcEnabled ? [genericOAuth({ config: [{
providerId: "sudloh",
clientId: process.env.SUDLOH_OIDC_CLIENT_ID!,
clientSecret: process.env.SUDLOH_OIDC_CLIENT_SECRET!,
redirectURI: process.env.SUDLOH_OIDC_REDIRECT_URI!,
discoveryUrl: `${(process.env.SUDLOH_OIDC_ISSUER || "https://account.sudloh.com/api/auth").replace(/\/$/, "")}/.well-known/openid-configuration`,
scopes: ["openid", "profile", "email"],
authentication: "basic",
requireIdTokenVerification: true,
requireEmailVerification: true,
disableProviderLogout: true,
}] })] : []),
...(!oidcOnly ? [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",