🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(oidc): developer OAuth apps — device-flow public clients (#17087)
Innei8e29c48d5e98
diff --git a/apps/server/src/routers/lambda/__tests__/integration/oauthApp.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/oauthApp.integration.test.tsnew file mode 100644index 00000000000..d40131f9f0d--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/integration/oauthApp.integration.test.ts@@ -0,0 +1,77 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { workspaceMembers, workspaces } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import { oauthAppRouter } from '../../oauthApp';+import { cleanupTestUser, createTestContext, createTestUser } from './setup';++let testDB: LobeChatDatabase;+vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(() => testDB),+}));++describe('OAuth app router integration', () => {+ const userId = 'oauth-app-router-user';+ const memberId = 'oauth-app-router-member';+ const workspaceId = 'oauth-app-router-workspace';+ const otherWorkspaceId = 'oauth-app-router-other-workspace';++ beforeEach(async () => {+ testDB = await getTestDB();+ await createTestUser(testDB, userId);+ await createTestUser(testDB, memberId);+ await testDB.insert(workspaces).values([+ {+ id: workspaceId,+ name: 'OAuth App Router Workspace',+ primaryOwnerId: userId,+ slug: workspaceId,+ },+ {+ id: otherWorkspaceId,+ name: 'OAuth App Router Other Workspace',+ primaryOwnerId: memberId,+ slug: otherWorkspaceId,+ },+ ]);+ await testDB.insert(workspaceMembers).values([+ { role: 'owner', userId, workspaceId },+ { role: 'member', userId: memberId, workspaceId },+ { role: 'owner', userId: memberId, workspaceId: otherWorkspaceId },+ ]);+ });++ afterEach(async () => {+ await cleanupTestUser(testDB, userId);+ await cleanupTestUser(testDB, memberId);+ });++ it('creates and isolates personal and workspace OAuth apps', async () => {+ const personalCaller = oauthAppRouter.createCaller(createTestContext(userId));+ const workspaceCaller = oauthAppRouter.createCaller({+ ...createTestContext(userId),+ workspaceId,+ });+ const memberCaller = oauthAppRouter.createCaller({+ ...createTestContext(memberId),+ workspaceId,+ });+ const otherWorkspaceCaller = oauthAppRouter.createCaller({+ ...createTestContext(memberId),+ workspaceId: otherWorkspaceId,+ });++ const personalApp = await personalCaller.create({ name: 'Personal App' });+ const workspaceApp = await workspaceCaller.create({ name: 'Workspace App' });++ expect(personalApp).toMatchObject({ name: 'Personal App', userId, workspaceId: null });+ expect(workspaceApp).toMatchObject({ name: 'Workspace App', userId, workspaceId });+ await expect(personalCaller.list()).resolves.toMatchObject([{ id: personalApp.id }]);+ await expect(memberCaller.list()).resolves.toMatchObject([{ id: workspaceApp.id }]);+ await expect(otherWorkspaceCaller.list()).resolves.toEqual([]);+ await expect(personalCaller.getById({ id: workspaceApp.id })).resolves.toBeUndefined();+ });+});diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.tsindex 336860de981..3cc3d17d1b3 100644--- a/apps/server/src/routers/lambda/index.ts+++ b/apps/server/src/routers/lambda/index.ts@@ -62,6 +62,7 @@ import { messageRouter } from './message';import { messengerRouter } from './messenger';import { notebookRouter } from './notebook';import { notificationRouter } from './notification';+import { oauthAppRouter } from './oauthApp';import { oauthDeviceFlowRouter } from './oauthDeviceFlow';import { pluginRouter } from './plugin';import { pushTokenRouter } from './pushToken';@@ -132,6 +133,7 @@ export const lambdaRouter = router({messenger: messengerRouter,notebook: notebookRouter,notification: notificationRouter,+ oauthApp: oauthAppRouter,oauthDeviceFlow: oauthDeviceFlowRouter,plugin: pluginRouter,pushToken: pushTokenRouter,diff --git a/apps/server/src/routers/lambda/oauthApp.ts b/apps/server/src/routers/lambda/oauthApp.tsnew file mode 100644index 00000000000..70cda2a7bb0--- /dev/null+++ b/apps/server/src/routers/lambda/oauthApp.ts@@ -0,0 +1,78 @@+import { z } from 'zod';++import {+ requireWorkspaceRoleWhenScoped,+ wsCompatProcedure,+} from '@/business/server/trpc-middlewares/workspaceAuth';+import { OidcClientModel } from '@/database/models/oidcClient';+import { router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';++const oauthAppProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {+ const { ctx } = opts;++ return opts.next({+ ctx: {+ oidcClientModel: new OidcClientModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined),+ },+ });+});++const oauthAppWriteProcedure = oauthAppProcedure.use(requireWorkspaceRoleWhenScoped('owner'));++const stripSecret = <T extends { clientSecret?: string | null }>(client: T) => {+ const { clientSecret: _clientSecret, ...rest } = client;+ return rest;+};++export const oauthAppRouter = router({+ create: oauthAppWriteProcedure+ .input(+ z.object({+ description: z.string().max(500).optional(),+ logoUri: z.string().max(300_000).optional(),+ name: z.string().min(1).max(64),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const client = await ctx.oidcClientModel.create(input);+ return stripSecret(client);+ }),++ delete: oauthAppWriteProcedure+ .input(z.object({ id: z.string() }))+ .mutation(async ({ input, ctx }) => {+ return ctx.oidcClientModel.delete(input.id);+ }),++ getById: oauthAppProcedure.input(z.object({ id: z.string() })).query(async ({ input, ctx }) => {+ const client = await ctx.oidcClientModel.findById(input.id);+ return client ? stripSecret(client) : undefined;+ }),++ list: oauthAppProcedure.query(async ({ ctx }) => {+ const clients = await ctx.oidcClientModel.list();+ return clients.map(stripSecret);+ }),++ setEnabled: oauthAppWriteProcedure+ .input(z.object({ enabled: z.boolean(), id: z.string() }))+ .mutation(async ({ input, ctx }) => {+ return ctx.oidcClientModel.setEnabled(input.id, input.enabled);+ }),++ update: oauthAppWriteProcedure+ .input(+ z.object({+ id: z.string(),+ value: z.object({+ description: z.string().max(500).optional(),+ logoUri: z.string().max(300_000).optional(),+ name: z.string().min(1).max(64).optional(),+ }),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ return ctx.oidcClientModel.update(input.id, input.value);+ }),+});diff --git a/apps/server/src/services/oidc/index.test.ts b/apps/server/src/services/oidc/index.test.tsindex 08bda7a1f28..8fdde039e2a 100644--- a/apps/server/src/services/oidc/index.test.ts+++ b/apps/server/src/services/oidc/index.test.ts@@ -5,6 +5,11 @@ import { createContextForInteractionDetails } from '@/libs/oidc-provider/http-adimport { OIDCService } from '.';import { getOIDCProvider } from './oidcProvider';+const dbMocks = vi.hoisted(() => ({+ findFirstClient: vi.fn(),+ findFirstUser: vi.fn(),+}));+vi.mock('@/libs/oidc-provider/http-adapter', () => ({createContextForInteractionDetails: vi.fn(),}));@@ -13,6 +18,33 @@ vi.mock('./oidcProvider', () => ({getOIDCProvider: vi.fn(),}));+vi.mock('@lobechat/database', () => ({+ getServerDB: vi.fn(async () => ({+ select: vi.fn((fields: Record<string, unknown>) => ({+ from: vi.fn(() => ({+ where: vi.fn(() => ({+ limit: vi.fn(async () => {+ const record = await ('userId' in fields+ ? dbMocks.findFirstClient()+ : dbMocks.findFirstUser());++ return record ? [record] : [];+ }),+ })),+ })),+ })),+ })),+}));++vi.mock('@lobechat/database/schemas', () => ({+ oidcClients: { id: 'id', name: 'name', policyUri: 'policyUri', userId: 'userId' },+ users: { fullName: 'fullName', id: 'id', username: 'username' },+}));++vi.mock('@/libs/oidc-provider/config', () => ({+ defaultClients: [{ client_id: 'lobehub-desktop' }],+}));+const createMockProvider = () => {const grantCtor = Object.assign(vi.fn().mockImplementation((payload) => ({@@ -229,4 +261,71 @@ describe('OIDCService', () => {expect(provider.Client.find).toHaveBeenCalledWith('client-missing');expect(metadata).toBeUndefined();});++ it('getConsentClientMetadata should mark first-party clients without a DB lookup', async () => {+ const provider = createMockProvider();+ provider.Client.find.mockResolvedValue({+ metadata: () => ({+ client_name: 'LobeHub Desktop',+ logo_uri: 'https://example.com/logo.png',+ }),+ });++ const service = new OIDCService(provider as any);+ const metadata = await service.getConsentClientMetadata('lobehub-desktop');++ expect(metadata).toEqual({+ clientName: 'LobeHub Desktop',+ isFirstParty: true,+ logo: 'https://example.com/logo.png',+ policyUri: undefined,+ });+ expect(dbMocks.findFirstClient).not.toHaveBeenCalled();+ });++ it('getConsentClientMetadata should resolve the developer name for third-party clients', async () => {+ const provider = createMockProvider();+ provider.Client.find.mockResolvedValue({+ metadata: () => ({ policy_uri: 'https://third.party/privacy' }),+ });+ dbMocks.findFirstClient.mockResolvedValue({+ name: 'Third Party App',+ policyUri: null,+ userId: 'user-1',+ });+ dbMocks.findFirstUser.mockResolvedValue({ fullName: 'Jane Doe', username: 'jane' });++ const service = new OIDCService(provider as any);+ const metadata = await service.getConsentClientMetadata('lca_thirdparty');++ expect(metadata).toEqual({+ clientName: 'Third Party App',+ developerName: 'Jane Doe',+ isFirstParty: false,+ logo: undefined,+ policyUri: 'https://third.party/privacy',+ });+ });++ it('getConsentClientMetadata should omit developerName when the owner has no name', async () => {+ const provider = createMockProvider();+ provider.Client.find.mockResolvedValue({ metadata: () => ({}) });+ dbMocks.findFirstClient.mockResolvedValue({+ name: 'Nameless App',+ policyUri: 'https://nameless.app/privacy',+ userId: 'user-2',+ });+ dbMocks.findFirstUser.mockResolvedValue({ fullName: null, username: null });++ const service = new OIDCService(provider as any);+ const metadata = await service.getConsentClientMetadata('lca_nameless');++ expect(metadata).toEqual({+ clientName: 'Nameless App',+ developerName: undefined,+ isFirstParty: false,+ logo: undefined,+ policyUri: 'https://nameless.app/privacy',+ });+ });});diff --git a/apps/server/src/services/oidc/index.ts b/apps/server/src/services/oidc/index.tsindex ae8c0b0ec4b..4afcc882dfc 100644--- a/apps/server/src/services/oidc/index.ts+++ b/apps/server/src/services/oidc/index.ts@@ -1,5 +1,9 @@+import { getServerDB } from '@lobechat/database';+import { oidcClients, users } from '@lobechat/database/schemas';import debug from 'debug';+import { eq } from 'drizzle-orm';+import { defaultClients } from '@/libs/oidc-provider/config';import { createContextForInteractionDetails } from '@/libs/oidc-provider/http-adapter';import { type OIDCProvider } from '@/libs/oidc-provider/provider';@@ -7,6 +11,16 @@ import { getOIDCProvider } from './oidcProvider';const log = debug('lobe-oidc:service');+const firstPartyClientIds = new Set(defaultClients.map((client) => client.client_id));++export interface ConsentClientMetadata {+ clientName?: string;+ developerName?: string;+ isFirstParty: boolean;+ logo?: string;+ policyUri?: string;+}+export class OIDCService {private provider: OIDCProvider;@@ -83,6 +97,51 @@ export class OIDCService {const client = await this.provider.Client.find(clientId);return client?.metadata();}++ async getConsentClientMetadata(clientId: string): Promise<ConsentClientMetadata> {+ const clientDetail = await this.getClientMetadata(clientId);+ const isFirstParty = firstPartyClientIds.has(clientId);++ const base: ConsentClientMetadata = {+ clientName: clientDetail?.client_name as string | undefined,+ isFirstParty,+ logo: clientDetail?.logo_uri as string | undefined,+ policyUri: clientDetail?.policy_uri as string | undefined,+ };++ if (isFirstParty) return base;++ const db = await getServerDB();+ const [record] = await db+ .select({+ name: oidcClients.name,+ policyUri: oidcClients.policyUri,+ userId: oidcClients.userId,+ })+ .from(oidcClients)+ .where(eq(oidcClients.id, clientId))+ .limit(1);++ if (!record) return base;++ let developerName: string | undefined;+ if (record.userId) {+ const [owner] = await db+ .select({ fullName: users.fullName, username: users.username })+ .from(users)+ .where(eq(users.id, record.userId))+ .limit(1);+ developerName = owner?.fullName || owner?.username || undefined;+ }++ return {+ clientName: base.clientName ?? record.name,+ developerName,+ isFirstParty: false,+ logo: base.logo,+ policyUri: base.policyUri ?? record.policyUri ?? undefined,+ };+ }}export { getOIDCProvider } from './oidcProvider';diff --git a/locales/en-US/auth.json b/locales/en-US/auth.jsonindex e65f0d86915..5ef781473c7 100644--- a/locales/en-US/auth.json+++ b/locales/en-US/auth.json@@ -175,6 +175,51 @@"loginGuide.f4": "Explore powerful plugins","loginGuide.title": "After signing in, you can:","loginOrSignup": "Sign In / Sign Up",+ "oauthApp.actions.disable": "Disable",+ "oauthApp.actions.enable": "Enable",+ "oauthApp.copy.error": "Copy failed",+ "oauthApp.copy.success": "Client ID copied to clipboard",+ "oauthApp.copy.tooltip": "Copy",+ "oauthApp.deleteConfirm.cancel": "Cancel",+ "oauthApp.deleteConfirm.content": "Are you sure you want to delete this app? Existing authorizations can no longer be renewed, and the app loses access once current tokens expire. This cannot be undone.",+ "oauthApp.deleteConfirm.ok": "Delete",+ "oauthApp.deleteConfirm.title": "Delete this app?",+ "oauthApp.detail.back": "Back to list",+ "oauthApp.detail.clientId": "Client ID",+ "oauthApp.detail.createdAt": "Created",+ "oauthApp.detail.dangerZone": "Danger Zone",+ "oauthApp.detail.delete": "Delete App",+ "oauthApp.detail.enabled": "Enabled",+ "oauthApp.detail.lastUsedAt": "Last Used",+ "oauthApp.detail.neverUsed": "Never used",+ "oauthApp.detail.save": "Save Changes",+ "oauthApp.detail.saveSuccess": "Changes saved",+ "oauthApp.detail.title": "App Details",+ "oauthApp.detail.type": "Type",+ "oauthApp.form.description.label": "Description",+ "oauthApp.form.description.placeholder": "What is this app for? (optional)",+ "oauthApp.form.logo.label": "Logo",+ "oauthApp.form.name.label": "Name",+ "oauthApp.form.name.placeholder": "Please enter app name",+ "oauthApp.form.submit": "Create",+ "oauthApp.form.title": "Create OAuth App",+ "oauthApp.item.disabledTag": "Disabled",+ "oauthApp.item.lastUsed": "Last used {{time}}",+ "oauthApp.list.actions.create": "Create App",+ "oauthApp.list.actions.delete": "Delete",+ "oauthApp.list.empty": "No OAuth apps yet. Create one to get started.",+ "oauthApp.list.neverUsed": "Never used",+ "oauthApp.stats.activeUsers": "Active Users",+ "oauthApp.stats.calls": "Total Calls",+ "oauthApp.stats.credits": "Credits Used",+ "oauthApp.stats.empty": "No usage data yet",+ "oauthApp.stats.lastUsed": "Last Called",+ "oauthApp.stats.neverUsed": "Never used",+ "oauthApp.stats.title": "Usage Stats",+ "oauthApp.stats.tokens": "Tokens",+ "oauthApp.type.badge": "Native · Device Flow",+ "oauthApp.type.deviceFlow": "Device Flow",+ "oauthApp.validation.nameRequired": "Name is required","profile.account": "Account","profile.authorizations.actions.revoke": "Revoke","profile.authorizations.revoke.description": "After revoking, the tool will no longer have access to your data. Re-authorization is required to use it again.",@@ -254,6 +299,7 @@"stats.workspace.members": "<span>{{count}}</span> members","stats.workspace.welcome": "<span>{{name}}</span> has been running for <span>{{days}}</span> days","tab.apikey": "API Key",+ "tab.oauthApps": "OAuth Apps","tab.profile": "My Account","tab.security": "Security","tab.stats": "Statistics",diff --git a/locales/en-US/labs.json b/locales/en-US/labs.jsonindex b5b294b8674..121bd4f405e 100644--- a/locales/en-US/labs.json+++ b/locales/en-US/labs.json@@ -25,6 +25,8 @@"features.inputMarkdown.title": "Input Markdown Rendering","features.messageTextSelectionActions.desc": "Show a quick action when selecting text in chat messages so the selected text can be added to the next conversation context.","features.messageTextSelectionActions.title": "Message Text Selection Actions",+ "features.oauthApps.desc": "Show OAuth app management in personal and workspace settings. This feature is hidden by default.",+ "features.oauthApps.title": "OAuth Apps","features.platformAgent.desc": "Show the \"Connect Agent\" entry in the create menu. Connected agents (e.g. OpenClaw, Hermes) run on your own devices and communicate back via lh connect.","features.platformAgent.title": "Connect Agent","features.taskVerify.desc": "Add a delivery-acceptance section to the task detail: describe acceptance in one sentence and let AI generate editable verify criteria.",diff --git a/locales/en-US/oauth.json b/locales/en-US/oauth.jsonindex 7fb2d7ee30b..7de65c3ce3c 100644--- a/locales/en-US/oauth.json+++ b/locales/en-US/oauth.json@@ -17,6 +17,10 @@"consent.scope.profile": "Access your basic profile information (name, avatar, etc.)","consent.scope.sync-read": "Read your synchronized data","consent.scope.sync-write": "Write and update your synchronized data",+ "consent.thirdParty.developedBy": "By {{developerName}}",+ "consent.thirdParty.notice": "This application is created by a third-party developer and is not operated by LobeHub. Once authorized, it can act on your behalf and use your account quota.",+ "consent.thirdParty.privacyPolicy": "Privacy Policy",+ "consent.thirdParty.unknownDeveloper": "a third-party developer","consent.title": "Authorize {{clientName}}","device.confirm.authorize": "Authorize","device.confirm.codeHint": "Confirm that this code matches the one shown in your terminal.",diff --git a/locales/zh-CN/auth.json b/locales/zh-CN/auth.jsonindex f913741c474..fef3cd1bf29 100644--- a/locales/zh-CN/auth.json+++ b/locales/zh-CN/auth.json@@ -175,6 +175,51 @@"loginGuide.f4": "探索强大的插件功能","loginGuide.title": "登录后,您可以:","loginOrSignup": "登录 / 注册",+ "oauthApp.actions.disable": "停用",+ "oauthApp.actions.enable": "启用",+ "oauthApp.copy.error": "复制失败,请再试一次",+ "oauthApp.copy.success": "已复制 Client ID",+ "oauthApp.copy.tooltip": "复制",+ "oauthApp.deleteConfirm.cancel": "取消",+ "oauthApp.deleteConfirm.content": "确定删除该应用吗?已有的授权将无法再续期,待当前令牌过期后该应用即失去访问权限,且此操作不可撤销。",+ "oauthApp.deleteConfirm.ok": "删除",+ "oauthApp.deleteConfirm.title": "确认删除该应用?",+ "oauthApp.detail.back": "返回列表",+ "oauthApp.detail.clientId": "Client ID",+ "oauthApp.detail.createdAt": "创建时间",+ "oauthApp.detail.dangerZone": "危险操作",+ "oauthApp.detail.delete": "删除应用",+ "oauthApp.detail.enabled": "已启用",+ "oauthApp.detail.lastUsedAt": "最后使用时间",+ "oauthApp.detail.neverUsed": "从未使用",+ "oauthApp.detail.save": "保存更改",+ "oauthApp.detail.saveSuccess": "已保存",+ "oauthApp.detail.title": "应用详情",+ "oauthApp.detail.type": "类型",+ "oauthApp.form.description.label": "描述",+ "oauthApp.form.description.placeholder": "这个应用是做什么的?(选填)",+ "oauthApp.form.logo.label": "图标",+ "oauthApp.form.name.label": "名称",+ "oauthApp.form.name.placeholder": "请输入应用名称",+ "oauthApp.form.submit": "创建",+ "oauthApp.form.title": "创建 OAuth 应用",+ "oauthApp.item.disabledTag": "已停用",+ "oauthApp.item.lastUsed": "最后使用 {{time}}",+ "oauthApp.list.actions.create": "创建应用",+ "oauthApp.list.actions.delete": "删除",+ "oauthApp.list.empty": "还没有 OAuth 应用,创建一个开始吧。",+ "oauthApp.list.neverUsed": "从未使用",+ "oauthApp.stats.activeUsers": "活跃用户",+ "oauthApp.stats.calls": "总调用次数",+ "oauthApp.stats.credits": "消耗积分",+ "oauthApp.stats.empty": "暂无使用数据",+ "oauthApp.stats.lastUsed": "最近调用",+ "oauthApp.stats.neverUsed": "从未使用",+ "oauthApp.stats.title": "使用统计",+ "oauthApp.stats.tokens": "Tokens",+ "oauthApp.type.badge": "原生 · 设备流",+ "oauthApp.type.deviceFlow": "设备流",+ "oauthApp.validation.nameRequired": "请输入名称","profile.account": "账户","profile.authorizations.actions.revoke": "取消授权","profile.authorizations.revoke.description": "取消后,该工具将无法继续访问你的数据;需要使用时可再重新授权。",@@ -254,6 +299,7 @@"stats.workspace.members": "<span>{{count}}</span> 位成员","stats.workspace.welcome": "<span>{{name}}</span> 已运行 <span>{{days}}</span> 天","tab.apikey": "API Key",+ "tab.oauthApps": "OAuth 应用","tab.profile": "账号","tab.security": "安全","tab.stats": "数据统计",diff --git a/locales/zh-CN/labs.json b/locales/zh-CN/labs.jsonindex 632411b0af4..9f5c334b4ab 100644--- a/locales/zh-CN/labs.json+++ b/locales/zh-CN/labs.json@@ -25,6 +25,8 @@"features.inputMarkdown.title": "输入框 Markdown 渲染","features.messageTextSelectionActions.desc": "在聊天消息中选中文本时显示快捷操作,可将选中的文本加入下一次对话上下文。","features.messageTextSelectionActions.title": "消息文本选择操作",+ "features.oauthApps.desc": "在个人和工作区设置中显示 OAuth 应用管理入口。此功能默认隐藏。",+ "features.oauthApps.title": "OAuth 应用","features.platformAgent.desc": "在创建菜单中显示「接入助理」入口。接入的助理(如 OpenClaw、Hermes)运行在你自己的设备上,通过 lh connect 与 LobeHub 通信。","features.platformAgent.title": "接入助理","features.taskVerify.desc": "在任务详情里增加「交付验收」模块:一句话描述验收要求,AI 自动生成可编辑的验收项。",diff --git a/locales/zh-CN/oauth.json b/locales/zh-CN/oauth.jsonindex f99a2f02f4a..55cc7ab24f5 100644--- a/locales/zh-CN/oauth.json+++ b/locales/zh-CN/oauth.json@@ -17,6 +17,10 @@"consent.scope.profile": "访问你的基本资料信息(名称、头像等)","consent.scope.sync-read": "读取你的同步数据","consent.scope.sync-write": "写入并更新你的同步数据",+ "consent.thirdParty.developedBy": "由 {{developerName}} 开发",+ "consent.thirdParty.notice": "此应用由第三方开发者创建,并非由 LobeHub 运营。授权后,它可代表你执行操作并消耗你的账户额度。",+ "consent.thirdParty.privacyPolicy": "隐私政策",+ "consent.thirdParty.unknownDeveloper": "第三方开发者","consent.title": "授权 {{clientName}}","device.confirm.authorize": "授权","device.confirm.codeHint": "确认此代码与您的终端上显示的代码一致。",diff --git a/packages/const/src/user.ts b/packages/const/src/user.tsindex ce4436a043b..8c475cb47c1 100644--- a/packages/const/src/user.ts+++ b/packages/const/src/user.ts@@ -18,6 +18,7 @@ export const DEFAULT_PREFERENCE: UserPreference = {enableFleet: false,enableInputMarkdown: true,enableMessageTextSelectionActions: false,+ enableOAuthApps: false,enablePlatformAgent: false,},topicGroupMode: 'byTime',diff --git a/packages/database/src/models/__tests__/oidcClient.test.ts b/packages/database/src/models/__tests__/oidcClient.test.tsnew file mode 100644index 00000000000..87a9e3e4061--- /dev/null+++ b/packages/database/src/models/__tests__/oidcClient.test.ts@@ -0,0 +1,344 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { oidcClients, oidcGrants, oidcRefreshTokens, users, workspaces } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { OidcClientModel } from '../oidcClient';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'oidc-client-model-test-user';+const otherUserId = 'oidc-client-model-other-user';+const workspaceId = 'oidc-client-model-test-workspace';+const otherWorkspaceId = 'oidc-client-model-other-workspace';++let oidcClientModel: OidcClientModel;++beforeEach(async () => {+ oidcClientModel = new OidcClientModel(serverDB, userId);+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+ await serverDB.insert(workspaces).values([+ {+ id: workspaceId,+ name: 'OIDC Client Test Workspace',+ primaryOwnerId: userId,+ slug: workspaceId,+ },+ {+ id: otherWorkspaceId,+ name: 'OIDC Client Other Workspace',+ primaryOwnerId: otherUserId,+ slug: otherWorkspaceId,+ },+ ]);+});++afterEach(async () => {+ await serverDB.delete(users);+});++describe('OidcClientModel', () => {+ describe('create', () => {+ it('should create a client with lca_ prefixed id and fixed device-flow fields', async () => {+ const result = await oidcClientModel.create({ name: 'My App' });++ expect(result.id).toMatch(/^lca_[\dA-Za-z]{24}$/);+ expect(result.name).toBe('My App');+ expect(result.userId).toBe(userId);+ expect(result.workspaceId).toBeNull();+ expect(result.enabled).toBe(true);+ expect(result.isFirstParty).toBe(false);+ expect(result.clientSecret).toBeNull();+ expect(result.tokenEndpointAuthMethod).toBe('none');+ expect(result.applicationType).toBe('native');+ expect(result.responseTypes).toEqual([]);+ expect(result.redirectUris).toEqual([]);+ expect(result.grants).toEqual([+ 'urn:ietf:params:oauth:grant-type:device_code',+ 'refresh_token',+ ]);+ expect(result.scopes).toEqual(['openid', 'profile', 'email', 'offline_access']);+ });++ it('should persist description and logoUri', async () => {+ const result = await oidcClientModel.create({+ description: 'a demo',+ logoUri: 'https://example.com/logo.png',+ name: 'My App',+ });++ expect(result.description).toBe('a demo');+ expect(result.logoUri).toBe('https://example.com/logo.png');+ });++ it('should create a workspace client with its creator and workspace scope', async () => {+ const workspaceModel = new OidcClientModel(serverDB, userId, workspaceId);++ const result = await workspaceModel.create({ name: 'Workspace App' });++ expect(result).toMatchObject({+ name: 'Workspace App',+ userId,+ workspaceId,+ });+ });+ });++ describe('list', () => {+ it('should list own clients newest first', async () => {+ await serverDB.insert(oidcClients).values({+ applicationType: 'native',+ createdAt: new Date('2024-01-01T00:00:00Z'),+ grants: [],+ id: 'lca_older',+ name: 'Older',+ userId,+ redirectUris: [],+ responseTypes: [],+ scopes: [],+ });+ await serverDB.insert(oidcClients).values({+ applicationType: 'native',+ createdAt: new Date('2024-02-01T00:00:00Z'),+ grants: [],+ id: 'lca_newer',+ name: 'Newer',+ userId,+ redirectUris: [],+ responseTypes: [],+ scopes: [],+ });++ const clients = await oidcClientModel.list();++ expect(clients).toHaveLength(2);+ expect(clients[0].id).toBe('lca_newer');+ expect(clients[1].id).toBe('lca_older');+ });++ it('should only list clients owned by the current user', async () => {+ await oidcClientModel.create({ name: 'Mine' });+ const otherModel = new OidcClientModel(serverDB, otherUserId);+ await otherModel.create({ name: 'Theirs' });++ const clients = await oidcClientModel.list();++ expect(clients).toHaveLength(1);+ expect(clients[0].name).toBe('Mine');+ });++ it('should exclude workspace clients from personal mode', async () => {+ const workspaceModel = new OidcClientModel(serverDB, userId, workspaceId);+ await oidcClientModel.create({ name: 'Personal App' });+ await workspaceModel.create({ name: 'Workspace App' });++ const clients = await oidcClientModel.list();++ expect(clients.map(({ name }) => name)).toEqual(['Personal App']);+ });++ it('should share clients within a workspace and isolate other workspaces', async () => {+ const creatorModel = new OidcClientModel(serverDB, userId, workspaceId);+ const memberModel = new OidcClientModel(serverDB, otherUserId, workspaceId);+ const otherWorkspaceModel = new OidcClientModel(serverDB, otherUserId, otherWorkspaceId);+ await creatorModel.create({ name: 'Shared App' });++ const memberClients = await memberModel.list();+ const otherWorkspaceClients = await otherWorkspaceModel.list();++ expect(memberClients.map(({ name }) => name)).toEqual(['Shared App']);+ expect(otherWorkspaceClients).toEqual([]);+ });+ });++ describe('findById', () => {+ it('should find an own client by id', async () => {+ const { id } = await oidcClientModel.create({ name: 'My App' });++ const found = await oidcClientModel.findById(id);++ expect(found?.id).toBe(id);+ });++ it('should not find a client owned by another user', async () => {+ const otherModel = new OidcClientModel(serverDB, otherUserId);+ const { id } = await otherModel.create({ name: 'Theirs' });++ const found = await oidcClientModel.findById(id);++ expect(found).toBeUndefined();+ });++ it('should find a client from the same workspace but not another workspace', async () => {+ const creatorModel = new OidcClientModel(serverDB, userId, workspaceId);+ const memberModel = new OidcClientModel(serverDB, otherUserId, workspaceId);+ const otherWorkspaceModel = new OidcClientModel(serverDB, otherUserId, otherWorkspaceId);+ const { id } = await creatorModel.create({ name: 'Shared App' });++ await expect(memberModel.findById(id)).resolves.toMatchObject({ id });+ await expect(otherWorkspaceModel.findById(id)).resolves.toBeUndefined();+ await expect(oidcClientModel.findById(id)).resolves.toBeUndefined();+ });+ });++ describe('update', () => {+ it('should update own client fields', async () => {+ const { id } = await oidcClientModel.create({ name: 'Old Name' });++ await oidcClientModel.update(id, { description: 'new desc', name: 'New Name' });++ const [updated] = await serverDB+ .select()+ .from(oidcClients)+ .where(eq(oidcClients.id, id))+ .limit(1);+ expect(updated?.name).toBe('New Name');+ expect(updated?.description).toBe('new desc');+ });++ it('should not update a client owned by another user', async () => {+ const otherModel = new OidcClientModel(serverDB, otherUserId);+ const { id } = await otherModel.create({ name: 'Theirs' });++ await oidcClientModel.update(id, { name: 'Hacked' });++ const [unchanged] = await serverDB+ .select()+ .from(oidcClients)+ .where(eq(oidcClients.id, id))+ .limit(1);+ expect(unchanged?.name).toBe('Theirs');+ });++ it('should not update a client from another workspace', async () => {+ const workspaceModel = new OidcClientModel(serverDB, userId, workspaceId);+ const otherWorkspaceModel = new OidcClientModel(serverDB, otherUserId, otherWorkspaceId);+ const { id } = await workspaceModel.create({ name: 'Workspace App' });++ await otherWorkspaceModel.update(id, { name: 'Hacked' });++ await expect(workspaceModel.findById(id)).resolves.toMatchObject({ name: 'Workspace App' });+ });+ });++ describe('setEnabled', () => {+ it('should toggle enabled on own client', async () => {+ const { id } = await oidcClientModel.create({ name: 'My App' });++ await oidcClientModel.setEnabled(id, false);++ const [updated] = await serverDB+ .select()+ .from(oidcClients)+ .where(eq(oidcClients.id, id))+ .limit(1);+ expect(updated?.enabled).toBe(false);+ });++ it('should not toggle enabled on another user client', async () => {+ const otherModel = new OidcClientModel(serverDB, otherUserId);+ const { id } = await otherModel.create({ name: 'Theirs' });++ await oidcClientModel.setEnabled(id, false);++ const [unchanged] = await serverDB+ .select()+ .from(oidcClients)+ .where(eq(oidcClients.id, id))+ .limit(1);+ expect(unchanged?.enabled).toBe(true);+ });+ });++ describe('delete', () => {+ it('should delete own client and its dependent token rows', async () => {+ const { id } = await oidcClientModel.create({ name: 'My App' });++ await serverDB.insert(oidcGrants).values({+ clientId: id,+ data: {},+ expiresAt: new Date(Date.now() + 3_600_000),+ id: 'grant-1',+ userId,+ });+ await serverDB.insert(oidcRefreshTokens).values({+ clientId: id,+ data: {},+ expiresAt: new Date(Date.now() + 3_600_000),+ id: 'refresh-1',+ userId,+ });++ await oidcClientModel.delete(id);++ const [client] = await serverDB+ .select()+ .from(oidcClients)+ .where(eq(oidcClients.id, id))+ .limit(1);+ const [grant] = await serverDB+ .select()+ .from(oidcGrants)+ .where(eq(oidcGrants.id, 'grant-1'))+ .limit(1);+ const [refresh] = await serverDB+ .select()+ .from(oidcRefreshTokens)+ .where(eq(oidcRefreshTokens.id, 'refresh-1'))+ .limit(1);++ expect(client).toBeUndefined();+ expect(grant).toBeUndefined();+ expect(refresh).toBeUndefined();+ });++ it('should not delete a client owned by another user', async () => {+ const otherModel = new OidcClientModel(serverDB, otherUserId);+ const { id } = await otherModel.create({ name: 'Theirs' });++ await oidcClientModel.delete(id);++ const [client] = await serverDB+ .select()+ .from(oidcClients)+ .where(eq(oidcClients.id, id))+ .limit(1);+ expect(client).toBeDefined();+ });++ it('should not delete a client from another workspace', async () => {+ const workspaceModel = new OidcClientModel(serverDB, userId, workspaceId);+ const otherWorkspaceModel = new OidcClientModel(serverDB, otherUserId, otherWorkspaceId);+ const { id } = await workspaceModel.create({ name: 'Workspace App' });++ await otherWorkspaceModel.delete(id);++ await expect(workspaceModel.findById(id)).resolves.toMatchObject({ id });+ });++ it('should not touch another user token rows when deleting fails ownership', async () => {+ const otherModel = new OidcClientModel(serverDB, otherUserId);+ const { id } = await otherModel.create({ name: 'Theirs' });++ await serverDB.insert(oidcGrants).values({+ clientId: id,+ data: {},+ expiresAt: new Date(Date.now() + 3_600_000),+ id: 'grant-other',+ userId: otherUserId,+ });++ await oidcClientModel.delete(id);++ const [grant] = await serverDB+ .select()+ .from(oidcGrants)+ .where(eq(oidcGrants.id, 'grant-other'))+ .limit(1);+ expect(grant).toBeDefined();+ });+ });+});diff --git a/packages/database/src/models/oidcClient.ts b/packages/database/src/models/oidcClient.tsnew file mode 100644index 00000000000..bd34b557b3f--- /dev/null+++ b/packages/database/src/models/oidcClient.ts@@ -0,0 +1,126 @@+import { and, desc, eq } from 'drizzle-orm';++import {+ oidcAccessTokens,+ oidcClients,+ oidcConsents,+ oidcDeviceCodes,+ oidcGrants,+ oidcRefreshTokens,+} from '../schemas';+import type { LobeChatDatabase } from '../type';+import { createNanoId } from '../utils/idGenerator';+import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';++interface CreateOidcClientParams {+ description?: string | null;+ logoUri?: string | null;+ name: string;+}++interface UpdateOidcClientParams {+ description?: string | null;+ logoUri?: string | null;+ name?: string;+}++const DEVICE_FLOW_GRANTS = ['urn:ietf:params:oauth:grant-type:device_code', 'refresh_token'];+const DEFAULT_SCOPES = ['openid', 'profile', 'email', 'offline_access'];++const generateClientId = () => `lca_${createNanoId(24)()}`;++export class OidcClientModel {+ private db: LobeChatDatabase;+ private userId: string;+ private workspaceId?: string;++ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {+ this.db = db;+ this.userId = userId;+ this.workspaceId = workspaceId;+ }++ private ownership = () =>+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, oidcClients);++ create = async (params: CreateOidcClientParams) => {+ const [result] = await this.db+ .insert(oidcClients)+ .values(+ buildWorkspacePayload(+ { userId: this.userId, workspaceId: this.workspaceId },+ {+ applicationType: 'native',+ clientSecret: null,+ description: params.description,+ grants: DEVICE_FLOW_GRANTS,+ id: generateClientId(),+ isFirstParty: false,+ logoUri: params.logoUri,+ name: params.name,+ redirectUris: [],+ responseTypes: [],+ scopes: DEFAULT_SCOPES,+ tokenEndpointAuthMethod: 'none',+ },+ ),+ )+ .returning();++ return result;+ };++ list = async () => {+ return this.db+ .select()+ .from(oidcClients)+ .where(this.ownership())+ .orderBy(desc(oidcClients.createdAt));+ };++ findById = async (id: string) => {+ const [result] = await this.db+ .select()+ .from(oidcClients)+ .where(and(eq(oidcClients.id, id), this.ownership()))+ .limit(1);++ return result;+ };++ update = async (id: string, value: UpdateOidcClientParams) => {+ return this.db+ .update(oidcClients)+ .set({ ...value, updatedAt: new Date() })+ .where(and(eq(oidcClients.id, id), this.ownership()));+ };++ setEnabled = async (id: string, enabled: boolean) => {+ return this.db+ .update(oidcClients)+ .set({ enabled, updatedAt: new Date() })+ .where(and(eq(oidcClients.id, id), this.ownership()));+ };++ delete = async (id: string) => {+ return this.db.transaction(async (trx) => {+ const [client] = await trx+ .select({ id: oidcClients.id })+ .from(oidcClients)+ .where(and(eq(oidcClients.id, id), this.ownership()))+ .limit(1);++ if (!client) return;++ await Promise.all([+ trx.delete(oidcGrants).where(eq(oidcGrants.clientId, id)),+ trx.delete(oidcRefreshTokens).where(eq(oidcRefreshTokens.clientId, id)),+ trx.delete(oidcAccessTokens).where(eq(oidcAccessTokens.clientId, id)),+ trx.delete(oidcDeviceCodes).where(eq(oidcDeviceCodes.clientId, id)),+ trx.delete(oidcConsents).where(eq(oidcConsents.clientId, id)),+ ]);++ await trx.delete(oidcClients).where(and(eq(oidcClients.id, id), this.ownership()));+ });+ };+}diff --git a/packages/locales/src/default/auth.ts b/packages/locales/src/default/auth.tsindex 01d90a54c78..eac3bd382f6 100644--- a/packages/locales/src/default/auth.ts+++ b/packages/locales/src/default/auth.ts@@ -190,6 +190,52 @@ export default {'loginGuide.f4': 'Explore powerful plugins','loginGuide.title': 'After signing in, you can:','loginOrSignup': 'Sign In / Sign Up',+ 'oauthApp.actions.disable': 'Disable',+ 'oauthApp.actions.enable': 'Enable',+ 'oauthApp.copy.error': 'Copy failed',+ 'oauthApp.copy.success': 'Client ID copied to clipboard',+ 'oauthApp.copy.tooltip': 'Copy',+ 'oauthApp.deleteConfirm.cancel': 'Cancel',+ 'oauthApp.deleteConfirm.content':+ 'Are you sure you want to delete this app? Existing authorizations can no longer be renewed, and the app loses access once current tokens expire. This cannot be undone.',+ 'oauthApp.deleteConfirm.ok': 'Delete',+ 'oauthApp.deleteConfirm.title': 'Delete this app?',+ 'oauthApp.detail.back': 'Back to list',+ 'oauthApp.detail.clientId': 'Client ID',+ 'oauthApp.detail.createdAt': 'Created',+ 'oauthApp.detail.dangerZone': 'Danger Zone',+ 'oauthApp.detail.delete': 'Delete App',+ 'oauthApp.detail.enabled': 'Enabled',+ 'oauthApp.detail.lastUsedAt': 'Last Used',+ 'oauthApp.detail.neverUsed': 'Never used',+ 'oauthApp.detail.save': 'Save Changes',+ 'oauthApp.detail.saveSuccess': 'Changes saved',+ 'oauthApp.detail.title': 'App Details',+ 'oauthApp.detail.type': 'Type',+ 'oauthApp.form.description.label': 'Description',+ 'oauthApp.form.description.placeholder': 'What is this app for? (optional)',+ 'oauthApp.form.logo.label': 'Logo',+ 'oauthApp.form.name.label': 'Name',+ 'oauthApp.form.name.placeholder': 'Please enter app name',+ 'oauthApp.form.submit': 'Create',+ 'oauthApp.form.title': 'Create OAuth App',+ 'oauthApp.item.disabledTag': 'Disabled',+ 'oauthApp.item.lastUsed': 'Last used {{time}}',+ 'oauthApp.list.actions.create': 'Create App',+ 'oauthApp.list.actions.delete': 'Delete',+ 'oauthApp.list.empty': 'No OAuth apps yet. Create one to get started.',+ 'oauthApp.list.neverUsed': 'Never used',+ 'oauthApp.stats.activeUsers': 'Active Users',+ 'oauthApp.stats.calls': 'Total Calls',+ 'oauthApp.stats.credits': 'Credits Used',+ 'oauthApp.stats.empty': 'No usage data yet',+ 'oauthApp.stats.lastUsed': 'Last Called',+ 'oauthApp.stats.neverUsed': 'Never used',+ 'oauthApp.stats.title': 'Usage Stats',+ 'oauthApp.stats.tokens': 'Tokens',+ 'oauthApp.type.badge': 'Native · Device Flow',+ 'oauthApp.type.deviceFlow': 'Device Flow',+ 'oauthApp.validation.nameRequired': 'Name is required','profile.account': 'Account','profile.authorizations.actions.revoke': 'Revoke','profile.authorizations.revoke.description':@@ -272,6 +318,7 @@ export default {'stats.workspace.welcome':'<span>{{name}}</span> has been running for <span>{{days}}</span> days','tab.apikey': 'API Key',+ 'tab.oauthApps': 'OAuth Apps','tab.profile': 'My Account','tab.security': 'Security','tab.stats': 'Statistics',diff --git a/packages/locales/src/default/labs.ts b/packages/locales/src/default/labs.tsindex f8a666d8a0f..c98b4a3b704 100644--- a/packages/locales/src/default/labs.ts+++ b/packages/locales/src/default/labs.ts@@ -37,6 +37,9 @@ export default {'features.messageTextSelectionActions.desc':'Show a quick action when selecting text in chat messages so the selected text can be added to the next conversation context.','features.messageTextSelectionActions.title': 'Message Text Selection Actions',+ 'features.oauthApps.desc':+ 'Show OAuth app management in personal and workspace settings. This feature is hidden by default.',+ 'features.oauthApps.title': 'OAuth Apps','features.platformAgent.desc':'Show the "Connect Agent" entry in the create menu. Connected agents (e.g. OpenClaw, Hermes) run on your own devices and communicate back via lh connect.','features.platformAgent.title': 'Connect Agent',diff --git a/packages/locales/src/default/oauth.ts b/packages/locales/src/default/oauth.tsindex 12fbe66b43d..cbfd2c9eb8e 100644--- a/packages/locales/src/default/oauth.ts+++ b/packages/locales/src/default/oauth.ts@@ -19,6 +19,11 @@ export default {'consent.scope.profile': 'Access your basic profile information (name, avatar, etc.)','consent.scope.sync-read': 'Read your synchronized data','consent.scope.sync-write': 'Write and update your synchronized data',+ 'consent.thirdParty.developedBy': 'By {{developerName}}',+ 'consent.thirdParty.notice':+ 'This application is created by a third-party developer and is not operated by LobeHub. Once authorized, it can act on your behalf and use your account quota.',+ 'consent.thirdParty.privacyPolicy': 'Privacy Policy',+ 'consent.thirdParty.unknownDeveloper': 'a third-party developer','consent.title': 'Authorize {{clientName}}','device.confirm.authorize': 'Authorize','device.confirm.codeHint': 'Confirm that this code matches the one shown in your terminal.',diff --git a/packages/trpc/src/lambda/context.test.ts b/packages/trpc/src/lambda/context.test.tsindex 071de7ff1de..4a082c5ce88 100644--- a/packages/trpc/src/lambda/context.test.ts+++ b/packages/trpc/src/lambda/context.test.ts@@ -110,6 +110,12 @@ describe('createContextInner', () => {expect(context.marketAccessToken).toBe('mp-token-xyz');});+ it('should create context with oidcClientId', async () => {+ const context = await createContextInner({ oidcClientId: 'lca_client_1' });++ expect(context.oidcClientId).toBe('lca_client_1');+ });+it('should create context with OIDC auth data', async () => {const oidcAuth = {sub: 'oidc-user-123',@@ -248,6 +254,32 @@ describe('createLambdaContext', () => {expect(mockGetSession).not.toHaveBeenCalled();});+ it('should carry oidcClientId from the validated OIDC JWT', async () => {+ mockValidateOIDCJWT.mockResolvedValueOnce({+ clientId: 'lca_dev_app_1',+ tokenData: { client_id: 'lca_dev_app_1', sub: 'oidc-user' },+ userId: 'oidc-user',+ });++ const request = new NextRequest('https://example.com/trpc/lambda', {+ headers: { 'Oidc-Auth': 'oidc-token' },+ });++ const context = await createLambdaContext(request);++ expect(context.oidcClientId).toBe('lca_dev_app_1');+ });++ it('should leave oidcClientId undefined when the JWT has no client_id', async () => {+ const request = new NextRequest('https://example.com/trpc/lambda', {+ headers: { 'Oidc-Auth': 'oidc-token' },+ });++ const context = await createLambdaContext(request);++ expect(context.oidcClientId).toBeUndefined();+ });+it('should reject inactive OIDC auth without falling back to session', async () => {const inactiveError = new Error('OIDC user is no longer active');mockAssertOIDCUserActive.mockRejectedValueOnce(inactiveError);diff --git a/packages/trpc/src/lambda/context.ts b/packages/trpc/src/lambda/context.tsindex f52dfa53392..12409f219c9 100644--- a/packages/trpc/src/lambda/context.ts+++ b/packages/trpc/src/lambda/context.ts@@ -74,6 +74,7 @@ export interface AuthContext {marketAccessToken?: string;// Add OIDC authentication informationoidcAuth?: OIDCAuth | null;+ oidcClientId?: string;resHeaders?: Headers;traceContext?: OtContext;userAgent?: string;@@ -89,6 +90,7 @@ export const createContextInner = async (params?: {clientIp?: string | null;marketAccessToken?: string;oidcAuth?: OIDCAuth | null;+ oidcClientId?: string;traceContext?: OtContext;userAgent?: string;userId?: string | null;@@ -101,6 +103,7 @@ export const createContextInner = async (params?: {clientIp: params?.clientIp,marketAccessToken: params?.marketAccessToken,oidcAuth: params?.oidcAuth,+ oidcClientId: params?.oidcClientId,resHeaders: responseHeaders,traceContext: params?.traceContext,userAgent: params?.userAgent,@@ -200,10 +203,14 @@ export const createLambdaContext = async (request: NextRequest): Promise<LambdaCawait assertOIDCUserActive(db, userId);log('OIDC authentication successful, userId: %s', userId);+ const oidcClientId =+ typeof tokenInfo.clientId === 'string' ? tokenInfo.clientId : undefined;+// If OIDC authentication is successful, return context immediatelylog('OIDC authentication successful, creating context and returning');return createContextInner({oidcAuth,+ oidcClientId,...commonContext,traceContext,userId,diff --git a/packages/types/src/oauthApp.ts b/packages/types/src/oauthApp.tsnew file mode 100644index 00000000000..29411ad2ed1--- /dev/null+++ b/packages/types/src/oauthApp.ts@@ -0,0 +1,24 @@+export interface OAuthAppItem {+ applicationType?: string | null;+ createdAt: Date;+ description?: string | null;+ enabled?: boolean | null;+ id: string;+ lastUsedAt?: Date | null;+ logoUri?: string | null;+ name: string;+ scopes?: string[] | null;+ updatedAt?: Date;+}++export interface CreateOAuthAppParams {+ description?: string;+ logoUri?: string;+ name: string;+}++export interface UpdateOAuthAppParams {+ description?: string;+ logoUri?: string;+ name?: string;+}diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.tsindex 64ccfa95528..1c3cb255263 100644--- a/packages/types/src/user/preference.ts+++ b/packages/types/src/user/preference.ts@@ -127,6 +127,10 @@ export const UserLabSchema = z.object({* enable selecting message text and adding it to the next conversation context*/enableMessageTextSelectionActions: z.boolean().optional(),+ /**+ * show OAuth app management in personal and workspace settings+ */+ enableOAuthApps: z.boolean().optional(),/*** show the "Add Platform Agent" entry in the create menu*/diff --git a/src/app/(backend)/oidc/client-metadata/[clientId]/route.test.ts b/src/app/(backend)/oidc/client-metadata/[clientId]/route.test.tsnew file mode 100644index 00000000000..59547e6dc3e--- /dev/null+++ b/src/app/(backend)/oidc/client-metadata/[clientId]/route.test.ts@@ -0,0 +1,92 @@+/**+ * @vitest-environment node+ */+import type { NextRequest } from 'next/server';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { GET } from './route';++const mocks = vi.hoisted(() => ({+ authEnv: { ENABLE_OIDC: true },+ getConsentClientMetadata: vi.fn(),+ getUserAuth: vi.fn(),+}));++vi.mock('debug', () => ({+ default: () => vi.fn(),+}));++vi.mock('@lobechat/utils/server', () => ({+ getUserAuth: mocks.getUserAuth,+}));++vi.mock('@/envs/auth', () => ({+ authEnv: mocks.authEnv,+}));++vi.mock('@/server/services/oidc', () => ({+ OIDCService: {+ initialize: vi.fn(async () => ({+ getConsentClientMetadata: mocks.getConsentClientMetadata,+ })),+ },+}));++const createRequest = (clientId: string) =>+ new Request(`https://example.com/oidc/client-metadata/${clientId}`) as unknown as NextRequest;++const createProps = (clientId: string) => ({ params: Promise.resolve({ clientId }) });++describe('GET /oidc/client-metadata/[clientId]', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.authEnv.ENABLE_OIDC = true;+ mocks.getUserAuth.mockResolvedValue({ userId: 'user-1' });+ });++ it('returns 404 when OIDC is not enabled', async () => {+ mocks.authEnv.ENABLE_OIDC = false;++ const response = await GET(createRequest('lca_1'), createProps('lca_1'));++ expect(response.status).toBe(404);+ expect(mocks.getConsentClientMetadata).not.toHaveBeenCalled();+ });++ it('returns 401 for an anonymous request', async () => {+ mocks.getUserAuth.mockResolvedValue({ userId: undefined });++ const response = await GET(createRequest('lca_1'), createProps('lca_1'));++ expect(response.status).toBe(401);+ expect(mocks.getConsentClientMetadata).not.toHaveBeenCalled();+ });++ it('returns metadata for an authenticated request', async () => {+ mocks.getConsentClientMetadata.mockResolvedValue({+ clientName: 'Third Party App',+ developerName: 'Jane Doe',+ isFirstParty: false,+ policyUri: 'https://third.party/privacy',+ });++ const response = await GET(createRequest('lca_1'), createProps('lca_1'));++ expect(response.status).toBe(200);+ await expect(response.json()).resolves.toEqual({+ clientName: 'Third Party App',+ developerName: 'Jane Doe',+ isFirstParty: false,+ policyUri: 'https://third.party/privacy',+ });+ expect(mocks.getConsentClientMetadata).toHaveBeenCalledWith('lca_1');+ });++ it('returns 500 on unexpected errors', async () => {+ mocks.getConsentClientMetadata.mockRejectedValue(new Error('database exploded'));++ const response = await GET(createRequest('lca_1'), createProps('lca_1'));++ expect(response.status).toBe(500);+ });+});diff --git a/src/app/(backend)/oidc/client-metadata/[clientId]/route.ts b/src/app/(backend)/oidc/client-metadata/[clientId]/route.tsnew file mode 100644index 00000000000..12840e7370b--- /dev/null+++ b/src/app/(backend)/oidc/client-metadata/[clientId]/route.ts@@ -0,0 +1,35 @@+import { getUserAuth } from '@lobechat/utils/server';+import debug from 'debug';+import { type NextRequest } from 'next/server';+import { NextResponse } from 'next/server';++import { authEnv } from '@/envs/auth';+import { OIDCService } from '@/server/services/oidc';+import type { OidcClientMetadata } from '@/types/oidc';++const log = debug('lobe-oidc:client-metadata');++export async function GET(_request: NextRequest, props: { params: Promise<{ clientId: string }> }) {+ if (!authEnv.ENABLE_OIDC) {+ log('OIDC is not enabled');+ return new NextResponse(null, { status: 404 });+ }++ const { userId } = await getUserAuth();+ if (!userId) {+ log('Unauthenticated request rejected');+ return new NextResponse(null, { status: 401 });+ }++ const { clientId } = await props.params;++ try {+ const oidcService = await OIDCService.initialize();+ const clientMetadata = await oidcService.getConsentClientMetadata(clientId);++ return NextResponse.json<OidcClientMetadata>(clientMetadata);+ } catch (error) {+ log('Error resolving client metadata for %s: %O', clientId, error);+ return new NextResponse(null, { status: 500 });+ }+}diff --git a/src/app/(backend)/oidc/interaction/[uid]/route.test.ts b/src/app/(backend)/oidc/interaction/[uid]/route.test.tsindex c4b2d209c72..9fc3c0ce49c 100644--- a/src/app/(backend)/oidc/interaction/[uid]/route.test.ts+++ b/src/app/(backend)/oidc/interaction/[uid]/route.test.ts@@ -8,7 +8,7 @@ import { GET } from './route';const mocks = vi.hoisted(() => ({authEnv: { ENABLE_OIDC: true },- getClientMetadata: vi.fn(),+ getConsentClientMetadata: vi.fn(),getInteractionDetails: vi.fn(),}));@@ -20,14 +20,10 @@ vi.mock('@/envs/auth', () => ({authEnv: mocks.authEnv,}));-vi.mock('@/libs/oidc-provider/config', () => ({- defaultClients: [{ client_id: 'lobehub-desktop' }],-}));-vi.mock('@/server/services/oidc', () => ({OIDCService: {initialize: vi.fn(async () => ({- getClientMetadata: mocks.getClientMetadata,+ getConsentClientMetadata: mocks.getConsentClientMetadata,getInteractionDetails: mocks.getInteractionDetails,})),},@@ -62,9 +58,10 @@ describe('GET /oidc/interaction/[uid]', () => {},prompt: { name: 'consent' },});- mocks.getClientMetadata.mockResolvedValue({- client_name: 'LobeHub Desktop',- logo_uri: 'https://example.com/logo.png',+ mocks.getConsentClientMetadata.mockResolvedValue({+ clientName: 'LobeHub Desktop',+ isFirstParty: true,+ logo: 'https://example.com/logo.png',});const response = await GET(createRequest('uid-1'), createProps('uid-1'));@@ -83,26 +80,36 @@ describe('GET /oidc/interaction/[uid]', () => {uid: 'uid-1',});expect(mocks.getInteractionDetails).toHaveBeenCalledWith('uid-1');- expect(mocks.getClientMetadata).toHaveBeenCalledWith('lobehub-desktop');+ expect(mocks.getConsentClientMetadata).toHaveBeenCalledWith('lobehub-desktop');});- it('marks third-party clients as not first party', async () => {+ it('passes through third-party client metadata with developer info', async () => {mocks.getInteractionDetails.mockResolvedValue({params: {- client_id: 'third-party-app',+ client_id: 'lca_thirdparty',redirect_uri: 'https://third.party/cb',scope: 'openid',},prompt: { name: 'consent' },});- mocks.getClientMetadata.mockResolvedValue(undefined);+ mocks.getConsentClientMetadata.mockResolvedValue({+ clientName: 'Third Party App',+ developerName: 'Jane Doe',+ isFirstParty: false,+ policyUri: 'https://third.party/privacy',+ });const response = await GET(createRequest('uid-2'), createProps('uid-2'));expect(response.status).toBe(200);const body = await response.json();- expect(body.clientMetadata).toEqual({ isFirstParty: false });- expect(body.clientId).toBe('third-party-app');+ expect(body.clientMetadata).toEqual({+ clientName: 'Third Party App',+ developerName: 'Jane Doe',+ isFirstParty: false,+ policyUri: 'https://third.party/privacy',+ });+ expect(body.clientId).toBe('lca_thirdparty');});it('returns interaction details for a login prompt', async () => {@@ -110,7 +117,10 @@ describe('GET /oidc/interaction/[uid]', () => {params: { client_id: 'lobehub-desktop' },prompt: { name: 'login' },});- mocks.getClientMetadata.mockResolvedValue({ client_name: 'LobeHub Desktop' });+ mocks.getConsentClientMetadata.mockResolvedValue({+ clientName: 'LobeHub Desktop',+ isFirstParty: true,+ });const response = await GET(createRequest('uid-3'), createProps('uid-3'));diff --git a/src/app/(backend)/oidc/interaction/[uid]/route.ts b/src/app/(backend)/oidc/interaction/[uid]/route.tsindex 32a7c35021b..8ce063b4362 100644--- a/src/app/(backend)/oidc/interaction/[uid]/route.ts+++ b/src/app/(backend)/oidc/interaction/[uid]/route.ts@@ -3,7 +3,6 @@ import { type NextRequest } from 'next/server';import { NextResponse } from 'next/server';import { authEnv } from '@/envs/auth';-import { defaultClients } from '@/libs/oidc-provider/config';import { OIDCService } from '@/server/services/oidc';import type { OidcInteractionDetailsResponse, OidcInteractionErrorResponse } from '@/types/oidc';@@ -38,15 +37,11 @@ export async function GET(request: NextRequest, props: { params: Promise<{ uid:const clientId = (details.params.client_id as string) || 'unknown';const scopes = (details.params.scope as string)?.split(' ') || [];- const clientDetail = await oidcService.getClientMetadata(clientId);+ const clientMetadata = await oidcService.getConsentClientMetadata(clientId);return NextResponse.json<OidcInteractionDetailsResponse>({clientId,- clientMetadata: {- clientName: clientDetail?.client_name,- isFirstParty: defaultClients.map((c) => c.client_id).includes(clientId),- logo: clientDetail?.logo_uri,- },+ clientMetadata,prompt: details.prompt.name,redirectUri: details.params.redirect_uri as string,scopes,diff --git a/src/business/client/OAuthAppStats/index.tsx b/src/business/client/OAuthAppStats/index.tsxnew file mode 100644index 00000000000..21ee2a8bcff--- /dev/null+++ b/src/business/client/OAuthAppStats/index.tsx@@ -0,0 +1,7 @@+interface OAuthAppStatsProps {+ clientId: string;+}++const OAuthAppStats = (_props: OAuthAppStatsProps) => null;++export default OAuthAppStats;diff --git a/src/features/Auth/OAuthConsent/Consent/index.tsx b/src/features/Auth/OAuthConsent/Consent/index.tsxindex 961603fb707..56063eead82 100644--- a/src/features/Auth/OAuthConsent/Consent/index.tsx+++ b/src/features/Auth/OAuthConsent/Consent/index.tsx@@ -9,6 +9,7 @@ import AuthCard from '@/features/AuthCard';import type { OidcClientMetadata } from '@/types/oidc';import OAuthApplicationLogo from '../OAuthApplicationLogo';+import ThirdPartyNotice from '../ThirdPartyNotice';import BuiltinConsent from './BuiltinConsent';interface ClientProps {@@ -82,6 +83,14 @@ const ConsentClient = memo<ClientProps>(({ uid, clientId, scopes, clientMetadata</form>}>+ {clientMetadata.isFirstParty === false && (+ <Flexbox style={{ marginBottom: 16 }}>+ <ThirdPartyNotice+ developerName={clientMetadata.developerName}+ policyUri={clientMetadata.policyUri}+ />+ </Flexbox>+ )}<Text fontSize={16} type={'secondary'}>{t('consent.permissionsTitle')}</Text>diff --git a/src/features/Auth/OAuthConsent/OAuthApplicationLogo.tsx b/src/features/Auth/OAuthConsent/OAuthApplicationLogo.tsxindex 38b34612044..dd02b62415d 100644--- a/src/features/Auth/OAuthConsent/OAuthApplicationLogo.tsx+++ b/src/features/Auth/OAuthConsent/OAuthApplicationLogo.tsx@@ -38,7 +38,7 @@ const OAuthApplicationLogo = memo<OAuthApplicationLogoProps>(return isFirstParty ? (<Avatar alt={clientDisplayName} avatar={logoUrl!} shape={'square'} size={size} />) : (- <Flexbox horizontal align={'center'} gap={8}>+ <Flexbox horizontal align={'center'} gap={8} justify={'center'}>{logoUrl ? (<Avatar alt={clientDisplayName} avatar={logoUrl} size={size} />) : (diff --git a/src/features/Auth/OAuthConsent/ThirdPartyNotice.tsx b/src/features/Auth/OAuthConsent/ThirdPartyNotice.tsxnew file mode 100644index 00000000000..617c977f127--- /dev/null+++ b/src/features/Auth/OAuthConsent/ThirdPartyNotice.tsx@@ -0,0 +1,39 @@+'use client';++import { Alert, Flexbox, Icon, Text } from '@lobehub/ui';+import { cssVar } from 'antd-style';+import { ExternalLinkIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++interface ThirdPartyNoticeProps {+ developerName?: string;+ policyUri?: string;+}++const ThirdPartyNotice = memo<ThirdPartyNoticeProps>(({ developerName, policyUri }) => {+ const { t } = useTranslation('oauth');++ const developer = developerName || t('consent.thirdParty.unknownDeveloper');++ return (+ <Flexbox gap={8} width={'100%'}>+ <Text type={'secondary'}>+ {t('consent.thirdParty.developedBy', { developerName: developer })}+ </Text>+ <Alert showIcon description={t('consent.thirdParty.notice')} type={'warning'} />+ {policyUri && (+ <a href={policyUri} rel={'noreferrer'} target={'_blank'}>+ <Flexbox horizontal align={'center'} gap={4}>+ <Text style={{ color: cssVar.colorLink }}>{t('consent.thirdParty.privacyPolicy')}</Text>+ <Icon icon={ExternalLinkIcon} style={{ color: cssVar.colorLink, fontSize: 14 }} />+ </Flexbox>+ </a>+ )}+ </Flexbox>+ );+});++ThirdPartyNotice.displayName = 'ThirdPartyNotice';++export default ThirdPartyNotice;diff --git a/src/features/Auth/OAuthConsent/useClientMetadata.ts b/src/features/Auth/OAuthConsent/useClientMetadata.tsnew file mode 100644index 00000000000..1d6324d2904--- /dev/null+++ b/src/features/Auth/OAuthConsent/useClientMetadata.ts@@ -0,0 +1,23 @@+import useSWR from 'swr';++import { authKeys } from '@/libs/swr/keys';+import type { OidcClientMetadata } from '@/types/oidc';++const fetchClientMetadata = async (clientId: string): Promise<OidcClientMetadata> => {+ const res = await fetch(`/oidc/client-metadata/${encodeURIComponent(clientId)}`);++ if (!res.ok) throw new Error(`Request failed with status ${res.status}`);++ return res.json();+};++export const useClientMetadata = (clientId?: string) =>+ useSWR(+ clientId ? authKeys.oidcClientMetadata(clientId) : null,+ ([, id]: [string, string]) => fetchClientMetadata(id),+ {+ revalidateOnFocus: false,+ revalidateOnReconnect: false,+ shouldRetryOnError: false,+ },+ );diff --git a/src/features/Auth/OAuthDevice/DeviceCodeConfirm.tsx b/src/features/Auth/OAuthDevice/DeviceCodeConfirm.tsxindex 10f7a6f5b59..97fcc0154a4 100644--- a/src/features/Auth/OAuthDevice/DeviceCodeConfirm.tsx+++ b/src/features/Auth/OAuthDevice/DeviceCodeConfirm.tsx@@ -7,62 +7,74 @@ import { useTranslation } from 'react-i18next';import AuthCard from '@/features/AuthCard';+import ThirdPartyNotice from '../OAuthConsent/ThirdPartyNotice';+interface DeviceCodeConfirmProps {clientName: string;+ developerName?: string;+ isFirstParty?: boolean;+ policyUri?: string;userCode: string;xsrf?: string;}-const DeviceCodeConfirm = memo<DeviceCodeConfirmProps>(({ xsrf, userCode, clientName }) => {- const { t } = useTranslation('oauth');- const [isLoading, setIsLoading] = useState(false);+const DeviceCodeConfirm = memo<DeviceCodeConfirmProps>(+ ({ xsrf, userCode, clientName, developerName, isFirstParty, policyUri }) => {+ const { t } = useTranslation('oauth');+ const [isLoading, setIsLoading] = useState(false);- return (- <AuthCard- subtitle={t('device.confirm.description', { clientName })}- title={t('device.confirm.title')}- footer={- <form action="/oidc/device" method="post" style={{ width: '100%' }}>- {xsrf && <input name="xsrf" type="hidden" value={xsrf} />}- <input name="user_code" type="hidden" value={userCode} />- <input name="confirm" type="hidden" value="yes" />- <Flexbox gap={12}>- <Button- block- htmlType="submit"- loading={isLoading}- size="large"- type="primary"- onClick={() => setIsLoading(true)}- >- {t('device.confirm.authorize')}- </Button>- <Button block htmlType="submit" name="abort" size="large" value="yes">- {t('device.confirm.deny')}- </Button>+ return (+ <AuthCard+ subtitle={t('device.confirm.description', { clientName })}+ title={t('device.confirm.title')}+ footer={+ <form action="/oidc/device" method="post" style={{ width: '100%' }}>+ {xsrf && <input name="xsrf" type="hidden" value={xsrf} />}+ <input name="user_code" type="hidden" value={userCode} />+ <input name="confirm" type="hidden" value="yes" />+ <Flexbox gap={12}>+ <Button+ block+ htmlType="submit"+ loading={isLoading}+ size="large"+ type="primary"+ onClick={() => setIsLoading(true)}+ >+ {t('device.confirm.authorize')}+ </Button>+ <Button block htmlType="submit" name="abort" size="large" value="yes">+ {t('device.confirm.deny')}+ </Button>+ </Flexbox>+ </form>+ }+ >+ {isFirstParty === false && (+ <Flexbox style={{ marginBottom: 16 }}>+ <ThirdPartyNotice developerName={developerName} policyUri={policyUri} /></Flexbox>- </form>- }- >- <Block padding={16} variant="filled">- <Text- style={{- fontFamily: 'monospace',- fontSize: 24,- fontWeight: 'bold',- letterSpacing: '0.15em',- textAlign: 'center',- }}- >- {userCode}+ )}+ <Block padding={16} variant="filled">+ <Text+ style={{+ fontFamily: 'monospace',+ fontSize: 24,+ fontWeight: 'bold',+ letterSpacing: '0.15em',+ textAlign: 'center',+ }}+ >+ {userCode}+ </Text>+ </Block>+ <Text style={{ marginTop: 8 }} type="secondary">+ {t('device.confirm.codeHint')}</Text>- </Block>- <Text style={{ marginTop: 8 }} type="secondary">- {t('device.confirm.codeHint')}- </Text>- </AuthCard>- );-});+ </AuthCard>+ );+ },+);DeviceCodeConfirm.displayName = 'DeviceCodeConfirm';diff --git a/src/features/Auth/OAuthDevice/DeviceConfirmPage.tsx b/src/features/Auth/OAuthDevice/DeviceConfirmPage.tsxindex 5360080384a..d6b161be101 100644--- a/src/features/Auth/OAuthDevice/DeviceConfirmPage.tsx+++ b/src/features/Auth/OAuthDevice/DeviceConfirmPage.tsx@@ -5,6 +5,7 @@ import { useSearchParams } from 'react-router';import NotFound from '@/components/404';+import { useClientMetadata } from '../OAuthConsent/useClientMetadata';import OAuthGuard from '../OAuthGuard';import DeviceCodeConfirm from './DeviceCodeConfirm';@@ -12,16 +13,23 @@ const DeviceConfirmPage = memo(() => {const [searchParams] = useSearchParams();const userCode = searchParams.get('user_code');+ const clientId = searchParams.get('client_id') ?? undefined;++ const { data: clientMetadata } = useClientMetadata(clientId);return (<OAuthGuard>{userCode ? (<DeviceCodeConfirm+ developerName={clientMetadata?.developerName}+ isFirstParty={clientMetadata?.isFirstParty}+ policyUri={clientMetadata?.policyUri}userCode={userCode}xsrf={searchParams.get('xsrf') ?? undefined}clientName={+ clientMetadata?.clientName ||searchParams.get('client_name') ||- searchParams.get('client_id') ||+ clientId ||'Unknown Application'}/>diff --git a/src/features/Workspace/__tests__/workspaceAwarePath.test.ts b/src/features/Workspace/__tests__/workspaceAwarePath.test.tsindex 99a264d2608..d89604b8fca 100644--- a/src/features/Workspace/__tests__/workspaceAwarePath.test.ts+++ b/src/features/Workspace/__tests__/workspaceAwarePath.test.ts@@ -77,6 +77,12 @@ describe('buildWorkspaceAwarePath', () => {expect(buildWorkspaceAwarePath('/settings/storage', 'acme')).toBe('/acme/settings/storage');expect(buildWorkspaceAwarePath('/settings/messenger', 'acme')).toBe('/acme/settings/messenger');expect(buildWorkspaceAwarePath('/settings/creds', 'acme')).toBe('/acme/settings/creds');+ expect(buildWorkspaceAwarePath('/settings/oauth-apps', 'acme')).toBe(+ '/acme/settings/oauth-apps',+ );+ expect(buildWorkspaceAwarePath('/settings/oauth-apps/client-1', 'acme')).toBe(+ '/acme/settings/oauth-apps/client-1',+ );expect(buildWorkspaceAwarePath('/settings/provider/openai', 'acme')).toBe('/acme/settings/provider/openai',);diff --git a/src/features/Workspace/workspaceAwarePath.ts b/src/features/Workspace/workspaceAwarePath.tsindex a3eca841e45..dfb1ff2282c 100644--- a/src/features/Workspace/workspaceAwarePath.ts+++ b/src/features/Workspace/workspaceAwarePath.ts@@ -40,6 +40,7 @@ export const WORKSPACE_SETTINGS_TABS: ReadonlySet<string> = new Set(['general','members','messenger',+ 'oauth-apps','plans','provider','service-model',diff --git a/src/features/WorkspaceSetting/hooks/useCategory.test.tsx b/src/features/WorkspaceSetting/hooks/useCategory.test.tsxnew file mode 100644index 00000000000..5fd2727cc40--- /dev/null+++ b/src/features/WorkspaceSetting/hooks/useCategory.test.tsx@@ -0,0 +1,62 @@+import { cleanup, renderHook } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { useUserStore } from '@/store/user';+import { WorkspaceSettingsTabs } from '@/types/workspaceSettings';++import { useWorkspaceSettingCategory } from './useCategory';++vi.hoisted(() => {+ Object.defineProperty(globalThis, 'localStorage', {+ configurable: true,+ value: {+ getItem: vi.fn(() => null),+ removeItem: vi.fn(),+ setItem: vi.fn(),+ },+ });+});++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ }),+}));++vi.mock('@/business/client/hooks/useIsWorkspaceOwner', () => ({+ useIsWorkspaceOwner: () => true,+}));++vi.mock('@/business/client/hooks/useIsWorkspaceViewer', () => ({+ useIsWorkspaceViewer: () => false,+}));++const initialUserStoreState = useUserStore.getState();++const getItemKeys = () => {+ const { result } = renderHook(() => useWorkspaceSettingCategory());++ return result.current.flatMap((group) => group.items.map((item) => item.key));+};++afterEach(() => {+ cleanup();+ useUserStore.setState(initialUserStoreState, true);+});++describe('workspace settings useCategory', () => {+ it('hides OAuth Apps by default', () => {+ expect(getItemKeys()).not.toContain(WorkspaceSettingsTabs.OAuthApps);+ });++ it('shows OAuth Apps when the Labs preference is enabled', () => {+ useUserStore.setState({+ preference: {+ ...initialUserStoreState.preference,+ lab: { ...initialUserStoreState.preference.lab, enableOAuthApps: true },+ },+ });++ expect(getItemKeys()).toContain(WorkspaceSettingsTabs.OAuthApps);+ });+});diff --git a/src/features/WorkspaceSetting/hooks/useCategory.tsx b/src/features/WorkspaceSetting/hooks/useCategory.tsxindex b812320b991..cd14885be8c 100644--- a/src/features/WorkspaceSetting/hooks/useCategory.tsx+++ b/src/features/WorkspaceSetting/hooks/useCategory.tsx@@ -1,5 +1,6 @@import { SkillsIcon } from '@lobehub/ui/icons';import {+ AppWindowIcon,Blocks,Brain,Building2,@@ -20,6 +21,8 @@ import { useTranslation } from 'react-i18next';import { useIsWorkspaceOwner } from '@/business/client/hooks/useIsWorkspaceOwner';import { useIsWorkspaceViewer } from '@/business/client/hooks/useIsWorkspaceViewer';+import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';import { WorkspaceSettingsTabs } from '@/types/workspaceSettings';export enum WorkspaceSettingsGroupKey {@@ -47,6 +50,7 @@ export const useWorkspaceSettingCategory = (): WorkspaceSettingCategoryGroup[] =const { t: tSubscription } = useTranslation('subscription');const isOwner = useIsWorkspaceOwner();const isViewer = useIsWorkspaceViewer();+ const enableOAuthApps = useUserStore(labPreferSelectors.enableOAuthApps);return useMemo(() =>@@ -141,6 +145,11 @@ export const useWorkspaceSettingCategory = (): WorkspaceSettingCategoryGroup[] =key: WorkspaceSettingsTabs.APIKey,label: tAuth('tab.apikey'),},+ enableOAuthApps && {+ icon: AppWindowIcon,+ key: WorkspaceSettingsTabs.OAuthApps,+ label: tAuth('tab.oauthApps'),+ },// Messenger (chat platform) is intentionally omitted from workspace// settings: the System Bot binding is a per-user/personal identity// (the link is owned by `userId`, not the workspace), and reaching a@@ -169,6 +178,6 @@ export const useWorkspaceSettingCategory = (): WorkspaceSettingCategoryGroup[] =title: t('workspaceSetting.group.admin'),},].filter(Boolean) as WorkspaceSettingCategoryGroup[],- [t, tAuth, tSubscription, isOwner, isViewer],+ [t, tAuth, tSubscription, enableOAuthApps, isOwner, isViewer],);};diff --git a/src/libs/next/proxy/define-config.test.ts b/src/libs/next/proxy/define-config.test.tsindex 49e698b9b4e..33f03cc6569 100644--- a/src/libs/next/proxy/define-config.test.ts+++ b/src/libs/next/proxy/define-config.test.ts@@ -7,7 +7,7 @@ import { describe, expect, it, vi } from 'vitest';import { defineConfig } from './define-config';vi.mock('@/auth', () => ({- auth: { api: { getSession: vi.fn().mockResolvedValue(null) } },+ auth: { api: { getSession: vi.fn().mockResolvedValue({ user: { id: 'user-1' } }) } },}));const { middleware } = defineConfig();@@ -36,4 +36,13 @@ describe('defineConfig locale path-traversal hardening', () => {expect(pathname.startsWith('/spa-auth/')).toBe(true);expect(pathname).toBe('/spa-auth/en-US/signin');});++ it('does not treat workspace slugs beginning with an auth route as auth SPA pages', async () => {+ const rewrite = await run(+ 'http://localhost:3010/oauth-preview-e2e-20260716/settings/oauth-apps?hl=en-US',+ );+ expect(new URL(rewrite!).pathname).toMatch(+ /^\/spa\/[^/]+\/oauth-preview-e2e-20260716\/settings\/oauth-apps$/,+ );+ });});diff --git a/src/libs/next/proxy/define-config.ts b/src/libs/next/proxy/define-config.tsindex 2df1f6732bd..1d146c83b96 100644--- a/src/libs/next/proxy/define-config.ts+++ b/src/libs/next/proxy/define-config.ts@@ -129,7 +129,9 @@ export function defineConfig() {return NextResponse.next();}- const isAuthSpaRoute = authSpaRoutes.some((r) => url.pathname.startsWith(r));+ const isAuthSpaRoute = authSpaRoutes.some(+ (route) => url.pathname === route || url.pathname.startsWith(`${route}/`),+ );// Auth SPA routes: rewrite to /spa-auth/[locale]/[[...path]] catch-allif (isAuthSpaRoute) {diff --git a/src/libs/oidc-provider/adapter.test.ts b/src/libs/oidc-provider/adapter.test.tsnew file mode 100644index 00000000000..70e4ba1360d--- /dev/null+++ b/src/libs/oidc-provider/adapter.test.ts@@ -0,0 +1,164 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { DrizzleAdapter } from './adapter';++vi.mock('debug', () => ({+ default: () => vi.fn(),+}));++const createSelectDb = (rows: any[]) => {+ const chain = {+ from: vi.fn(() => chain),+ limit: vi.fn(() => Promise.resolve(rows)),+ where: vi.fn(() => chain),+ };+ return { select: vi.fn(() => chain) };+};++const createUpsertDb = (options?: { updateRejects?: boolean }) => {+ const updateWhere = vi.fn(() =>+ options?.updateRejects+ ? Promise.reject(new Error('update failed'))+ : Promise.resolve(undefined),+ );+ const updateChain = {+ set: vi.fn(() => updateChain),+ where: updateWhere,+ };++ const insertChain = {+ onConflictDoUpdate: vi.fn(() => Promise.resolve(undefined)),+ values: vi.fn(() => insertChain),+ };++ const update = vi.fn(() => updateChain);++ return {+ db: {+ insert: vi.fn(() => insertChain),+ update,+ },+ update,+ updateChain,+ };+};++describe('OIDCAdapter (DrizzleAdapter)', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ describe('find Client enforcement', () => {+ const clientRow = {+ applicationType: 'native',+ clientSecret: null,+ enabled: true,+ grants: ['urn:ietf:params:oauth:grant-type:device_code'],+ id: 'lca_client_1',+ isFirstParty: false,+ redirectUris: [],+ responseTypes: [],+ scopes: ['openid', 'profile'],+ };++ it('returns the mapped client when enabled', async () => {+ const db = createSelectDb([clientRow]);+ const adapter = new DrizzleAdapter('Client', db as any);++ const result = await adapter.find('lca_client_1');++ expect(result).toMatchObject({+ client_id: 'lca_client_1',+ scope: 'openid profile',+ });+ });++ it('returns undefined when the client is disabled', async () => {+ const db = createSelectDb([{ ...clientRow, enabled: false }]);+ const adapter = new DrizzleAdapter('Client', db as any);++ const result = await adapter.find('lca_client_1');++ expect(result).toBeUndefined();+ });++ it('omits null optional fields so oidc-provider client schema accepts the metadata', async () => {+ const db = createSelectDb([+ {+ ...clientRow,+ clientUri: null,+ logoUri: null,+ policyUri: null,+ tokenEndpointAuthMethod: 'none',+ tosUri: null,+ },+ ]);+ const adapter = new DrizzleAdapter('Client', db as any);++ const result = (await adapter.find('lca_client_1')) as Record<string, unknown>;++ for (const key of ['client_secret', 'client_uri', 'logo_uri', 'policy_uri', 'tos_uri']) {+ expect(result).not.toHaveProperty(key);+ }+ expect(result).toMatchObject({+ client_id: 'lca_client_1',+ token_endpoint_auth_method: 'none',+ });+ });+ });++ describe('lastUsedAt stamping', () => {+ const flush = () => new Promise((resolve) => setTimeout(resolve, 0));++ it('stamps last_used_at for a user-created (lca_) client on AccessToken upsert', async () => {+ const { db, update, updateChain } = createUpsertDb();+ const adapter = new DrizzleAdapter('AccessToken', db as any);++ await adapter.upsert('token-1', { accountId: 'user-1', clientId: 'lca_client_1' }, 3600);+ await flush();++ expect(update).toHaveBeenCalledTimes(1);+ expect(updateChain.set).toHaveBeenCalledWith(+ expect.objectContaining({ lastUsedAt: expect.any(Date) }),+ );+ });++ it('stamps last_used_at on DeviceCode upsert', async () => {+ const { db, update } = createUpsertDb();+ const adapter = new DrizzleAdapter('DeviceCode', db as any);++ await adapter.upsert(+ 'device-1',+ { accountId: 'user-1', clientId: 'lca_client_2', userCode: 'ABCD' },+ 600,+ );+ await flush();++ expect(update).toHaveBeenCalledTimes(1);+ });++ it('does not stamp for static first-party clients', async () => {+ const { db, update } = createUpsertDb();+ const adapter = new DrizzleAdapter('AccessToken', db as any);++ await adapter.upsert('token-2', { accountId: 'user-1', clientId: 'lobehub-cli' }, 3600);+ await flush();++ expect(update).not.toHaveBeenCalled();+ });++ it('does not throw when the stamping update fails', async () => {+ const { db } = createUpsertDb({ updateRejects: true });+ const adapter = new DrizzleAdapter('AccessToken', db as any);++ await expect(+ adapter.upsert('token-3', { accountId: 'user-1', clientId: 'lca_client_3' }, 3600),+ ).resolves.toBeUndefined();+ await flush();+ });+ });+});diff --git a/src/libs/oidc-provider/adapter.ts b/src/libs/oidc-provider/adapter.tsindex 2d7c6e033a8..a66613d416e 100644--- a/src/libs/oidc-provider/adapter.ts+++ b/src/libs/oidc-provider/adapter.ts@@ -237,6 +237,10 @@ class OIDCAdapter {target: (table as any).id,});log('[%s] Successfully upserted record: %s', this.name, id);++ if (this.name === 'AccessToken' || this.name === 'DeviceCode') {+ this.stampClientLastUsed(payload.clientId);+ }} catch (error) {log('[%s] ERROR upserting record: %O', this.name, error);console.error(`[OIDC Adapter] Error upserting ${this.name}:`, error);@@ -244,6 +248,20 @@ class OIDCAdapter {}}+ private stampClientLastUsed(clientId?: string): void {+ if (!clientId || !clientId.startsWith('lca_')) return;++ // last_used_at is a best-effort UX signal for user-created OAuth clients;+ // a failed stamp must never break token issuance, so swallow all errors.+ void this.db+ .update(oidcClients)+ .set({ lastUsedAt: new Date() })+ .where(eq(oidcClients.id, clientId))+ .then(undefined, (error: unknown) => {+ log('[%s] Failed to stamp last_used_at for client %s: %O', this.name, clientId, error);+ });+ }+/*** Find model instance*/@@ -275,8 +293,12 @@ class OIDCAdapter {// Special handling for client modelif (this.name === 'Client') {+ if (model.enabled === false) {+ log('[Client] Client %s is disabled, treating as not found', id);+ return undefined;+ }log('[Client] Converting client record to expected format');- return {+ const clientMetadata: Record<string, any> = {application_type: model.applicationType,client_id: model.id,client_secret: model.clientSecret,@@ -291,6 +313,14 @@ class OIDCAdapter {token_endpoint_auth_method: model.tokenEndpointAuthMethod,tos_uri: model.tosUri,};+ // oidc-provider's client schema treats any non-undefined value as "provided" and+ // rejects null for optional string fields (`must be a non-empty string if provided`),+ // so nullable DB columns must be stripped instead of passed through.+ for (const key of Object.keys(clientMetadata)) {+ if (clientMetadata[key] === null || clientMetadata[key] === undefined)+ delete clientMetadata[key];+ }+ return clientMetadata;}// If record has expired, return undefineddiff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 30232c007cb..01c25492b88 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -878,6 +878,12 @@ export const ollamaKeys = {downloadModel: def('ollama:downloadModel', (model: string) => ['ollama:downloadModel', model]),};export const authKeys = {+ oauthAppById: def('auth:oauthAppById', (id: string) => ['auth:oauthAppById', id]),+ oauthAppList: def('auth:oauthAppList', () => ['auth:oauthAppList']),+ oidcClientMetadata: def('auth:oidcClientMetadata', (clientId: string) => [+ 'auth:oidcClientMetadata',+ clientId,+ ]),oidcInteraction: def('auth:oidcInteraction', (uid: string) => ['auth:oidcInteraction', uid]),};export const cronKeys = {diff --git a/src/routes/(main)/[workspaceSlug]/settings/oauth-apps/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/oauth-apps/index.tsxnew file mode 100644index 00000000000..dddd6f2a751--- /dev/null+++ b/src/routes/(main)/[workspaceSlug]/settings/oauth-apps/index.tsx@@ -0,0 +1,5 @@+'use client';++import Page from '@/routes/(main)/settings/oauth-apps';++export default Page;diff --git a/src/routes/(main)/settings/advanced/index.test.tsx b/src/routes/(main)/settings/advanced/index.test.tsxindex 11c5ca66185..c1f3eea051f 100644--- a/src/routes/(main)/settings/advanced/index.test.tsx+++ b/src/routes/(main)/settings/advanced/index.test.tsx@@ -1,4 +1,4 @@-import { render, screen } from '@testing-library/react';+import { cleanup, render, screen } from '@testing-library/react';import { type ReactNode } from 'react';import { afterEach, describe, expect, it, vi } from 'vitest';@@ -73,7 +73,7 @@ vi.mock('@/routes/(main)/settings/features/SettingHeader', () => ({vi.mock('@/services/electron/autoUpdate', () => ({autoUpdateService: {- getUpdateChannel: vi.fn().mockResolvedValue('stable'),+ getUpdateChannel: vi.fn(() => new Promise(() => {})),setUpdateChannel: vi.fn(),},}));@@ -89,6 +89,7 @@ const createWrapper = () => {const initialUserStoreState = useUserStore.getState();afterEach(() => {+ cleanup();useUserStore.setState(initialUserStoreState, true);});@@ -118,6 +119,18 @@ describe('Advanced settings page', () => {expect(screen.getByText('features.messageTextSelectionActions.title')).toBeDefined();});+ it('renders the OAuth Apps lab toggle', () => {+ useUserStore.setState({+ isUserStateInit: true,+ setSettings: vi.fn(),+ updateLab: vi.fn(),+ });++ render(<Page />, { wrapper: createWrapper() });++ expect(screen.getByText('features.oauthApps.title')).toBeDefined();+ });+it('does not render released task verify as a lab toggle', () => {useUserStore.setState({isUserStateInit: true,diff --git a/src/routes/(main)/settings/advanced/index.tsx b/src/routes/(main)/settings/advanced/index.tsxindex d21b82f19f4..c782ac2f525 100644--- a/src/routes/(main)/settings/advanced/index.tsx+++ b/src/routes/(main)/settings/advanced/index.tsx@@ -57,6 +57,7 @@ const Page = memo(() => {enableClaudeCodeSdk,enableFoldFinishedTurn,enableMessageTextSelectionActions,+ enableOAuthApps,enableInAppBrowser,enableArtifactDeployment,enableBuiltinTerminal,@@ -71,6 +72,7 @@ const Page = memo(() => {labPreferSelectors.enableClaudeCodeSdk(s),labPreferSelectors.enableFoldFinishedTurn(s),labPreferSelectors.enableMessageTextSelectionActions(s),+ labPreferSelectors.enableOAuthApps(s),labPreferSelectors.enableInAppBrowser(s),labPreferSelectors.enableArtifactDeployment(s),labPreferSelectors.enableBuiltinTerminal(s),@@ -232,6 +234,19 @@ const Page = memo(() => {label: tLabs('features.messageTextSelectionActions.title'),minWidth: undefined,},+ {+ children: (+ <Switch+ checked={enableOAuthApps}+ loading={!isPreferenceInit}+ onChange={(checked) => updateLab({ enableOAuthApps: checked })}+ />+ ),+ className: styles.labItem,+ desc: tLabs('features.oauthApps.desc'),+ label: tLabs('features.oauthApps.title'),+ minWidth: undefined,+ },...(isDesktop? [{diff --git a/src/routes/(main)/settings/features/componentMap.desktop.ts b/src/routes/(main)/settings/features/componentMap.desktop.tsindex 038a6a3e3f2..f2f61c90fd6 100644--- a/src/routes/(main)/settings/features/componentMap.desktop.ts+++ b/src/routes/(main)/settings/features/componentMap.desktop.ts@@ -16,6 +16,7 @@ import Devices from '../devices';import Hotkey from '../hotkey';import Memory from '../memory';import Messenger from '../messenger';+import OAuthApps from '../oauth-apps';import Profile from '../profile';import Provider from '../provider';import Proxy from '../proxy';@@ -45,6 +46,7 @@ export const componentMap = {[SettingsTabs.Stats]: Stats,[SettingsTabs.Usage]: Usage,[SettingsTabs.APIKey]: APIKey,+ [SettingsTabs.OAuthApps]: OAuthApps,[SettingsTabs.Creds]: Creds,[SettingsTabs.Security]: Security,[SettingsTabs.Skill]: Skill,diff --git a/src/routes/(main)/settings/features/componentMap.ts b/src/routes/(main)/settings/features/componentMap.tsindex 7bad94a732d..2ffcfc1e628 100644--- a/src/routes/(main)/settings/features/componentMap.ts+++ b/src/routes/(main)/settings/features/componentMap.ts@@ -62,6 +62,9 @@ export const componentMap = {[SettingsTabs.APIKey]: dynamic(() => import('../apikey'), {loading: loading('Settings > APIKey'),}),+ [SettingsTabs.OAuthApps]: dynamic(() => import('../oauth-apps'), {+ loading: loading('Settings > OAuthApps'),+ }),[SettingsTabs.Creds]: dynamic(() => import('../creds'), {loading: loading('Settings > Creds'),}),diff --git a/src/routes/(main)/settings/hooks/useCategory.test.tsx b/src/routes/(main)/settings/hooks/useCategory.test.tsxindex d940ec2cf48..bd4e74f1fc8 100644--- a/src/routes/(main)/settings/hooks/useCategory.test.tsx+++ b/src/routes/(main)/settings/hooks/useCategory.test.tsx@@ -1,4 +1,4 @@-import { renderHook } from '@testing-library/react';+import { cleanup, renderHook } from '@testing-library/react';import { type ReactNode } from 'react';import { afterEach, describe, expect, it, vi } from 'vitest';@@ -58,6 +58,7 @@ const getItemKeys = () => {const initialUserStoreState = useUserStore.getState();afterEach(() => {+ cleanup();useUserStore.setState(initialUserStoreState, true);});@@ -75,4 +76,19 @@ describe('settings useCategory', () => {expect(keys).not.toContain(SettingsTabs.Provider);});++ it('hides OAuth Apps by default', () => {+ expect(getItemKeys()).not.toContain(SettingsTabs.OAuthApps);+ });++ it('shows OAuth Apps when the Labs preference is enabled', () => {+ useUserStore.setState({+ preference: {+ ...initialUserStoreState.preference,+ lab: { ...initialUserStoreState.preference.lab, enableOAuthApps: true },+ },+ });++ expect(getItemKeys()).toContain(SettingsTabs.OAuthApps);+ });});diff --git a/src/routes/(main)/settings/hooks/useCategory.tsx b/src/routes/(main)/settings/hooks/useCategory.tsxindex 3f64a476a97..d22bf77c158 100644--- a/src/routes/(main)/settings/hooks/useCategory.tsx+++ b/src/routes/(main)/settings/hooks/useCategory.tsx@@ -2,6 +2,7 @@ import { isDesktop } from '@lobechat/const';import { Avatar } from '@lobehub/ui';import { SkillsIcon } from '@lobehub/ui/icons';import {+ AppWindowIcon,BellIcon,Blocks,Brain,@@ -36,6 +37,7 @@ import {useServerConfigStore,} from '@/store/serverConfig';import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';import { userProfileSelectors } from '@/store/user/slices/auth/selectors';import { userGeneralSettingsSelectors } from '@/store/user/slices/settings/selectors';@@ -72,6 +74,7 @@ export const useCategory = () => {]);const remoteServerUrl = useElectronStore(electronSyncSelectors.remoteServerUrl);const isDevMode = useUserStore((s) => userGeneralSettingsSelectors.config(s).isDevMode);+ const enableOAuthApps = useUserStore(labPreferSelectors.enableOAuthApps);const avatarUrl = useMemo(() => {if (!avatar) return undefined;@@ -217,6 +220,11 @@ export const useCategory = () => {key: SettingsTabs.APIKey,label: tAuth('tab.apikey'),},+ enableOAuthApps && {+ icon: AppWindowIcon,+ key: SettingsTabs.OAuthApps,+ label: tAuth('tab.oauthApps'),+ },{icon: EllipsisIcon,key: SettingsTabs.Advanced,@@ -246,6 +254,7 @@ export const useCategory = () => {showApiKeyManage,showProvider,isDevMode,+ enableOAuthApps,avatarUrl,username,]);diff --git a/src/routes/(main)/settings/oauth-apps/features/AppDetail/EditForm.tsx b/src/routes/(main)/settings/oauth-apps/features/AppDetail/EditForm.tsxnew file mode 100644index 00000000000..8fe2e743695--- /dev/null+++ b/src/routes/(main)/settings/oauth-apps/features/AppDetail/EditForm.tsx@@ -0,0 +1,104 @@+'use client';++import { Flexbox, Input, TextArea } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';+import { Form } from 'antd';+import { type FC, useState } from 'react';+import { useTranslation } from 'react-i18next';++import AvatarUpload from '@/components/AvatarUpload';+import { type OAuthAppItem, type UpdateOAuthAppParams } from '@/types/oauthApp';++interface AppFormValues {+ description?: string;+ name: string;+}++interface EditFormProps {+ canEdit: boolean;+ detail: OAuthAppItem;+ onSubmit: (value: UpdateOAuthAppParams) => Promise<void>;+}++const EditForm: FC<EditFormProps> = ({ canEdit, detail, onSubmit }) => {+ const { t } = useTranslation('auth');+ const [form] = Form.useForm<AppFormValues>();+ const [dirty, setDirty] = useState(false);+ const [saving, setSaving] = useState(false);+ const [logoUri, setLogoUri] = useState<string | undefined>(detail.logoUri ?? undefined);++ const handleUpload = (file: File) => {+ const reader = new FileReader();+ reader.addEventListener('load', () => {+ setLogoUri(reader.result as string);+ setDirty(true);+ });+ reader.readAsDataURL(file);+ };++ const handleFinish = async (values: AppFormValues) => {+ setSaving(true);+ try {+ await onSubmit({+ description: values.description,+ logoUri,+ name: values.name.trim(),+ });+ setDirty(false);+ } finally {+ setSaving(false);+ }+ };++ return (+ <Form+ colon={false}+ disabled={!canEdit}+ form={form}+ initialValues={{ description: detail.description ?? '', name: detail.name }}+ layout={'vertical'}+ onFinish={handleFinish}+ onValuesChange={() => setDirty(true)}+ >+ <Flexbox gap={16}>+ <Form.Item label={t('oauthApp.form.logo.label')} style={{ marginBottom: 0 }}>+ <AvatarUpload+ title={detail.name}+ value={logoUri}+ onUpload={canEdit ? handleUpload : undefined}+ />+ </Form.Item>++ <Form.Item+ label={t('oauthApp.form.name.label')}+ name={'name'}+ rules={[{ message: t('oauthApp.validation.nameRequired'), required: true }]}+ style={{ marginBottom: 0 }}+ >+ <Input placeholder={t('oauthApp.form.name.placeholder')} />+ </Form.Item>++ <Form.Item+ label={t('oauthApp.form.description.label')}+ name={'description'}+ style={{ marginBottom: 0 }}+ >+ <TextArea placeholder={t('oauthApp.form.description.placeholder')} rows={3} />+ </Form.Item>++ <Flexbox horizontal justify={'flex-end'}>+ <Button+ disabled={!canEdit || !dirty}+ htmlType={'submit'}+ loading={saving}+ type={'primary'}+ >+ {t('oauthApp.detail.save')}+ </Button>+ </Flexbox>+ </Flexbox>+ </Form>+ );+};++export default EditForm;diff --git a/src/routes/(main)/settings/oauth-apps/features/AppDetail/index.tsx b/src/routes/(main)/settings/oauth-apps/features/AppDetail/index.tsxnew file mode 100644index 00000000000..f9cadcd7802--- /dev/null+++ b/src/routes/(main)/settings/oauth-apps/features/AppDetail/index.tsx@@ -0,0 +1,214 @@+'use client';++import { Flexbox, Icon, Skeleton, Tag, Text } from '@lobehub/ui';+import { Button, confirmModal, Switch } from '@lobehub/ui/base-ui';+import { App } from 'antd';+import { createStaticStyles } from 'antd-style';+import { ArrowLeftIcon, Trash2Icon } from 'lucide-react';+import { type FC, useEffect } from 'react';+import { useTranslation } from 'react-i18next';++import OAuthAppStats from '@/business/client/OAuthAppStats';+import { useClientDataSWR } from '@/libs/swr';+import { authKeys } from '@/libs/swr/keys';+import { lambdaClient, lambdaQuery } from '@/libs/trpc/client';+import { type OAuthAppItem } from '@/types/oauthApp';++import ClientIdDisplay from '../ClientIdDisplay';+import EditForm from './EditForm';++const styles = createStaticStyles(({ css, cssVar }) => ({+ backButton: css`+ cursor: pointer;++ display: inline-flex;+ align-items: center;+ justify-content: center;++ width: 28px;+ height: 28px;+ border-radius: ${cssVar.borderRadius};++ color: ${cssVar.colorTextSecondary};++ &:hover {+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillTertiary};+ }+ `,+ card: css`+ padding: 16px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};+ background: ${cssVar.colorBgContainer};+ `,+ dangerCard: css`+ padding: 16px;+ border: 1px solid ${cssVar.colorErrorBorder};+ border-radius: ${cssVar.borderRadiusLG};+ background: ${cssVar.colorBgContainer};+ `,+ label: css`+ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ `,+ row: css`+ display: flex;+ align-items: center;+ justify-content: space-between;+ `,+}));++interface AppDetailProps {+ canEdit: boolean;+ id: string;+ onBack: () => void;+ onChanged: () => void;+}++const AppDetail: FC<AppDetailProps> = ({ canEdit, id, onBack, onChanged }) => {+ const { t } = useTranslation('auth');+ const { message } = App.useApp();++ const { data, error, isLoading, mutate } = useClientDataSWR(authKeys.oauthAppById(id), () =>+ lambdaClient.oauthApp.getById.query({ id }),+ );+ const detail = data as OAuthAppItem | undefined;++ useEffect(() => {+ if (error || (!isLoading && !detail)) onBack();+ }, [error, isLoading, detail, onBack]);++ const revalidate = () => {+ mutate();+ onChanged();+ };++ const updateMutation = lambdaQuery.oauthApp.update.useMutation({+ onSuccess: () => {+ revalidate();+ message.success(t('oauthApp.detail.saveSuccess'));+ },+ });+ const enabledMutation = lambdaQuery.oauthApp.setEnabled.useMutation({ onSuccess: revalidate });+ const deleteMutation = lambdaQuery.oauthApp.delete.useMutation({+ onSuccess: () => {+ onChanged();+ onBack();+ },+ });++ const handleDelete = () =>+ confirmModal({+ content: t('oauthApp.deleteConfirm.content'),+ okButtonProps: { danger: true },+ okText: t('oauthApp.deleteConfirm.ok'),+ onOk: async () => {+ await deleteMutation.mutateAsync({ id });+ },+ title: t('oauthApp.deleteConfirm.title'),+ });++ if (!detail)+ return (+ <Flexbox gap={16}>+ <Skeleton active paragraph={{ rows: 1, width: 200 }} title={false} />+ <div className={styles.card}>+ <Skeleton active paragraph={{ rows: 4 }} title={false} />+ </div>+ </Flexbox>+ );++ return (+ <Flexbox gap={20}>+ <Flexbox horizontal align={'center'} gap={8}>+ <span+ aria-label={t('oauthApp.detail.back')}+ className={styles.backButton}+ role={'button'}+ tabIndex={0}+ onClick={onBack}+ onKeyDown={(e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ onBack();+ }+ }}+ >+ <Icon icon={ArrowLeftIcon} size={'small'} />+ </span>+ <Text strong style={{ fontSize: 20 }}>+ {detail.name}+ </Text>+ {!detail.enabled && <Tag>{t('oauthApp.item.disabledTag')}</Tag>}+ </Flexbox>++ <div className={styles.card}>+ <EditForm+ canEdit={canEdit}+ detail={detail}+ key={detail.id}+ onSubmit={async (value) => {+ await updateMutation.mutateAsync({ id, value });+ }}+ />+ </div>++ <Flexbox className={styles.card} gap={16}>+ <div className={styles.row}>+ <span className={styles.label}>{t('oauthApp.detail.clientId')}</span>+ <ClientIdDisplay clientId={detail.id} />+ </div>++ <div className={styles.row}>+ <span className={styles.label}>{t('oauthApp.detail.type')}</span>+ <Tag>{t('oauthApp.type.badge')}</Tag>+ </div>++ <div className={styles.row}>+ <span className={styles.label}>{t('oauthApp.detail.createdAt')}</span>+ <Text type={'secondary'}>{detail.createdAt.toLocaleString()}</Text>+ </div>++ <div className={styles.row}>+ <span className={styles.label}>{t('oauthApp.detail.lastUsedAt')}</span>+ <Text type={'secondary'}>+ {detail.lastUsedAt+ ? detail.lastUsedAt.toLocaleString()+ : t('oauthApp.detail.neverUsed')}+ </Text>+ </div>++ <div className={styles.row}>+ <span className={styles.label}>{t('oauthApp.detail.enabled')}</span>+ <Switch+ checked={!!detail.enabled}+ disabled={!canEdit || enabledMutation.isPending}+ onChange={(checked) => enabledMutation.mutate({ enabled: checked, id })}+ />+ </div>+ </Flexbox>++ <div className={styles.card}>+ <OAuthAppStats clientId={detail.id} />+ </div>++ <Flexbox className={styles.dangerCard} gap={12}>+ <Text weight={500}>{t('oauthApp.detail.dangerZone')}</Text>+ <div className={styles.row}>+ <Button+ danger+ disabled={!canEdit}+ icon={<Trash2Icon size={16} />}+ loading={deleteMutation.isPending}+ onClick={handleDelete}+ >+ {t('oauthApp.detail.delete')}+ </Button>+ </div>+ </Flexbox>+ </Flexbox>+ );+};++export default AppDetail;diff --git a/src/routes/(main)/settings/oauth-apps/features/AppItem/index.tsx b/src/routes/(main)/settings/oauth-apps/features/AppItem/index.tsxnew file mode 100644index 00000000000..66118d3c378--- /dev/null+++ b/src/routes/(main)/settings/oauth-apps/features/AppItem/index.tsx@@ -0,0 +1,151 @@+'use client';++import { ActionIcon, Avatar, DropdownMenu, Flexbox, Icon, Tag, Text } from '@lobehub/ui';+import { confirmModal } from '@lobehub/ui/base-ui';+import { createStaticStyles } from 'antd-style';+import dayjs from 'dayjs';+import {+ ChevronRightIcon,+ MoreVerticalIcon,+ PowerIcon,+ PowerOffIcon,+ Trash2Icon,+} from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { lambdaQuery } from '@/libs/trpc/client';+import { type OAuthAppItem } from '@/types/oauthApp';++import ClientIdDisplay from '../ClientIdDisplay';++const styles = createStaticStyles(({ css, cssVar }) => ({+ chevron: css`+ flex: none;+ color: ${cssVar.colorTextQuaternary};+ `,+ meta: css`+ font-size: ${cssVar.fontSizeSM};+ color: ${cssVar.colorTextSecondary};+ `,+ row: css`+ cursor: pointer;++ padding-block: 12px;+ padding-inline: 12px;+ border-radius: ${cssVar.borderRadius};++ transition: background 0.15s ease;++ &:hover {+ background: ${cssVar.colorFillTertiary};+ }++ &:focus-visible {+ outline: 2px solid ${cssVar.colorPrimary};+ outline-offset: -1px;+ }+ `,+}));++interface AppItemProps {+ app: OAuthAppItem;+ canEdit: boolean;+ onChanged: () => void;+ onDeleted: () => void;+ onOpen: () => void;+}++const AppItem = memo<AppItemProps>(({ app, canEdit, onChanged, onDeleted, onOpen }) => {+ const { t } = useTranslation('auth');++ const setEnabled = lambdaQuery.oauthApp.setEnabled.useMutation({ onSuccess: onChanged });+ const deleteApp = lambdaQuery.oauthApp.delete.useMutation({ onSuccess: onDeleted });++ const handleDelete = () =>+ confirmModal({+ content: t('oauthApp.deleteConfirm.content'),+ okButtonProps: { danger: true },+ okText: t('oauthApp.deleteConfirm.ok'),+ onOk: async () => {+ await deleteApp.mutateAsync({ id: app.id });+ },+ title: t('oauthApp.deleteConfirm.title'),+ });++ const lastUsed = app.lastUsedAt+ ? t('oauthApp.item.lastUsed', { time: dayjs(app.lastUsedAt).fromNow() })+ : t('oauthApp.list.neverUsed');++ return (+ <Flexbox+ horizontal+ align={'center'}+ className={styles.row}+ gap={12}+ role={'button'}+ tabIndex={0}+ onClick={onOpen}+ onKeyDown={(e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ onOpen();+ }+ }}+ >+ <Avatar avatar={app.logoUri || app.name} shape={'square'} size={36} title={app.name} />++ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>+ <Flexbox horizontal align={'center'} gap={8}>+ <Text ellipsis weight={500}>+ {app.name}+ </Text>+ {!app.enabled && <Tag>{t('oauthApp.item.disabledTag')}</Tag>}+ </Flexbox>+ <span style={{ alignSelf: 'flex-start' }} onClick={(e) => e.stopPropagation()}>+ <ClientIdDisplay clientId={app.id} />+ </span>+ <span className={styles.meta}>+ {t('oauthApp.type.deviceFlow')} · {lastUsed}+ </span>+ </Flexbox>++ {canEdit && (+ <span style={{ flex: 'none' }} onClick={(e) => e.stopPropagation()}>+ <DropdownMenu+ items={[+ app.enabled+ ? {+ icon: <Icon icon={PowerOffIcon} />,+ key: 'disable',+ label: t('oauthApp.actions.disable'),+ onClick: () => setEnabled.mutate({ enabled: false, id: app.id }),+ }+ : {+ icon: <Icon icon={PowerIcon} />,+ key: 'enable',+ label: t('oauthApp.actions.enable'),+ onClick: () => setEnabled.mutate({ enabled: true, id: app.id }),+ },+ {+ danger: true,+ icon: <Icon icon={Trash2Icon} />,+ key: 'delete',+ label: t('oauthApp.list.actions.delete'),+ onClick: handleDelete,+ },+ ]}+ >+ <ActionIcon icon={MoreVerticalIcon} size={'small'} />+ </DropdownMenu>+ </span>+ )}++ <Icon className={styles.chevron} icon={ChevronRightIcon} size={'small'} />+ </Flexbox>+ );+});++AppItem.displayName = 'AppItem';++export default AppItem;diff --git a/src/routes/(main)/settings/oauth-apps/features/ClientIdDisplay/index.tsx b/src/routes/(main)/settings/oauth-apps/features/ClientIdDisplay/index.tsxnew file mode 100644index 00000000000..61fc854f53d--- /dev/null+++ b/src/routes/(main)/settings/oauth-apps/features/ClientIdDisplay/index.tsx@@ -0,0 +1,51 @@+'use client';++import { ActionIcon } from '@lobehub/ui';+import { App, Flex } from 'antd';+import { createStaticStyles } from 'antd-style';+import { Copy } from 'lucide-react';+import { type FC } from 'react';+import { useTranslation } from 'react-i18next';++const styles = createStaticStyles(({ css, cssVar }) => ({+ id: css`+ overflow: hidden;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 13px;+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+}));++interface ClientIdDisplayProps {+ clientId: string;+}++const ClientIdDisplay: FC<ClientIdDisplayProps> = ({ clientId }) => {+ const { t } = useTranslation('auth');+ const { message } = App.useApp();++ const handleCopy = async () => {+ try {+ await navigator.clipboard.writeText(clientId);+ message.success(t('oauthApp.copy.success'));+ } catch {+ message.error(t('oauthApp.copy.error'));+ }+ };++ return (+ <Flex align="center" gap={4}>+ <span className={styles.id}>{clientId}</span>+ <ActionIcon+ icon={Copy}+ size="small"+ title={t('oauthApp.copy.tooltip')}+ onClick={handleCopy}+ />+ </Flex>+ );+};++export default ClientIdDisplay;diff --git a/src/routes/(main)/settings/oauth-apps/features/CreateAppModal/Content.tsx b/src/routes/(main)/settings/oauth-apps/features/CreateAppModal/Content.tsxnew file mode 100644index 00000000000..7c54eae458a--- /dev/null+++ b/src/routes/(main)/settings/oauth-apps/features/CreateAppModal/Content.tsx@@ -0,0 +1,90 @@+'use client';++import { Flexbox, Input, TextArea } from '@lobehub/ui';+import { Button, useModalContext } from '@lobehub/ui/base-ui';+import { Form } from 'antd';+import { type FC, useState } from 'react';+import { useTranslation } from 'react-i18next';++import AvatarUpload from '@/components/AvatarUpload';+import { type CreateOAuthAppParams } from '@/types/oauthApp';++export interface CreateAppModalContentProps {+ onSubmit: (values: CreateOAuthAppParams) => Promise<void>;+}++const CreateAppModalContent: FC<CreateAppModalContentProps> = ({ onSubmit }) => {+ const { t } = useTranslation('auth');+ const { close, setCanDismissByClickOutside } = useModalContext();+ const [form] = Form.useForm<CreateOAuthAppParams>();+ const [loading, setLoading] = useState(false);+ const [logoUri, setLogoUri] = useState<string>();++ // Once the form is dirty, a mask click must not dismiss the modal (it would+ // 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 handleFinish = async (values: CreateOAuthAppParams) => {+ setLoading(true);+ try {+ await onSubmit({ ...values, logoUri });+ close();+ } finally {+ setLoading(false);+ }+ };++ const itemStyle = { marginBottom: 0 };++ return (+ <Form+ colon={false}+ form={form}+ layout={'vertical'}+ onFinish={handleFinish}+ onValuesChange={markDirty}+ >+ <Flexbox gap={16}>+ <Form.Item label={t('oauthApp.form.logo.label')} style={itemStyle}>+ <AvatarUpload+ title={t('oauthApp.form.name.label')}+ value={logoUri}+ onUpload={handleUpload}+ />+ </Form.Item>++ <Form.Item+ label={t('oauthApp.form.name.label')}+ name={'name'}+ rules={[{ message: t('oauthApp.validation.nameRequired'), required: true }]}+ style={itemStyle}+ >+ <Input placeholder={t('oauthApp.form.name.placeholder')} />+ </Form.Item>++ <Form.Item+ label={t('oauthApp.form.description.label')}+ name={'description'}+ style={itemStyle}+ >+ <TextArea placeholder={t('oauthApp.form.description.placeholder')} rows={3} />+ </Form.Item>++ <Button block htmlType={'submit'} loading={loading} type={'primary'}>+ {t('oauthApp.form.submit')}+ </Button>+ </Flexbox>+ </Form>+ );+};++export default CreateAppModalContent;diff --git a/src/routes/(main)/settings/oauth-apps/features/CreateAppModal/index.tsx b/src/routes/(main)/settings/oauth-apps/features/CreateAppModal/index.tsxnew file mode 100644index 00000000000..8a541659aa1--- /dev/null+++ b/src/routes/(main)/settings/oauth-apps/features/CreateAppModal/index.tsx@@ -0,0 +1,18 @@+'use client';++import { createModal, type ModalInstance } from '@lobehub/ui/base-ui';+import { t } from 'i18next';++import CreateAppModalContent, { type CreateAppModalContentProps } from './Content';++export const createOAuthAppModal = (props: CreateAppModalContentProps): ModalInstance =>+ createModal({+ content: <CreateAppModalContent {...props} />,+ footer: null,+ maskClosable: true,+ styles: {+ content: { paddingBlock: 16, paddingInline: 24 },+ },+ title: t('oauthApp.form.title', { ns: 'auth' }),+ width: 'min(90vw, 560px)',+ });diff --git a/src/routes/(main)/settings/oauth-apps/features/OAuthApps.tsx b/src/routes/(main)/settings/oauth-apps/features/OAuthApps.tsxnew file mode 100644index 00000000000..efa1e4f5225--- /dev/null+++ b/src/routes/(main)/settings/oauth-apps/features/OAuthApps.tsx@@ -0,0 +1,92 @@+'use client';++import { Flexbox, Skeleton, Text } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import { type FC } from 'react';+import { useTranslation } from 'react-i18next';+import { useParams } from 'react-router';++import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useClientDataSWR } from '@/libs/swr';+import { authKeys } from '@/libs/swr/keys';+import { lambdaClient } from '@/libs/trpc/client';+import { type OAuthAppItem } from '@/types/oauthApp';++import AppDetail from './AppDetail';+import AppItem from './AppItem';++const styles = createStaticStyles(({ css, cssVar }) => ({+ listCol: css`+ overflow: hidden;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};+ background: ${cssVar.colorBgContainer};+ `,+}));++interface OAuthAppsProps {+ canEdit: boolean;+}++const OAuthApps: FC<OAuthAppsProps> = ({ canEdit }) => {+ const { t } = useTranslation('auth');+ const navigate = useWorkspaceAwareNavigate();+ const params = useParams<{ sub?: string }>();++ const {+ data: apps,+ isLoading,+ mutate,+ } = useClientDataSWR(authKeys.oauthAppList(), async () => {+ const list = await lambdaClient.oauthApp.list.query();+ return list as OAuthAppItem[];+ });++ const reload = () => mutate();++ if (params.sub)+ return (+ <AppDetail+ canEdit={canEdit}+ id={params.sub}+ onBack={() => navigate('/settings/oauth-apps')}+ onChanged={reload}+ />+ );++ const renderRows = () => {+ if (isLoading)+ return (+ <Flexbox gap={12} padding={12}>+ <Skeleton paragraph={{ rows: 2 }} title={false} />+ <Skeleton paragraph={{ rows: 2 }} title={false} />+ </Flexbox>+ );++ if (!apps?.length)+ return (+ <Flexbox align={'center'} gap={12} paddingBlock={40}>+ <Text type={'secondary'}>{t('oauthApp.list.empty')}</Text>+ </Flexbox>+ );++ return apps.map((app) => (+ <AppItem+ app={app}+ canEdit={canEdit}+ key={app.id}+ onChanged={reload}+ onDeleted={reload}+ onOpen={() => navigate(`/settings/oauth-apps/${app.id}`)}+ />+ ));+ };++ return (+ <Flexbox className={styles.listCol} gap={2} padding={4}>+ {renderRows()}+ </Flexbox>+ );+};++export default OAuthApps;diff --git a/src/routes/(main)/settings/oauth-apps/features/index.ts b/src/routes/(main)/settings/oauth-apps/features/index.tsnew file mode 100644index 00000000000..45a2470c93c--- /dev/null+++ b/src/routes/(main)/settings/oauth-apps/features/index.ts@@ -0,0 +1,3 @@+export { default as AppDetail } from './AppDetail';+export { default as ClientIdDisplay } from './ClientIdDisplay';+export { createOAuthAppModal } from './CreateAppModal';diff --git a/src/routes/(main)/settings/oauth-apps/index.test.tsx b/src/routes/(main)/settings/oauth-apps/index.test.tsxnew file mode 100644index 00000000000..3cfd4cb6e67--- /dev/null+++ b/src/routes/(main)/settings/oauth-apps/index.test.tsx@@ -0,0 +1,99 @@+import { cleanup, render, screen } from '@testing-library/react';+import { type ReactNode } from 'react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { useUserStore } from '@/store/user';++import Page from './index';++vi.hoisted(() => {+ Object.defineProperty(globalThis, 'localStorage', {+ configurable: true,+ value: {+ getItem: vi.fn(() => null),+ removeItem: vi.fn(),+ setItem: vi.fn(),+ },+ });+});++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock('react-router', () => ({+ useParams: () => ({}),+}));++vi.mock('@lobehub/ui/base-ui', () => ({+ Button: ({ children }: { children: ReactNode }) => <button>{children}</button>,+}));++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ useActiveWorkspaceId: () => null,+}));++vi.mock('@/business/client/hooks/useIsWorkspaceOwner', () => ({+ useIsWorkspaceOwner: () => true,+}));++vi.mock('@/components/404', () => ({+ default: () => <div>not-found</div>,+}));++vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({+ useWorkspaceAwareNavigate: () => vi.fn(),+}));++vi.mock('@/hooks/usePermission', () => ({+ usePermission: () => ({ allowed: true }),+}));++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: { oauthApp: { create: { mutate: vi.fn() } } },+}));++vi.mock('@/routes/(main)/settings/features/SettingHeader', () => ({+ default: ({ title }: { title: string }) => <h1>{title}</h1>,+}));++vi.mock('./features/CreateAppModal', () => ({+ createOAuthAppModal: vi.fn(),+}));++vi.mock('./features/OAuthApps', () => ({+ default: () => <div>oauth-apps-page</div>,+}));++const initialUserStoreState = useUserStore.getState();++afterEach(() => {+ cleanup();+ useUserStore.setState(initialUserStoreState, true);+});++describe('OAuth Apps settings page', () => {+ it('returns not found when the Labs preference is disabled', () => {+ useUserStore.setState({ isUserStateInit: true });++ render(<Page />);++ expect(screen.getByText('not-found')).toBeDefined();+ expect(screen.queryByText('oauth-apps-page')).toBeNull();+ });++ it('renders OAuth app management when the Labs preference is enabled', () => {+ useUserStore.setState({+ isUserStateInit: true,+ preference: {+ ...initialUserStoreState.preference,+ lab: { ...initialUserStoreState.preference.lab, enableOAuthApps: true },+ },+ });++ render(<Page />);++ expect(screen.getByText('tab.oauthApps')).toBeDefined();+ expect(screen.getByText('oauth-apps-page')).toBeDefined();+ });+});diff --git a/src/routes/(main)/settings/oauth-apps/index.tsx b/src/routes/(main)/settings/oauth-apps/index.tsxnew file mode 100644index 00000000000..a8c853becc6--- /dev/null+++ b/src/routes/(main)/settings/oauth-apps/index.tsx@@ -0,0 +1,70 @@+import { Skeleton } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';+import { useTranslation } from 'react-i18next';+import { useParams } from 'react-router';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { useIsWorkspaceOwner } from '@/business/client/hooks/useIsWorkspaceOwner';+import NotFound from '@/components/404';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { usePermission } from '@/hooks/usePermission';+import { lambdaClient } from '@/libs/trpc/client';+import SettingHeader from '@/routes/(main)/settings/features/SettingHeader';+import { useUserStore } from '@/store/user';+import { labPreferSelectors, preferenceSelectors } from '@/store/user/selectors';++import { createOAuthAppModal } from './features/CreateAppModal';+import OAuthApps from './features/OAuthApps';++const CreateAppButton = () => {+ const { t } = useTranslation('auth');+ const { allowed: hasEditPermission, reason } = usePermission('create_content');+ const activeWorkspaceId = useActiveWorkspaceId();+ const isWorkspaceOwner = useIsWorkspaceOwner();+ const canEdit = hasEditPermission && (!activeWorkspaceId || isWorkspaceOwner);+ const navigate = useWorkspaceAwareNavigate();++ const handleCreate = () => {+ if (!canEdit) return;+ createOAuthAppModal({+ onSubmit: async (values) => {+ const created = await lambdaClient.oauthApp.create.mutate(values);+ navigate(`/settings/oauth-apps/${created.id}`);+ },+ });+ };++ return (+ <Button disabled={!canEdit} title={reason} type={'primary'} onClick={handleCreate}>+ {t('oauthApp.list.actions.create')}+ </Button>+ );+};++const Page = () => {+ const { t } = useTranslation('auth');+ const { allowed: hasEditPermission } = usePermission('create_content');+ const activeWorkspaceId = useActiveWorkspaceId();+ const isWorkspaceOwner = useIsWorkspaceOwner();+ const params = useParams<{ sub?: string }>();+ const canEdit = hasEditPermission && (!activeWorkspaceId || isWorkspaceOwner);+ const [isPreferenceInit, enableOAuthApps] = useUserStore((s) => [+ preferenceSelectors.isPreferenceInit(s),+ labPreferSelectors.enableOAuthApps(s),+ ]);++ if (!isPreferenceInit) return <Skeleton active paragraph={{ rows: 5 }} title={false} />;+ if (!enableOAuthApps) return <NotFound />;++ return (+ <>+ <SettingHeader+ extra={!params.sub && canEdit && <CreateAppButton />}+ title={t('tab.oauthApps')}+ />+ <OAuthApps canEdit={canEdit} />+ </>+ );+};++export default Page;diff --git a/src/routes/(mobile)/me/settings/features/useCategory.test.tsx b/src/routes/(mobile)/me/settings/features/useCategory.test.tsxindex b49a14294db..07ee50b58f7 100644--- a/src/routes/(mobile)/me/settings/features/useCategory.test.tsx+++ b/src/routes/(mobile)/me/settings/features/useCategory.test.tsx@@ -1,4 +1,4 @@-import { renderHook } from '@testing-library/react';+import { cleanup, renderHook } from '@testing-library/react';import { type ReactNode } from 'react';import { afterEach, describe, expect, it, vi } from 'vitest';@@ -56,6 +56,7 @@ const createWrapper = (showProvider: boolean) => {const initialUserStoreState = useUserStore.getState();afterEach(() => {+ cleanup();navigate.mockReset();useUserStore.setState(initialUserStoreState, true);});@@ -86,4 +87,31 @@ describe('mobile settings useCategory', () => {expect(keys).not.toContain(SettingsTabs.Provider);});++ it('hides OAuth Apps by default', () => {+ const { result } = renderHook(() => useCategory(), {+ wrapper: createWrapper(true),+ });++ const keys = result.current.flatMap((group) => group.items.map((item) => item.key));++ expect(keys).not.toContain(SettingsTabs.OAuthApps);+ });++ it('shows OAuth Apps when the Labs preference is enabled', () => {+ useUserStore.setState({+ preference: {+ ...initialUserStoreState.preference,+ lab: { ...initialUserStoreState.preference.lab, enableOAuthApps: true },+ },+ });++ const { result } = renderHook(() => useCategory(), {+ wrapper: createWrapper(true),+ });++ const keys = result.current.flatMap((group) => group.items.map((item) => item.key));++ expect(keys).toContain(SettingsTabs.OAuthApps);+ });});diff --git a/src/routes/(mobile)/me/settings/features/useCategory.tsx b/src/routes/(mobile)/me/settings/features/useCategory.tsxindex c66e3ff7f3f..5a0acd08be2 100644--- a/src/routes/(mobile)/me/settings/features/useCategory.tsx+++ b/src/routes/(mobile)/me/settings/features/useCategory.tsx@@ -1,5 +1,6 @@import { SkillsIcon } from '@lobehub/ui/icons';import {+ AppWindowIcon,Blocks,Brain,BrainCircuit,@@ -29,6 +30,7 @@ import {useServerConfigStore,} from '@/store/serverConfig';import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';import { userGeneralSettingsSelectors } from '@/store/user/slices/settings/selectors';export enum SettingsGroupKey {@@ -54,6 +56,7 @@ export const useCategory = (): CategoryGroup[] => {const { hideDocs, showApiKeyManage, showProvider } = useServerConfigStore(featureFlagsSelectors);const enableBusinessFeatures = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);const isDevMode = useUserStore((s) => userGeneralSettingsSelectors.config(s).isDevMode);+ const enableOAuthApps = useUserStore(labPreferSelectors.enableOAuthApps);return useMemo(() => {const navigateTo = (key: SettingsTabs) =>@@ -122,6 +125,12 @@ export const useCategory = (): CategoryGroup[] => {makeItem({ icon: Database, key: SettingsTabs.Storage, label: t('setting:tab.storage') }),isDevMode &&makeItem({ icon: KeyIcon, key: SettingsTabs.APIKey, label: t('auth:tab.apikey') }),+ enableOAuthApps &&+ makeItem({+ icon: AppWindowIcon,+ key: SettingsTabs.OAuthApps,+ label: t('auth:tab.oauthApps'),+ }),makeItem({icon: EllipsisIcon,key: SettingsTabs.Advanced,@@ -140,5 +149,14 @@ export const useCategory = (): CategoryGroup[] => {{ items: agent, key: SettingsGroupKey.Agent, title: t('setting:group.aiConfig') },{ items: system, key: SettingsGroupKey.System, title: t('setting:group.system') },].filter((group) => group.items.length > 0);- }, [t, enableBusinessFeatures, hideDocs, showApiKeyManage, showProvider, isDevMode, navigate]);+ }, [+ t,+ enableBusinessFeatures,+ hideDocs,+ showApiKeyManage,+ showProvider,+ isDevMode,+ enableOAuthApps,+ navigate,+ ]);};diff --git a/src/spa/router/desktopRouter.config.desktop.tsx b/src/spa/router/desktopRouter.config.desktop.tsxindex 2d1359877b2..f60f6bc3ab5 100644--- a/src/spa/router/desktopRouter.config.desktop.tsx+++ b/src/spa/router/desktopRouter.config.desktop.tsx@@ -48,6 +48,7 @@ import WorkspaceSlugSettingsCredsPage from '@/routes/(main)/[workspaceSlug]/settimport WorkspaceSlugSettingsDevicesPage from '@/routes/(main)/[workspaceSlug]/settings/devices';import WorkspaceSlugSettingsGeneralPage from '@/routes/(main)/[workspaceSlug]/settings/general';import WorkspaceSlugSettingsMembersPage from '@/routes/(main)/[workspaceSlug]/settings/members';+import WorkspaceSlugSettingsOAuthAppsPage from '@/routes/(main)/[workspaceSlug]/settings/oauth-apps';import WorkspaceSlugSettingsPlansPage from '@/routes/(main)/[workspaceSlug]/settings/plans';import WorkspaceSlugSettingsProviderPage from '@/routes/(main)/[workspaceSlug]/settings/provider';import WorkspaceSlugSettingsServiceModelPage from '@/routes/(main)/[workspaceSlug]/settings/service-model';@@ -728,6 +729,8 @@ export const desktopRoutes: RouteObject[] = [{ element: <WorkspaceSlugSettingsServiceModelPage />, path: 'service-model' },{ element: <WorkspaceSlugSettingsCredsPage />, path: 'creds' },{ element: <WorkspaceSlugSettingsApiKeyPage />, path: 'apikey' },+ { element: <WorkspaceSlugSettingsOAuthAppsPage />, path: 'oauth-apps' },+ { element: <WorkspaceSlugSettingsOAuthAppsPage />, path: 'oauth-apps/:sub' },{ element: <WorkspaceSlugSettingsAuditLogPage />, path: 'audit-log' },{ element: <WorkspaceSlugSettingsStoragePage />, path: 'storage' },{ element: <WorkspaceSlugSettingsDevicesPage />, path: 'devices' },diff --git a/src/spa/router/desktopRouter.config.tsx b/src/spa/router/desktopRouter.config.tsxindex 65086f29ab4..c9b4a5ebbc8 100644--- a/src/spa/router/desktopRouter.config.tsx+++ b/src/spa/router/desktopRouter.config.tsx@@ -921,6 +921,20 @@ export const desktopRoutes: RouteObject[] = [),path: 'apikey',},+ {+ element: dynamicElement(+ () => import('@/routes/(main)/[workspaceSlug]/settings/oauth-apps'),+ 'Desktop > Workspace > Settings > OAuth Apps',+ ),+ path: 'oauth-apps',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/[workspaceSlug]/settings/oauth-apps'),+ 'Desktop > Workspace > Settings > OAuth App Detail',+ ),+ path: 'oauth-apps/:sub',+ },{element: dynamicElement(() => import('@/routes/(main)/[workspaceSlug]/settings/audit-log'),diff --git a/src/spa/router/desktopRouter.sync.test.tsx b/src/spa/router/desktopRouter.sync.test.tsxindex 76a23e2fc07..42299203d41 100644--- a/src/spa/router/desktopRouter.sync.test.tsx+++ b/src/spa/router/desktopRouter.sync.test.tsx@@ -140,6 +140,7 @@ describe('desktopRouter config sync', () => {'@/routes/(main)/[workspaceSlug]/settings/usage','@/routes/(main)/[workspaceSlug]/settings/skill','@/routes/(main)/[workspaceSlug]/settings/connector',+ '@/routes/(main)/[workspaceSlug]/settings/oauth-apps','@/routes/(main)/[workspaceSlug]/settings/audit-log',];@@ -173,7 +174,9 @@ describe('desktopRouter config sync', () => {? [route.path, ...collectPaths(route.children ?? [])]: collectPaths(route.children ?? []),);- const registeredTabs = collectPaths(settingsRoute?.children ?? []);+ const registeredTabs = collectPaths(settingsRoute?.children ?? []).map(+ (registeredPath) => registeredPath.split('/')[0],+ );const missingTabs = registeredTabs.filter((tab) => !WORKSPACE_SETTINGS_TABS.has(tab));expect(@@ -182,6 +185,15 @@ describe('desktopRouter config sync', () => {).toEqual([]);});+ it('workspace OAuth apps list and detail routes are registered', () => {+ const listMatches = matchRoutes(desktopRoutes, '/acme/settings/oauth-apps');+ const detailMatches = matchRoutes(desktopRoutes, '/acme/settings/oauth-apps/client-1');++ expect(listMatches?.at(-1)?.route.path).toBe('oauth-apps');+ expect(detailMatches?.at(-1)?.route.path).toBe('oauth-apps/:sub');+ expect(detailMatches?.at(-1)?.params).toMatchObject({ sub: 'client-1', workspaceSlug: 'acme' });+ });+it('both configs import and spread BusinessResourceRoutes into /resource children', async () => {const [asyncSource, syncSource] = await readDesktopRouterSources();diff --git a/src/spa/router/mobileRouter.config.tsx b/src/spa/router/mobileRouter.config.tsxindex db6314af485..626d3786faa 100644--- a/src/spa/router/mobileRouter.config.tsx+++ b/src/spa/router/mobileRouter.config.tsx@@ -320,6 +320,13 @@ export const mobileRoutes: RouteObject[] = [),path: ':tab',},+ {+ element: dynamicElement(+ () => import('@/routes/(main)/settings'),+ 'Mobile > Settings > Tab > Sub',+ ),+ path: ':tab/:sub',+ },],element: dynamicLayout(() => import('@/routes/(mobile)/settings/_layout'),@@ -461,6 +468,20 @@ export const mobileRoutes: RouteObject[] = [),path: 'audit-log',},+ {+ element: dynamicElement(+ () => import('@/routes/(main)/[workspaceSlug]/settings/oauth-apps'),+ 'Mobile > Workspace > Settings > OAuth Apps',+ ),+ path: 'oauth-apps',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/[workspaceSlug]/settings/oauth-apps'),+ 'Mobile > Workspace > Settings > OAuth App Detail',+ ),+ path: 'oauth-apps/:sub',+ },],element: dynamicLayout(() => import('@/routes/(mobile)/settings/_layout'),diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.tsindex fc5f069bc51..e6a72a9f379 100644--- a/src/store/global/initialState.ts+++ b/src/store/global/initialState.ts@@ -71,6 +71,7 @@ export enum SettingsTabs {Memory = 'memory',Messenger = 'messenger',Notification = 'notification',+ OAuthApps = 'oauth-apps',// businessPlans = 'plans',Profile = 'profile',diff --git a/src/store/user/slices/preference/selectors.test.ts b/src/store/user/slices/preference/selectors.test.tsindex bb70ba9129f..6071f14694f 100644--- a/src/store/user/slices/preference/selectors.test.ts+++ b/src/store/user/slices/preference/selectors.test.ts@@ -79,5 +79,17 @@ describe('preferenceSelectors', () => {expect(labPreferSelectors.enableMessageTextSelectionActions(store)).toBe(true);});++ it('keeps OAuth app management hidden by default', () => {+ store.preference.lab = undefined;++ expect(labPreferSelectors.enableOAuthApps(store)).toBe(false);+ });++ it('returns the configured OAuth app management preference', () => {+ store.preference.lab = { enableOAuthApps: true };++ expect(labPreferSelectors.enableOAuthApps(store)).toBe(true);+ });});});diff --git a/src/store/user/slices/preference/selectors/labPrefer.ts b/src/store/user/slices/preference/selectors/labPrefer.tsindex d5eb586be8a..bfacb554b83 100644--- a/src/store/user/slices/preference/selectors/labPrefer.ts+++ b/src/store/user/slices/preference/selectors/labPrefer.ts@@ -25,6 +25,7 @@ export const labPreferSelectors = {s.preference.lab?.enableMessageTextSelectionActions ??DEFAULT_PREFERENCE.lab?.enableMessageTextSelectionActions ??false,+ enableOAuthApps: (s: UserState): boolean => s.preference.lab?.enableOAuthApps ?? false,enablePlatformAgent: (s: UserState): boolean => s.preference.lab?.enablePlatformAgent ?? false,enableTaskVerify: (s: UserState): boolean => s.preference.lab?.enableTaskVerify ?? false,};diff --git a/src/types/oidc.ts b/src/types/oidc.tsindex 5b46f58ff02..f06c96821e1 100644--- a/src/types/oidc.ts+++ b/src/types/oidc.ts@@ -1,7 +1,9 @@export interface OidcClientMetadata {clientName?: string;+ developerName?: string;isFirstParty: boolean;logo?: string;+ policyUri?: string;}export interface OidcInteractionDetailsResponse {diff --git a/src/types/workspaceSettings.ts b/src/types/workspaceSettings.tsindex 9813a192237..1faf06bffb0 100644--- a/src/types/workspaceSettings.ts+++ b/src/types/workspaceSettings.ts@@ -15,6 +15,7 @@ export enum WorkspaceSettingsTabs {Devices = 'devices',General = 'general',Members = 'members',+ OAuthApps = 'oauth-apps',Plans = 'plans',Provider = 'provider',ServiceModel = 'service-model',