🤯 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(oauth-apps): support web applications with redirect URIs (#19504)
Arvin Xuc3a764229522
diff --git a/apps/server/src/routers/lambda/__tests__/oauthApp.test.ts b/apps/server/src/routers/lambda/__tests__/oauthApp.test.tsnew file mode 100644index 00000000000..51a649c1aeb--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/oauthApp.test.ts@@ -0,0 +1,169 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return {};+ }),+}));++vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {+ const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');+ // The real `wsCompatProcedure` validates a Better-Auth session; these tests+ // exercise input validation, so auth is skipped and ctx carries the userId.+ return {+ requireWorkspaceRoleWhenScoped: () => mod.trpc.middleware(async (opts: any) => opts.next()),+ wsCompatProcedure: mod.trpc.procedure,+ };+});++const mockCreate = vi.fn();+const mockFindById = vi.fn();+const mockList = vi.fn();+const mockRotateSecret = vi.fn();+const mockUpdate = vi.fn();++vi.mock('@/database/models/oidcClient', () => ({+ OidcClientModel: vi.fn(function () {+ return {+ create: mockCreate,+ findById: mockFindById,+ list: mockList,+ rotateSecret: mockRotateSecret,+ update: mockUpdate,+ };+ }),+}));++const { oauthAppRouter } = await import('../oauthApp');++const webApp = {+ applicationType: 'web',+ clientSecret: 'iv:tag:cipher',+ id: 'lca_app',+ name: 'Develop Center',+ redirectUris: ['https://dc.lobehub.com/callback'],+};++describe('oauthAppRouter', () => {+ const ctx: any = { serverDB: {}, userId: 'user-1' };+ const caller = () => oauthAppRouter.createCaller(ctx);++ beforeEach(() => {+ vi.clearAllMocks();+ mockCreate.mockResolvedValue({ client: webApp, secret: 'lcs_plain' });+ });++ describe('create', () => {+ it('defaults to a device app when no type is given', async () => {+ mockCreate.mockResolvedValue({+ client: { ...webApp, clientSecret: null },+ secret: undefined,+ });++ await caller().create({ name: 'My CLI' });++ expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ type: 'device' }));+ });++ it('returns the plaintext secret exactly once, alongside hasSecret', async () => {+ const created = await caller().create({+ name: 'Develop Center',+ redirectUris: ['https://dc.lobehub.com/callback'],+ type: 'web',+ });++ expect(created.clientSecret).toBe('lcs_plain');+ expect(created.hasSecret).toBe(true);+ expect(created).not.toHaveProperty('clientSecret', 'iv:tag:cipher');+ });++ it('lets a web app be created before its redirect URIs are configured', async () => {+ await caller().create({ name: 'Develop Center', type: 'web' });++ const [input] = mockCreate.mock.calls[0];+ expect(input.type).toBe('web');+ expect(input.redirectUris).toBeUndefined();+ });++ it.each([+ ['plain http on a public host', 'http://dc.lobehub.com/callback'],+ ['a wildcard host', 'https://*.lobehub.com/callback'],+ ['a fragment', 'https://dc.lobehub.com/callback#token'],+ ['a relative path', '/callback'],+ ])('rejects %s', async (_label, redirectUri) => {+ await expect(+ caller().create({ name: 'Develop Center', redirectUris: [redirectUri], type: 'web' }),+ ).rejects.toThrow();+ expect(mockCreate).not.toHaveBeenCalled();+ });++ it('trims and de-duplicates redirect URIs before they reach the model', async () => {+ await caller().create({+ name: 'Develop Center',+ redirectUris: [+ ' https://dc.lobehub.com/callback ',+ 'https://dc.lobehub.com/callback',+ 'http://localhost:3022/callback',+ ],+ type: 'web',+ });++ expect(mockCreate).toHaveBeenCalledWith(+ expect.objectContaining({+ redirectUris: ['https://dc.lobehub.com/callback', 'http://localhost:3022/callback'],+ }),+ );+ });+ });++ describe('read paths', () => {+ it('never leaks the stored secret', async () => {+ mockList.mockResolvedValue([webApp]);+ mockFindById.mockResolvedValue(webApp);++ const [listed] = await caller().list();+ const detail = await caller().getById({ id: 'lca_app' });++ expect(listed).not.toHaveProperty('clientSecret');+ expect(listed.hasSecret).toBe(true);+ expect(detail).not.toHaveProperty('clientSecret');+ expect(detail?.hasSecret).toBe(true);+ });+ });++ describe('update', () => {+ it('applies the same redirect URI rules', async () => {+ await expect(+ caller().update({ id: 'lca_app', value: { redirectUris: ['http://evil.example.com/cb'] } }),+ ).rejects.toThrow();+ expect(mockUpdate).not.toHaveBeenCalled();+ });++ it('refuses to strip a web app of every callback', async () => {+ await expect(+ caller().update({ id: 'lca_app', value: { redirectUris: [] } }),+ ).rejects.toThrow();+ await expect(+ caller().update({ id: 'lca_app', value: { redirectUris: [' '] } }),+ ).rejects.toThrow();+ expect(mockUpdate).not.toHaveBeenCalled();+ });+ });++ describe('rotateSecret', () => {+ it('returns the new plaintext secret', async () => {+ mockRotateSecret.mockResolvedValue('lcs_rotated');++ await expect(caller().rotateSecret({ id: 'lca_app' })).resolves.toEqual({+ clientSecret: 'lcs_rotated',+ });+ });++ it('404s when the app has no secret to rotate', async () => {+ mockRotateSecret.mockResolvedValue(undefined);++ await expect(caller().rotateSecret({ id: 'lca_app' })).rejects.toThrow();+ });+ });+});diff --git a/apps/server/src/routers/lambda/oauthApp.ts b/apps/server/src/routers/lambda/oauthApp.tsindex 1371de45532..86e427e37a0 100644--- a/apps/server/src/routers/lambda/oauthApp.ts+++ b/apps/server/src/routers/lambda/oauthApp.ts@@ -1,3 +1,9 @@+import {+ MAX_OAUTH_REDIRECT_URIS,+ normalizeRedirectUris,+ validateRedirectUri,+} from '@lobechat/utils/oauthApp';+import { TRPCError } from '@trpc/server';import { z } from 'zod';import {@@ -20,23 +26,50 @@ const oauthAppProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts)const oauthAppWriteProcedure = oauthAppProcedure.use(requireWorkspaceRoleWhenScoped('admin'));+/**+ * The stored secret is encrypted and is never a useful thing to ship to a+ * browser, so every read path replaces it with a boolean. The plaintext is+ * returned exactly once, by `create` and `rotateSecret`.+ */const stripSecret = <T extends { clientSecret?: string | null }>(client: T) => {- const { clientSecret: _clientSecret, ...rest } = client;- return rest;+ const { clientSecret, ...rest } = client;+ return { ...rest, hasSecret: !!clientSecret };};+const redirectUrisSchema = z+ .array(z.string().max(2000))+ .max(MAX_OAUTH_REDIRECT_URIS)+ .transform(normalizeRedirectUris)+ .superRefine((uris, ctx) => {+ // An authorization-code client with no callback can never complete a login,+ // so a list that normalizes to empty is rejected wherever one is supplied.+ if (uris.length === 0) ctx.addIssue({ code: 'custom', message: 'redirectUri.required' });++ for (const uri of uris) {+ const issue = validateRedirectUri(uri);+ if (issue) ctx.addIssue({ code: 'custom', message: `redirectUri.${issue}`, params: { uri } });+ }+ });+export const oauthAppRouter = router({create: oauthAppWriteProcedure.input(+ // Redirect URIs are configured on the app page after creation, so a web+ // app may start with none; it simply cannot complete a login until one is+ // added, and the provider refuses any unregistered redirect in the meantime.z.object({description: z.string().max(500).optional(),logoUri: z.string().max(300_000).optional(),name: z.string().min(1).max(64),+ redirectUris: redirectUrisSchema.optional(),+ type: z.enum(['device', 'web']).default('device'),}),).mutation(async ({ input, ctx }) => {- const client = await ctx.oidcClientModel.create(input);- return stripSecret(client);+ const { client, secret } = await ctx.oidcClientModel.create(input);++ // The only time the plaintext secret ever leaves the server.+ return { ...stripSecret(client), clientSecret: secret };}),delete: oauthAppWriteProcedure@@ -55,6 +88,16 @@ export const oauthAppRouter = router({return clients.map(stripSecret);}),+ rotateSecret: oauthAppWriteProcedure+ .input(z.object({ id: z.string() }))+ .mutation(async ({ input, ctx }) => {+ const clientSecret = await ctx.oidcClientModel.rotateSecret(input.id);++ if (!clientSecret) throw new TRPCError({ code: 'NOT_FOUND' });++ return { clientSecret };+ }),+setEnabled: oauthAppWriteProcedure.input(z.object({ enabled: z.boolean(), id: z.string() })).mutation(async ({ input, ctx }) => {@@ -69,6 +112,7 @@ export const oauthAppRouter = router({description: z.string().max(500).optional(),logoUri: z.string().max(300_000).optional(),name: z.string().min(1).max(64).optional(),+ redirectUris: redirectUrisSchema.optional(),}),}),)diff --git a/locales/en-US/auth.json b/locales/en-US/auth.jsonindex ec826fb959f..a7c1887c7dd 100644--- a/locales/en-US/auth.json+++ b/locales/en-US/auth.json@@ -235,13 +235,18 @@"oauthApp.deleteConfirm.ok": "Delete","oauthApp.deleteConfirm.title": "Delete this app?","oauthApp.detail.back": "Back to list",+ "oauthApp.detail.basicInfo": "Basic Info",+ "oauthApp.detail.cancel": "Cancel","oauthApp.detail.clientId": "Client ID",+ "oauthApp.detail.clientSecret": "Client Secret","oauthApp.detail.createdAt": "Created","oauthApp.detail.dangerZone": "Danger Zone","oauthApp.detail.delete": "Delete App",+ "oauthApp.detail.edit": "Edit","oauthApp.detail.enabled": "Enabled","oauthApp.detail.lastUsedAt": "Last Used","oauthApp.detail.neverUsed": "Never used",+ "oauthApp.detail.noDescription": "No description","oauthApp.detail.save": "Save Changes","oauthApp.detail.saveSuccess": "Changes saved","oauthApp.detail.title": "App Details",@@ -251,14 +256,36 @@"oauthApp.form.logo.label": "Logo","oauthApp.form.name.label": "Name","oauthApp.form.name.placeholder": "Please enter app name",+ "oauthApp.form.redirectUris.extra": "Each URI must be an exact https URL (http is allowed on localhost only) and is matched exactly.",+ "oauthApp.form.redirectUris.label": "Redirect URIs",+ "oauthApp.form.redirectUris.placeholder": "https://example.com/api/auth/callback","oauthApp.form.submit": "Create","oauthApp.form.title": "Create OAuth App",+ "oauthApp.form.type.deviceDesc": "For CLIs and devices without a browser. Users authorize with a code shown in the terminal.",+ "oauthApp.form.type.immutable": "The type cannot be changed after the app is created.",+ "oauthApp.form.type.label": "Application Type",+ "oauthApp.form.type.webDesc": "For server-side apps. Users are redirected back to your app, which authenticates with a client secret.",+ "oauthApp.form.type.webNext": "You will add redirect URIs on the app page after it is created.","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.redirectUris.add": "Add redirect URI",+ "oauthApp.redirectUris.configure": "Configure",+ "oauthApp.redirectUris.empty": "No redirect URIs yet. This app can't be used to sign in until you add one.",+ "oauthApp.redirectUris.remove": "Remove",+ "oauthApp.redirectUris.title": "Redirect URIs",+ "oauthApp.secret.copy": "Copy secret",+ "oauthApp.secret.hidden": "Hidden after creation",+ "oauthApp.secret.onceWarning": "This is the only time the client secret is shown. Store it somewhere safe before closing.",+ "oauthApp.secret.revealTitle": "Your client secret",+ "oauthApp.secret.rotate": "Rotate",+ "oauthApp.secret.rotateConfirm.content": "The current secret stops working immediately. Any deployment still using it will fail to sign users in until you update it.",+ "oauthApp.secret.rotateConfirm.ok": "Rotate secret",+ "oauthApp.secret.rotateConfirm.title": "Rotate this client secret?",+ "oauthApp.secret.usage": "Send it to the token endpoint as `client_secret` in the request body.","oauthApp.stats.activeUsers": "Active Users","oauthApp.stats.calls": "Total Calls","oauthApp.stats.credits": "Credits Used",@@ -268,8 +295,18 @@"oauthApp.stats.title": "Usage Stats","oauthApp.stats.tokens": "Tokens","oauthApp.type.badge": "Native · Device Flow",+ "oauthApp.type.device": "CLI / Device","oauthApp.type.deviceFlow": "Device Flow",+ "oauthApp.type.web": "Web App",+ "oauthApp.type.webBadge": "Web · Authorization Code","oauthApp.validation.nameRequired": "Name is required",+ "oauthApp.validation.redirectUri.credentials": "A redirect URI cannot embed a username or password",+ "oauthApp.validation.redirectUri.fragment": "A redirect URI cannot contain a fragment (#)",+ "oauthApp.validation.redirectUri.insecure": "A redirect URI must use https, except on localhost",+ "oauthApp.validation.redirectUri.malformed": "Please enter a full absolute URL",+ "oauthApp.validation.redirectUri.wildcard": "Wildcards are not allowed; redirect URIs are matched exactly",+ "oauthApp.validation.redirectUriRequired": "At least one redirect URI is required",+ "oauthApp.validation.redirectUriTooMany": "At most {{count}} redirect URIs are allowed","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.",diff --git a/locales/en-US/oauth.json b/locales/en-US/oauth.jsonindex 7de65c3ce3c..fad2dabee74 100644--- a/locales/en-US/oauth.json+++ b/locales/en-US/oauth.json@@ -1,4 +1,15 @@{+ "authorizeError.backToHome": "Back to Home",+ "authorizeError.code": "Error code",+ "authorizeError.reason.access_denied": "The authorization was denied.",+ "authorizeError.reason.invalid_client": "This app could not be found, or it has been disabled.",+ "authorizeError.reason.invalid_redirect_uri": "The app asked to send you back to an address it hasn't registered, so the request was stopped to protect your account. If you develop this app, add this redirect URI in its OAuth app settings.",+ "authorizeError.reason.invalid_request": "The authorization request is malformed or missing required parameters.",+ "authorizeError.reason.invalid_scope": "The app requested permissions it is not allowed to request.",+ "authorizeError.reason.server_error": "Something went wrong on our side. Please try again later.",+ "authorizeError.reason.unauthorized_client": "This app is not allowed to use this sign-in method.",+ "authorizeError.reason.unknown": "The authorization request could not be completed.",+ "authorizeError.title": "Authorization Can't Continue","consent.buttons.accept": "Authorize","consent.buttons.deny": "Deny","consent.description": "The application {{clientName}} is requesting authorization for your account",diff --git a/locales/zh-CN/auth.json b/locales/zh-CN/auth.jsonindex 442816a569c..152e6c2ba44 100644--- a/locales/zh-CN/auth.json+++ b/locales/zh-CN/auth.json@@ -235,13 +235,18 @@"oauthApp.deleteConfirm.ok": "删除","oauthApp.deleteConfirm.title": "确认删除该应用?","oauthApp.detail.back": "返回列表",+ "oauthApp.detail.basicInfo": "基本信息",+ "oauthApp.detail.cancel": "取消","oauthApp.detail.clientId": "Client ID",+ "oauthApp.detail.clientSecret": "客户端密钥","oauthApp.detail.createdAt": "创建时间","oauthApp.detail.dangerZone": "危险操作","oauthApp.detail.delete": "删除应用",+ "oauthApp.detail.edit": "编辑","oauthApp.detail.enabled": "已启用","oauthApp.detail.lastUsedAt": "最后使用时间","oauthApp.detail.neverUsed": "从未使用",+ "oauthApp.detail.noDescription": "暂无描述","oauthApp.detail.save": "保存更改","oauthApp.detail.saveSuccess": "已保存","oauthApp.detail.title": "应用详情",@@ -251,14 +256,36 @@"oauthApp.form.logo.label": "图标","oauthApp.form.name.label": "名称","oauthApp.form.name.placeholder": "请输入应用名称",+ "oauthApp.form.redirectUris.extra": "每个地址都必须是完整的 https 地址(仅 localhost 允许 http),并按完全匹配校验。",+ "oauthApp.form.redirectUris.label": "回调地址",+ "oauthApp.form.redirectUris.placeholder": "https://example.com/api/auth/callback","oauthApp.form.submit": "创建","oauthApp.form.title": "创建 OAuth 应用",+ "oauthApp.form.type.deviceDesc": "适用于命令行工具和没有浏览器的设备,用户通过终端里显示的验证码完成授权。",+ "oauthApp.form.type.immutable": "应用类型创建后不可更改。",+ "oauthApp.form.type.label": "应用类型",+ "oauthApp.form.type.webDesc": "适用于服务端应用,用户授权后跳回你的应用,由服务端用客户端密钥完成认证。",+ "oauthApp.form.type.webNext": "创建后在应用详情页添加回调地址。","oauthApp.item.disabledTag": "已停用","oauthApp.item.lastUsed": "最后使用 {{time}}","oauthApp.list.actions.create": "创建应用","oauthApp.list.actions.delete": "删除","oauthApp.list.empty": "还没有 OAuth 应用,创建一个开始吧。","oauthApp.list.neverUsed": "从未使用",+ "oauthApp.redirectUris.add": "添加回调地址",+ "oauthApp.redirectUris.configure": "配置",+ "oauthApp.redirectUris.empty": "还没有配置回调地址。添加之前,这个应用无法用于登录。",+ "oauthApp.redirectUris.remove": "移除",+ "oauthApp.redirectUris.title": "回调地址",+ "oauthApp.secret.copy": "复制密钥",+ "oauthApp.secret.hidden": "创建后不再展示",+ "oauthApp.secret.onceWarning": "客户端密钥只会展示这一次,请先妥善保存再关闭。",+ "oauthApp.secret.revealTitle": "你的客户端密钥",+ "oauthApp.secret.rotate": "轮换",+ "oauthApp.secret.rotateConfirm.content": "当前密钥会立即失效。仍在使用它的部署在你更新之前将无法完成登录。",+ "oauthApp.secret.rotateConfirm.ok": "轮换密钥",+ "oauthApp.secret.rotateConfirm.title": "要轮换这个客户端密钥吗?",+ "oauthApp.secret.usage": "在请求体中以 `client_secret` 传给令牌端点。","oauthApp.stats.activeUsers": "活跃用户","oauthApp.stats.calls": "总调用次数","oauthApp.stats.credits": "消耗积分",@@ -268,8 +295,18 @@"oauthApp.stats.title": "使用统计","oauthApp.stats.tokens": "Tokens","oauthApp.type.badge": "原生 · 设备流",+ "oauthApp.type.device": "命令行 / 设备","oauthApp.type.deviceFlow": "设备流",+ "oauthApp.type.web": "Web 应用",+ "oauthApp.type.webBadge": "Web · 授权码","oauthApp.validation.nameRequired": "请输入名称",+ "oauthApp.validation.redirectUri.credentials": "回调地址不能包含用户名或密码",+ "oauthApp.validation.redirectUri.fragment": "回调地址不能包含片段标识(#)",+ "oauthApp.validation.redirectUri.insecure": "回调地址必须使用 https,localhost 除外",+ "oauthApp.validation.redirectUri.malformed": "请输入完整的绝对地址",+ "oauthApp.validation.redirectUri.wildcard": "不支持通配符,回调地址按完全匹配校验",+ "oauthApp.validation.redirectUriRequired": "至少需要一个回调地址",+ "oauthApp.validation.redirectUriTooMany": "最多只能填写 {{count}} 个回调地址","profile.account": "账户","profile.authorizations.actions.revoke": "取消授权","profile.authorizations.revoke.description": "取消后,该工具将无法继续访问你的数据;需要使用时可再重新授权。",diff --git a/locales/zh-CN/oauth.json b/locales/zh-CN/oauth.jsonindex 55cc7ab24f5..f89ac5241fa 100644--- a/locales/zh-CN/oauth.json+++ b/locales/zh-CN/oauth.json@@ -1,4 +1,15 @@{+ "authorizeError.backToHome": "返回首页",+ "authorizeError.code": "错误码",+ "authorizeError.reason.access_denied": "授权已被拒绝。",+ "authorizeError.reason.invalid_client": "找不到这个应用,或它已被停用。",+ "authorizeError.reason.invalid_redirect_uri": "这个应用请求把你跳转到一个没有登记过的地址,为保护你的账户,授权已被中止。如果你是该应用的开发者,请在 OAuth 应用设置里添加这个回调地址。",+ "authorizeError.reason.invalid_request": "授权请求的参数不完整或格式有误。",+ "authorizeError.reason.invalid_scope": "这个应用请求了不被允许的权限。",+ "authorizeError.reason.server_error": "服务出现异常,请稍后再试。",+ "authorizeError.reason.unauthorized_client": "这个应用不被允许使用这种登录方式。",+ "authorizeError.reason.unknown": "授权请求未能完成。",+ "authorizeError.title": "无法继续授权","consent.buttons.accept": "授权","consent.buttons.deny": "拒绝","consent.description": "应用 {{clientName}} 申请你的账户授权",diff --git a/packages/database/src/models/__tests__/oidcClient.test.ts b/packages/database/src/models/__tests__/oidcClient.test.tsindex 87a9e3e4061..cdd10fad4ee 100644--- a/packages/database/src/models/__tests__/oidcClient.test.ts+++ b/packages/database/src/models/__tests__/oidcClient.test.ts@@ -2,6 +2,8 @@import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';+import { getTestDB } from '../../core/getTestDB';import { oidcClients, oidcGrants, oidcRefreshTokens, users, workspaces } from '../../schemas';import type { LobeChatDatabase } from '../../type';@@ -10,13 +12,17 @@ import { OidcClientModel } from '../oidcClient';const serverDB: LobeChatDatabase = await getTestDB();const userId = 'oidc-client-model-test-user';+const validKeyVaultsSecret = 'ofQiJCXLF8mYemwfMWLOHoHimlPu91YmLfU7YZ4lreQ=';const otherUserId = 'oidc-client-model-other-user';const workspaceId = 'oidc-client-model-test-workspace';const otherWorkspaceId = 'oidc-client-model-other-workspace';let oidcClientModel: OidcClientModel;+let originalKeyVaultsSecret: string | undefined;beforeEach(async () => {+ originalKeyVaultsSecret = process.env.KEY_VAULTS_SECRET;+ process.env.KEY_VAULTS_SECRET = validKeyVaultsSecret;oidcClientModel = new OidcClientModel(serverDB, userId);await serverDB.delete(users);await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);@@ -38,12 +44,13 @@ beforeEach(async () => {afterEach(async () => {await serverDB.delete(users);+ process.env.KEY_VAULTS_SECRET = originalKeyVaultsSecret;});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' });+ const { client: result } = await oidcClientModel.create({ name: 'My App' });expect(result.id).toMatch(/^lca_[\dA-Za-z]{24}$/);expect(result.name).toBe('My App');@@ -64,7 +71,7 @@ describe('OidcClientModel', () => {});it('should persist description and logoUri', async () => {- const result = await oidcClientModel.create({+ const { client: result } = await oidcClientModel.create({description: 'a demo',logoUri: 'https://example.com/logo.png',name: 'My App',@@ -77,7 +84,7 @@ describe('OidcClientModel', () => {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' });+ const { client: result } = await workspaceModel.create({ name: 'Workspace App' });expect(result).toMatchObject({name: 'Workspace App',@@ -156,7 +163,9 @@ describe('OidcClientModel', () => {describe('findById', () => {it('should find an own client by id', async () => {- const { id } = await oidcClientModel.create({ name: 'My App' });+ const {+ client: { id },+ } = await oidcClientModel.create({ name: 'My App' });const found = await oidcClientModel.findById(id);@@ -165,7 +174,9 @@ describe('OidcClientModel', () => {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 {+ client: { id },+ } = await otherModel.create({ name: 'Theirs' });const found = await oidcClientModel.findById(id);@@ -176,7 +187,9 @@ describe('OidcClientModel', () => {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' });+ const {+ client: { id },+ } = await creatorModel.create({ name: 'Shared App' });await expect(memberModel.findById(id)).resolves.toMatchObject({ id });await expect(otherWorkspaceModel.findById(id)).resolves.toBeUndefined();@@ -186,7 +199,9 @@ describe('OidcClientModel', () => {describe('update', () => {it('should update own client fields', async () => {- const { id } = await oidcClientModel.create({ name: 'Old Name' });+ const {+ client: { id },+ } = await oidcClientModel.create({ name: 'Old Name' });await oidcClientModel.update(id, { description: 'new desc', name: 'New Name' });@@ -201,7 +216,9 @@ describe('OidcClientModel', () => {it('should not update a client owned by another user', async () => {const otherModel = new OidcClientModel(serverDB, otherUserId);- const { id } = await otherModel.create({ name: 'Theirs' });+ const {+ client: { id },+ } = await otherModel.create({ name: 'Theirs' });await oidcClientModel.update(id, { name: 'Hacked' });@@ -216,7 +233,9 @@ describe('OidcClientModel', () => {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' });+ const {+ client: { id },+ } = await workspaceModel.create({ name: 'Workspace App' });await otherWorkspaceModel.update(id, { name: 'Hacked' });@@ -226,7 +245,9 @@ describe('OidcClientModel', () => {describe('setEnabled', () => {it('should toggle enabled on own client', async () => {- const { id } = await oidcClientModel.create({ name: 'My App' });+ const {+ client: { id },+ } = await oidcClientModel.create({ name: 'My App' });await oidcClientModel.setEnabled(id, false);@@ -240,7 +261,9 @@ describe('OidcClientModel', () => {it('should not toggle enabled on another user client', async () => {const otherModel = new OidcClientModel(serverDB, otherUserId);- const { id } = await otherModel.create({ name: 'Theirs' });+ const {+ client: { id },+ } = await otherModel.create({ name: 'Theirs' });await oidcClientModel.setEnabled(id, false);@@ -255,7 +278,9 @@ describe('OidcClientModel', () => {describe('delete', () => {it('should delete own client and its dependent token rows', async () => {- const { id } = await oidcClientModel.create({ name: 'My App' });+ const {+ client: { id },+ } = await oidcClientModel.create({ name: 'My App' });await serverDB.insert(oidcGrants).values({clientId: id,@@ -297,7 +322,9 @@ describe('OidcClientModel', () => {it('should not delete a client owned by another user', async () => {const otherModel = new OidcClientModel(serverDB, otherUserId);- const { id } = await otherModel.create({ name: 'Theirs' });+ const {+ client: { id },+ } = await otherModel.create({ name: 'Theirs' });await oidcClientModel.delete(id);@@ -312,7 +339,9 @@ describe('OidcClientModel', () => {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' });+ const {+ client: { id },+ } = await workspaceModel.create({ name: 'Workspace App' });await otherWorkspaceModel.delete(id);@@ -321,7 +350,9 @@ describe('OidcClientModel', () => {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' });+ const {+ client: { id },+ } = await otherModel.create({ name: 'Theirs' });await serverDB.insert(oidcGrants).values({clientId: id,@@ -341,4 +372,128 @@ describe('OidcClientModel', () => {expect(grant).toBeDefined();});});+ describe('create web app', () => {+ const redirectUris = ['https://dc.lobehub.com/api/auth/oauth2/callback/lobehub'];++ it('should create a confidential client that can run the authorization code flow', async () => {+ const { client, secret } = await oidcClientModel.create({+ name: 'Develop Center',+ redirectUris,+ type: 'web',+ });++ expect(client.applicationType).toBe('web');+ expect(client.grants).toEqual(['authorization_code', 'refresh_token']);+ expect(client.responseTypes).toEqual(['code']);+ expect(client.redirectUris).toEqual(redirectUris);+ expect(client.tokenEndpointAuthMethod).toBe('client_secret_post');+ expect(client.isFirstParty).toBe(false);+ expect(secret).toMatch(/^lcs_[\w-]{43}$/);+ });++ it('should store the secret encrypted rather than in plaintext', async () => {+ const { client, secret } = await oidcClientModel.create({+ name: 'Develop Center',+ redirectUris,+ type: 'web',+ });++ expect(client.clientSecret).not.toBe(secret);++ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();+ const { plaintext, wasAuthentic } = await gateKeeper.decrypt(client.clientSecret!);++ expect(wasAuthentic).toBe(true);+ expect(plaintext).toBe(secret);+ });++ it('should not give a device app a secret or redirect uris', async () => {+ const { client, secret } = await oidcClientModel.create({+ name: 'My CLI',+ redirectUris,+ type: 'device',+ });++ expect(secret).toBeUndefined();+ expect(client.clientSecret).toBeNull();+ expect(client.redirectUris).toEqual([]);+ });+ });++ describe('rotateSecret', () => {+ const createWebApp = () =>+ oidcClientModel.create({+ name: 'Develop Center',+ redirectUris: ['https://dc.lobehub.com/callback'],+ type: 'web',+ });++ it('should replace the stored secret and return the new plaintext', async () => {+ const { client, secret } = await createWebApp();++ const rotated = await oidcClientModel.rotateSecret(client.id);++ expect(rotated).toMatch(/^lcs_[\w-]{43}$/);+ expect(rotated).not.toBe(secret);++ const stored = await oidcClientModel.findById(client.id);+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();+ const { plaintext } = await gateKeeper.decrypt(stored.clientSecret!);++ expect(plaintext).toBe(rotated);+ });++ it('should refuse to mint a secret for a device app', async () => {+ const {+ client: { id },+ } = await oidcClientModel.create({ name: 'My CLI' });++ expect(await oidcClientModel.rotateSecret(id)).toBeUndefined();+ });++ it("should not rotate another user's app", async () => {+ const { client } = await createWebApp();+ const otherModel = new OidcClientModel(serverDB, otherUserId);++ expect(await otherModel.rotateSecret(client.id)).toBeUndefined();++ const stored = await oidcClientModel.findById(client.id);+ expect(stored.clientSecret).toBe(client.clientSecret);+ });+ });++ describe('update redirectUris', () => {+ it('should update redirect uris of a web app', async () => {+ const { client } = await oidcClientModel.create({+ name: 'Develop Center',+ redirectUris: ['https://dc.lobehub.com/callback'],+ type: 'web',+ });++ await oidcClientModel.update(client.id, {+ redirectUris: ['https://dc.lobehub.com/callback', 'http://localhost:3022/callback'],+ });++ const updated = await oidcClientModel.findById(client.id);+ expect(updated.redirectUris).toEqual([+ 'https://dc.lobehub.com/callback',+ 'http://localhost:3022/callback',+ ]);+ });++ it('should ignore redirect uris sent for a device app', async () => {+ const {+ client: { id },+ } = await oidcClientModel.create({ name: 'My CLI' });++ await oidcClientModel.update(id, {+ name: 'Renamed CLI',+ redirectUris: ['https://evil.example.com/callback'],+ });++ const updated = await oidcClientModel.findById(id);+ expect(updated.name).toBe('Renamed CLI');+ expect(updated.redirectUris).toEqual([]);+ });+ });});diff --git a/packages/database/src/models/oidcClient.ts b/packages/database/src/models/oidcClient.tsindex bd34b557b3f..5f8cc26a45c 100644--- a/packages/database/src/models/oidcClient.ts+++ b/packages/database/src/models/oidcClient.ts@@ -1,5 +1,8 @@+import { type OAuthAppType } from '@lobechat/types';import { and, desc, eq } from 'drizzle-orm';+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';+import {oidcAccessTokens,oidcClients,@@ -16,23 +19,40 @@ interface CreateOidcClientParams {description?: string | null;logoUri?: string | null;name: string;+ /** Required for `web` apps, ignored for `device` apps. */+ redirectUris?: string[];+ type?: OAuthAppType;}interface UpdateOidcClientParams {description?: string | null;logoUri?: string | null;name?: string;+ /** Only meaningful for `web` apps; ignored when the app has no redirect flow. */+ redirectUris?: string[];}const DEVICE_FLOW_GRANTS = ['urn:ietf:params:oauth:grant-type:device_code', 'refresh_token'];+const WEB_FLOW_GRANTS = ['authorization_code', 'refresh_token'];const DEFAULT_SCOPES = ['openid', 'profile', 'email', 'offline_access'];const generateClientId = () => `lca_${createNanoId(24)()}`;+/**+ * Client secrets are issued once and never shown again, so they carry real+ * entropy from the platform CSPRNG rather than the non-secure nanoid used for+ * public identifiers.+ */+const generateClientSecret = () => {+ const bytes = crypto.getRandomValues(new Uint8Array(32));+ return `lcs_${Buffer.from(bytes).toString('base64url')}`;+};+export class OidcClientModel {private db: LobeChatDatabase;private userId: string;private workspaceId?: string;+ private gateKeeperPromise: Promise<KeyVaultsGateKeeper> | null = null;constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {this.db = db;@@ -43,31 +63,86 @@ export class OidcClientModel {private ownership = () =>buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, oidcClients);+ private async getGateKeeper() {+ if (!this.gateKeeperPromise) {+ this.gateKeeperPromise = KeyVaultsGateKeeper.initWithEnvKey();+ }++ return this.gateKeeperPromise;+ }++ /**+ * Issues a secret and returns both halves: the plaintext to hand back to the+ * creator exactly once, and the encrypted form to store. The OIDC token+ * endpoint needs the plaintext to authenticate the client, so this is+ * encrypted at rest rather than hashed (see the adapter's `find`).+ */+ private issueClientSecret = async () => {+ const secret = generateClientSecret();+ const gateKeeper = await this.getGateKeeper();++ return { encrypted: await gateKeeper.encrypt(secret), secret };+ };++ /**+ * Creates an app and, for `web` apps, issues its one-time client secret.+ *+ * `device` apps stay public clients with no secret: the device flow has no+ * confidential channel to keep one in. `web` apps are confidential clients+ * because the only consumer that can use a redirect flow here is a server+ * that can hold a secret.+ */create = async (params: CreateOidcClientParams) => {+ const isWeb = params.type === 'web';+ const { encrypted, secret } = isWeb+ ? await this.issueClientSecret()+ : { encrypted: null, secret: undefined };+const [result] = await this.db.insert(oidcClients).values(buildWorkspacePayload({ userId: this.userId, workspaceId: this.workspaceId },{- applicationType: 'native',- clientSecret: null,+ applicationType: isWeb ? 'web' : 'native',+ clientSecret: encrypted,description: params.description,- grants: DEVICE_FLOW_GRANTS,+ grants: isWeb ? WEB_FLOW_GRANTS : DEVICE_FLOW_GRANTS,id: generateClientId(),isFirstParty: false,logoUri: params.logoUri,name: params.name,- redirectUris: [],- responseTypes: [],+ redirectUris: isWeb ? (params.redirectUris ?? []) : [],+ responseTypes: isWeb ? ['code'] : [],scopes: DEFAULT_SCOPES,- tokenEndpointAuthMethod: 'none',+ tokenEndpointAuthMethod: isWeb ? 'client_secret_post' : 'none',},),).returning();- return result;+ return { client: result, secret };+ };++ /**+ * Replaces the client secret and returns the new plaintext once.+ *+ * Returns `undefined` when the app is not the caller's or has no secret to+ * rotate, so a device-flow app can never be turned into a confidential one+ * through this path.+ */+ rotateSecret = async (id: string) => {+ const existing = await this.findById(id);+ if (!existing || !existing.clientSecret) return undefined;++ const { encrypted, secret } = await this.issueClientSecret();++ await this.db+ .update(oidcClients)+ .set({ clientSecret: encrypted, updatedAt: new Date() })+ .where(and(eq(oidcClients.id, id), this.ownership()));++ return secret;};list = async () => {@@ -89,9 +164,19 @@ export class OidcClientModel {};update = async (id: string, value: UpdateOidcClientParams) => {+ const { redirectUris, ...rest } = value;++ // A device-flow app has no redirect leg, so ignoring the field for anything+ // but a web app keeps a stray payload from granting it one.+ const isWeb = redirectUris ? (await this.findById(id))?.applicationType === 'web' : false;+return this.db.update(oidcClients)- .set({ ...value, updatedAt: new Date() })+ .set({+ ...rest,+ ...(redirectUris && isWeb ? { redirectUris } : {}),+ updatedAt: new Date(),+ }).where(and(eq(oidcClients.id, id), this.ownership()));};diff --git a/packages/locales/src/default/auth.ts b/packages/locales/src/default/auth.tsindex de98c9eff17..34fcecb0b66 100644--- a/packages/locales/src/default/auth.ts+++ b/packages/locales/src/default/auth.ts@@ -255,13 +255,18 @@ export default {'oauthApp.deleteConfirm.ok': 'Delete','oauthApp.deleteConfirm.title': 'Delete this app?','oauthApp.detail.back': 'Back to list',+ 'oauthApp.detail.basicInfo': 'Basic Info',+ 'oauthApp.detail.cancel': 'Cancel','oauthApp.detail.clientId': 'Client ID',+ 'oauthApp.detail.clientSecret': 'Client Secret','oauthApp.detail.createdAt': 'Created','oauthApp.detail.dangerZone': 'Danger Zone','oauthApp.detail.delete': 'Delete App',+ 'oauthApp.detail.edit': 'Edit','oauthApp.detail.enabled': 'Enabled','oauthApp.detail.lastUsedAt': 'Last Used','oauthApp.detail.neverUsed': 'Never used',+ 'oauthApp.detail.noDescription': 'No description','oauthApp.detail.save': 'Save Changes','oauthApp.detail.saveSuccess': 'Changes saved','oauthApp.detail.title': 'App Details',@@ -271,14 +276,42 @@ export default {'oauthApp.form.logo.label': 'Logo','oauthApp.form.name.label': 'Name','oauthApp.form.name.placeholder': 'Please enter app name',+ 'oauthApp.form.redirectUris.extra':+ 'Each URI must be an exact https URL (http is allowed on localhost only) and is matched exactly.',+ 'oauthApp.form.redirectUris.label': 'Redirect URIs',+ 'oauthApp.form.redirectUris.placeholder': 'https://example.com/api/auth/callback','oauthApp.form.submit': 'Create','oauthApp.form.title': 'Create OAuth App',+ 'oauthApp.form.type.deviceDesc':+ 'For CLIs and devices without a browser. Users authorize with a code shown in the terminal.',+ 'oauthApp.form.type.immutable': 'The type cannot be changed after the app is created.',+ 'oauthApp.form.type.label': 'Application Type',+ 'oauthApp.form.type.webDesc':+ 'For server-side apps. Users are redirected back to your app, which authenticates with a client secret.',+ 'oauthApp.form.type.webNext': 'You will add redirect URIs on the app page after it is created.','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.redirectUris.add': 'Add redirect URI',+ 'oauthApp.redirectUris.configure': 'Configure',+ 'oauthApp.redirectUris.empty':+ "No redirect URIs yet. This app can't be used to sign in until you add one.",+ 'oauthApp.redirectUris.remove': 'Remove',+ 'oauthApp.redirectUris.title': 'Redirect URIs',+ 'oauthApp.secret.copy': 'Copy secret',+ 'oauthApp.secret.hidden': 'Hidden after creation',+ 'oauthApp.secret.onceWarning':+ 'This is the only time the client secret is shown. Store it somewhere safe before closing.',+ 'oauthApp.secret.revealTitle': 'Your client secret',+ 'oauthApp.secret.rotate': 'Rotate',+ 'oauthApp.secret.rotateConfirm.content':+ 'The current secret stops working immediately. Any deployment still using it will fail to sign users in until you update it.',+ 'oauthApp.secret.rotateConfirm.ok': 'Rotate secret',+ 'oauthApp.secret.rotateConfirm.title': 'Rotate this client secret?',+ 'oauthApp.secret.usage': 'Send it to the token endpoint as `client_secret` in the request body.','oauthApp.stats.activeUsers': 'Active Users','oauthApp.stats.calls': 'Total Calls','oauthApp.stats.credits': 'Credits Used',@@ -288,8 +321,20 @@ export default {'oauthApp.stats.title': 'Usage Stats','oauthApp.stats.tokens': 'Tokens','oauthApp.type.badge': 'Native · Device Flow',+ 'oauthApp.type.device': 'CLI / Device','oauthApp.type.deviceFlow': 'Device Flow',+ 'oauthApp.type.web': 'Web App',+ 'oauthApp.type.webBadge': 'Web · Authorization Code','oauthApp.validation.nameRequired': 'Name is required',+ 'oauthApp.validation.redirectUri.credentials':+ 'A redirect URI cannot embed a username or password',+ 'oauthApp.validation.redirectUri.fragment': 'A redirect URI cannot contain a fragment (#)',+ 'oauthApp.validation.redirectUri.insecure': 'A redirect URI must use https, except on localhost',+ 'oauthApp.validation.redirectUri.malformed': 'Please enter a full absolute URL',+ 'oauthApp.validation.redirectUri.wildcard':+ 'Wildcards are not allowed; redirect URIs are matched exactly',+ 'oauthApp.validation.redirectUriRequired': 'At least one redirect URI is required',+ 'oauthApp.validation.redirectUriTooMany': 'At most {{count}} redirect URIs are allowed','profile.account': 'Account','profile.authorizations.actions.revoke': 'Revoke','profile.authorizations.revoke.description':diff --git a/packages/locales/src/default/oauth.ts b/packages/locales/src/default/oauth.tsindex cbfd2c9eb8e..376f86d7edb 100644--- a/packages/locales/src/default/oauth.ts+++ b/packages/locales/src/default/oauth.ts@@ -1,4 +1,19 @@export default {+ 'authorizeError.backToHome': 'Back to Home',+ 'authorizeError.code': 'Error code',+ 'authorizeError.reason.access_denied': 'The authorization was denied.',+ 'authorizeError.reason.invalid_client': 'This app could not be found, or it has been disabled.',+ 'authorizeError.reason.invalid_redirect_uri':+ "The app asked to send you back to an address it hasn't registered, so the request was stopped to protect your account. If you develop this app, add this redirect URI in its OAuth app settings.",+ 'authorizeError.reason.invalid_request':+ 'The authorization request is malformed or missing required parameters.',+ 'authorizeError.reason.invalid_scope':+ 'The app requested permissions it is not allowed to request.',+ 'authorizeError.reason.server_error': 'Something went wrong on our side. Please try again later.',+ 'authorizeError.reason.unauthorized_client':+ 'This app is not allowed to use this sign-in method.',+ 'authorizeError.reason.unknown': 'The authorization request could not be completed.',+ 'authorizeError.title': "Authorization Can't Continue",'consent.buttons.accept': 'Authorize','consent.buttons.deny': 'Deny','consent.description':diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex 811d8ead5c5..2497ae18b61 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -66,6 +66,7 @@ export * from './work';export * from './acceptanceComment';export * from './acceptanceFlow';export * from './agentRuntime';+export * from './oauthApp';export * from './openai/chat';export * from './openai/plugin';export * from './subscription';diff --git a/packages/types/src/oauthApp.ts b/packages/types/src/oauthApp.tsindex 29411ad2ed1..c0e84a24789 100644--- a/packages/types/src/oauthApp.ts+++ b/packages/types/src/oauthApp.ts@@ -1,12 +1,19 @@+/** An OAuth app either talks to a browser redirect or polls a device code. */+export type OAuthAppType = 'device' | 'web';+export interface OAuthAppItem {applicationType?: string | null;createdAt: Date;description?: string | null;enabled?: boolean | null;+ grants?: string[] | null;+ /** Whether a client secret has been issued; the secret itself is never read back. */+ hasSecret?: boolean;id: string;lastUsedAt?: Date | null;logoUri?: string | null;name: string;+ redirectUris?: string[] | null;scopes?: string[] | null;updatedAt?: Date;}@@ -15,10 +22,13 @@ export interface CreateOAuthAppParams {description?: string;logoUri?: string;name: string;+ redirectUris?: string[];+ type?: OAuthAppType;}export interface UpdateOAuthAppParams {description?: string;logoUri?: string;name?: string;+ redirectUris?: string[];}diff --git a/packages/utils/src/oauthApp.test.ts b/packages/utils/src/oauthApp.test.tsnew file mode 100644index 00000000000..50440816ef2--- /dev/null+++ b/packages/utils/src/oauthApp.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest';++import { normalizeRedirectUris, validateRedirectUri } from './oauthApp';++describe('validateRedirectUri', () => {+ it('accepts https urls', () => {+ expect(validateRedirectUri('https://dc.lobehub.com/api/auth/callback/lobehub')).toBeUndefined();+ });++ it('accepts http on loopback hosts', () => {+ expect(validateRedirectUri('http://localhost:3022/api/auth/callback')).toBeUndefined();+ expect(validateRedirectUri('http://127.0.0.1:3022/api/auth/callback')).toBeUndefined();+ });++ it('rejects plain http on a public host', () => {+ expect(validateRedirectUri('http://dc.lobehub.com/callback')).toBe('insecure');+ });++ it('rejects non-http schemes', () => {+ expect(validateRedirectUri('javascript:alert(1)')).toBe('insecure');+ expect(validateRedirectUri('com.lobehub.app://auth/callback')).toBe('insecure');+ });++ it('rejects wildcards so matching stays exact', () => {+ expect(validateRedirectUri('https://*.lobehub.com/callback')).toBe('wildcard');+ });++ it('rejects fragments and embedded credentials', () => {+ expect(validateRedirectUri('https://dc.lobehub.com/cb#token')).toBe('fragment');+ expect(validateRedirectUri('https://user:[email protected]/cb')).toBe('credentials');+ });++ it('rejects relative or garbage values', () => {+ expect(validateRedirectUri('/callback')).toBe('malformed');+ expect(validateRedirectUri('not a url')).toBe('malformed');+ });+});++describe('normalizeRedirectUris', () => {+ it('trims, drops blanks and de-duplicates while keeping order', () => {+ expect(+ normalizeRedirectUris([+ ' https://a.com/cb ',+ '',+ 'https://b.com/cb',+ 'https://a.com/cb',+ ' ',+ ]),+ ).toEqual(['https://a.com/cb', 'https://b.com/cb']);+ });+});diff --git a/packages/utils/src/oauthApp.ts b/packages/utils/src/oauthApp.tsnew file mode 100644index 00000000000..04318b17adb--- /dev/null+++ b/packages/utils/src/oauthApp.ts@@ -0,0 +1,69 @@+/**+ * Shared rules for user-created OAuth applications.+ *+ * The same checks run on the client (form validation) and on the server (tRPC+ * input validation). Redirect URIs are the only real attack surface of a+ * self-service OAuth app: a loose rule here turns every app into an open+ * redirect that leaks authorization codes, so the server never trusts the+ * client-side pass.+ */++/** Web apps redirect back to a handful of environments at most (prod + staging + local). */+export const MAX_OAUTH_REDIRECT_URIS = 5;++export type RedirectUriIssue =+ /** Not parseable as an absolute URL. */+ | 'malformed'+ /** Plain http outside loopback, or a non-http(s) scheme. */+ | 'insecure'+ /** Carries a fragment, which is never sent to the server anyway. */+ | 'fragment'+ /** Carries userinfo credentials. */+ | 'credentials'+ /** Contains a wildcard; matching is exact by design. */+ | 'wildcard';++const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);++/**+ * Validates one redirect URI.+ *+ * Returns `undefined` when the URI is acceptable, otherwise the reason it was+ * rejected so the caller can map it onto a localized message.+ */+export const validateRedirectUri = (input: string): RedirectUriIssue | undefined => {+ const value = input.trim();++ if (value.includes('*')) return 'wildcard';++ let url: URL;+ try {+ url = new URL(value);+ } catch {+ return 'malformed';+ }++ if (url.protocol !== 'https:' && url.protocol !== 'http:') return 'insecure';+ if (url.protocol === 'http:' && !LOOPBACK_HOSTS.has(url.hostname)) return 'insecure';+ if (url.hash) return 'fragment';+ if (url.username || url.password) return 'credentials';++ return undefined;+};++/**+ * Normalizes a submitted redirect URI list: trims, drops blanks, de-duplicates.+ *+ * Order is preserved so the UI renders the list back the way it was typed.+ */+export const normalizeRedirectUris = (input: string[]): string[] => {+ const seen = new Set<string>();++ return input+ .map((item) => item.trim())+ .filter((item) => {+ if (!item || seen.has(item)) return false;+ seen.add(item);+ return true;+ });+};diff --git a/src/features/Auth/OAuthAuthorizeError/index.tsx b/src/features/Auth/OAuthAuthorizeError/index.tsxnew file mode 100644index 00000000000..c557296f394--- /dev/null+++ b/src/features/Auth/OAuthAuthorizeError/index.tsx@@ -0,0 +1,88 @@+'use client';++import { Block, Flexbox, FluentEmoji } from '@lobehub/ui';+import { Button, Text } from '@lobehub/ui/base-ui';+import { Result } from 'antd';+import { cssVar } from 'antd-style';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';+import { useSearchParams } from 'react-router';++const REASON_KEYS = {+ access_denied: 'authorizeError.reason.access_denied',+ invalid_client: 'authorizeError.reason.invalid_client',+ invalid_redirect_uri: 'authorizeError.reason.invalid_redirect_uri',+ invalid_request: 'authorizeError.reason.invalid_request',+ invalid_scope: 'authorizeError.reason.invalid_scope',+ server_error: 'authorizeError.reason.server_error',+ unauthorized_client: 'authorizeError.reason.unauthorized_client',+} as const;++const isKnownError = (code: string | null): code is keyof typeof REASON_KEYS =>+ !!code && Object.prototype.hasOwnProperty.call(REASON_KEYS, code);++/**+ * Where the OIDC provider sends the browser when an authorization request+ * cannot continue (unregistered redirect URI, unknown client, bad parameters).+ * The provider never redirects back to the requesting app in these cases, so+ * this page is the user's only explanation of what happened.+ */+const OAuthAuthorizeError = memo(() => {+ const { t } = useTranslation('oauth');+ const [searchParams] = useSearchParams();++ const error = searchParams.get('error');+ const description = searchParams.get('error_description');+ const reason = isKnownError(error) ? t(REASON_KEYS[error]) : t('authorizeError.reason.unknown');++ const codeStyle = { fontFamily: cssVar.fontFamilyCode, fontSize: 12, wordBreak: 'break-word' };++ return (+ <Result+ icon={<FluentEmoji emoji={'🥵'} size={96} type={'anim'} />}+ status={'error'}+ extra={+ <a href="/">+ <Button block size={'large'} style={{ minWidth: 240 }}>+ {t('authorizeError.backToHome')}+ </Button>+ </a>+ }+ subTitle={+ <Flexbox align={'center'} gap={16} style={{ marginInline: 'auto', maxWidth: 440 }}>+ <Text fontSize={16} type={'secondary'}>+ {reason}+ </Text>+ {(error || description) && (+ <Block+ gap={6}+ padding={12}+ style={{ textAlign: 'start', width: '100%' }}+ variant={'filled'}+ >+ {error && (+ <Text style={codeStyle as any} type={'secondary'}>+ {t('authorizeError.code')}: {error}+ </Text>+ )}+ {description && (+ <Text style={codeStyle as any} type={'secondary'}>+ {description}+ </Text>+ )}+ </Block>+ )}+ </Flexbox>+ }+ title={+ <Text fontSize={32} weight={'bold'}>+ {t('authorizeError.title')}+ </Text>+ }+ />+ );+});++OAuthAuthorizeError.displayName = 'OAuthAuthorizeError';++export default OAuthAuthorizeError;diff --git a/src/features/Auth/OAuthConsent/Consent/index.tsx b/src/features/Auth/OAuthConsent/Consent/index.tsxindex 79da20cc841..c24a1c0cd98 100644--- a/src/features/Auth/OAuthConsent/Consent/index.tsx+++ b/src/features/Auth/OAuthConsent/Consent/index.tsx@@ -49,6 +49,7 @@ const ConsentClient = memo<ClientProps>(({ uid, clientId, scopes, clientMetadatalogoUrl={clientMetadata.logo}/><AuthCard+ centeredsubtitle={t('consent.description', { clientName: clientDisplayName })}title={t('consent.title', { clientName: clientDisplayName })}footer={diff --git a/src/features/Auth/OAuthConsent/Login.tsx b/src/features/Auth/OAuthConsent/Login.tsxindex 8e2777fd4c5..831c1150aa7 100644--- a/src/features/Auth/OAuthConsent/Login.tsx+++ b/src/features/Auth/OAuthConsent/Login.tsx@@ -40,6 +40,7 @@ const LoginConfirmClient = memo<LoginConfirmProps>(({ uid, clientMetadata }) =>logoUrl={clientMetadata.logo}/><AuthCard+ centeredsubtitle={descriptionText}title={titleText}footer={diff --git a/src/features/AuthCard/index.tsx b/src/features/AuthCard/index.tsxindex f86d6a62684..e7b8d9c2e94 100644--- a/src/features/AuthCard/index.tsx+++ b/src/features/AuthCard/index.tsx@@ -7,32 +7,46 @@ import { type ReactNode } from 'react';import { memo } from 'react';export interface AuthCardProps extends Omit<FlexboxProps, 'title'> {+ /**+ * Center the title and subtitle. Use it when the card sits under a centered+ * header such as an application logo, so the text lines up with it.+ */+ centered?: boolean;footer?: ReactNode;subtitle?: ReactNode;title?: ReactNode;}-export const AuthCard = memo<AuthCardProps>(({ children, title, subtitle, footer, ...rest }) => {- return (- <Flexbox width={'min(100%,440px)'} {...rest}>- <Flexbox gap={16}>- {title && (- <Text fontSize={28} style={{ lineHeight: 1.4 }} weight={'bold'}>- {title}- </Text>- )}- {subtitle && (- <Text fontSize={18} style={{ lineHeight: 1.4 }} type={'secondary'} weight={500}>- {subtitle}- </Text>- )}- </Flexbox>- <Flexbox gap={4} paddingBlock={32}>- {children}+export const AuthCard = memo<AuthCardProps>(+ ({ centered, children, title, subtitle, footer, ...rest }) => {+ const textAlign = centered ? 'center' : undefined;++ return (+ <Flexbox width={'min(100%,440px)'} {...rest}>+ <Flexbox align={centered ? 'center' : undefined} gap={16}>+ {title && (+ <Text fontSize={28} style={{ lineHeight: 1.4, textAlign }} weight={'bold'}>+ {title}+ </Text>+ )}+ {subtitle && (+ <Text+ fontSize={18}+ style={{ lineHeight: 1.4, textAlign }}+ type={'secondary'}+ weight={500}+ >+ {subtitle}+ </Text>+ )}+ </Flexbox>+ <Flexbox gap={4} paddingBlock={32}>+ {children}+ </Flexbox>+ {footer}</Flexbox>- {footer}- </Flexbox>- );-});+ );+ },+);export default AuthCard;diff --git a/src/features/Settings/oauth-apps/features/AppDetail/BasicInfoCard.tsx b/src/features/Settings/oauth-apps/features/AppDetail/BasicInfoCard.tsxnew file mode 100644index 00000000000..419a20818cd--- /dev/null+++ b/src/features/Settings/oauth-apps/features/AppDetail/BasicInfoCard.tsx@@ -0,0 +1,130 @@+'use client';++import { Flexbox, Input, TextArea } from '@lobehub/ui';+import { Button, Text } from '@lobehub/ui/base-ui';+import { Form } from 'antd';+import { PencilIcon } from 'lucide-react';+import { type FC, useState } from 'react';+import { useTranslation } from 'react-i18next';++import AvatarUpload from '@/components/AvatarUpload';+import { type OAuthAppItem, type UpdateOAuthAppParams } from '@/types/oauthApp';++import SectionCard from './SectionCard';++interface BasicInfoValues {+ description?: string;+ name: string;+}++interface BasicInfoCardProps {+ canEdit: boolean;+ detail: OAuthAppItem;+ onSubmit: (value: UpdateOAuthAppParams) => Promise<void>;+}++/**+ * Name, logo and description, read-only until the user asks to edit. The edit+ * form mounts fresh from the saved values each time, so cancelling needs no+ * reset and a half-typed change never lingers into the next edit.+ */+const BasicInfoCard: FC<BasicInfoCardProps> = ({ canEdit, detail, onSubmit }) => {+ const { t } = useTranslation('auth');+ const [editing, setEditing] = useState(false);+ const [saving, setSaving] = useState(false);+ const [logoUri, setLogoUri] = useState<string | undefined>(detail.logoUri ?? undefined);++ const startEditing = () => {+ setLogoUri(detail.logoUri ?? undefined);+ setEditing(true);+ };++ const handleUpload = (file: File) => {+ const reader = new FileReader();+ reader.addEventListener('load', () => setLogoUri(reader.result as string));+ reader.readAsDataURL(file);+ };++ const handleFinish = async (values: BasicInfoValues) => {+ setSaving(true);+ try {+ await onSubmit({ description: values.description, logoUri, name: values.name.trim() });+ setEditing(false);+ } finally {+ setSaving(false);+ }+ };++ const itemStyle = { marginBottom: 0 };++ return (+ <SectionCard+ title={t('oauthApp.detail.basicInfo')}+ extra={+ !editing && (+ <Button+ disabled={!canEdit}+ icon={<PencilIcon size={14} />}+ size={'small'}+ onClick={startEditing}+ >+ {t('oauthApp.detail.edit')}+ </Button>+ )+ }+ >+ {editing ? (+ <Form+ colon={false}+ initialValues={{ description: detail.description ?? '', name: detail.name }}+ layout={'vertical'}+ onFinish={handleFinish}+ >+ <Flexbox gap={16}>+ <Form.Item label={t('oauthApp.form.logo.label')} style={itemStyle}>+ <AvatarUpload title={detail.name} 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>++ <Flexbox horizontal gap={8} justify={'flex-end'}>+ <Button onClick={() => setEditing(false)}>{t('oauthApp.detail.cancel')}</Button>+ <Button htmlType={'submit'} loading={saving} type={'primary'}>+ {t('oauthApp.detail.save')}+ </Button>+ </Flexbox>+ </Flexbox>+ </Form>+ ) : (+ <Flexbox horizontal align={'center'} gap={16}>+ <AvatarUpload title={detail.name} value={detail.logoUri ?? undefined} />+ <Flexbox gap={4} style={{ minWidth: 0 }}>+ <Text strong style={{ fontSize: 16 }}>+ {detail.name}+ </Text>+ <Text type={'secondary'}>+ {detail.description || t('oauthApp.detail.noDescription')}+ </Text>+ </Flexbox>+ </Flexbox>+ )}+ </SectionCard>+ );+};++export default BasicInfoCard;diff --git a/src/features/Settings/oauth-apps/features/AppDetail/EditForm.tsx b/src/features/Settings/oauth-apps/features/AppDetail/EditForm.tsxdeleted file mode 100644index 8fe2e743695..00000000000--- a/src/features/Settings/oauth-apps/features/AppDetail/EditForm.tsx+++ /dev/null@@ -1,104 +0,0 @@-'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/features/Settings/oauth-apps/features/AppDetail/RedirectUrisCard.tsx b/src/features/Settings/oauth-apps/features/AppDetail/RedirectUrisCard.tsxnew file mode 100644index 00000000000..95d2a87247a--- /dev/null+++ b/src/features/Settings/oauth-apps/features/AppDetail/RedirectUrisCard.tsx@@ -0,0 +1,178 @@+'use client';++import { Flexbox, Input } from '@lobehub/ui';+import { ActionIcon, Alert, Button, Text } from '@lobehub/ui/base-ui';+import { Form } from 'antd';+import { createStaticStyles } from 'antd-style';+import { PencilIcon, PlusIcon, Trash2Icon } from 'lucide-react';+import { type FC, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { type OAuthAppItem, type UpdateOAuthAppParams } from '@/types/oauthApp';++import {+ MAX_OAUTH_REDIRECT_URIS,+ normalizeRedirectUris,+ redirectUriListMessageKey,+ redirectUriMessageKey,+} from '../../redirectUris';+import SectionCard from './SectionCard';++const styles = createStaticStyles(({ css, cssVar }) => ({+ // antd's ErrorList only picks up error styling inside a Form.Item that has an+ // error status; the list-level message sits outside one, so it is colored here.+ listError: css`+ font-size: 14px;+ line-height: 1.5;+ color: ${cssVar.colorError};+ `,+ uri: css`+ padding-block: 8px;+ padding-inline: 12px;+ border-radius: ${cssVar.borderRadius};++ font-family: ${cssVar.fontFamilyCode};+ font-size: 13px;+ overflow-wrap: anywhere;++ background: ${cssVar.colorFillQuaternary};+ `,+}));++interface RedirectUrisValues {+ redirectUris: string[];+}++interface RedirectUrisCardProps {+ canEdit: boolean;+ detail: OAuthAppItem;+ onSubmit: (value: UpdateOAuthAppParams) => Promise<void>;+}++/**+ * The redirect URIs a web app may send users back to. A freshly created app has+ * none, which is a legitimate "not yet configured" state shown as a warning;+ * once the user opens the editor, a save needs at least one URI.+ */+const RedirectUrisCard: FC<RedirectUrisCardProps> = ({ canEdit, detail, onSubmit }) => {+ const { t } = useTranslation('auth');+ const [editing, setEditing] = useState(false);+ const [saving, setSaving] = useState(false);+ const saved = detail.redirectUris ?? [];++ const handleFinish = async ({ redirectUris }: RedirectUrisValues) => {+ setSaving(true);+ try {+ await onSubmit({ redirectUris: normalizeRedirectUris(redirectUris ?? []) });+ setEditing(false);+ } finally {+ setSaving(false);+ }+ };++ return (+ <SectionCard+ title={t('oauthApp.redirectUris.title')}+ extra={+ !editing && (+ <Button+ disabled={!canEdit}+ icon={<PencilIcon size={14} />}+ size={'small'}+ onClick={() => setEditing(true)}+ >+ {t(saved.length > 0 ? 'oauthApp.detail.edit' : 'oauthApp.redirectUris.configure')}+ </Button>+ )+ }+ >+ {editing ? (+ <Form+ colon={false}+ initialValues={{ redirectUris: saved.length > 0 ? saved : [''] }}+ layout={'vertical'}+ onFinish={handleFinish}+ >+ <Flexbox gap={12}>+ <Text style={{ fontSize: 12 }} type={'secondary'}>+ {t('oauthApp.form.redirectUris.extra')}+ </Text>++ <Form.List+ name={'redirectUris'}+ rules={[+ {+ validator: async (_, values?: (string | undefined)[]) => {+ const messageKey = redirectUriListMessageKey(values);+ if (messageKey)+ throw new Error(t(messageKey, { count: MAX_OAUTH_REDIRECT_URIS }));+ },+ },+ ]}+ >+ {(fields, { add, remove }, { errors }) => (+ <Flexbox gap={8}>+ {fields.map((field) => (+ <Flexbox horizontal align={'flex-start'} gap={8} key={field.key}>+ <Form.Item+ name={field.name}+ style={{ flex: 1, marginBottom: 0 }}+ rules={[+ {+ validator: async (_, value?: string) => {+ const messageKey = redirectUriMessageKey(value);+ if (messageKey) throw new Error(t(messageKey));+ },+ },+ ]}+ >+ <Input placeholder={t('oauthApp.form.redirectUris.placeholder')} />+ </Form.Item>+ <ActionIcon+ aria-label={t('oauthApp.redirectUris.remove')}+ icon={Trash2Icon}+ style={{ marginTop: 4 }}+ title={t('oauthApp.redirectUris.remove')}+ onClick={() => remove(field.name)}+ />+ </Flexbox>+ ))}++ {errors.length > 0 && <div className={styles.listError}>{errors}</div>}++ <Button+ block+ disabled={fields.length >= MAX_OAUTH_REDIRECT_URIS}+ icon={<PlusIcon size={14} />}+ onClick={() => add('')}+ >+ {t('oauthApp.redirectUris.add')}+ </Button>+ </Flexbox>+ )}+ </Form.List>++ <Flexbox horizontal gap={8} justify={'flex-end'}>+ <Button onClick={() => setEditing(false)}>{t('oauthApp.detail.cancel')}</Button>+ <Button htmlType={'submit'} loading={saving} type={'primary'}>+ {t('oauthApp.detail.save')}+ </Button>+ </Flexbox>+ </Flexbox>+ </Form>+ ) : saved.length > 0 ? (+ <Flexbox gap={6}>+ {saved.map((uri) => (+ <div className={styles.uri} key={uri}>+ {uri}+ </div>+ ))}+ </Flexbox>+ ) : (+ <Alert showIcon message={t('oauthApp.redirectUris.empty')} type={'warning'} />+ )}+ </SectionCard>+ );+};++export default RedirectUrisCard;diff --git a/src/features/Settings/oauth-apps/features/AppDetail/SectionCard.tsx b/src/features/Settings/oauth-apps/features/AppDetail/SectionCard.tsxnew file mode 100644index 00000000000..7b7c6ff9f44--- /dev/null+++ b/src/features/Settings/oauth-apps/features/AppDetail/SectionCard.tsx@@ -0,0 +1,32 @@+'use client';++import { Flexbox } from '@lobehub/ui';+import { Text } from '@lobehub/ui/base-ui';+import { createStaticStyles } from 'antd-style';+import { type FC, type PropsWithChildren, type ReactNode } from 'react';++const styles = createStaticStyles(({ css, cssVar }) => ({+ card: css`+ padding: 16px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};+ background: ${cssVar.colorBgContainer};+ `,+}));++interface SectionCardProps {+ extra?: ReactNode;+ title: ReactNode;+}++const SectionCard: FC<PropsWithChildren<SectionCardProps>> = ({ children, extra, title }) => (+ <Flexbox className={styles.card} gap={16}>+ <Flexbox horizontal align={'center'} justify={'space-between'} style={{ minHeight: 28 }}>+ <Text weight={500}>{title}</Text>+ {extra}+ </Flexbox>+ {children}+ </Flexbox>+);++export default SectionCard;diff --git a/src/features/Settings/oauth-apps/features/AppDetail/index.tsx b/src/features/Settings/oauth-apps/features/AppDetail/index.tsxindex 59a227c8ee9..8b12387718f 100644--- a/src/features/Settings/oauth-apps/features/AppDetail/index.tsx+++ b/src/features/Settings/oauth-apps/features/AppDetail/index.tsx@@ -14,7 +14,9 @@ import { lambdaClient, lambdaQuery } from '@/libs/trpc/client';import { type OAuthAppItem } from '@/types/oauthApp';import ClientIdDisplay from '../ClientIdDisplay';-import EditForm from './EditForm';+import { showClientSecretModal } from '../SecretModal';+import BasicInfoCard from './BasicInfoCard';+import RedirectUrisCard from './RedirectUrisCard';const styles = createStaticStyles(({ css, cssVar }) => ({backButton: css`@@ -89,6 +91,12 @@ const AppDetail: FC<AppDetailProps> = ({ canEdit, id, onBack, onChanged }) => {},});const enabledMutation = lambdaQuery.oauthApp.setEnabled.useMutation({ onSuccess: revalidate });+ const rotateSecretMutation = lambdaQuery.oauthApp.rotateSecret.useMutation({+ onSuccess: ({ clientSecret }) => {+ revalidate();+ showClientSecretModal({ clientSecret });+ },+ });const deleteMutation = lambdaQuery.oauthApp.delete.useMutation({onSuccess: () => {onChanged();@@ -96,6 +104,21 @@ const AppDetail: FC<AppDetailProps> = ({ canEdit, id, onBack, onChanged }) => {},});+ const handleUpdate = async (value: Parameters<typeof updateMutation.mutateAsync>[0]['value']) => {+ await updateMutation.mutateAsync({ id, value });+ };++ const handleRotateSecret = () =>+ confirmModal({+ content: t('oauthApp.secret.rotateConfirm.content'),+ okButtonProps: { danger: true },+ okText: t('oauthApp.secret.rotateConfirm.ok'),+ onOk: async () => {+ await rotateSecretMutation.mutateAsync({ id });+ },+ title: t('oauthApp.secret.rotateConfirm.title'),+ });+const handleDelete = () =>confirmModal({content: t('oauthApp.deleteConfirm.content'),@@ -107,6 +130,8 @@ const AppDetail: FC<AppDetailProps> = ({ canEdit, id, onBack, onChanged }) => {title: t('oauthApp.deleteConfirm.title'),});+ const isWebApp = detail?.applicationType === 'web';+if (!detail)return (<Flexbox gap={16}>@@ -141,16 +166,21 @@ const AppDetail: FC<AppDetailProps> = ({ canEdit, id, onBack, onChanged }) => {{!detail.enabled && <Tag>{t('oauthApp.item.disabledTag')}</Tag>}</Flexbox>- <div className={styles.card}>- <EditForm+ <BasicInfoCard+ canEdit={canEdit}+ detail={detail}+ key={`basic-${detail.id}`}+ onSubmit={handleUpdate}+ />++ {isWebApp && (+ <RedirectUrisCardcanEdit={canEdit}detail={detail}- key={detail.id}- onSubmit={async (value) => {- await updateMutation.mutateAsync({ id, value });- }}+ key={`redirect-${detail.id}`}+ onSubmit={handleUpdate}/>- </div>+ )}<Flexbox className={styles.card} gap={16}><div className={styles.row}>@@ -160,9 +190,26 @@ const AppDetail: FC<AppDetailProps> = ({ canEdit, id, onBack, onChanged }) => {<div className={styles.row}><span className={styles.label}>{t('oauthApp.detail.type')}</span>- <Tag>{t('oauthApp.type.badge')}</Tag>+ <Tag>{t(isWebApp ? 'oauthApp.type.webBadge' : 'oauthApp.type.badge')}</Tag></div>+ {detail.hasSecret && (+ <div className={styles.row}>+ <span className={styles.label}>{t('oauthApp.detail.clientSecret')}</span>+ <Flexbox horizontal align={'center'} gap={8}>+ <Text type={'secondary'}>{t('oauthApp.secret.hidden')}</Text>+ <Button+ disabled={!canEdit}+ loading={rotateSecretMutation.isPending}+ size={'small'}+ onClick={handleRotateSecret}+ >+ {t('oauthApp.secret.rotate')}+ </Button>+ </Flexbox>+ </div>+ )}+<div className={styles.row}><span className={styles.label}>{t('oauthApp.detail.createdAt')}</span><Text type={'secondary'}>{detail.createdAt.toLocaleString()}</Text>diff --git a/src/features/Settings/oauth-apps/features/CreateAppModal/Content.tsx b/src/features/Settings/oauth-apps/features/CreateAppModal/Content.tsxindex 7c54eae458a..d9ce30702f6 100644--- a/src/features/Settings/oauth-apps/features/CreateAppModal/Content.tsx+++ b/src/features/Settings/oauth-apps/features/CreateAppModal/Content.tsx@@ -1,14 +1,130 @@'use client';-import { Flexbox, Input, TextArea } from '@lobehub/ui';-import { Button, useModalContext } from '@lobehub/ui/base-ui';+import { type OAuthAppType } from '@lobechat/types';+import { Flexbox, Icon, Input, TextArea } from '@lobehub/ui';+import { Button, Text, useModalContext } from '@lobehub/ui/base-ui';import { Form } from 'antd';+import { createStaticStyles, cx } from 'antd-style';+import { CheckIcon, GlobeIcon, type LucideIcon, TerminalIcon } from 'lucide-react';import { type FC, useState } from 'react';import { useTranslation } from 'react-i18next';import AvatarUpload from '@/components/AvatarUpload';import { type CreateOAuthAppParams } from '@/types/oauthApp';+const styles = createStaticStyles(({ css, cssVar }) => ({+ typeCard: css`+ cursor: pointer;++ position: relative;++ flex: 1;++ padding: 14px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};++ transition:+ border-color 0.15s ease,+ background 0.15s ease;++ &:hover {+ border-color: ${cssVar.colorBorder};+ }++ &:focus-visible {+ outline: 2px solid ${cssVar.colorBorder};+ outline-offset: 2px;+ }+ `,+ // LobeHub's primary is a near-black neutral, so the selection rides a+ // text-colored border and a light fill instead of `colorPrimaryBg`.+ typeCardSelected: css`+ border-color: ${cssVar.colorText};+ background: ${cssVar.colorFillQuaternary};++ &:hover {+ border-color: ${cssVar.colorText};+ }+ `,+ typeCheck: css`+ position: absolute;+ inset-block-start: 12px;+ inset-inline-end: 12px;+ color: ${cssVar.colorText};+ `,+ typeDesc: css`+ font-size: 12px;+ line-height: 1.5;+ color: ${cssVar.colorTextSecondary};+ `,+ typeIcon: css`+ display: inline-flex;+ align-items: center;+ justify-content: center;++ width: 32px;+ height: 32px;+ border-radius: ${cssVar.borderRadius};++ color: ${cssVar.colorText};++ background: ${cssVar.colorFillTertiary};+ `,+}));++interface TypeOption {+ description: string;+ icon: LucideIcon;+ title: string;+ value: OAuthAppType;+}++interface TypeSelectProps {+ onChange?: (value: OAuthAppType) => void;+ options: TypeOption[];+ value?: OAuthAppType;+}++const TypeSelect: FC<TypeSelectProps> = ({ onChange, options, value }) => (+ <Flexbox horizontal gap={12} role={'radiogroup'}>+ {options.map((option) => {+ const selected = option.value === value;++ return (+ <Flexbox+ aria-checked={selected}+ className={cx(styles.typeCard, selected && styles.typeCardSelected)}+ gap={10}+ key={option.value}+ role={'radio'}+ tabIndex={0}+ onClick={() => onChange?.(option.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ onChange?.(option.value);+ }+ }}+ >+ <span className={styles.typeIcon}>+ <Icon icon={option.icon} size={18} />+ </span>+ <Text weight={500}>{option.title}</Text>+ <span className={styles.typeDesc}>{option.description}</span>+ {selected && <Icon className={styles.typeCheck} icon={CheckIcon} size={16} />}+ </Flexbox>+ );+ })}+ </Flexbox>+);++interface CreateAppFormValues {+ description?: string;+ name: string;+ type: OAuthAppType;+}+export interface CreateAppModalContentProps {onSubmit: (values: CreateOAuthAppParams) => Promise<void>;}@@ -16,7 +132,8 @@ export interface CreateAppModalContentProps {const CreateAppModalContent: FC<CreateAppModalContentProps> = ({ onSubmit }) => {const { t } = useTranslation('auth');const { close, setCanDismissByClickOutside } = useModalContext();- const [form] = Form.useForm<CreateOAuthAppParams>();+ const [form] = Form.useForm<CreateAppFormValues>();+ const type = Form.useWatch('type', form);const [loading, setLoading] = useState(false);const [logoUri, setLogoUri] = useState<string>();@@ -33,10 +150,18 @@ const CreateAppModalContent: FC<CreateAppModalContentProps> = ({ onSubmit }) =>reader.readAsDataURL(file);};- const handleFinish = async (values: CreateOAuthAppParams) => {+ // Only what defines the app is asked for up front. Redirect URIs are+ // configured on the app page afterwards; the type is not, because it decides+ // whether a client secret is issued and cannot change once the app exists.+ const handleFinish = async (values: CreateAppFormValues) => {setLoading(true);try {- await onSubmit({ ...values, logoUri });+ await onSubmit({+ description: values.description,+ logoUri,+ name: values.name,+ type: values.type,+ });close();} finally {setLoading(false);@@ -49,6 +174,7 @@ const CreateAppModalContent: FC<CreateAppModalContentProps> = ({ onSubmit }) =><Formcolon={false}form={form}+ initialValues={{ type: 'device' }}layout={'vertical'}onFinish={handleFinish}onValuesChange={markDirty}@@ -71,6 +197,35 @@ const CreateAppModalContent: FC<CreateAppModalContentProps> = ({ onSubmit }) =><Input placeholder={t('oauthApp.form.name.placeholder')} /></Form.Item>+ <Form.Item+ label={t('oauthApp.form.type.label')}+ name={'type'}+ style={itemStyle}+ extra={+ <Flexbox gap={2} style={{ marginTop: 8 }}>+ <span>{t('oauthApp.form.type.immutable')}</span>+ {type === 'web' && <span>{t('oauthApp.form.type.webNext')}</span>}+ </Flexbox>+ }+ >+ <TypeSelect+ options={[+ {+ description: t('oauthApp.form.type.deviceDesc'),+ icon: TerminalIcon,+ title: t('oauthApp.type.device'),+ value: 'device',+ },+ {+ description: t('oauthApp.form.type.webDesc'),+ icon: GlobeIcon,+ title: t('oauthApp.type.web'),+ value: 'web',+ },+ ]}+ />+ </Form.Item>+<Form.Itemlabel={t('oauthApp.form.description.label')}name={'description'}diff --git a/src/features/Settings/oauth-apps/features/SecretModal/index.tsx b/src/features/Settings/oauth-apps/features/SecretModal/index.tsxnew file mode 100644index 00000000000..dbda30cd22a--- /dev/null+++ b/src/features/Settings/oauth-apps/features/SecretModal/index.tsx@@ -0,0 +1,56 @@+'use client';++import { CopyButton, Flexbox } from '@lobehub/ui';+import { Alert, createModal, type ModalInstance, Text } from '@lobehub/ui/base-ui';+import { createStaticStyles } from 'antd-style';+import { t } from 'i18next';+import { type FC } from 'react';+import { useTranslation } from 'react-i18next';++const styles = createStaticStyles(({ css, cssVar }) => ({+ secret: css`+ padding-block: 8px;+ padding-inline: 12px;+ border-radius: ${cssVar.borderRadius};++ font-family: ${cssVar.fontFamilyCode};+ font-size: 13px;+ overflow-wrap: anywhere;++ background: ${cssVar.colorFillTertiary};+ `,+}));++interface ClientSecretContentProps {+ clientSecret: string;+}++const ClientSecretContent: FC<ClientSecretContentProps> = ({ clientSecret }) => {+ const { t } = useTranslation('auth');++ return (+ <Flexbox gap={12}>+ <Alert message={t('oauthApp.secret.onceWarning')} type={'warning'} />+ <div className={styles.secret}>{clientSecret}</div>+ <Flexbox horizontal justify={'flex-end'}>+ <CopyButton content={clientSecret} title={t('oauthApp.secret.copy')} />+ </Flexbox>+ <Text style={{ fontSize: 12 }} type={'secondary'}>+ {t('oauthApp.secret.usage')}+ </Text>+ </Flexbox>+ );+};++/**+ * Shows a freshly issued client secret. This is the only moment the plaintext+ * exists outside the creating request, so the modal is deliberately explicit+ * that it will not be shown again.+ */+export const showClientSecretModal = (props: ClientSecretContentProps): ModalInstance =>+ createModal({+ content: <ClientSecretContent {...props} />,+ footer: null,+ title: t('oauthApp.secret.revealTitle', { ns: 'auth' }),+ width: 'min(90vw, 520px)',+ });diff --git a/src/features/Settings/oauth-apps/features/index.ts b/src/features/Settings/oauth-apps/features/index.tsindex 45a2470c93c..7ad16dc2858 100644--- a/src/features/Settings/oauth-apps/features/index.ts+++ b/src/features/Settings/oauth-apps/features/index.ts@@ -1,3 +1,4 @@export { default as AppDetail } from './AppDetail';export { default as ClientIdDisplay } from './ClientIdDisplay';export { createOAuthAppModal } from './CreateAppModal';+export { showClientSecretModal } from './SecretModal';diff --git a/src/features/Settings/oauth-apps/index.tsx b/src/features/Settings/oauth-apps/index.tsxindex 5bab2e40d52..c8fa885bef7 100644--- a/src/features/Settings/oauth-apps/index.tsx+++ b/src/features/Settings/oauth-apps/index.tsx@@ -13,6 +13,7 @@ import { labPreferSelectors, preferenceSelectors } from '@/store/user/selectors'import { createOAuthAppModal } from './features/CreateAppModal';import OAuthApps from './features/OAuthApps';+import { showClientSecretModal } from './features/SecretModal';const CreateAppButton = () => {const { t } = useTranslation('auth');@@ -30,6 +31,10 @@ const CreateAppButton = () => {onSubmit: async (values) => {const created = await lambdaClient.oauthApp.create.mutate(values);navigate(`/settings/oauth-apps/${created.id}`);++ // Web apps get a confidential secret, and this is the one and only+ // render of its plaintext.+ if (created.clientSecret) showClientSecretModal({ clientSecret: created.clientSecret });},});};diff --git a/src/features/Settings/oauth-apps/redirectUris.test.ts b/src/features/Settings/oauth-apps/redirectUris.test.tsnew file mode 100644index 00000000000..4547522f3b9--- /dev/null+++ b/src/features/Settings/oauth-apps/redirectUris.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from 'vitest';++import { redirectUriListMessageKey, redirectUriMessageKey } from './redirectUris';++describe('redirectUriMessageKey', () => {+ it('accepts a valid URI and a blank row', () => {+ expect(redirectUriMessageKey('https://dc.lobehub.com/callback')).toBeUndefined();+ expect(redirectUriMessageKey(' ')).toBeUndefined();+ expect(redirectUriMessageKey(undefined)).toBeUndefined();+ });++ it('maps each rejected URI to its message', () => {+ expect(redirectUriMessageKey('https://*.lobehub.com/cb')).toBe(+ 'oauthApp.validation.redirectUri.wildcard',+ );+ expect(redirectUriMessageKey('http://dc.lobehub.com/cb')).toBe(+ 'oauthApp.validation.redirectUri.insecure',+ );+ });+});++describe('redirectUriListMessageKey', () => {+ it('refuses a list that is empty once blank rows are dropped', () => {+ expect(redirectUriListMessageKey([])).toBe('oauthApp.validation.redirectUriRequired');+ expect(redirectUriListMessageKey(['', ' ', undefined])).toBe(+ 'oauthApp.validation.redirectUriRequired',+ );+ });++ it('refuses more URIs than the cap', () => {+ const uris = Array.from({ length: 6 }, (_, i) => `https://a${i}.com/cb`);+ expect(redirectUriListMessageKey(uris)).toBe('oauthApp.validation.redirectUriTooMany');+ });++ it('accepts a list with at least one URI', () => {+ expect(redirectUriListMessageKey(['https://a.com/cb', ''])).toBeUndefined();+ });+});diff --git a/src/features/Settings/oauth-apps/redirectUris.ts b/src/features/Settings/oauth-apps/redirectUris.tsnew file mode 100644index 00000000000..526b89ffd4a--- /dev/null+++ b/src/features/Settings/oauth-apps/redirectUris.ts@@ -0,0 +1,41 @@+import {+ MAX_OAUTH_REDIRECT_URIS,+ normalizeRedirectUris,+ validateRedirectUri,+} from '@lobechat/utils/oauthApp';++export { MAX_OAUTH_REDIRECT_URIS, normalizeRedirectUris };++const ISSUE_MESSAGE_KEYS = {+ credentials: 'oauthApp.validation.redirectUri.credentials',+ fragment: 'oauthApp.validation.redirectUri.fragment',+ insecure: 'oauthApp.validation.redirectUri.insecure',+ malformed: 'oauthApp.validation.redirectUri.malformed',+ wildcard: 'oauthApp.validation.redirectUri.wildcard',+} as const;++/**+ * Message key for one row of the redirect URI editor, or `undefined` when the+ * value is acceptable. Blank rows pass here because saving drops them; the+ * list-level rule is what refuses a list with nothing left in it.+ */+export const redirectUriMessageKey = (value?: string) => {+ if (!value?.trim()) return undefined;++ const issue = validateRedirectUri(value);+ return issue ? ISSUE_MESSAGE_KEYS[issue] : undefined;+};++/**+ * Message key for the whole list, mirroring the server: a save needs at least+ * one redirect URI and no more than the cap.+ */+export const redirectUriListMessageKey = (values: (string | undefined)[] = []) => {+ const uris = normalizeRedirectUris(values.map((value) => value ?? ''));++ if (uris.length === 0) return 'oauthApp.validation.redirectUriRequired' as const;+ if (uris.length > MAX_OAUTH_REDIRECT_URIS)+ return 'oauthApp.validation.redirectUriTooMany' as const;++ return undefined;+};diff --git a/src/libs/oidc-provider/adapter.test.ts b/src/libs/oidc-provider/adapter.test.tsindex 70e4ba1360d..cac1996d5fc 100644--- a/src/libs/oidc-provider/adapter.test.ts+++ b/src/libs/oidc-provider/adapter.test.ts@@ -6,6 +6,15 @@ vi.mock('debug', () => ({default: () => vi.fn(),}));+const mockDecrypt = vi.hoisted(() => vi.fn());+const mockEncrypt = vi.hoisted(() => vi.fn());++vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({+ KeyVaultsGateKeeper: {+ initWithEnvKey: async () => ({ decrypt: mockDecrypt, encrypt: mockEncrypt }),+ },+}));+const createSelectDb = (rows: any[]) => {const chain = {from: vi.fn(() => chain),@@ -86,6 +95,27 @@ describe('OIDCAdapter (DrizzleAdapter)', () => {expect(result).toBeUndefined();});+ it('hands oidc-provider the decrypted client secret', async () => {+ mockDecrypt.mockResolvedValue({ plaintext: 'lcs_plain', wasAuthentic: true });+ const db = createSelectDb([{ ...clientRow, clientSecret: 'iv:tag:cipher' }]);+ const adapter = new DrizzleAdapter('Client', db as any);++ const result = (await adapter.find('lca_client_1')) as Record<string, unknown>;++ expect(mockDecrypt).toHaveBeenCalledWith('iv:tag:cipher');+ expect(result.client_secret).toBe('lcs_plain');+ });++ it('drops a client secret that fails to decrypt instead of passing ciphertext through', async () => {+ mockDecrypt.mockResolvedValue({ plaintext: '', wasAuthentic: false });+ const db = createSelectDb([{ ...clientRow, clientSecret: 'iv:tag:cipher' }]);+ const adapter = new DrizzleAdapter('Client', db as any);++ const result = (await adapter.find('lca_client_1')) as Record<string, unknown>;++ expect(result).not.toHaveProperty('client_secret');+ });+it('omits null optional fields so oidc-provider client schema accepts the metadata', async () => {const db = createSelectDb([{@@ -111,6 +141,34 @@ describe('OIDCAdapter (DrizzleAdapter)', () => {});});+ describe('upsert Client', () => {+ it('encrypts the secret on the way in so find can read it back', async () => {+ mockEncrypt.mockResolvedValue('iv:tag:cipher');+ const { db } = createUpsertDb();+ const insertChain = (db.insert as any)();+ const adapter = new DrizzleAdapter('Client', db as any);++ await adapter.upsert('lca_client_1', { client_secret: 'plain' }, 0);++ expect(mockEncrypt).toHaveBeenCalledWith('plain');+ expect(insertChain.values).toHaveBeenCalledWith(+ expect.objectContaining({ clientSecret: 'iv:tag:cipher' }),+ );+ });++ it('leaves the stored secret alone when the payload carries none', async () => {+ const { db } = createUpsertDb();+ const insertChain = (db.insert as any)();+ const adapter = new DrizzleAdapter('Client', db as any);++ await adapter.upsert('lca_client_1', { client_id: 'lca_client_1' }, 0);++ expect(mockEncrypt).not.toHaveBeenCalled();+ const [{ set }] = insertChain.onConflictDoUpdate.mock.calls.at(-1);+ expect(set).not.toHaveProperty('clientSecret');+ });+ });+describe('lastUsedAt stamping', () => {const flush = () => new Promise((resolve) => setTimeout(resolve, 0));diff --git a/src/libs/oidc-provider/adapter.ts b/src/libs/oidc-provider/adapter.tsindex a66613d416e..e76089e3b9c 100644--- a/src/libs/oidc-provider/adapter.ts+++ b/src/libs/oidc-provider/adapter.ts@@ -12,6 +12,8 @@ import {import debug from 'debug';import { eq, sql } from 'drizzle-orm';+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';+// Create adapter logging namespaceconst log = debug('lobe-oidc:adapter');@@ -29,6 +31,47 @@ const log = debug('lobe-oidc:adapter');*/const REFRESH_TOKEN_GRACE_PERIOD_SECONDS = 180;+/**+ * Client secrets of user-created OAuth apps are stored encrypted (see+ * `OidcClientModel`), but oidc-provider compares them in plaintext at the token+ * endpoint, so they are decrypted on the way out.+ *+ * A secret that fails to decrypt is dropped rather than passed through: handing+ * over ciphertext would make it the thing clients have to present. Dropping it+ * fails the request as `invalid_client`, which is the honest outcome.+ */+/**+ * Keeps the write side symmetric with `decryptClientSecret`: whatever this+ * adapter stores, it must be able to read back. Encryption failures throw+ * rather than fall back to plaintext, because a secret written in the clear+ * would read back as an undecryptable one and silently break the client.+ */+const encryptClientSecret = async (plaintext?: string | null) => {+ if (!plaintext) return plaintext;++ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();+ return gateKeeper.encrypt(plaintext);+};++const decryptClientSecret = async (clientId: string, stored: string | null) => {+ if (!stored) return stored;++ try {+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();+ const { plaintext, wasAuthentic } = await gateKeeper.decrypt(stored);++ if (!wasAuthentic) {+ log('[Client] Failed to decrypt the client secret of %s', clientId);+ return null;+ }++ return plaintext;+ } catch (error) {+ log('[Client] Error while decrypting the client secret of %s: %O', clientId, error);+ return null;+ }+};+class OIDCAdapter {private db: LobeChatDatabase;private name: string;@@ -111,11 +154,13 @@ class OIDCAdapter {// Special handling for client model, directly use the passed datalog('[Client] Upserting client record');try {+ const clientSecret = await encryptClientSecret(payload.client_secret);+await this.db.insert(table).values({applicationType: payload.application_type,- clientSecret: payload.client_secret,+ clientSecret,clientUri: payload.client_uri,description: payload.description,grants: payload.grant_types || [],@@ -137,7 +182,9 @@ class OIDCAdapter {.onConflictDoUpdate({set: {applicationType: payload.application_type,- clientSecret: payload.clientSecret,+ // Left untouched when the payload carries no secret, so an update+ // that omits it cannot wipe the stored one.+ ...(clientSecret ? { clientSecret } : {}),clientUri: payload.client_uri,description: payload.description,grants: payload.grant_types || [],@@ -301,7 +348,7 @@ class OIDCAdapter {const clientMetadata: Record<string, any> = {application_type: model.applicationType,client_id: model.id,- client_secret: model.clientSecret,+ client_secret: await decryptClientSecret(model.id, model.clientSecret),client_uri: model.clientUri,grant_types: model.grants,isFirstParty: model.isFirstParty,diff --git a/src/libs/oidc-provider/provider.ts b/src/libs/oidc-provider/provider.tsindex c000df0176f..d98e32ba3f9 100644--- a/src/libs/oidc-provider/provider.ts+++ b/src/libs/oidc-provider/provider.ts@@ -281,20 +281,18 @@ export const createOIDCProvider = async (db: LobeChatDatabase): Promise<Provider},// 12. Other configuration+ // Errors the provider will not redirect back to the client with (an+ // unregistered redirect_uri, an unknown client, malformed parameters) land+ // on a dedicated page instead of a raw JSON dump. Only the spec-defined+ // `error` and `error_description` travel along; `state` stays behind.renderError: async (ctx, out, error) => {- ctx.type = 'html';- ctx.body = `- <html>- <head>- <title>LobeHub OIDC Error</title>- </head>- <body>- <h1>LobeHub OIDC Error</h1>- <p>${JSON.stringify(error, null, 2)}</p>- <p>${JSON.stringify(out, null, 2)}</p>- </body>- </html>- `;+ logProvider('renderError: %O', error);++ const params = new URLSearchParams();+ if (out.error) params.set('error', String(out.error));+ if (out.error_description) params.set('error_description', String(out.error_description));++ ctx.redirect(`/oauth/error?${params.toString()}`);},// Added: enable refresh token rotationdiff --git a/src/routes/auth/oauth/error/index.tsx b/src/routes/auth/oauth/error/index.tsxnew file mode 100644index 00000000000..14aea123774--- /dev/null+++ b/src/routes/auth/oauth/error/index.tsx@@ -0,0 +1 @@+export { default } from '@/features/Auth/OAuthAuthorizeError';diff --git a/src/spa/router/authRouter.config.tsx b/src/spa/router/authRouter.config.tsxindex b121397e269..ae87adc92b3 100644--- a/src/spa/router/authRouter.config.tsx+++ b/src/spa/router/authRouter.config.tsx@@ -102,6 +102,10 @@ export const authRoutes: RouteObject[] = [element: lazyElement(() => import('@/routes/auth/oauth/consent/[uid]')),path: 'oauth/consent/:uid',},+ {+ element: lazyElement(() => import('@/routes/auth/oauth/error')),+ path: 'oauth/error',+ },{element: lazyElement(() => import('@/routes/auth/oauth/device')),path: 'oauth/device',