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(desktop): route Better Auth through the backend proxy (#19298)

Inneid3790f279275
diff --git a/src/features/Settings/profile/features/EmailRow.tsx b/src/features/Settings/profile/features/EmailRow.tsx
index 96c8d8c6eaf..bb9ceec6f23 100644
--- a/src/features/Settings/profile/features/EmailRow.tsx
+++ b/src/features/Settings/profile/features/EmailRow.tsx
@@ -1,14 +1,19 @@
'use client';
-import { Flexbox, Input } from '@lobehub/ui';
+import { isDesktop } from '@lobechat/const';
+import { Flexbox, Icon, Input } from '@lobehub/ui';
import { Button, Text, toast } from '@lobehub/ui/base-ui';
-import { AnimatePresence, m } from 'motion/react';
+import { ExternalLinkIcon } from 'lucide-react';
import { useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import urlJoin from 'url-join';
+import { useAppOrigin } from '@/hooks/useAppOrigin';
import { changeEmail } from '@/libs/better-auth/auth-client';
+import { electronSystemService } from '@/services/electron/system';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
+import { saveToast } from '@/store/utils/saveToast';
import ProfileRow from './ProfileRow';
@@ -20,18 +25,16 @@ const EmailRow = () => {
const [isEditing, setIsEditing] = useState(false);
const [editValue, setEditValue] = useState('');
const [saving, setSaving] = useState(false);
- const [error, setError] = useState('');
+ const appOrigin = useAppOrigin();
const handleStartEdit = () => {
setEditValue('');
- setError('');
setIsEditing(true);
};
const handleCancel = () => {
setIsEditing(false);
setEditValue('');
- setError('');
};
const handleSave = useCallback(async () => {
@@ -39,93 +42,91 @@ const EmailRow = () => {
if (!trimmed) return;
if (!EMAIL_REGEX.test(trimmed)) {
- setError(t('profile.emailInvalid'));
+ toast.error(t('profile.emailInvalid'));
return;
}
try {
setSaving(true);
- setError('');
const res = await changeEmail({ callbackURL: '/settings/profile', newEmail: trimmed });
if (res.error) {
- setError(res.error.message ?? res.error.statusText ?? 'Failed to change email');
+ toast.error(res.error.message ?? res.error.statusText ?? t('profile.saveError'));
return;
}
setIsEditing(false);
toast.success(t('profile.emailChangeSuccess'));
} catch (err) {
console.error('Failed to change email:', err);
- setError(err instanceof Error ? err.message : String(err));
+ saveToast(err, { retry: () => void handleSave(), title: t('profile.saveError') });
} finally {
setSaving(false);
}
}, [editValue, t]);
- const editingContent = (
- <m.div
- animate={{ opacity: 1, y: 0 }}
- exit={{ opacity: 0, y: -10 }}
- initial={{ opacity: 0, y: -10 }}
- key="editing"
- transition={{ duration: 0.2 }}
- >
- <Flexbox gap={12}>
- <Input
- autoFocus
- autoComplete="email"
- inputMode="email"
- placeholder={t('profile.emailPlaceholder')}
- status={error ? 'error' : undefined}
- type="email"
- value={editValue}
- onPressEnter={handleSave}
- onChange={(e) => {
- setEditValue(e.target.value);
- if (error) setError('');
- }}
- />
- {error && (
- <Text style={{ fontSize: 12 }} type="danger">
- {error}
+ // Desktop OIDC and Better Auth sessions are not bridged, so change-email can only
+ // be completed on the web app.
+ if (isDesktop)
+ return (
+ <ProfileRow
+ anchor={'profile-email'}
+ label={t('profile.email')}
+ action={
+ <Text
+ style={{ cursor: 'pointer', fontSize: 13 }}
+ onClick={() => {
+ if (!appOrigin) return;
+ void electronSystemService.openExternalLink(urlJoin(appOrigin, '/settings/profile'));
+ }}
+ >
+ <Flexbox horizontal align={'center'} gap={4}>
+ {t('profile.updateEmail')}
+ <Icon icon={ExternalLinkIcon} size={12} />
+ </Flexbox>
</Text>
- )}
- <Flexbox horizontal gap={8} justify="flex-end">
- <Button disabled={saving} size="small" onClick={handleCancel}>
- {t('profile.cancel')}
- </Button>
- <Button loading={saving} size="small" type="primary" onClick={handleSave}>
- {t('profile.save')}
- </Button>
- </Flexbox>
- </Flexbox>
- </m.div>
- );
-
- const displayContent = (
- <m.div
- animate={{ opacity: 1 }}
- exit={{ opacity: 0 }}
- initial={{ opacity: 0 }}
- key="display"
- transition={{ duration: 0.2 }}
- >
- <Text>{email || '--'}</Text>
- </m.div>
- );
+ }
+ >
+ <Text>{email || '--'}</Text>
+ </ProfileRow>
+ );
return (
<ProfileRow
anchor={'profile-email'}
label={t('profile.email')}
action={
- !isEditing && (
+ isEditing ? (
+ <Flexbox horizontal gap={8}>
+ <Button disabled={saving} size="small" onClick={handleCancel}>
+ {t('profile.cancel')}
+ </Button>
+ <Button loading={saving} size="small" type="primary" onClick={handleSave}>
+ {t('profile.save')}
+ </Button>
+ </Flexbox>
+ ) : (
<Text style={{ cursor: 'pointer', fontSize: 13 }} onClick={handleStartEdit}>
{t('profile.updateEmail')}
</Text>
)
}
>
- <AnimatePresence mode="wait">{isEditing ? editingContent : displayContent}</AnimatePresence>
+ {isEditing ? (
+ <Input
+ autoFocus
+ autoComplete="email"
+ inputMode="email"
+ placeholder={t('profile.emailPlaceholder')}
+ size="small"
+ style={{ flex: 1, minWidth: 0, width: '100%' }}
+ type="email"
+ value={editValue}
+ variant="filled"
+ onChange={(e) => setEditValue(e.target.value)}
+ onPressEnter={handleSave}
+ />
+ ) : (
+ <Text>{email || '--'}</Text>
+ )}
</ProfileRow>
);
};
diff --git a/src/libs/better-auth/auth-client.desktop.test.ts b/src/libs/better-auth/auth-client.desktop.test.ts
new file mode 100644
index 00000000000..22b181c6993
--- /dev/null
+++ b/src/libs/better-auth/auth-client.desktop.test.ts
@@ -0,0 +1,28 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { changeEmail, listAccounts } from './auth-client.desktop';
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+const requestUrl = (input: RequestInfo | URL) => {
+ if (typeof input === 'string') return input;
+ if (input instanceof URL) return input.href;
+ return input.url;
+};
+
+describe('desktop better-auth client', () => {
+ it('sends account requests to the renderer instead of the remote server', async () => {
+ const fetch = vi.fn<typeof globalThis.fetch>(async () => Response.json({ status: true }));
+ vi.stubGlobal('fetch', fetch);
+
+ await changeEmail({ callbackURL: '/settings/profile', newEmail: '[email protected]' });
+ await listAccounts();
+
+ expect(fetch.mock.calls.map(([input]) => requestUrl(input))).toEqual([
+ '/api/auth/change-email',
+ '/api/auth/list-accounts',
+ ]);
+ });
+});
diff --git a/src/libs/better-auth/auth-client.desktop.ts b/src/libs/better-auth/auth-client.desktop.ts
index dc2615a4ede..3ca867dfcfe 100644
--- a/src/libs/better-auth/auth-client.desktop.ts
+++ b/src/libs/better-auth/auth-client.desktop.ts
@@ -7,17 +7,22 @@ import {
import { createAuthClient } from 'better-auth/react';
import { type auth } from '@/auth';
-import { electronSyncSelectors } from '@/store/electron/selectors/sync';
-import { getElectronStoreState } from '@/store/electron/store';
let _client: any = null;
+const desktopAuthFetch: typeof fetch = (input, init) => {
+ const url = new URL(input instanceof Request ? input.url : input.toString());
+ return fetch(`${url.pathname}${url.search}`, init);
+};
+
function getClient() {
if (!_client) {
- const baseURL = electronSyncSelectors.remoteServerUrl(getElectronStoreState());
-
_client = createAuthClient({
- baseURL,
+ // better-auth getBaseURL only accepts http(s); app://renderer throws.
+ baseURL: 'http://lobehub.invalid',
+ fetchOptions: {
+ customFetchImpl: desktopAuthFetch,
+ },
plugins: [
adminClient(),
inferAdditionalFields<typeof auth>(),