Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(auth): reject email changes to an address another account uses (#23590)

YuTengjingaa88a6c418df
diff --git a/locales/en-US/auth.json b/locales/en-US/auth.json
index b17455d09f9..f728b3c4927 100644
--- a/locales/en-US/auth.json
+++ b/locales/en-US/auth.json
@@ -348,6 +348,7 @@
"profile.changePassword": "Reset password",
"profile.email": "Email Address",
"profile.emailChangeSuccess": "Verification email sent. Please check your new email inbox.",
+ "profile.emailInUse": "This email is already used by another account. Please use a different email.",
"profile.emailInvalid": "Please enter a valid email address",
"profile.emailPlaceholder": "[email protected]",
"profile.fullName": "Fullname",
diff --git a/locales/zh-CN/auth.json b/locales/zh-CN/auth.json
index 51f3035824c..76d081b6b97 100644
--- a/locales/zh-CN/auth.json
+++ b/locales/zh-CN/auth.json
@@ -348,6 +348,7 @@
"profile.changePassword": "重置密码",
"profile.email": "邮箱",
"profile.emailChangeSuccess": "验证邮件已发送,请查收新邮箱。",
+ "profile.emailInUse": "该邮箱已被其他账号使用,请换一个邮箱。",
"profile.emailInvalid": "请输入有效的邮箱地址",
"profile.emailPlaceholder": "[email protected]",
"profile.fullName": "全名",
diff --git a/packages/locales/src/default/auth.ts b/packages/locales/src/default/auth.ts
index 170f1699b87..7d4e4a7a26a 100644
--- a/packages/locales/src/default/auth.ts
+++ b/packages/locales/src/default/auth.ts
@@ -387,6 +387,8 @@ export default {
'profile.changePassword': 'Reset password',
'profile.email': 'Email Address',
'profile.emailChangeSuccess': 'Verification email sent. Please check your new email inbox.',
+ 'profile.emailInUse':
+ 'This email is already used by another account. Please use a different email.',
'profile.emailInvalid': 'Please enter a valid email address',
'profile.emailPlaceholder': '[email protected]',
'profile.fullName': 'Fullname',
diff --git a/src/features/Settings/profile/features/EmailRow.tsx b/src/features/Settings/profile/features/EmailRow.tsx
index f181b635322..fd4f4e163e9 100644
--- a/src/features/Settings/profile/features/EmailRow.tsx
+++ b/src/features/Settings/profile/features/EmailRow.tsx
@@ -9,6 +9,7 @@ import urlJoin from 'url-join';
import { useAppOrigin } from '@/hooks/useAppOrigin';
import { changeEmail } from '@/libs/better-auth/auth-client';
+import { CHANGE_EMAIL_IN_USE_CODE } from '@/libs/better-auth/constants';
import { electronSystemService } from '@/services/electron/system';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
@@ -49,6 +50,10 @@ const EmailRow = () => {
setSaving(true);
const res = await changeEmail({ callbackURL: '/settings/profile', newEmail: trimmed });
if (res.error) {
+ if (res.error.code === CHANGE_EMAIL_IN_USE_CODE) {
+ toast.error(t('profile.emailInUse'));
+ return;
+ }
toast.error(res.error.message ?? res.error.statusText ?? t('profile.saveError'));
return;
}
diff --git a/src/libs/better-auth/constants.ts b/src/libs/better-auth/constants.ts
index 8766623f7ef..fc1d8339df8 100644
--- a/src/libs/better-auth/constants.ts
+++ b/src/libs/better-auth/constants.ts
@@ -17,3 +17,9 @@ export const BUILTIN_BETTER_AUTH_PROVIDERS = [
export const PROVIDER_ALIAS_MAP: Record<string, string> = {
'microsoft-entra-id': 'microsoft',
};
+
+/**
+ * Error code returned by `/change-email` when the new address already belongs to another
+ * account. Shared by the server plugin and the profile settings row that localizes it.
+ */
+export const CHANGE_EMAIL_IN_USE_CODE = 'EMAIL_ALREADY_IN_USE';
diff --git a/src/libs/better-auth/define-config.ts b/src/libs/better-auth/define-config.ts
index c8db6122dd0..eecb1bbd810 100644
--- a/src/libs/better-auth/define-config.ts
+++ b/src/libs/better-auth/define-config.ts
@@ -21,6 +21,7 @@ import {
getVerificationEmailTemplate,
getVerificationOTPEmailTemplate,
} from '@/libs/better-auth/email-templates';
+import { changeEmailUniqueness } from '@/libs/better-auth/plugins/change-email-uniqueness';
import { deferredSessionRefresh } from '@/libs/better-auth/plugins/deferred-session-refresh';
import { emailWhitelist } from '@/libs/better-auth/plugins/email-whitelist';
import { sessionOptions } from '@/libs/better-auth/session-options';
@@ -313,6 +314,7 @@ export function defineConfig(customOptions: CustomBetterAuthOptions) {
plugins: [
...customOptions.plugins,
deferredSessionRefresh(),
+ changeEmailUniqueness(),
emailWhitelist(),
expo(),
admin(),
diff --git a/src/libs/better-auth/plugins/change-email-uniqueness.test.ts b/src/libs/better-auth/plugins/change-email-uniqueness.test.ts
new file mode 100644
index 00000000000..a9a6084db80
--- /dev/null
+++ b/src/libs/better-auth/plugins/change-email-uniqueness.test.ts
@@ -0,0 +1,100 @@
+// @vitest-environment node
+import { betterAuth } from 'better-auth';
+import { memoryAdapter } from 'better-auth/adapters/memory';
+import { describe, expect, it, vi } from 'vitest';
+
+import { CHANGE_EMAIL_IN_USE_CODE } from '../constants';
+import { changeEmailUniqueness } from './change-email-uniqueness';
+
+const BASE_URL = 'http://localhost:3000';
+const PASSWORD = 'password-123456';
+
+/**
+ * A real Better Auth instance with the production change-email setup (enabled, verification
+ * email configured, no confirmation to the old address), so the test exercises Better Auth's
+ * actual existing-email branch instead of asserting hook wiring.
+ */
+const createAuth = (plugins = [changeEmailUniqueness()]) => {
+ const db: Record<string, any[]> = { account: [], session: [], user: [], verification: [] };
+ const sendVerificationEmail = vi.fn(async (_data: unknown, _request?: Request) => {});
+ const auth = betterAuth({
+ baseURL: BASE_URL,
+ database: memoryAdapter(db),
+ emailAndPassword: { enabled: true },
+ emailVerification: { sendVerificationEmail },
+ plugins,
+ secret: 'test-secret-test-secret-test-secret',
+ user: { changeEmail: { enabled: true } },
+ });
+
+ return { auth, sendVerificationEmail };
+};
+
+const signUp = async (auth: ReturnType<typeof createAuth>['auth'], email: string) => {
+ const result = await auth.api.signUpEmail({
+ body: { email, name: email, password: PASSWORD },
+ returnHeaders: true,
+ });
+ const cookie = result.headers.get('set-cookie')?.match(/better-auth\.session_token=[^;]+/)?.[0];
+ if (!cookie) throw new Error(`Sign-up for ${email} returned no session cookie`);
+
+ return new Headers({ cookie, origin: BASE_URL });
+};
+
+const changeEmail = (
+ auth: ReturnType<typeof createAuth>['auth'],
+ headers: Headers,
+ newEmail: string,
+) =>
+ auth.api.changeEmail({
+ body: { callbackURL: '/settings/profile', newEmail },
+ headers,
+ });
+
+describe('changeEmailUniqueness', () => {
+ it('rejects an address that already belongs to another account instead of reporting a sent email', async () => {
+ const { auth, sendVerificationEmail } = createAuth();
+ const headers = await signUp(auth, '[email protected]');
+ await signUp(auth, '[email protected]');
+
+ await expect(changeEmail(auth, headers, '[email protected]')).rejects.toMatchObject({
+ body: { code: CHANGE_EMAIL_IN_USE_CODE },
+ statusCode: 400,
+ });
+ expect(sendVerificationEmail).not.toHaveBeenCalled();
+ });
+
+ it('documents the Better Auth default this plugin overrides: silent success without email', async () => {
+ const { auth, sendVerificationEmail } = createAuth([]);
+ const headers = await signUp(auth, '[email protected]');
+ await signUp(auth, '[email protected]');
+
+ await expect(changeEmail(auth, headers, '[email protected]')).resolves.toEqual({
+ status: true,
+ });
+ expect(sendVerificationEmail).not.toHaveBeenCalled();
+ });
+
+ it('still sends the verification email for an unused address', async () => {
+ const { auth, sendVerificationEmail } = createAuth();
+ const headers = await signUp(auth, '[email protected]');
+
+ await expect(changeEmail(auth, headers, '[email protected]')).resolves.toEqual({
+ status: true,
+ });
+ expect(sendVerificationEmail).toHaveBeenCalledTimes(1);
+ expect(sendVerificationEmail).toHaveBeenCalledWith(
+ expect.objectContaining({ user: expect.objectContaining({ email: '[email protected]' }) }),
+ undefined,
+ );
+ });
+
+ it('leaves the requester’s own address to Better Auth’s same-email error', async () => {
+ const { auth } = createAuth();
+ const headers = await signUp(auth, '[email protected]');
+
+ await expect(changeEmail(auth, headers, '[email protected]')).rejects.toMatchObject({
+ body: { message: 'Email is the same' },
+ });
+ });
+});
diff --git a/src/libs/better-auth/plugins/change-email-uniqueness.ts b/src/libs/better-auth/plugins/change-email-uniqueness.ts
new file mode 100644
index 00000000000..0f7de1d0d26
--- /dev/null
+++ b/src/libs/better-auth/plugins/change-email-uniqueness.ts
@@ -0,0 +1,58 @@
+import { APIError, createAuthMiddleware, getSessionFromCtx } from 'better-auth/api';
+import { type BetterAuthPlugin } from 'better-auth/types';
+
+import { CHANGE_EMAIL_IN_USE_CODE } from '../constants';
+
+const CHANGE_EMAIL_PATH = '/change-email';
+
+/**
+ * Reject a change-email request whose new address already belongs to another account.
+ *
+ * Better Auth answers such a request with `{ status: true }` and sends no email, to avoid
+ * revealing which addresses are registered. The settings page then reports a sent
+ * verification email that never arrives. That concealment protects nothing here: sign-in
+ * (`/api/auth/check-user`) and sign-up already tell visitors whether an email is registered,
+ * while this endpoint requires a signed-in session.
+ */
+export const changeEmailUniqueness = (): BetterAuthPlugin => ({
+ hooks: {
+ before: [
+ {
+ handler: createAuthMiddleware(async (ctx) => {
+ const newEmail = ctx.body?.newEmail;
+ if (typeof newEmail !== 'string') return;
+
+ /**
+ * The endpoint's session middleware has not run yet. Resolve the session first so
+ * anonymous requests reach its 401 without an email lookup, and do it on a detached
+ * context: Better Auth memoizes the lookup on the supplied context and lets query
+ * parameters override its options, and this check must not seed either.
+ */
+ const session = await getSessionFromCtx(
+ {
+ ...ctx,
+ context: { ...ctx.context, session: null },
+ query: { disableCookieCache: true, disableRefresh: true },
+ },
+ { disableCookieCache: true, disableRefresh: true },
+ );
+ if (!session) return;
+
+ // Better Auth lowercases the address before its own lookup; match that.
+ const existing = await ctx.context.internalAdapter.findUserByEmail(
+ newEmail.toLowerCase(),
+ );
+ // The requester's own address is left to Better Auth's "Email is the same" error.
+ if (!existing || existing.user.id === session.user.id) return;
+
+ throw new APIError('BAD_REQUEST', {
+ code: CHANGE_EMAIL_IN_USE_CODE,
+ message: 'This email is already used by another account.',
+ });
+ }),
+ matcher: (ctx) => ctx.path === CHANGE_EMAIL_PATH,
+ },
+ ],
+ },
+ id: 'change-email-uniqueness',
+});