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(oauth-apps): upload app logos to storage instead of inlining them (#19937)

Arvin Xucdbe3a98b681
diff --git a/apps/server/src/routers/lambda/__tests__/oauthApp.test.ts b/apps/server/src/routers/lambda/__tests__/oauthApp.test.ts
index 51a649c1aeb..fedb5a8659b 100644
--- a/apps/server/src/routers/lambda/__tests__/oauthApp.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/oauthApp.test.ts
@@ -117,6 +117,36 @@ describe('oauthAppRouter', () => {
});
});
+ describe('logo', () => {
+ it('rejects an inline data-URI logo that oidc-provider would refuse', async () => {
+ await expect(
+ caller().create({ logoUri: 'data:image/png;base64,iVBORw0KGgo=', name: 'Logo App' }),
+ ).rejects.toThrow();
+ await expect(
+ caller().update({
+ id: 'lca_app',
+ value: { logoUri: 'data:image/png;base64,iVBORw0KGgo=' },
+ }),
+ ).rejects.toThrow();
+ expect(mockCreate).not.toHaveBeenCalled();
+ expect(mockUpdate).not.toHaveBeenCalled();
+ });
+
+ it('accepts an uploaded https logo', async () => {
+ await caller().create({ logoUri: 'https://files.lobehub.com/logo.png', name: 'Logo App' });
+
+ expect(mockCreate).toHaveBeenCalledWith(
+ expect.objectContaining({ logoUri: 'https://files.lobehub.com/logo.png' }),
+ );
+ });
+
+ it('lets an update clear the logo with null', async () => {
+ await caller().update({ id: 'lca_app', value: { logoUri: null } });
+
+ expect(mockUpdate).toHaveBeenCalledWith('lca_app', { logoUri: null });
+ });
+ });
+
describe('read paths', () => {
it('never leaks the stored secret', async () => {
mockList.mockResolvedValue([webApp]);
diff --git a/apps/server/src/routers/lambda/oauthApp.ts b/apps/server/src/routers/lambda/oauthApp.ts
index 86e427e37a0..49bb4a18d56 100644
--- a/apps/server/src/routers/lambda/oauthApp.ts
+++ b/apps/server/src/routers/lambda/oauthApp.ts
@@ -36,6 +36,23 @@ const stripSecret = <T extends { clientSecret?: string | null }>(client: T) => {
return { ...rest, hasSecret: !!clientSecret };
};
+/**
+ * A logo must be a web URL: it becomes the OIDC client's `logo_uri`, and
+ * oidc-provider rejects the whole client as `invalid_client_metadata` when that
+ * is anything else, such as an inline `data:` image.
+ */
+const logoUriSchema = z
+ .string()
+ .max(2048)
+ .refine((value) => {
+ try {
+ const { protocol } = new URL(value);
+ return protocol === 'https:' || protocol === 'http:';
+ } catch {
+ return false;
+ }
+ }, 'logoUri.notWebUrl');
+
const redirectUrisSchema = z
.array(z.string().max(2000))
.max(MAX_OAUTH_REDIRECT_URIS)
@@ -59,7 +76,7 @@ export const oauthAppRouter = router({
// added, and the provider refuses any unregistered redirect in the meantime.
z.object({
description: z.string().max(500).optional(),
- logoUri: z.string().max(300_000).optional(),
+ logoUri: logoUriSchema.optional(),
name: z.string().min(1).max(64),
redirectUris: redirectUrisSchema.optional(),
type: z.enum(['device', 'web']).default('device'),
@@ -110,7 +127,8 @@ export const oauthAppRouter = router({
id: z.string(),
value: z.object({
description: z.string().max(500).optional(),
- logoUri: z.string().max(300_000).optional(),
+ // `null` removes the logo.
+ logoUri: logoUriSchema.nullable().optional(),
name: z.string().min(1).max(64).optional(),
redirectUris: redirectUrisSchema.optional(),
}),
diff --git a/locales/en-US/auth.json b/locales/en-US/auth.json
index a7c1887c7dd..e6bfae71639 100644
--- a/locales/en-US/auth.json
+++ b/locales/en-US/auth.json
@@ -254,6 +254,8 @@
"oauthApp.form.description.label": "Description",
"oauthApp.form.description.placeholder": "What is this app for? (optional)",
"oauthApp.form.logo.label": "Logo",
+ "oauthApp.form.logo.tooLarge": "The logo must be 2 MB or smaller.",
+ "oauthApp.form.logo.uploadFailed": "The logo could not be uploaded. Please try again.",
"oauthApp.form.name.label": "Name",
"oauthApp.form.name.placeholder": "Please enter app name",
"oauthApp.form.redirectUris.extra": "Each URI must be an exact https URL (http is allowed on localhost only) and is matched exactly.",
diff --git a/locales/zh-CN/auth.json b/locales/zh-CN/auth.json
index 152e6c2ba44..b050ab6a719 100644
--- a/locales/zh-CN/auth.json
+++ b/locales/zh-CN/auth.json
@@ -254,6 +254,8 @@
"oauthApp.form.description.label": "描述",
"oauthApp.form.description.placeholder": "这个应用是做什么的?(选填)",
"oauthApp.form.logo.label": "图标",
+ "oauthApp.form.logo.tooLarge": "图标不能超过 2 MB。",
+ "oauthApp.form.logo.uploadFailed": "图标上传失败,请重试。",
"oauthApp.form.name.label": "名称",
"oauthApp.form.name.placeholder": "请输入应用名称",
"oauthApp.form.redirectUris.extra": "每个地址都必须是完整的 https 地址(仅 localhost 允许 http),并按完全匹配校验。",
diff --git a/packages/locales/src/default/auth.ts b/packages/locales/src/default/auth.ts
index 34fcecb0b66..8afc38a3521 100644
--- a/packages/locales/src/default/auth.ts
+++ b/packages/locales/src/default/auth.ts
@@ -274,6 +274,8 @@ export default {
'oauthApp.form.description.label': 'Description',
'oauthApp.form.description.placeholder': 'What is this app for? (optional)',
'oauthApp.form.logo.label': 'Logo',
+ 'oauthApp.form.logo.tooLarge': 'The logo must be 2 MB or smaller.',
+ 'oauthApp.form.logo.uploadFailed': 'The logo could not be uploaded. Please try again.',
'oauthApp.form.name.label': 'Name',
'oauthApp.form.name.placeholder': 'Please enter app name',
'oauthApp.form.redirectUris.extra':
diff --git a/packages/types/src/oauthApp.ts b/packages/types/src/oauthApp.ts
index c0e84a24789..350ccb084fe 100644
--- a/packages/types/src/oauthApp.ts
+++ b/packages/types/src/oauthApp.ts
@@ -28,7 +28,8 @@ export interface CreateOAuthAppParams {
export interface UpdateOAuthAppParams {
description?: string;
- logoUri?: string;
+ /** `null` removes the logo. */
+ logoUri?: string | null;
name?: string;
redirectUris?: string[];
}
diff --git a/src/features/Settings/oauth-apps/features/AppDetail/BasicInfoCard.tsx b/src/features/Settings/oauth-apps/features/AppDetail/BasicInfoCard.tsx
index 419a20818cd..e74704fa6b6 100644
--- a/src/features/Settings/oauth-apps/features/AppDetail/BasicInfoCard.tsx
+++ b/src/features/Settings/oauth-apps/features/AppDetail/BasicInfoCard.tsx
@@ -10,6 +10,7 @@ import { useTranslation } from 'react-i18next';
import AvatarUpload from '@/components/AvatarUpload';
import { type OAuthAppItem, type UpdateOAuthAppParams } from '@/types/oauthApp';
+import { useLogoUpload } from '../../useLogoUpload';
import SectionCard from './SectionCard';
interface BasicInfoValues {
@@ -32,23 +33,39 @@ const BasicInfoCard: FC<BasicInfoCardProps> = ({ canEdit, detail, onSubmit }) =>
const { t } = useTranslation('auth');
const [editing, setEditing] = useState(false);
const [saving, setSaving] = useState(false);
- const [logoUri, setLogoUri] = useState<string | undefined>(detail.logoUri ?? undefined);
+ const [logoUri, setLogoUri] = useState<string | null>(detail.logoUri ?? null);
+ // Only a logo the user actually touched is sent. Older apps may still hold an
+ // inline `data:` logo the server no longer accepts, and renaming such an app
+ // must not fail on a field nobody edited.
+ const [logoChanged, setLogoChanged] = useState(false);
+ const { upload: uploadLogo, uploading: logoUploading } = useLogoUpload();
const startEditing = () => {
- setLogoUri(detail.logoUri ?? undefined);
+ setLogoUri(detail.logoUri ?? null);
+ setLogoChanged(false);
setEditing(true);
};
- const handleUpload = (file: File) => {
- const reader = new FileReader();
- reader.addEventListener('load', () => setLogoUri(reader.result as string));
- reader.readAsDataURL(file);
+ const handleUpload = async (file: File) => {
+ const url = await uploadLogo(file);
+ if (!url) return;
+ setLogoUri(url);
+ setLogoChanged(true);
+ };
+
+ const handleDeleteLogo = () => {
+ setLogoUri(null);
+ setLogoChanged(true);
};
const handleFinish = async (values: BasicInfoValues) => {
setSaving(true);
try {
- await onSubmit({ description: values.description, logoUri, name: values.name.trim() });
+ await onSubmit({
+ description: values.description,
+ name: values.name.trim(),
+ ...(logoChanged ? { logoUri } : {}),
+ });
setEditing(false);
} finally {
setSaving(false);
@@ -82,7 +99,14 @@ const BasicInfoCard: FC<BasicInfoCardProps> = ({ canEdit, detail, onSubmit }) =>
>
<Flexbox gap={16}>
<Form.Item label={t('oauthApp.form.logo.label')} style={itemStyle}>
- <AvatarUpload title={detail.name} value={logoUri} onUpload={handleUpload} />
+ <AvatarUpload
+ allowDelete={!!logoUri}
+ loading={logoUploading}
+ title={detail.name}
+ value={logoUri ?? undefined}
+ onDelete={handleDeleteLogo}
+ onUpload={handleUpload}
+ />
</Form.Item>
<Form.Item
@@ -104,7 +128,12 @@ const BasicInfoCard: FC<BasicInfoCardProps> = ({ canEdit, detail, onSubmit }) =>
<Flexbox horizontal gap={8} justify={'flex-end'}>
<Button onClick={() => setEditing(false)}>{t('oauthApp.detail.cancel')}</Button>
- <Button htmlType={'submit'} loading={saving} type={'primary'}>
+ <Button
+ disabled={logoUploading}
+ htmlType={'submit'}
+ loading={saving}
+ type={'primary'}
+ >
{t('oauthApp.detail.save')}
</Button>
</Flexbox>
diff --git a/src/features/Settings/oauth-apps/features/CreateAppModal/Content.tsx b/src/features/Settings/oauth-apps/features/CreateAppModal/Content.tsx
index d9ce30702f6..c8715a3cbe3 100644
--- a/src/features/Settings/oauth-apps/features/CreateAppModal/Content.tsx
+++ b/src/features/Settings/oauth-apps/features/CreateAppModal/Content.tsx
@@ -12,6 +12,8 @@ import { useTranslation } from 'react-i18next';
import AvatarUpload from '@/components/AvatarUpload';
import { type CreateOAuthAppParams } from '@/types/oauthApp';
+import { useLogoUpload } from '../../useLogoUpload';
+
const styles = createStaticStyles(({ css, cssVar }) => ({
typeCard: css`
cursor: pointer;
@@ -141,13 +143,13 @@ const CreateAppModalContent: FC<CreateAppModalContentProps> = ({ onSubmit }) =>
// silently drop the user's input); the explicit ✕/ESC close still works.
const markDirty = () => setCanDismissByClickOutside(false);
- const handleUpload = (file: File) => {
- const reader = new FileReader();
- reader.addEventListener('load', () => {
- setLogoUri(reader.result as string);
- markDirty();
- });
- reader.readAsDataURL(file);
+ const { upload: uploadLogo, uploading: logoUploading } = useLogoUpload();
+
+ const handleUpload = async (file: File) => {
+ const url = await uploadLogo(file);
+ if (!url) return;
+ setLogoUri(url);
+ markDirty();
};
// Only what defines the app is asked for up front. Redirect URIs are
@@ -182,8 +184,11 @@ const CreateAppModalContent: FC<CreateAppModalContentProps> = ({ onSubmit }) =>
<Flexbox gap={16}>
<Form.Item label={t('oauthApp.form.logo.label')} style={itemStyle}>
<AvatarUpload
+ allowDelete={!!logoUri}
+ loading={logoUploading}
title={t('oauthApp.form.name.label')}
value={logoUri}
+ onDelete={() => setLogoUri(undefined)}
onUpload={handleUpload}
/>
</Form.Item>
@@ -234,7 +239,13 @@ const CreateAppModalContent: FC<CreateAppModalContentProps> = ({ onSubmit }) =>
<TextArea placeholder={t('oauthApp.form.description.placeholder')} rows={3} />
</Form.Item>
- <Button block htmlType={'submit'} loading={loading} type={'primary'}>
+ <Button
+ block
+ disabled={logoUploading}
+ htmlType={'submit'}
+ loading={loading}
+ type={'primary'}
+ >
{t('oauthApp.form.submit')}
</Button>
</Flexbox>
diff --git a/src/features/Settings/oauth-apps/useLogoUpload.test.ts b/src/features/Settings/oauth-apps/useLogoUpload.test.ts
new file mode 100644
index 00000000000..fda765d1c8d
--- /dev/null
+++ b/src/features/Settings/oauth-apps/useLogoUpload.test.ts
@@ -0,0 +1,79 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useLogoUpload } from './useLogoUpload';
+
+const mocks = vi.hoisted(() => ({
+ toastError: vi.fn(),
+ uploadWithProgress: vi.fn(),
+}));
+
+vi.mock('@lobehub/ui/base-ui', () => ({ toast: { error: mocks.toastError } }));
+
+vi.mock('@/store/file', () => ({
+ useFileStore: (selector: (s: unknown) => unknown) =>
+ selector({ uploadWithProgress: mocks.uploadWithProgress }),
+}));
+
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+
+const file = (size = 1024) => new File([new Uint8Array(size)], 'logo.png', { type: 'image/png' });
+
+describe('useLogoUpload', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('returns the uploaded https URL, never an inline data URI', async () => {
+ mocks.uploadWithProgress.mockResolvedValue({ url: 'https://files.lobehub.com/logo.png' });
+ const { result } = renderHook(() => useLogoUpload());
+
+ let url: string | undefined;
+ await act(async () => {
+ url = await result.current.upload(file());
+ });
+
+ expect(url).toBe('https://files.lobehub.com/logo.png');
+ expect(url?.startsWith('data:')).toBe(false);
+ });
+
+ it('turns a storage path into an absolute URL the provider accepts', async () => {
+ mocks.uploadWithProgress.mockResolvedValue({ url: '/f/logo.png' });
+ const { result } = renderHook(() => useLogoUpload());
+
+ let url: string | undefined;
+ await act(async () => {
+ url = await result.current.upload(file());
+ });
+
+ expect(url).toBe(`${window.location.origin}/f/logo.png`);
+ });
+
+ it('refuses a file over 2 MB without uploading it', async () => {
+ const { result } = renderHook(() => useLogoUpload());
+
+ let url: string | undefined;
+ await act(async () => {
+ url = await result.current.upload(file(2 * 1024 * 1024 + 1));
+ });
+
+ expect(url).toBeUndefined();
+ expect(mocks.uploadWithProgress).not.toHaveBeenCalled();
+ expect(mocks.toastError).toHaveBeenCalledWith('oauthApp.form.logo.tooLarge');
+ });
+
+ it('reports a failed upload and returns nothing', async () => {
+ mocks.uploadWithProgress.mockRejectedValue(new Error('network'));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const { result } = renderHook(() => useLogoUpload());
+
+ let url: string | undefined;
+ await act(async () => {
+ url = await result.current.upload(file());
+ });
+
+ expect(url).toBeUndefined();
+ expect(mocks.toastError).toHaveBeenCalledWith('oauthApp.form.logo.uploadFailed');
+ expect(result.current.uploading).toBe(false);
+ });
+});
diff --git a/src/features/Settings/oauth-apps/useLogoUpload.ts b/src/features/Settings/oauth-apps/useLogoUpload.ts
new file mode 100644
index 00000000000..29d8330629a
--- /dev/null
+++ b/src/features/Settings/oauth-apps/useLogoUpload.ts
@@ -0,0 +1,46 @@
+import { toast } from '@lobehub/ui/base-ui';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useFileStore } from '@/store/file';
+
+const MAX_LOGO_SIZE = 2 * 1024 * 1024;
+
+/**
+ * Uploads an app logo to file storage and returns its absolute URL.
+ *
+ * The logo ends up as the OIDC client's `logo_uri`, which oidc-provider only
+ * accepts as a web URI; a `data:` URI makes the provider reject the whole
+ * client. So the image goes to storage, never inline into the record.
+ */
+export const useLogoUpload = () => {
+ const { t } = useTranslation('auth');
+ const uploadWithProgress = useFileStore((s) => s.uploadWithProgress);
+ const [uploading, setUploading] = useState(false);
+
+ const upload = async (file: File): Promise<string | undefined> => {
+ if (file.size > MAX_LOGO_SIZE) {
+ toast.error(t('oauthApp.form.logo.tooLarge'));
+ return;
+ }
+
+ setUploading(true);
+ try {
+ const result = await uploadWithProgress({ file });
+ if (!result?.url) {
+ toast.error(t('oauthApp.form.logo.uploadFailed'));
+ return;
+ }
+
+ // Local storage returns a path; the provider needs an absolute URL.
+ return result.url.startsWith('/') ? `${window.location.origin}${result.url}` : result.url;
+ } catch (error) {
+ console.error('[OAuthApps] Logo upload failed:', error);
+ toast.error(t('oauthApp.form.logo.uploadFailed'));
+ } finally {
+ setUploading(false);
+ }
+ };
+
+ return { upload, uploading };
+};