🤯 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(auth): support API key scopes (#18029)
Rdmclin20c7e2c7135da
diff --git a/apps/server/src/routers/lambda/__tests__/apiKeyScopeCoverage.test.ts b/apps/server/src/routers/lambda/__tests__/apiKeyScopeCoverage.test.tsnew file mode 100644index 00000000000..154280f3d26--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/apiKeyScopeCoverage.test.ts@@ -0,0 +1,40 @@+import { TRPC_NAMESPACE_API_KEY_RULES } from '@lobechat/const';+import { describe, expect, it } from 'vitest';++import { lambdaRouter } from '@/server/routers/lambda';+import { toolsRouter } from '@/server/routers/tools';++/**+ * The API key scope guard (`apiKeyScopeGuard`) denies any namespace missing+ * from `TRPC_NAMESPACE_API_KEY_RULES` — fail closed. That is the safe default+ * for restricted keys, but it must never happen *silently*: a newly mounted+ * router has to be consciously categorized (open / blocked / scoped).+ *+ * If this test fails, add the new namespace to+ * `packages/const/src/apiKeyScope.ts`.+ */+const namespacesOf = (router: { _def: { procedures: Record<string, unknown> } }) => {+ const namespaces = new Set<string>();+ for (const path of Object.keys(router._def.procedures)) {+ namespaces.add(path.split('.')[0]);+ }+ return namespaces;+};++describe('API key scope namespace coverage', () => {+ it('every lambda router namespace is categorized', () => {+ const uncategorized = [...namespacesOf(lambdaRouter)].filter(+ (ns) => !(ns in TRPC_NAMESPACE_API_KEY_RULES),+ );++ expect(uncategorized).toEqual([]);+ });++ it('every tools router namespace is categorized', () => {+ const uncategorized = [...namespacesOf(toolsRouter)].filter(+ (ns) => !(ns in TRPC_NAMESPACE_API_KEY_RULES),+ );++ expect(uncategorized).toEqual([]);+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/user.test.ts b/apps/server/src/routers/lambda/__tests__/user.test.tsindex b8fdeee83c5..9f65d9d3242 100644--- a/apps/server/src/routers/lambda/__tests__/user.test.ts+++ b/apps/server/src/routers/lambda/__tests__/user.test.ts@@ -17,11 +17,16 @@ import { MessageModel } from '@/database/models/message';import { SessionModel } from '@/database/models/session';import { UserModel } from '@/database/models/user';import { serverDB } from '@/database/server';+import { router } from '@/libs/trpc/lambda';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';import { UnderstandingWorkflowUnavailableError } from '@/server/workflows/onboardingUnderstanding';import { userRouter } from '../user';+// mounts userRouter under its production namespace so the apiKeyScopeGuard+// derives the real `user.*` path for API-key-authenticated calls+const namespacedRouter = router({ user: userRouter });+const mockAfterTasks = vi.hoisted((): Promise<void>[] => []);const mockUnderstandingService = vi.hoisted(() => ({confirm: vi.fn(),@@ -623,6 +628,67 @@ describe('userRouter', () => {expect(mockGateKeeper.encrypt).toHaveBeenCalledWith(JSON.stringify(mockSettings.keyVaults));});+ it('rejects keyVaults updates from restricted keys without model:write', async () => {+ await expect(+ namespacedRouter+ .createCaller({ ...mockCtx, apiKeyScopes: ['user:write'] })+ .user.updateSettings({ keyVaults: { openai: { key: 'stolen' } } }),+ ).rejects.toMatchObject({+ code: 'FORBIDDEN',+ message: expect.stringContaining('model:write'),+ });+ });++ it('rejects market token updates from restricted keys without model:write', async () => {+ await expect(+ namespacedRouter+ .createCaller({ ...mockCtx, apiKeyScopes: ['user:write'] })+ .user.updateSettings({ market: { accessToken: 'x' } } as any),+ ).rejects.toMatchObject({+ code: 'FORBIDDEN',+ message: expect.stringContaining('model:write'),+ });+ });++ it('rejects keyVaults clears (null) from restricted keys without model:write', async () => {+ await expect(+ namespacedRouter+ .createCaller({ ...mockCtx, apiKeyScopes: ['user:write'] })+ .user.updateSettings({ keyVaults: null } as any),+ ).rejects.toMatchObject({+ code: 'FORBIDDEN',+ message: expect.stringContaining('model:write'),+ });+ });++ it('does not touch stored keyVaults when the field is omitted', async () => {+ const updateSetting = vi.fn().mockResolvedValue({ rowCount: 1 });+ vi.mocked(UserModel).mockImplementation(() => ({ updateSetting }) as any);++ await userRouter.createCaller({ ...mockCtx }).updateSettings({+ general: { language: 'en-US' },+ } as any);++ expect(updateSetting.mock.calls[0][0]).not.toHaveProperty('keyVaults');+ });++ it('allows keyVaults updates from restricted keys holding model:write', async () => {+ const mockGateKeeper = { encrypt: vi.fn().mockResolvedValue('encrypted') };+ vi.mocked(KeyVaultsGateKeeper.initWithEnvKey).mockResolvedValue(mockGateKeeper as any);+ vi.mocked(UserModel).mockImplementation(+ () =>+ ({+ updateSetting: vi.fn().mockResolvedValue({ rowCount: 1 }),+ }) as any,+ );++ await namespacedRouter+ .createCaller({ ...mockCtx, apiKeyScopes: ['user:write', 'model:write'] })+ .user.updateSettings({ keyVaults: { openai: { key: 'mine' } } });++ expect(mockGateKeeper.encrypt).toHaveBeenCalled();+ });+it('should update settings without key vaults', async () => {const mockSettings = {general: { language: 'en-US' },diff --git a/apps/server/src/routers/lambda/agentNotify.ts b/apps/server/src/routers/lambda/agentNotify.tsindex caad3b956dc..52dfe8a358c 100644--- a/apps/server/src/routers/lambda/agentNotify.ts+++ b/apps/server/src/routers/lambda/agentNotify.ts@@ -1,3 +1,4 @@+import { isFullAccessApiKey } from '@lobechat/const/apiKeyScope';import { RequestTrigger } from '@lobechat/types';import { TRPCError } from '@trpc/server';import debug from 'debug';@@ -32,7 +33,11 @@ const agentNotifyProcedure = wsCompatProcedure.use(serverDatabase).use(async (opreturn opts.next({ctx: {- aiAgentService: new AiAgentService(ctx.serverDB, ctx.userId, { workspaceId: wsId }),+ aiAgentService: new AiAgentService(ctx.serverDB, ctx.userId, {+ withholdGatewayToken:+ ctx.apiKeyScopes !== undefined && !isFullAccessApiKey(ctx.apiKeyScopes),+ workspaceId: wsId,+ }),messageModel: new MessageModel(ctx.serverDB, ctx.userId, wsId),topicModel: new TopicModel(ctx.serverDB, ctx.userId, wsId),},diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex 612c9cc99d8..c8761c8eaca 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -1,4 +1,5 @@import { type AgentStreamEvent } from '@lobechat/agent-gateway-client';+import { isFullAccessApiKey } from '@lobechat/const/apiKeyScope';import { parse } from '@lobechat/conversation-flow';import type { TaskCurrentActivity, TaskStatusResult } from '@lobechat/types';import {@@ -635,7 +636,11 @@ const aiAgentProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts)agentRuntimeService: new AgentRuntimeService(ctx.serverDB, ctx.userId, {workspaceId: wsId,}),- aiAgentService: new AiAgentService(ctx.serverDB, ctx.userId, { workspaceId: wsId }),+ aiAgentService: new AiAgentService(ctx.serverDB, ctx.userId, {+ withholdGatewayToken:+ ctx.apiKeyScopes !== undefined && !isFullAccessApiKey(ctx.apiKeyScopes),+ workspaceId: wsId,+ }),aiChatService: new AiChatService(ctx.serverDB, ctx.userId, wsId),heterogeneousAgentService: new HeterogeneousAgentService(ctx.serverDB, ctx.userId, {workspaceId: wsId,diff --git a/apps/server/src/routers/lambda/aiProvider.ts b/apps/server/src/routers/lambda/aiProvider.tsindex 7ab6af36b12..7f5e5a562b4 100644--- a/apps/server/src/routers/lambda/aiProvider.ts+++ b/apps/server/src/routers/lambda/aiProvider.ts@@ -1,4 +1,5 @@import { isOfficialProvider, OFFICIAL_PROVIDER_DISABLE_ERROR } from '@lobechat/business-const';+import { isFullAccessApiKey } from '@lobechat/const/apiKeyScope';import { RequestTrigger } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { z } from 'zod';@@ -128,7 +129,17 @@ export const aiProviderRouter = router({.input(z.object({ id: z.string() })).query(async ({ input, ctx }): Promise<AiProviderDetailItem | undefined> => {- return ctx.aiInfraRepos.getAiProviderDetail(input.id, KeyVaultsGateKeeper.getUserKeyVaults);+ const detail = await ctx.aiInfraRepos.getAiProviderDetail(+ input.id,+ KeyVaultsGateKeeper.getUserKeyVaults,+ );++ // restricted API keys must not exfiltrate decrypted provider credentials+ if (detail && ctx.apiKeyScopes !== undefined && !isFullAccessApiKey(ctx.apiKeyScopes)) {+ return { ...detail, keyVaults: undefined };+ }++ return detail;}),getAiProviderList: aiProviderProcedure.query(async ({ ctx }) => {@@ -138,9 +149,24 @@ export const aiProviderRouter = router({getAiProviderRuntimeState: aiProviderProcedure.input(z.object({ isLogin: z.boolean().optional() })).query(async ({ ctx }): Promise<AiProviderRuntimeState> => {- return getUserScopedAiProviderRuntimeState(ctx.userId, () =>+ const state = await getUserScopedAiProviderRuntimeState(ctx.userId, () =>ctx.aiInfraRepos.getAiProviderRuntimeState(KeyVaultsGateKeeper.getUserKeyVaults),);++ // restricted API keys must not exfiltrate decrypted provider credentials+ if (ctx.apiKeyScopes !== undefined && !isFullAccessApiKey(ctx.apiKeyScopes)) {+ return {+ ...state,+ runtimeConfig: Object.fromEntries(+ Object.entries(state.runtimeConfig).map(([id, config]) => [+ id,+ { ...config, keyVaults: {} },+ ]),+ ),+ };+ }++ return state;}),// Provider rows carry workspace-shared credentials and the model-layer where isdiff --git a/apps/server/src/routers/lambda/apiKey.ts b/apps/server/src/routers/lambda/apiKey.tsindex a60667e5a71..a7a022a16b1 100644--- a/apps/server/src/routers/lambda/apiKey.ts+++ b/apps/server/src/routers/lambda/apiKey.ts@@ -1,3 +1,4 @@+import { API_KEY_FULL_ACCESS_SCOPE, isValidApiKeyScope } from '@lobechat/const';import { TRPCError } from '@trpc/server';import { z } from 'zod';@@ -32,6 +33,13 @@ export const apiKeyRouter = router({z.object({expiresAt: z.date().nullish(),name: z.string(),+ // Scopes are set at creation time only (immutable afterwards).+ // `undefined`/`null` = full access; entries must come from the+ // catalog — unknown scope strings are rejected.+ scopes: z+ .array(z.string().refine(isValidApiKeyScope, { message: 'Unknown API key scope' }))+ .min(1)+ .nullish(),}),).mutation(async ({ input, ctx }) => {@@ -42,7 +50,12 @@ export const apiKeyRouter = router({});}- return await ctx.apiKeyModel.create(input);+ // normalize: an explicit full-access selection stores exactly ['*']+ const scopes = input.scopes?.includes(API_KEY_FULL_ACCESS_SCOPE)+ ? [API_KEY_FULL_ACCESS_SCOPE]+ : input.scopes;++ return await ctx.apiKeyModel.create({ ...input, scopes });}),deleteAllApiKeys: apiKeyProcedurediff --git a/apps/server/src/routers/lambda/asr.ts b/apps/server/src/routers/lambda/asr.tsindex cd5b0a87f0d..1e68148732e 100644--- a/apps/server/src/routers/lambda/asr.ts+++ b/apps/server/src/routers/lambda/asr.ts@@ -1,3 +1,4 @@+import { hasApiKeyScope, isFullAccessApiKey } from '@lobechat/const/apiKeyScope';import { TRPCError } from '@trpc/server';import { z } from 'zod';@@ -83,6 +84,21 @@ export const asrRouter = router({.mutation(async ({ ctx, input }): Promise<{ text: string }> => {const workspaceId = ctx.workspaceId ?? undefined;+ // the `fileId` path reads a stored file's bytes — a restricted key needs+ // `file:read` on top of the namespace's `model:invoke` to use it+ if (+ input.fileId &&+ ctx.apiKeyScopes !== undefined &&+ !isFullAccessApiKey(ctx.apiKeyScopes) &&+ !hasApiKeyScope(ctx.apiKeyScopes, 'file:read')+ ) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message:+ "This API key cannot transcribe a stored file ('fileId'): missing required scope 'file:read'.",+ });+ }+const { bytes, fileName, mimeType } = await resolveAudio(ctx, input, workspaceId);// Resolve the user's provider config (key + baseURL) from the database,diff --git a/apps/server/src/routers/lambda/user.ts b/apps/server/src/routers/lambda/user.tsindex c393ba66c35..1a71f63a727 100644--- a/apps/server/src/routers/lambda/user.ts+++ b/apps/server/src/routers/lambda/user.ts@@ -3,6 +3,7 @@ import {formatWebOnboardingStateMessage,} from '@lobechat/builtin-tool-web-onboarding/utils';import { isDesktop } from '@lobechat/const';+import { hasApiKeyScope, isFullAccessApiKey } from '@lobechat/const/apiKeyScope';import { applyMarkdownPatch, formatMarkdownPatchError } from '@lobechat/markdown-patch';import type {ConfirmOnboardingUnderstandingInput,@@ -353,7 +354,12 @@ export const userRouter = router({lastName: state.lastName,onboarding: state.onboarding,preference: state.preference as UserPreference,- settings: state.settings,+ // restricted API keys must not read decrypted provider/tool credentials+ // or Marketplace OAuth tokens+ settings:+ ctx.apiKeyScopes !== undefined && !isFullAccessApiKey(ctx.apiKeyScopes)+ ? { ...state.settings, keyVaults: undefined, market: undefined }+ : state.settings,userId: ctx.userId,username: state.username,@@ -708,6 +714,27 @@ export const userRouter = router({updateSettings: userProcedure.input(UserSettingsSchema).mutation(async ({ ctx, input }) => {const { keyVaults, ...res } = input as Partial<UserSettings>;+ // presence, not truthiness: `keyVaults: null` is an explicit credential clear+ const hasKeyVaultsUpdate = 'keyVaults' in (input as Partial<UserSettings>);++ // credential-bearing settings: `keyVaults` holds provider/tool credentials,+ // `market` holds Marketplace OAuth access/refresh tokens. A restricted key+ // needs `model:write` on top of the namespace's `user:write` to touch (or+ // clear) either; full-access keys pass through.+ const touchedCredentialFields = ['keyVaults', 'market'].filter(+ (field) => field in (input as Partial<UserSettings>),+ );+ if (+ touchedCredentialFields.length > 0 &&+ ctx.apiKeyScopes !== undefined &&+ !isFullAccessApiKey(ctx.apiKeyScopes) &&+ !hasApiKeyScope(ctx.apiKeyScopes, 'model:write')+ ) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: `This API key cannot update credential settings ('${touchedCredentialFields.join("', '")}'): missing required scope 'model:write'.`,+ });+ }if (ctx.workspaceId && (hasOwnerSettingChange(res) || hasMemberSettingChange(res))) {const rbac = new RbacModel(ctx.serverDB, ctx.userId);@@ -727,18 +754,23 @@ export const userRouter = router({}}- // Encrypt keyVaults- let encryptedKeyVaults: string | null = null;+ // Encrypt keyVaults; only touch the column when the caller sent the field,+ // so a settings update without `keyVaults` no longer clears stored creds+ const nextValue: Record<string, unknown> = { ...res };- if (keyVaults) {- // TODO: better to add a validation- const data = JSON.stringify(keyVaults);- const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();+ if (hasKeyVaultsUpdate) {+ let encryptedKeyVaults: string | null = null;- encryptedKeyVaults = await gateKeeper.encrypt(data);- }+ if (keyVaults) {+ // TODO: better to add a validation+ const data = JSON.stringify(keyVaults);+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();- const nextValue = { ...res, keyVaults: encryptedKeyVaults };+ encryptedKeyVaults = await gateKeeper.encrypt(data);+ }++ nextValue.keyVaults = encryptedKeyVaults;+ }return ctx.userModel.updateSetting(nextValue);}),diff --git a/apps/server/src/routers/lambda/workspaceUserSettings.ts b/apps/server/src/routers/lambda/workspaceUserSettings.tsindex 717d0a6742f..456511fdde0 100644--- a/apps/server/src/routers/lambda/workspaceUserSettings.ts+++ b/apps/server/src/routers/lambda/workspaceUserSettings.ts@@ -1,3 +1,4 @@+import { hasApiKeyScope, isFullAccessApiKey } from '@lobechat/const/apiKeyScope';import type { WorkspaceUserPreference } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { z } from 'zod';@@ -82,6 +83,20 @@ export const workspaceUserSettingsRouter = router({// under the same role gate as `home.updateAgentSessionGroupId`.const legacyAssignments = (input as Partial<WorkspaceUserPreference>).sidebarGroupAssignments;if (legacyAssignments && Object.keys(legacyAssignments).length > 0) {+ // the legacy move path writes agent/chat-group organization — a+ // restricted key needs `agent:write` beyond the namespace's+ // `workspace:write`, matching `home.updateAgentSessionGroupId`+ if (+ ctx.apiKeyScopes !== undefined &&+ !isFullAccessApiKey(ctx.apiKeyScopes) &&+ !hasApiKeyScope(ctx.apiKeyScopes, 'agent:write')+ ) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message:+ "This API key cannot move sidebar agents ('sidebarGroupAssignments'): missing required scope 'agent:write'.",+ });+ }const canOrganize = await hasWorkspaceScopedPermission({action: 'AGENT_UPDATE',db: ctx.serverDB,diff --git a/apps/server/src/routers/tools/search.ts b/apps/server/src/routers/tools/search.tsindex 682d4de58f8..2a2da0cfb57 100644--- a/apps/server/src/routers/tools/search.ts+++ b/apps/server/src/routers/tools/search.ts@@ -1,9 +1,33 @@+import { hasApiKeyScope, isFullAccessApiKey } from '@lobechat/const/apiKeyScope';+import { TRPCError } from '@trpc/server';import { z } from 'zod';import { authedProcedure, router } from '@/libs/trpc/lambda';+import { trpc } from '@/libs/trpc/lambda/init';import { searchService } from '@/server/services/search';-const searchProcedure = authedProcedure;+// This surface executes external search/crawl providers and spends server-side+// search quota — unlike the lambda `search` namespace (app content search),+// which shares the same `search.*` paths, so the generic path-based guard+// cannot tell them apart. Gate it here: restricted keys need `model:invoke`.+const requireModelInvokeForRestrictedKeys = trpc.middleware(async ({ ctx, next }) => {+ const scopes = (ctx as { apiKeyScopes?: string[] | null }).apiKeyScopes;++ if (+ scopes !== undefined &&+ !isFullAccessApiKey(scopes) &&+ !hasApiKeyScope(scopes, 'model:invoke')+ ) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: "This API key cannot use external search: missing required scope 'model:invoke'.",+ });+ }++ return next();+});++const searchProcedure = authedProcedure.use(requireModelInvokeForRestrictedKeys);export const searchRouter = router({crawlPages: searchProcedurediff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 102688fb4a3..90084f57a90 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -574,15 +574,27 @@ export class AiAgentService {private readonly composioService: ComposioService;private readonly workspaceId?: string;+ /**+ * When the caller authenticated with a restricted API key, the unrestricted+ * user JWT minted for gateway WebSocket auth must not be handed back — it+ * passes `oidcAuth` as non-API-key auth and would bypass the scope guard+ * entirely.+ */+ private readonly withholdGatewayToken: boolean;constructor(db: LobeChatDatabase,userId: string,- options?: { runtimeOptions?: AgentRuntimeServiceOptions; workspaceId?: string },+ options?: {+ runtimeOptions?: AgentRuntimeServiceOptions;+ withholdGatewayToken?: boolean;+ workspaceId?: string;+ },) {this.userId = userId;this.db = db;this.workspaceId = options?.workspaceId;+ this.withholdGatewayToken = options?.withholdGatewayToken ?? false;const wsId = this.workspaceId;this.agentDocumentsService = new AgentDocumentsService(db, userId, wsId);this.agentModel = new AgentModel(db, userId, wsId);@@ -2673,10 +2685,12 @@ export class AiAgentService {}let gatewayToken: string | undefined;- try {- gatewayToken = await signUserJWT(this.userId);- } catch {- // non-critical+ if (!this.withholdGatewayToken) {+ try {+ gatewayToken = await signUserJWT(this.userId);+ } catch {+ // non-critical+ }}return {@@ -4436,10 +4450,12 @@ export class AiAgentService {// Generate a short-lived JWT for Gateway WebSocket authenticationlet gatewayToken: string | undefined;- try {- gatewayToken = await signUserJWT(this.userId);- } catch {- log('execAgent: failed to sign gateway JWT, gateway auth will be unavailable');+ if (!this.withholdGatewayToken) {+ try {+ gatewayToken = await signUserJWT(this.userId);+ } catch {+ log('execAgent: failed to sign gateway JWT, gateway auth will be unavailable');+ }}return {diff --git a/locales/ar/auth.json b/locales/ar/auth.jsonindex 3a487c93ce0..ebe9c14b0e7 100644--- a/locales/ar/auth.json+++ b/locales/ar/auth.json@@ -3,6 +3,8 @@"agreement.confirm.content": "بتحديد \"موافق ومتابعة\"، فإنك تؤكد أنك قد قرأت وتوافق على <terms>الشروط والأحكام</terms> و<privacy>سياسة الخصوصية</privacy>.","agreement.confirm.ok": "موافق ومتابعة","agreement.confirm.title": "الشروط وسياسة الخصوصية",+ "apikey.detail.createdAt": "تم الإنشاء",+ "apikey.detail.title": "تفاصيل مفتاح API","apikey.display.autoGenerated": "تم إنشاؤه تلقائيًا","apikey.display.copy": "نسخ","apikey.display.copyError": "فشل النسخ",@@ -18,6 +20,10 @@"apikey.form.fields.expiresAt.placeholder": "لا تنتهي صلاحيته","apikey.form.fields.name.label": "الاسم","apikey.form.fields.name.placeholder": "يرجى إدخال اسم مفتاح API",+ "apikey.form.fields.scopes.fullAccess": "وصول كامل",+ "apikey.form.fields.scopes.fullAccessDescription": "يمكن لهذا المفتاح القيام بكل ما يمكن لحسابك القيام به",+ "apikey.form.fields.scopes.label": "النطاق",+ "apikey.form.fields.scopes.required": "اختر نطاقًا واحدًا على الأقل","apikey.form.submit": "إنشاء","apikey.form.title": "إنشاء مفتاح API","apikey.list.actions.create": "إنشاء مفتاح API",@@ -27,7 +33,6 @@"apikey.list.actions.deleteConfirm.content": "هل أنت متأكد أنك تريد حذف مفتاح API هذا؟","apikey.list.actions.deleteConfirm.title": "تأكيد الإجراء","apikey.list.actions.viewDocs": "وثائق API",- "apikey.list.columns.actions": "الإجراءات","apikey.list.columns.creator": "المنشئ","apikey.list.columns.expiresAt": "تاريخ الانتهاء","apikey.list.columns.key": "المفتاح",@@ -36,6 +41,21 @@"apikey.list.columns.status": "حالة التمكين","apikey.list.empty": "لا توجد مفاتيح API حتى الآن","apikey.list.title": "قائمة مفاتيح API",+ "apikey.scopes.fullAccess": "وصول كامل",+ "apikey.scopes.grantJoin": ": ",+ "apikey.scopes.groups.agent": "الوكلاء",+ "apikey.scopes.groups.chat": "الدردشة",+ "apikey.scopes.groups.file": "الملفات",+ "apikey.scopes.groups.knowledge": "المعرفة",+ "apikey.scopes.groups.model": "النماذج",+ "apikey.scopes.groups.user": "المستخدم",+ "apikey.scopes.groups.workspace": "مساحة العمل",+ "apikey.scopes.invoke": "استدعاء",+ "apikey.scopes.modelInvoke": "استدعاء النماذج",+ "apikey.scopes.none": "هذا المفتاح ليس لديه أي نطاقات",+ "apikey.scopes.read": "قراءة",+ "apikey.scopes.separator": ", ",+ "apikey.scopes.write": "كتابة","apikey.validation.required": "لا يمكن ترك هذا الحقل فارغًا","authModal.description": "انتهت صلاحية جلسة تسجيل الدخول الخاصة بك. يرجى تسجيل الدخول مرة أخرى لمتابعة استخدام ميزات مزامنة السحابة.","authModal.later": "لاحقًا",diff --git a/locales/bg-BG/auth.json b/locales/bg-BG/auth.jsonindex 8c75461359d..5ea2f1df2c5 100644--- a/locales/bg-BG/auth.json+++ b/locales/bg-BG/auth.json@@ -3,6 +3,8 @@"agreement.confirm.content": "С избора на \"Съгласен съм и продължавам\", потвърждавате, че сте прочели и се съгласявате с <terms>Условията за ползване</terms> и <privacy>Политиката за поверителност</privacy>.","agreement.confirm.ok": "Съгласен съм и продължавам","agreement.confirm.title": "Условия и Политика за поверителност",+ "apikey.detail.createdAt": "Създадено",+ "apikey.detail.title": "Детайли за API ключ","apikey.display.autoGenerated": "Автоматично генериран","apikey.display.copy": "Копирай","apikey.display.copyError": "Копирането не бе успешно",@@ -18,6 +20,10 @@"apikey.form.fields.expiresAt.placeholder": "Без срок на валидност","apikey.form.fields.name.label": "Име","apikey.form.fields.name.placeholder": "Моля, въведете име на API ключа",+ "apikey.form.fields.scopes.fullAccess": "Пълен достъп",+ "apikey.form.fields.scopes.fullAccessDescription": "Този ключ може да прави всичко, което вашият акаунт може да прави",+ "apikey.form.fields.scopes.label": "Обхват",+ "apikey.form.fields.scopes.required": "Изберете поне един обхват","apikey.form.submit": "Създай","apikey.form.title": "Създаване на API ключ","apikey.list.actions.create": "Създай API ключ",@@ -27,7 +33,6 @@"apikey.list.actions.deleteConfirm.content": "Сигурни ли сте, че искате да изтриете този API ключ?","apikey.list.actions.deleteConfirm.title": "Потвърдете действието","apikey.list.actions.viewDocs": "Документация за API",- "apikey.list.columns.actions": "Действия","apikey.list.columns.creator": "Създател","apikey.list.columns.expiresAt": "Дата на изтичане","apikey.list.columns.key": "Ключ",@@ -36,6 +41,21 @@"apikey.list.columns.status": "Статус","apikey.list.empty": "Все още няма API ключове","apikey.list.title": "Списък с API ключове",+ "apikey.scopes.fullAccess": "Пълен достъп",+ "apikey.scopes.grantJoin": ": ",+ "apikey.scopes.groups.agent": "Агенти",+ "apikey.scopes.groups.chat": "Чат",+ "apikey.scopes.groups.file": "Файлове",+ "apikey.scopes.groups.knowledge": "Знания",+ "apikey.scopes.groups.model": "Модели",+ "apikey.scopes.groups.user": "Потребител",+ "apikey.scopes.groups.workspace": "Работно пространство",+ "apikey.scopes.invoke": "Извикване",+ "apikey.scopes.modelInvoke": "Извикване на модели",+ "apikey.scopes.none": "Този ключ няма обхвати",+ "apikey.scopes.read": "Четене",+ "apikey.scopes.separator": ", ",+ "apikey.scopes.write": "Писане","apikey.validation.required": "Това поле не може да бъде празно","authModal.description": "Вашата сесия за вход е изтекла. Моля, влезте отново, за да продължите да използвате функциите за синхронизация в облака.","authModal.later": "По-късно",diff --git a/locales/de-DE/auth.json b/locales/de-DE/auth.jsonindex 28a1cb4be56..a1f8ff4749b 100644--- a/locales/de-DE/auth.json+++ b/locales/de-DE/auth.json@@ -3,6 +3,8 @@"agreement.confirm.content": "Indem Sie \"Zustimmen und fortfahren\" auswählen, bestätigen Sie, dass Sie die <terms>Allgemeinen Geschäftsbedingungen</terms> und die <privacy>Datenschutzrichtlinie</privacy> gelesen haben und ihnen zustimmen.","agreement.confirm.ok": "Zustimmen und fortfahren","agreement.confirm.title": "Allgemeine Geschäftsbedingungen und Datenschutzrichtlinie",+ "apikey.detail.createdAt": "Erstellt",+ "apikey.detail.title": "API-Schlüsseldetails","apikey.display.autoGenerated": "Automatisch generiert","apikey.display.copy": "Kopieren","apikey.display.copyError": "Kopieren fehlgeschlagen",@@ -18,6 +20,10 @@"apikey.form.fields.expiresAt.placeholder": "Läuft nie ab","apikey.form.fields.name.label": "Name","apikey.form.fields.name.placeholder": "Bitte API-Schlüssel-Namen eingeben",+ "apikey.form.fields.scopes.fullAccess": "Vollzugriff",+ "apikey.form.fields.scopes.fullAccessDescription": "Dieser Schlüssel kann alles tun, was Ihr Konto tun kann",+ "apikey.form.fields.scopes.label": "Bereich",+ "apikey.form.fields.scopes.required": "Wählen Sie mindestens einen Bereich aus","apikey.form.submit": "Erstellen","apikey.form.title": "API-Schlüssel erstellen","apikey.list.actions.create": "API-Schlüssel erstellen",@@ -27,7 +33,6 @@"apikey.list.actions.deleteConfirm.content": "Möchten Sie diesen API-Schlüssel wirklich löschen?","apikey.list.actions.deleteConfirm.title": "Aktion bestätigen","apikey.list.actions.viewDocs": "API-Dokumentation",- "apikey.list.columns.actions": "Aktionen","apikey.list.columns.creator": "Ersteller","apikey.list.columns.expiresAt": "Ablaufdatum","apikey.list.columns.key": "Schlüssel",@@ -36,6 +41,21 @@"apikey.list.columns.status": "Status aktiviert","apikey.list.empty": "Noch keine API-Schlüssel","apikey.list.title": "API-Schlüsselliste",+ "apikey.scopes.fullAccess": "Vollzugriff",+ "apikey.scopes.grantJoin": ": ",+ "apikey.scopes.groups.agent": "Agenten",+ "apikey.scopes.groups.chat": "Chat",+ "apikey.scopes.groups.file": "Dateien",+ "apikey.scopes.groups.knowledge": "Wissen",+ "apikey.scopes.groups.model": "Modelle",+ "apikey.scopes.groups.user": "Benutzer",+ "apikey.scopes.groups.workspace": "Arbeitsbereich",+ "apikey.scopes.invoke": "Aufrufen",+ "apikey.scopes.modelInvoke": "Modelle aufrufen",+ "apikey.scopes.none": "Dieser Schlüssel hat keine Berechtigungen",+ "apikey.scopes.read": "Lesen",+ "apikey.scopes.separator": ", ",+ "apikey.scopes.write": "Schreiben","apikey.validation.required": "Dieses Feld darf nicht leer sein","authModal.description": "Ihre Anmeldesitzung ist abgelaufen. Bitte melden Sie sich erneut an, um die Cloud-Synchronisierungsfunktionen weiterhin nutzen zu können.","authModal.later": "Später",diff --git a/locales/en-US/auth.json b/locales/en-US/auth.jsonindex 532e80df645..e5be7b9e2c2 100644--- a/locales/en-US/auth.json+++ b/locales/en-US/auth.json@@ -3,6 +3,8 @@"agreement.confirm.content": "By selecting \"Agree and continue\", you confirm that you have read and agree to the <terms>Terms and Conditions</terms> and <privacy>Privacy Policy</privacy>.","agreement.confirm.ok": "Agree and continue","agreement.confirm.title": "Terms and Privacy Policy",+ "apikey.detail.createdAt": "Created",+ "apikey.detail.title": "API Key Details","apikey.display.autoGenerated": "Auto-generated","apikey.display.copy": "Copy","apikey.display.copyError": "Copy failed",@@ -18,6 +20,10 @@"apikey.form.fields.expiresAt.placeholder": "Never expires","apikey.form.fields.name.label": "Name","apikey.form.fields.name.placeholder": "Please enter API Key name",+ "apikey.form.fields.scopes.fullAccess": "Full access",+ "apikey.form.fields.scopes.fullAccessDescription": "This key can do everything your account can do",+ "apikey.form.fields.scopes.label": "Scope",+ "apikey.form.fields.scopes.required": "Select at least one scope","apikey.form.submit": "Create","apikey.form.title": "Create API Key","apikey.list.actions.create": "Create API Key",@@ -27,7 +33,6 @@"apikey.list.actions.deleteConfirm.content": "Are you sure you want to delete this API Key?","apikey.list.actions.deleteConfirm.title": "Confirm Action","apikey.list.actions.viewDocs": "API Docs",- "apikey.list.columns.actions": "Actions","apikey.list.columns.creator": "Creator","apikey.list.columns.expiresAt": "Expiration Date","apikey.list.columns.key": "Key",@@ -36,6 +41,21 @@"apikey.list.columns.status": "Enabled","apikey.list.empty": "No API Keys yet","apikey.list.title": "API Key List",+ "apikey.scopes.fullAccess": "Full access",+ "apikey.scopes.grantJoin": ": ",+ "apikey.scopes.groups.agent": "Agents",+ "apikey.scopes.groups.chat": "Chat",+ "apikey.scopes.groups.file": "Files",+ "apikey.scopes.groups.knowledge": "Knowledge",+ "apikey.scopes.groups.model": "Models",+ "apikey.scopes.groups.user": "User",+ "apikey.scopes.groups.workspace": "Workspace",+ "apikey.scopes.invoke": "Invoke",+ "apikey.scopes.modelInvoke": "Invoke models",+ "apikey.scopes.none": "This key has no scopes",+ "apikey.scopes.read": "Read",+ "apikey.scopes.separator": ", ",+ "apikey.scopes.write": "Write","apikey.validation.required": "This field cannot be empty","authModal.description": "Your sign-in session has expired. Please sign in again to continue using cloud sync features.","authModal.later": "Later",diff --git a/locales/es-ES/auth.json b/locales/es-ES/auth.jsonindex c367f89c154..a1301aa0c79 100644--- a/locales/es-ES/auth.json+++ b/locales/es-ES/auth.json@@ -3,6 +3,8 @@"agreement.confirm.content": "Al seleccionar \"Aceptar y continuar\", confirmas que has leído y aceptas los <terms>Términos y Condiciones</terms> y la <privacy>Política de Privacidad</privacy>.","agreement.confirm.ok": "Aceptar y continuar","agreement.confirm.title": "Términos y Política de Privacidad",+ "apikey.detail.createdAt": "Creado",+ "apikey.detail.title": "Detalles de la Clave API","apikey.display.autoGenerated": "Generado automáticamente","apikey.display.copy": "Copiar","apikey.display.copyError": "Error al copiar",@@ -18,6 +20,10 @@"apikey.form.fields.expiresAt.placeholder": "Nunca expira","apikey.form.fields.name.label": "Nombre","apikey.form.fields.name.placeholder": "Por favor, ingrese el nombre de la clave API",+ "apikey.form.fields.scopes.fullAccess": "Acceso completo",+ "apikey.form.fields.scopes.fullAccessDescription": "Esta clave puede hacer todo lo que puede hacer tu cuenta",+ "apikey.form.fields.scopes.label": "Alcance",+ "apikey.form.fields.scopes.required": "Selecciona al menos un alcance","apikey.form.submit": "Crear","apikey.form.title": "Crear clave API","apikey.list.actions.create": "Crear clave API",@@ -27,7 +33,6 @@"apikey.list.actions.deleteConfirm.content": "¿Está seguro de que desea eliminar esta clave API?","apikey.list.actions.deleteConfirm.title": "Confirmar acción","apikey.list.actions.viewDocs": "Documentación de la API",- "apikey.list.columns.actions": "Acciones","apikey.list.columns.creator": "Creador","apikey.list.columns.expiresAt": "Fecha de expiración","apikey.list.columns.key": "Clave",@@ -36,6 +41,21 @@"apikey.list.columns.status": "Estado habilitado","apikey.list.empty": "Aún no hay claves API","apikey.list.title": "Lista de claves API",+ "apikey.scopes.fullAccess": "Acceso completo",+ "apikey.scopes.grantJoin": ": ",+ "apikey.scopes.groups.agent": "Agentes",+ "apikey.scopes.groups.chat": "Chat",+ "apikey.scopes.groups.file": "Archivos",+ "apikey.scopes.groups.knowledge": "Conocimiento",+ "apikey.scopes.groups.model": "Modelos",+ "apikey.scopes.groups.user": "Usuario",+ "apikey.scopes.groups.workspace": "Espacio de trabajo",+ "apikey.scopes.invoke": "Invocar",+ "apikey.scopes.modelInvoke": "Invocar modelos",+ "apikey.scopes.none": "Esta clave no tiene alcances",+ "apikey.scopes.read": "Leer",+ "apikey.scopes.separator": ", ",+ "apikey.scopes.write": "Escribir","apikey.validation.required": "Este campo no puede estar vacío","authModal.description": "Tu sesión ha expirado. Por favor, inicia sesión nuevamente para seguir utilizando las funciones de sincronización en la nube.","authModal.later": "Más tarde",diff --git a/locales/fa-IR/auth.json b/locales/fa-IR/auth.jsonindex 2ec99cbac2c..1dd2798f5ae 100644--- a/locales/fa-IR/auth.json+++ b/locales/fa-IR/auth.json@@ -3,6 +3,8 @@"agreement.confirm.content": "با انتخاب «موافقت و ادامه»، شما تأیید میکنید که <terms>شرایط و ضوابط</terms> و <privacy>سیاست حفظ حریم خصوصی</privacy> را خوانده و قبول کردهاید.","agreement.confirm.ok": "موافقت و ادامه","agreement.confirm.title": "شرایط و سیاست حفظ حریم خصوصی",+ "apikey.detail.createdAt": "ایجاد شده",+ "apikey.detail.title": "جزئیات کلید API","apikey.display.autoGenerated": "بهصورت خودکار تولید شده","apikey.display.copy": "کپی","apikey.display.copyError": "کپی انجام نشد",@@ -18,6 +20,10 @@"apikey.form.fields.expiresAt.placeholder": "بدون تاریخ انقضا","apikey.form.fields.name.label": "نام","apikey.form.fields.name.placeholder": "لطفاً نام کلید API را وارد کنید",+ "apikey.form.fields.scopes.fullAccess": "دسترسی کامل",+ "apikey.form.fields.scopes.fullAccessDescription": "این کلید میتواند هر کاری که حساب شما قادر به انجام آن است را انجام دهد",+ "apikey.form.fields.scopes.label": "دامنه",+ "apikey.form.fields.scopes.required": "حداقل یک دامنه را انتخاب کنید","apikey.form.submit": "ایجاد","apikey.form.title": "ایجاد کلید API","apikey.list.actions.create": "ایجاد کلید API",@@ -27,7 +33,6 @@"apikey.list.actions.deleteConfirm.content": "آیا از حذف این کلید API مطمئن هستید؟","apikey.list.actions.deleteConfirm.title": "تأیید عملیات","apikey.list.actions.viewDocs": "مستندات API",- "apikey.list.columns.actions": "عملیات","apikey.list.columns.creator": "سازنده","apikey.list.columns.expiresAt": "تاریخ انقضا","apikey.list.columns.key": "کلید",@@ -36,6 +41,21 @@"apikey.list.columns.status": "وضعیت فعال بودن","apikey.list.empty": "هنوز هیچ کلید API وجود ندارد","apikey.list.title": "فهرست کلیدهای API",+ "apikey.scopes.fullAccess": "دسترسی کامل",+ "apikey.scopes.grantJoin": ": ",+ "apikey.scopes.groups.agent": "نمایندگان",+ "apikey.scopes.groups.chat": "چت",+ "apikey.scopes.groups.file": "فایلها",+ "apikey.scopes.groups.knowledge": "دانش",+ "apikey.scopes.groups.model": "مدلها",+ "apikey.scopes.groups.user": "کاربر",+ "apikey.scopes.groups.workspace": "محیط کار",+ "apikey.scopes.invoke": "فراخوانی",+ "apikey.scopes.modelInvoke": "فراخوانی مدلها",+ "apikey.scopes.none": "این کلید هیچ محدودهای ندارد",+ "apikey.scopes.read": "خواندن",+ "apikey.scopes.separator": ", ",+ "apikey.scopes.write": "نوشتن","apikey.validation.required": "این فیلد نمیتواند خالی باشد","authModal.description": "نشست ورود شما منقضی شده است. لطفاً برای ادامه استفاده از قابلیتهای همگامسازی ابری، دوباره وارد شوید.","authModal.later": "بعداً",diff --git a/locales/fr-FR/auth.json b/locales/fr-FR/auth.jsonindex 6f939cab41a..4d77e70079d 100644--- a/locales/fr-FR/auth.json+++ b/locales/fr-FR/auth.json@@ -3,6 +3,8 @@"agreement.confirm.content": "En sélectionnant « Accepter et continuer », vous confirmez que vous avez lu et accepté les <terms>Conditions générales</terms> et la <privacy>Politique de confidentialité</privacy>.","agreement.confirm.ok": "Accepter et continuer","agreement.confirm.title": "Conditions générales et Politique de confidentialité",+ "apikey.detail.createdAt": "Créé",+ "apikey.detail.title": "Détails de la clé API","apikey.display.autoGenerated": "Généré automatiquement","apikey.display.copy": "Copier","apikey.display.copyError": "Échec de la copie",@@ -18,6 +20,10 @@"apikey.form.fields.expiresAt.placeholder": "N'expire jamais","apikey.form.fields.name.label": "Nom","apikey.form.fields.name.placeholder": "Veuillez saisir le nom de la clé API",+ "apikey.form.fields.scopes.fullAccess": "Accès complet",+ "apikey.form.fields.scopes.fullAccessDescription": "Cette clé peut faire tout ce que votre compte peut faire",+ "apikey.form.fields.scopes.label": "Portée",+ "apikey.form.fields.scopes.required": "Sélectionnez au moins une portée","apikey.form.submit": "Créer","apikey.form.title": "Créer une clé API","apikey.list.actions.create": "Créer une clé API",@@ -27,7 +33,6 @@"apikey.list.actions.deleteConfirm.content": "Êtes-vous sûr de vouloir supprimer cette clé API ?","apikey.list.actions.deleteConfirm.title": "Confirmer l'action","apikey.list.actions.viewDocs": "Documentation API",- "apikey.list.columns.actions": "Actions","apikey.list.columns.creator": "Créateur","apikey.list.columns.expiresAt": "Date d'expiration","apikey.list.columns.key": "Clé",@@ -36,6 +41,21 @@"apikey.list.columns.status": "Statut activé","apikey.list.empty": "Aucune clé API pour le moment","apikey.list.title": "Liste des clés API",+ "apikey.scopes.fullAccess": "Accès complet",+ "apikey.scopes.grantJoin": ": ",+ "apikey.scopes.groups.agent": "Agents",+ "apikey.scopes.groups.chat": "Chat",+ "apikey.scopes.groups.file": "Fichiers",+ "apikey.scopes.groups.knowledge": "Connaissances",+ "apikey.scopes.groups.model": "Modèles",+ "apikey.scopes.groups.user": "Utilisateur",+ "apikey.scopes.groups.workspace": "Espace de travail",+ "apikey.scopes.invoke": "Invoquer",+ "apikey.scopes.modelInvoke": "Invoquer des modèles",+ "apikey.scopes.none": "Cette clé n'a pas de portées",+ "apikey.scopes.read": "Lire",+ "apikey.scopes.separator": ", ",+ "apikey.scopes.write": "Écrire","apikey.validation.required": "Ce champ ne peut pas être vide","authModal.description": "Votre session de connexion a expiré. Veuillez vous reconnecter pour continuer à utiliser les fonctionnalités de synchronisation cloud.","authModal.later": "Plus tard",diff --git a/locales/it-IT/auth.json b/locales/it-IT/auth.jsonindex 990bd55ba20..5ab6f97aed0 100644--- a/locales/it-IT/auth.json+++ b/locales/it-IT/auth.json@@ -3,6 +3,8 @@"agreement.confirm.content": "Selezionando \"Accetta e continua\", confermi di aver letto e accettato i <terms>Termini e Condizioni</terms> e la <privacy>Informativa sulla Privacy</privacy>.","agreement.confirm.ok": "Accetta e continua","agreement.confirm.title": "Termini e Informativa sulla Privacy",+ "apikey.detail.createdAt": "Creato",+ "apikey.detail.title": "Dettagli Chiave API","apikey.display.autoGenerated": "Generata automaticamente","apikey.display.copy": "Copia","apikey.display.copyError": "Copia non riuscita",@@ -18,6 +20,10 @@"apikey.form.fields.expiresAt.placeholder": "Non scade mai","apikey.form.fields.name.label": "Nome","apikey.form.fields.name.placeholder": "Inserisci il nome della chiave API",+ "apikey.form.fields.scopes.fullAccess": "Accesso completo",+ "apikey.form.fields.scopes.fullAccessDescription": "Questa chiave può fare tutto ciò che il tuo account può fare",+ "apikey.form.fields.scopes.label": "Ambito",+ "apikey.form.fields.scopes.required": "Seleziona almeno un ambito","apikey.form.submit": "Crea","apikey.form.title": "Crea Chiave API","apikey.list.actions.create": "Crea Chiave API",@@ -27,7 +33,6 @@"apikey.list.actions.deleteConfirm.content": "Sei sicuro di voler eliminare questa chiave API?","apikey.list.actions.deleteConfirm.title": "Conferma Azione","apikey.list.actions.viewDocs": "Documentazione API",- "apikey.list.columns.actions": "Azioni","apikey.list.columns.creator": "Creatore","apikey.list.columns.expiresAt": "Data di scadenza","apikey.list.columns.key": "Chiave",@@ -36,6 +41,21 @@"apikey.list.columns.status": "Stato abilitazione","apikey.list.empty": "Nessuna chiave API disponibile","apikey.list.title": "Elenco Chiavi API",+ "apikey.scopes.fullAccess": "Accesso completo",+ "apikey.scopes.grantJoin": ": ",+ "apikey.scopes.groups.agent": "Agenti",+ "apikey.scopes.groups.chat": "Chat",+ "apikey.scopes.groups.file": "File",+ "apikey.scopes.groups.knowledge": "Conoscenza",+ "apikey.scopes.groups.model": "Modelli",+ "apikey.scopes.groups.user": "Utente",+ "apikey.scopes.groups.workspace": "Spazio di lavoro",+ "apikey.scopes.invoke": "Invoca",+ "apikey.scopes.modelInvoke": "Richiamare modelli",+ "apikey.scopes.none": "Questa chiave non ha ambiti",+ "apikey.scopes.read": "Leggere",+ "apikey.scopes.separator": ", ",+ "apikey.scopes.write": "Scrivere","apikey.validation.required": "Questo campo non può essere vuoto","authModal.description": "La tua sessione di accesso è scaduta. Accedi nuovamente per continuare a utilizzare le funzionalità di sincronizzazione cloud.","authModal.later": "Più tardi",diff --git a/locales/ja-JP/auth.json b/locales/ja-JP/auth.jsonindex 77d3435c409..8d54bf7ffe7 100644--- a/locales/ja-JP/auth.json+++ b/locales/ja-JP/auth.json@@ -3,6 +3,8 @@"agreement.confirm.content": "「同意して続行」を選択することで、<terms>利用規約</terms>および<privacy>プライバシーポリシー</privacy>を読み、同意したことを確認します。","agreement.confirm.ok": "同意して続行","agreement.confirm.title": "利用規約とプライバシーポリシー",+ "apikey.detail.createdAt": "作成日",+ "apikey.detail.title": "APIキーの詳細","apikey.display.autoGenerated": "自動生成","apikey.display.copy": "コピー","apikey.display.copyError": "コピーに失敗しました",@@ -18,6 +20,10 @@"apikey.form.fields.expiresAt.placeholder": "期限なし","apikey.form.fields.name.label": "名前","apikey.form.fields.name.placeholder": "APIキーの名前を入力してください",+ "apikey.form.fields.scopes.fullAccess": "フルアクセス",+ "apikey.form.fields.scopes.fullAccessDescription": "このキーは、あなたのアカウントができるすべての操作を行うことができます",+ "apikey.form.fields.scopes.label": "スコープ",+ "apikey.form.fields.scopes.required": "少なくとも1つのスコープを選択してください","apikey.form.submit": "作成","apikey.form.title": "APIキーを作成","apikey.list.actions.create": "APIキーを作成",@@ -27,7 +33,6 @@"apikey.list.actions.deleteConfirm.content": "このAPIキーを削除してもよろしいですか?","apikey.list.actions.deleteConfirm.title": "操作の確認","apikey.list.actions.viewDocs": "API ドキュメント",- "apikey.list.columns.actions": "操作","apikey.list.columns.creator": "作成者","apikey.list.columns.expiresAt": "有効期限","apikey.list.columns.key": "キー",@@ -36,6 +41,21 @@"apikey.list.columns.status": "有効状態","apikey.list.empty": "APIキーはまだありません","apikey.list.title": "APIキー一覧",+ "apikey.scopes.fullAccess": "フルアクセス",+ "apikey.scopes.grantJoin": ":",+ "apikey.scopes.groups.agent": "エージェント",+ "apikey.scopes.groups.chat": "チャット",+ "apikey.scopes.groups.file": "ファイル",+ "apikey.scopes.groups.knowledge": "ナレッジ",+ "apikey.scopes.groups.model": "モデル",+ "apikey.scopes.groups.user": "ユーザー",+ "apikey.scopes.groups.workspace": "ワークスペース",+ "apikey.scopes.invoke": "呼び出し",+ "apikey.scopes.modelInvoke": "モデルの呼び出し",+ "apikey.scopes.none": "このキーにはスコープがありません",+ "apikey.scopes.read": "読み取り",+ "apikey.scopes.separator": "、",+ "apikey.scopes.write": "書き込み","apikey.validation.required": "内容を入力してください","authModal.description": "ログインセッションの有効期限が切れました。クラウド同期機能を引き続きご利用いただくには、再度サインインしてください。","authModal.later": "後で",diff --git a/locales/ko-KR/auth.json b/locales/ko-KR/auth.jsonindex 78e6690a3aa..3a621822821 100644--- a/locales/ko-KR/auth.json+++ b/locales/ko-KR/auth.json@@ -3,6 +3,8 @@"agreement.confirm.content": "\"동의하고 계속하기\"를 선택함으로써, 귀하는 <terms>이용 약관</terms> 및 <privacy>개인정보 처리방침</privacy>을 읽고 이에 동의했음을 확인합니다.","agreement.confirm.ok": "동의하고 계속하기","agreement.confirm.title": "이용 약관 및 개인정보 처리방침",+ "apikey.detail.createdAt": "생성됨",+ "apikey.detail.title": "API 키 세부정보","apikey.display.autoGenerated": "자동 생성됨","apikey.display.copy": "복사","apikey.display.copyError": "복사 실패",@@ -18,6 +20,10 @@"apikey.form.fields.expiresAt.placeholder": "만료되지 않음","apikey.form.fields.name.label": "이름","apikey.form.fields.name.placeholder": "API 키 이름을 입력해 주세요",+ "apikey.form.fields.scopes.fullAccess": "전체 액세스",+ "apikey.form.fields.scopes.fullAccessDescription": "이 키는 계정이 할 수 있는 모든 작업을 수행할 수 있습니다",+ "apikey.form.fields.scopes.label": "범위",+ "apikey.form.fields.scopes.required": "적어도 하나의 범위를 선택하세요","apikey.form.submit": "생성","apikey.form.title": "API 키 생성","apikey.list.actions.create": "API 키 생성",@@ -27,7 +33,6 @@"apikey.list.actions.deleteConfirm.content": "이 API 키를 삭제하시겠습니까?","apikey.list.actions.deleteConfirm.title": "작업 확인","apikey.list.actions.viewDocs": "API 문서",- "apikey.list.columns.actions": "작업","apikey.list.columns.creator": "생성자","apikey.list.columns.expiresAt": "만료 시간","apikey.list.columns.key": "키",@@ -36,6 +41,21 @@"apikey.list.columns.status": "활성 상태","apikey.list.empty": "API 키가 아직 없습니다","apikey.list.title": "API 키 목록",+ "apikey.scopes.fullAccess": "전체 액세스",+ "apikey.scopes.grantJoin": ": ",+ "apikey.scopes.groups.agent": "에이전트",+ "apikey.scopes.groups.chat": "채팅",+ "apikey.scopes.groups.file": "파일",+ "apikey.scopes.groups.knowledge": "지식",+ "apikey.scopes.groups.model": "모델",+ "apikey.scopes.groups.user": "사용자",+ "apikey.scopes.groups.workspace": "작업 공간",+ "apikey.scopes.invoke": "호출",+ "apikey.scopes.modelInvoke": "모델 호출",+ "apikey.scopes.none": "이 키에는 범위가 없습니다",+ "apikey.scopes.read": "읽기",+ "apikey.scopes.separator": ", ",+ "apikey.scopes.write": "쓰기","apikey.validation.required": "내용을 비워둘 수 없습니다","authModal.description": "로그인 세션이 만료되었습니다. 클라우드 동기화 기능을 계속 사용하려면 다시 로그인해 주세요.","authModal.later": "나중에",diff --git a/locales/nl-NL/auth.json b/locales/nl-NL/auth.jsonindex 087b05f3221..5f001647b3e 100644--- a/locales/nl-NL/auth.json+++ b/locales/nl-NL/auth.json@@ -3,6 +3,8 @@"agreement.confirm.content": "Door \"Akkoord en doorgaan\" te selecteren, bevestigt u dat u de <terms>Algemene Voorwaarden</terms> en het <privacy>Privacybeleid</privacy> heeft gelezen en ermee akkoord gaat.","agreement.confirm.ok": "Akkoord en doorgaan","agreement.confirm.title": "Algemene Voorwaarden en Privacybeleid",+ "apikey.detail.createdAt": "Gemaakt",+ "apikey.detail.title": "API-sleutel Details","apikey.display.autoGenerated": "Automatisch gegenereerd","apikey.display.copy": "Kopiëren","apikey.display.copyError": "Kopiëren mislukt",@@ -18,6 +20,10 @@"apikey.form.fields.expiresAt.placeholder": "Verloopt nooit","apikey.form.fields.name.label": "Naam","apikey.form.fields.name.placeholder": "Voer een naam voor de API-sleutel in",+ "apikey.form.fields.scopes.fullAccess": "Volledige toegang",+ "apikey.form.fields.scopes.fullAccessDescription": "Deze sleutel kan alles doen wat uw account kan doen",+ "apikey.form.fields.scopes.label": "Scope",+ "apikey.form.fields.scopes.required": "Selecteer ten minste één scope","apikey.form.submit": "Aanmaken","apikey.form.title": "API-sleutel aanmaken","apikey.list.actions.create": "API-sleutel aanmaken",@@ -27,7 +33,6 @@"apikey.list.actions.deleteConfirm.content": "Weet je zeker dat je deze API-sleutel wilt verwijderen?","apikey.list.actions.deleteConfirm.title": "Actie bevestigen","apikey.list.actions.viewDocs": "API-documentatie",- "apikey.list.columns.actions": "Acties","apikey.list.columns.creator": "Maker","apikey.list.columns.expiresAt": "Vervaldatum","apikey.list.columns.key": "Sleutel",@@ -36,6 +41,21 @@"apikey.list.columns.status": "Status ingeschakeld","apikey.list.empty": "Nog geen API-sleutels","apikey.list.title": "Lijst van API-sleutels",+ "apikey.scopes.fullAccess": "Volledige toegang",+ "apikey.scopes.grantJoin": ": ",+ "apikey.scopes.groups.agent": "Agenten",+ "apikey.scopes.groups.chat": "Chat",+ "apikey.scopes.groups.file": "Bestanden",+ "apikey.scopes.groups.knowledge": "Kennis",+ "apikey.scopes.groups.model": "Modellen",+ "apikey.scopes.groups.user": "Gebruiker",+ "apikey.scopes.groups.workspace": "Werkruimte",+ "apikey.scopes.invoke": "Aanroepen",+ "apikey.scopes.modelInvoke": "Modellen aanroepen",+ "apikey.scopes.none": "Deze sleutel heeft geen scopes",+ "apikey.scopes.read": "Lezen",+ "apikey.scopes.separator": ", ",+ "apikey.scopes.write": "Schrijven","apikey.validation.required": "Dit veld mag niet leeg zijn","authModal.description": "Je sessie is verlopen. Meld je opnieuw aan om de cloud-synchronisatiefuncties te blijven gebruiken.","authModal.later": "Later",diff --git a/locales/pl-PL/auth.json b/locales/pl-PL/auth.jsonindex b5ed2b489c7..346012c823f 100644--- a/locales/pl-PL/auth.json+++ b/locales/pl-PL/auth.json@@ -3,6 +3,8 @@"agreement.confirm.content": "Wybierając „Zgadzam się i kontynuuję”, potwierdzasz, że przeczytałeś i zgadzasz się z <terms>Warunkami korzystania</terms> oraz <privacy>Polityką prywatności</privacy>.","agreement.confirm.ok": "Zgadzam się i kontynuuję","agreement.confirm.title": "Warunki i Polityka prywatności",+ "apikey.detail.createdAt": "Utworzono",+ "apikey.detail.title": "Szczegóły Klucza API","apikey.display.autoGenerated": "Wygenerowany automatycznie","apikey.display.copy": "Kopiuj","apikey.display.copyError": "Kopiowanie nie powiodło się",@@ -18,6 +20,10 @@"apikey.form.fields.expiresAt.placeholder": "Nigdy nie wygasa","apikey.form.fields.name.label": "Nazwa","apikey.form.fields.name.placeholder": "Wprowadź nazwę klucza API",+ "apikey.form.fields.scopes.fullAccess": "Pełny dostęp",+ "apikey.form.fields.scopes.fullAccessDescription": "Ten klucz może robić wszystko, co może robić Twoje konto",+ "apikey.form.fields.scopes.label": "Zakres",+ "apikey.form.fields.scopes.required": "Wybierz co najmniej jeden zakres","apikey.form.submit": "Utwórz","apikey.form.title": "Utwórz klucz API","apikey.list.actions.create": "Utwórz klucz API",@@ -27,7 +33,6 @@"apikey.list.actions.deleteConfirm.content": "Czy na pewno chcesz usunąć ten klucz API?","apikey.list.actions.deleteConfirm.title": "Potwierdź działanie","apikey.list.actions.viewDocs": "Dokumentacja API",- "apikey.list.columns.actions": "Działania","apikey.list.columns.creator": "Twórca","apikey.list.columns.expiresAt": "Data wygaśnięcia","apikey.list.columns.key": "Klucz",@@ -36,6 +41,21 @@"apikey.list.columns.status": "Status włączenia","apikey.list.empty": "Brak kluczy API","apikey.list.title": "Lista kluczy API",+ "apikey.scopes.fullAccess": "Pełny dostęp",+ "apikey.scopes.grantJoin": ": ",+ "apikey.scopes.groups.agent": "Agenci",+ "apikey.scopes.groups.chat": "Czat",+ "apikey.scopes.groups.file": "Pliki",+ "apikey.scopes.groups.knowledge": "Wiedza",+ "apikey.scopes.groups.model": "Modele",+ "apikey.scopes.groups.user": "Użytkownik",+ "apikey.scopes.groups.workspace": "Przestrzeń robocza",+ "apikey.scopes.invoke": "Wywołaj",+ "apikey.scopes.modelInvoke": "Wywoływanie modeli",+ "apikey.scopes.none": "Ten klucz nie ma żadnych zakresów",+ "apikey.scopes.read": "Odczyt",+ "apikey.scopes.separator": ", ",+ "apikey.scopes.write": "Zapis","apikey.validation.required": "To pole nie może być puste","authModal.description": "Twoja sesja logowania wygasła. Zaloguj się ponownie, aby kontynuować korzystanie z funkcji synchronizacji w chmurze.","authModal.later": "Później",diff --git a/locales/pt-BR/auth.json b/locales/pt-BR/auth.jsonindex 54f94d53979..d9891285238 100644--- a/locales/pt-BR/auth.json+++ b/locales/pt-BR/auth.json@@ -3,6 +3,8 @@"agreement.confirm.content": "Ao selecionar \"Concordar e continuar\", você confirma que leu e concorda com os <terms>Termos e Condições</terms> e a <privacy>Política de Privacidade</privacy>.","agreement.confirm.ok": "Concordar e continuar","agreement.confirm.title": "Termos e Política de Privacidade",+ "apikey.detail.createdAt": "Criado",+ "apikey.detail.title": "Detalhes da Chave de API","apikey.display.autoGenerated": "Gerado automaticamente","apikey.display.copy": "Copiar","apikey.display.copyError": "Falha ao copiar",@@ -18,6 +20,10 @@"apikey.form.fields.expiresAt.placeholder": "Nunca expira","apikey.form.fields.name.label": "Nome","apikey.form.fields.name.placeholder": "Insira o nome da Chave de API",+ "apikey.form.fields.scopes.fullAccess": "Acesso total",+ "apikey.form.fields.scopes.fullAccessDescription": "Esta chave pode fazer tudo o que sua conta pode fazer",+ "apikey.form.fields.scopes.label": "Escopo",+ "apikey.form.fields.scopes.required": "Selecione pelo menos um escopo","apikey.form.submit": "Criar","apikey.form.title": "Criar Chave de API","apikey.list.actions.create": "Criar Chave de API",@@ -27,7 +33,6 @@"apikey.list.actions.deleteConfirm.content": "Tem certeza de que deseja excluir esta Chave de API?","apikey.list.actions.deleteConfirm.title": "Confirmar Ação","apikey.list.actions.viewDocs": "Documentação da API",- "apikey.list.columns.actions": "Ações","apikey.list.columns.creator": "Criador","apikey.list.columns.expiresAt": "Data de Expiração","apikey.list.columns.key": "Chave",@@ -36,6 +41,21 @@"apikey.list.columns.status": "Status Ativado","apikey.list.empty": "Nenhuma chave de API ainda","apikey.list.title": "Lista de Chaves de API",+ "apikey.scopes.fullAccess": "Acesso total",+ "apikey.scopes.grantJoin": ": ",+ "apikey.scopes.groups.agent": "Agentes",+ "apikey.scopes.groups.chat": "Chat",+ "apikey.scopes.groups.file": "Arquivos",+ "apikey.scopes.groups.knowledge": "Conhecimento",+ "apikey.scopes.groups.model": "Modelos",+ "apikey.scopes.groups.user": "Usuário",+ "apikey.scopes.groups.workspace": "Espaço de trabalho",+ "apikey.scopes.invoke": "Invocar",+ "apikey.scopes.modelInvoke": "Invocar modelos",+ "apikey.scopes.none": "Esta chave não possui escopos",+ "apikey.scopes.read": "Ler",+ "apikey.scopes.separator": ", ",+ "apikey.scopes.write": "Escrever","apikey.validation.required": "Este campo não pode estar vazio","authModal.description": "Sua sessão de login expirou. Faça login novamente para continuar usando os recursos de sincronização na nuvem.","authModal.later": "Mais tarde",diff --git a/locales/ru-RU/auth.json b/locales/ru-RU/auth.jsonindex bd1d423ceef..5ea56e6349c 100644--- a/locales/ru-RU/auth.json+++ b/locales/ru-RU/auth.json@@ -3,6 +3,8 @@"agreement.confirm.content": "Выбирая «Согласиться и продолжить», вы подтверждаете, что прочитали и согласны с <terms>Условиями использования</terms> и <privacy>Политикой конфиденциальности</privacy>.","agreement.confirm.ok": "Согласиться и продолжить","agreement.confirm.title": "Условия и Политика конфиденциальности",+ "apikey.detail.createdAt": "Создано",+ "apikey.detail.title": "Детали API-ключа","apikey.display.autoGenerated": "Автоматически сгенерировано","apikey.display.copy": "Копировать","apikey.display.copyError": "Не удалось скопировать",@@ -18,6 +20,10 @@"apikey.form.fields.expiresAt.placeholder": "Не истекает","apikey.form.fields.name.label": "Имя","apikey.form.fields.name.placeholder": "Пожалуйста, введите имя API-ключа",+ "apikey.form.fields.scopes.fullAccess": "Полный доступ",+ "apikey.form.fields.scopes.fullAccessDescription": "Этот ключ может делать всё, что может ваш аккаунт",+ "apikey.form.fields.scopes.label": "Область действия",+ "apikey.form.fields.scopes.required": "Выберите хотя бы одну область действия","apikey.form.submit": "Создать","apikey.form.title": "Создание API-ключа","apikey.list.actions.create": "Создать API-ключ",@@ -27,7 +33,6 @@"apikey.list.actions.deleteConfirm.content": "Вы уверены, что хотите удалить этот API-ключ?","apikey.list.actions.deleteConfirm.title": "Подтверждение действия","apikey.list.actions.viewDocs": "Документация API",- "apikey.list.columns.actions": "Действия","apikey.list.columns.creator": "Создатель","apikey.list.columns.expiresAt": "Дата истечения","apikey.list.columns.key": "Ключ",@@ -36,6 +41,21 @@"apikey.list.columns.status": "Статус","apikey.list.empty": "API-ключи отсутствуют","apikey.list.title": "Список API-ключей",+ "apikey.scopes.fullAccess": "Полный доступ",+ "apikey.scopes.grantJoin": ": ",+ "apikey.scopes.groups.agent": "Агенты",+ "apikey.scopes.groups.chat": "Чат",+ "apikey.scopes.groups.file": "Файлы",+ "apikey.scopes.groups.knowledge": "Знания",+ "apikey.scopes.groups.model": "Модели",+ "apikey.scopes.groups.user": "Пользователь",+ "apikey.scopes.groups.workspace": "Рабочая область",+ "apikey.scopes.invoke": "Вызов",+ "apikey.scopes.modelInvoke": "Вызов моделей",+ "apikey.scopes.none": "У этого ключа нет областей",+ "apikey.scopes.read": "Чтение",+ "apikey.scopes.separator": ", ",+ "apikey.scopes.write": "Запись","apikey.validation.required": "Это поле не может быть пустым","authModal.description": "Срок действия вашей сессии истёк. Пожалуйста, войдите снова, чтобы продолжить использовать функции облачной синхронизации.","authModal.later": "Позже",diff --git a/locales/tr-TR/auth.json b/locales/tr-TR/auth.jsonindex d55893cd869..f2dd681064b 100644--- a/locales/tr-TR/auth.json+++ b/locales/tr-TR/auth.json@@ -3,6 +3,8 @@"agreement.confirm.content": "\"Kabul et ve devam et\" seçeneğini belirleyerek, <terms>Şartlar ve Koşullar</terms> ile <privacy>Gizlilik Politikası</privacy>'nı okuduğunuzu ve kabul ettiğinizi onaylıyorsunuz.","agreement.confirm.ok": "Kabul et ve devam et","agreement.confirm.title": "Şartlar ve Gizlilik Politikası",+ "apikey.detail.createdAt": "Oluşturulma Tarihi",+ "apikey.detail.title": "API Anahtarı Detayları","apikey.display.autoGenerated": "Otomatik oluşturuldu","apikey.display.copy": "Kopyala","apikey.display.copyError": "Kopyalama başarısız",@@ -18,6 +20,10 @@"apikey.form.fields.expiresAt.placeholder": "Süresi dolmaz","apikey.form.fields.name.label": "Ad","apikey.form.fields.name.placeholder": "API Anahtarı adını girin",+ "apikey.form.fields.scopes.fullAccess": "Tam erişim",+ "apikey.form.fields.scopes.fullAccessDescription": "Bu anahtar, hesabınızın yapabileceği her şeyi yapabilir",+ "apikey.form.fields.scopes.label": "Kapsam",+ "apikey.form.fields.scopes.required": "En az bir kapsam seçin","apikey.form.submit": "Oluştur","apikey.form.title": "API Anahtarı Oluştur","apikey.list.actions.create": "API Anahtarı Oluştur",@@ -27,7 +33,6 @@"apikey.list.actions.deleteConfirm.content": "Bu API Anahtarını silmek istediğinizden emin misiniz?","apikey.list.actions.deleteConfirm.title": "İşlemi Onayla","apikey.list.actions.viewDocs": "API Belgeleri",- "apikey.list.columns.actions": "İşlemler","apikey.list.columns.creator": "Oluşturucu","apikey.list.columns.expiresAt": "Son Kullanma Tarihi","apikey.list.columns.key": "Anahtar",@@ -36,6 +41,21 @@"apikey.list.columns.status": "Etkinlik Durumu","apikey.list.empty": "Henüz API Anahtarı yok","apikey.list.title": "API Anahtarı Listesi",+ "apikey.scopes.fullAccess": "Tam erişim",+ "apikey.scopes.grantJoin": ": ",+ "apikey.scopes.groups.agent": "Temsilciler",+ "apikey.scopes.groups.chat": "Sohbet",+ "apikey.scopes.groups.file": "Dosyalar",+ "apikey.scopes.groups.knowledge": "Bilgi",+ "apikey.scopes.groups.model": "Modeller",+ "apikey.scopes.groups.user": "Kullanıcı",+ "apikey.scopes.groups.workspace": "Çalışma Alanı",+ "apikey.scopes.invoke": "Çağır",+ "apikey.scopes.modelInvoke": "Modelleri çağır",+ "apikey.scopes.none": "Bu anahtarın kapsamı yok",+ "apikey.scopes.read": "Okuma",+ "apikey.scopes.separator": ", ",+ "apikey.scopes.write": "Yazma","apikey.validation.required": "Bu alan boş bırakılamaz","authModal.description": "Oturum süreniz sona erdi. Bulut senkronizasyon özelliklerini kullanmaya devam etmek için lütfen tekrar giriş yapın.","authModal.later": "Daha Sonra",diff --git a/locales/vi-VN/auth.json b/locales/vi-VN/auth.jsonindex 0495bce32c4..3ee61b27da2 100644--- a/locales/vi-VN/auth.json+++ b/locales/vi-VN/auth.json@@ -3,6 +3,8 @@"agreement.confirm.content": "Bằng cách chọn \"Đồng ý và tiếp tục\", bạn xác nhận rằng bạn đã đọc và đồng ý với <terms>Điều khoản và Điều kiện</terms> và <privacy>Chính sách Bảo mật</privacy>.","agreement.confirm.ok": "Đồng ý và tiếp tục","agreement.confirm.title": "Điều khoản và Chính sách Bảo mật",+ "apikey.detail.createdAt": "Đã tạo",+ "apikey.detail.title": "Chi tiết API Key","apikey.display.autoGenerated": "Tự động tạo","apikey.display.copy": "Sao chép","apikey.display.copyError": "Sao chép thất bại",@@ -18,6 +20,10 @@"apikey.form.fields.expiresAt.placeholder": "Không bao giờ hết hạn","apikey.form.fields.name.label": "Tên","apikey.form.fields.name.placeholder": "Vui lòng nhập tên API Key",+ "apikey.form.fields.scopes.fullAccess": "Quyền truy cập đầy đủ",+ "apikey.form.fields.scopes.fullAccessDescription": "Khóa này có thể thực hiện mọi thứ mà tài khoản của bạn có thể làm",+ "apikey.form.fields.scopes.label": "Phạm vi",+ "apikey.form.fields.scopes.required": "Chọn ít nhất một phạm vi","apikey.form.submit": "Tạo","apikey.form.title": "Tạo API Key","apikey.list.actions.create": "Tạo API Key",@@ -27,7 +33,6 @@"apikey.list.actions.deleteConfirm.content": "Bạn có chắc chắn muốn xóa API Key này không?","apikey.list.actions.deleteConfirm.title": "Xác nhận hành động","apikey.list.actions.viewDocs": "Tài liệu API",- "apikey.list.columns.actions": "Hành động","apikey.list.columns.creator": "Người tạo","apikey.list.columns.expiresAt": "Ngày hết hạn","apikey.list.columns.key": "Khóa",@@ -36,6 +41,21 @@"apikey.list.columns.status": "Trạng thái kích hoạt","apikey.list.empty": "Chưa có API Key nào","apikey.list.title": "Danh sách API Key",+ "apikey.scopes.fullAccess": "Quyền truy cập đầy đủ",+ "apikey.scopes.grantJoin": ": ",+ "apikey.scopes.groups.agent": "Đại lý",+ "apikey.scopes.groups.chat": "Trò chuyện",+ "apikey.scopes.groups.file": "Tệp",+ "apikey.scopes.groups.knowledge": "Kiến thức",+ "apikey.scopes.groups.model": "Mô hình",+ "apikey.scopes.groups.user": "Người dùng",+ "apikey.scopes.groups.workspace": "Không gian làm việc",+ "apikey.scopes.invoke": "Gọi",+ "apikey.scopes.modelInvoke": "Kích hoạt mô hình",+ "apikey.scopes.none": "Khóa này không có phạm vi nào",+ "apikey.scopes.read": "Đọc",+ "apikey.scopes.separator": ", ",+ "apikey.scopes.write": "Viết","apikey.validation.required": "Trường này không được để trống","authModal.description": "Phiên đăng nhập của bạn đã hết hạn. Vui lòng đăng nhập lại để tiếp tục sử dụng các tính năng đồng bộ đám mây.","authModal.later": "Để sau",diff --git a/locales/zh-CN/auth.json b/locales/zh-CN/auth.jsonindex 8667f8d2f71..29e9f708551 100644--- a/locales/zh-CN/auth.json+++ b/locales/zh-CN/auth.json@@ -3,6 +3,8 @@"agreement.confirm.content": "点击“同意并继续”即表示你已阅读并同意<terms>服务条款</terms>与<privacy>隐私政策</privacy>。","agreement.confirm.ok": "同意并继续","agreement.confirm.title": "确认服务条款与隐私政策",+ "apikey.detail.createdAt": "创建时间",+ "apikey.detail.title": "API Key 详情","apikey.display.autoGenerated": "自动生成","apikey.display.copy": "复制","apikey.display.copyError": "复制失败,请再试一次",@@ -18,6 +20,10 @@"apikey.form.fields.expiresAt.placeholder": "永久有效","apikey.form.fields.name.label": "名称","apikey.form.fields.name.placeholder": "请输入 API Key 名称",+ "apikey.form.fields.scopes.fullAccess": "完全访问",+ "apikey.form.fields.scopes.fullAccessDescription": "该密钥拥有你账户的全部能力",+ "apikey.form.fields.scopes.label": "权限范围",+ "apikey.form.fields.scopes.required": "请至少选择一项权限","apikey.form.submit": "创建","apikey.form.title": "创建 API Key","apikey.list.actions.create": "创建 API Key",@@ -27,7 +33,6 @@"apikey.list.actions.deleteConfirm.content": "删除后将无法再用此 API Key 访问接口。需要时你可以随时创建新的 API Key。","apikey.list.actions.deleteConfirm.title": "确认删除这个 API Key?","apikey.list.actions.viewDocs": "API 文档",- "apikey.list.columns.actions": "操作","apikey.list.columns.creator": "创建者","apikey.list.columns.expiresAt": "过期时间","apikey.list.columns.key": "密钥",@@ -36,6 +41,21 @@"apikey.list.columns.status": "启用","apikey.list.empty": "暂无 API Key","apikey.list.title": "API Key 列表",+ "apikey.scopes.fullAccess": "完全访问",+ "apikey.scopes.grantJoin": ":",+ "apikey.scopes.groups.agent": "助手",+ "apikey.scopes.groups.chat": "会话",+ "apikey.scopes.groups.file": "文件",+ "apikey.scopes.groups.knowledge": "知识库",+ "apikey.scopes.groups.model": "模型",+ "apikey.scopes.groups.user": "用户",+ "apikey.scopes.groups.workspace": "工作区",+ "apikey.scopes.invoke": "调用",+ "apikey.scopes.modelInvoke": "调用模型",+ "apikey.scopes.none": "该密钥没有任何权限",+ "apikey.scopes.read": "读取",+ "apikey.scopes.separator": "、",+ "apikey.scopes.write": "写入","apikey.validation.required": "内容不得为空","authModal.description": "您的登录会话已过期,请重新登录以继续使用云同步功能。","authModal.later": "稍后",diff --git a/locales/zh-TW/auth.json b/locales/zh-TW/auth.jsonindex 68a34dec1c1..78e94a3b340 100644--- a/locales/zh-TW/auth.json+++ b/locales/zh-TW/auth.json@@ -3,6 +3,8 @@"agreement.confirm.content": "選擇「同意並繼續」即表示您確認已閱讀並同意<terms>條款與條件</terms>及<privacy>隱私政策</privacy>。","agreement.confirm.ok": "同意並繼續","agreement.confirm.title": "條款與隱私政策",+ "apikey.detail.createdAt": "建立時間",+ "apikey.detail.title": "API 金鑰詳細資訊","apikey.display.autoGenerated": "自動生成","apikey.display.copy": "複製","apikey.display.copyError": "複製失敗",@@ -18,6 +20,10 @@"apikey.form.fields.expiresAt.placeholder": "永不過期","apikey.form.fields.name.label": "名稱","apikey.form.fields.name.placeholder": "請輸入 API Key 名稱",+ "apikey.form.fields.scopes.fullAccess": "完全存取",+ "apikey.form.fields.scopes.fullAccessDescription": "此密鑰可以執行您的帳戶能執行的所有操作",+ "apikey.form.fields.scopes.label": "範圍",+ "apikey.form.fields.scopes.required": "請至少選擇一個範圍","apikey.form.submit": "建立","apikey.form.title": "建立 API Key","apikey.list.actions.create": "建立 API Key",@@ -27,7 +33,6 @@"apikey.list.actions.deleteConfirm.content": "確認刪除該 API Key 嗎?","apikey.list.actions.deleteConfirm.title": "確認操作","apikey.list.actions.viewDocs": "API 文件",- "apikey.list.columns.actions": "操作","apikey.list.columns.creator": "建立者","apikey.list.columns.expiresAt": "過期時間","apikey.list.columns.key": "密鑰",@@ -36,6 +41,21 @@"apikey.list.columns.status": "啟用狀態","apikey.list.empty": "尚未有 API 密鑰","apikey.list.title": "API Key 列表",+ "apikey.scopes.fullAccess": "完全存取",+ "apikey.scopes.grantJoin": ":",+ "apikey.scopes.groups.agent": "代理",+ "apikey.scopes.groups.chat": "聊天",+ "apikey.scopes.groups.file": "檔案",+ "apikey.scopes.groups.knowledge": "知識",+ "apikey.scopes.groups.model": "模型",+ "apikey.scopes.groups.user": "使用者",+ "apikey.scopes.groups.workspace": "工作區",+ "apikey.scopes.invoke": "調用",+ "apikey.scopes.modelInvoke": "調用模型",+ "apikey.scopes.none": "此金鑰沒有任何範圍",+ "apikey.scopes.read": "讀取",+ "apikey.scopes.separator": ",",+ "apikey.scopes.write": "寫入","apikey.validation.required": "內容不得為空","authModal.description": "您的登入階段已過期。請重新登入以繼續使用雲端同步功能。","authModal.later": "稍後再說",diff --git a/packages/const/package.json b/packages/const/package.jsonindex fa5afafaa56..3160f57b6c8 100644--- a/packages/const/package.json+++ b/packages/const/package.json@@ -4,6 +4,7 @@"private": true,"exports": {".": "./src/index.ts",+ "./apiKeyScope": "./src/apiKeyScope.ts","./currency": "./src/currency.ts","./desktopGlobalShortcuts": "./src/desktopGlobalShortcuts.ts","./hotkeys": "./src/hotkeys.ts",diff --git a/packages/const/src/apiKeyScope.test.ts b/packages/const/src/apiKeyScope.test.tsnew file mode 100644index 00000000000..d7eb344a5c4--- /dev/null+++ b/packages/const/src/apiKeyScope.test.ts@@ -0,0 +1,201 @@+import { describe, expect, it } from 'vitest';++import {+ API_KEY_SCOPES,+ hasApiKeyScope,+ isFullAccessApiKey,+ isValidApiKeyScope,+ requiredApiKeyScopeForPermission,+ requiredApiKeyScopeForTrpc,+ TRPC_NAMESPACE_API_KEY_RULES,+ TRPC_PROCEDURE_EXTRA_SCOPES,+} from './apiKeyScope';++describe('isValidApiKeyScope', () => {+ it('accepts every catalog scope and rejects unknown strings', () => {+ for (const scope of API_KEY_SCOPES) expect(isValidApiKeyScope(scope)).toBe(true);++ expect(isValidApiKeyScope('agent:admin')).toBe(false);+ expect(isValidApiKeyScope('')).toBe(false);+ expect(isValidApiKeyScope('billing:read')).toBe(false);+ });+});++describe('isFullAccessApiKey', () => {+ it('treats NULL (legacy) and ["*"] as full access', () => {+ expect(isFullAccessApiKey(null)).toBe(true);+ expect(isFullAccessApiKey(undefined)).toBe(true);+ expect(isFullAccessApiKey(['*'])).toBe(true);+ expect(isFullAccessApiKey(['agent:read', '*'])).toBe(true);+ });++ it('treats a restricted list as not full access', () => {+ expect(isFullAccessApiKey(['agent:read'])).toBe(false);+ expect(isFullAccessApiKey([])).toBe(false);+ });+});++describe('hasApiKeyScope', () => {+ it('write implies read', () => {+ expect(hasApiKeyScope(['chat:write'], 'chat:read')).toBe(true);+ expect(hasApiKeyScope(['chat:read'], 'chat:write')).toBe(false);+ });++ it('full access satisfies everything', () => {+ expect(hasApiKeyScope(null, 'model:invoke')).toBe(true);+ expect(hasApiKeyScope(['*'], 'model:invoke')).toBe(true);+ });++ it('does not cross domains', () => {+ expect(hasApiKeyScope(['agent:write'], 'chat:read')).toBe(false);+ });+});++describe('requiredApiKeyScopeForPermission', () => {+ it('maps resource actions to scope domains', () => {+ expect(requiredApiKeyScopeForPermission('agent:read')).toBe('agent:read');+ expect(requiredApiKeyScopeForPermission('agent:create')).toBe('agent:write');+ expect(requiredApiKeyScopeForPermission('session:update')).toBe('chat:write');+ expect(requiredApiKeyScopeForPermission('knowledge_base:read')).toBe('knowledge:read');+ expect(requiredApiKeyScopeForPermission('workspace_member:read')).toBe('workspace:read');+ });++ it('accepts scope-suffixed permission codes', () => {+ expect(requiredApiKeyScopeForPermission('agent:create:owner')).toBe('agent:write');+ expect(requiredApiKeyScopeForPermission('file:read:all')).toBe('file:read');+ });++ it('gives model invocation its own tier', () => {+ expect(requiredApiKeyScopeForPermission('ai_model:invoke')).toBe('model:invoke');+ expect(requiredApiKeyScopeForPermission('ai_model:read')).toBe('model:read');+ });++ it('blocks self-provisioning and privilege-escalation resources', () => {+ expect(requiredApiKeyScopeForPermission('api_key:create')).toBeNull();+ expect(requiredApiKeyScopeForPermission('rbac:role_update')).toBeNull();+ expect(requiredApiKeyScopeForPermission('workspace_role:create')).toBeNull();+ });++ it('blocks unknown resources (fail closed)', () => {+ expect(requiredApiKeyScopeForPermission('billing:read')).toBeNull();+ expect(requiredApiKeyScopeForPermission('malformed')).toBeNull();+ });+});++describe('requiredApiKeyScopeForTrpc', () => {+ it('derives read/write from operation type', () => {+ expect(requiredApiKeyScopeForTrpc('agent.getAgents', 'query')).toEqual({+ scopes: ['agent:read'],+ });+ expect(requiredApiKeyScopeForTrpc('agent.createAgent', 'mutation')).toEqual({+ scopes: ['agent:write'],+ });+ expect(requiredApiKeyScopeForTrpc('topic.getTopics', 'query')).toEqual({+ scopes: ['chat:read'],+ });+ });++ it('uses a single tier for money-burning namespaces', () => {+ expect(requiredApiKeyScopeForTrpc('aiChat.outputJSON', 'mutation')).toEqual({+ scopes: ['model:invoke'],+ });+ expect(requiredApiKeyScopeForTrpc('image.createImage', 'mutation')).toEqual({+ scopes: ['model:invoke'],+ });+ });++ it('stacks procedure-level extra scopes on the namespace rule', () => {+ expect(requiredApiKeyScopeForTrpc('agentDocument.generateSkillMeta', 'mutation')).toEqual({+ scopes: ['knowledge:write', 'model:invoke'],+ });+ // stateful chat procedures need chat:write on top of the model tier+ expect(requiredApiKeyScopeForTrpc('aiChat.sendMessageInServer', 'mutation')).toEqual({+ scopes: ['model:invoke', 'chat:write'],+ });+ // agent-run execution needs the full chat + model tier on top of agent:write+ expect(requiredApiKeyScopeForTrpc('aiAgent.execAgent', 'mutation')).toEqual({+ scopes: ['agent:write', 'chat:write', 'model:invoke'],+ });+ // provider connectivity test sends a real model request+ expect(requiredApiKeyScopeForTrpc('aiProvider.checkProviderConnectivity', 'mutation')).toEqual({+ scopes: ['model:write', 'model:invoke'],+ });+ // MCP tool execution needs agent:write on top of the model tier+ expect(requiredApiKeyScopeForTrpc('mcp.callTool', 'mutation')).toEqual({+ scopes: ['model:invoke', 'agent:write'],+ });+ // onboarding generation triggers stack model:invoke on user:write+ expect(requiredApiKeyScopeForTrpc('user.startOnboardingUnderstanding', 'mutation')).toEqual({+ scopes: ['user:write', 'model:invoke'],+ });+ // sibling procedures in the namespace are untouched+ expect(requiredApiKeyScopeForTrpc('agentDocument.createDocument', 'mutation')).toEqual({+ scopes: ['knowledge:write'],+ });+ });++ it('blocks sensitive namespaces for restricted keys', () => {+ expect(requiredApiKeyScopeForTrpc('apiKey.createApiKey', 'mutation')).toEqual({+ blocked: true,+ });+ expect(requiredApiKeyScopeForTrpc('subscription.getSubscription', 'query')).toEqual({+ blocked: true,+ });+ expect(requiredApiKeyScopeForTrpc('topUp.createCheckout', 'mutation')).toEqual({+ blocked: true,+ });+ });++ it('blocks the write half when only read is granted to the namespace', () => {+ expect(requiredApiKeyScopeForTrpc('workspaceMember.list', 'query')).toEqual({+ scopes: ['workspace:read'],+ });+ expect(requiredApiKeyScopeForTrpc('workspaceMember.remove', 'mutation')).toEqual({+ blocked: true,+ });+ });++ it('blocks sensitive nested sub-surfaces regardless of the parent namespace', () => {+ expect(requiredApiKeyScopeForTrpc('market.creds.list', 'query')).toEqual({ blocked: true });+ expect(requiredApiKeyScopeForTrpc('market.creds.createKV', 'mutation')).toEqual({+ blocked: true,+ });+ expect(requiredApiKeyScopeForTrpc('market.oidc.getToken', 'query')).toEqual({ blocked: true });+ // the rest of the market surface keeps its agent scopes+ expect(requiredApiKeyScopeForTrpc('market.getAgentsByPlugin', 'query')).toEqual({+ scopes: ['agent:read'],+ });+ });++ it('fails closed on unknown namespaces', () => {+ expect(requiredApiKeyScopeForTrpc('brandNewRouter.doThing', 'mutation')).toEqual({+ blocked: true,+ });+ });++ it('keeps bootstrap namespaces open', () => {+ expect(requiredApiKeyScopeForTrpc('healthcheck', 'query')).toEqual({ open: true });+ expect(requiredApiKeyScopeForTrpc('config.getGlobalConfig', 'query')).toEqual({ open: true });+ });++ it('every rule references catalog scopes only', () => {+ for (const rule of Object.values(TRPC_NAMESPACE_API_KEY_RULES)) {+ if (rule === 'open' || rule === 'blocked') continue;+ if ('any' in rule) {+ expect(isValidApiKeyScope(rule.any)).toBe(true);+ continue;+ }+ if (rule.read) expect(isValidApiKeyScope(rule.read)).toBe(true);+ if (rule.write) expect(isValidApiKeyScope(rule.write)).toBe(true);+ }+ });++ it('every extra-scope path targets a registered namespace and catalog scopes', () => {+ for (const [path, scopes] of Object.entries(TRPC_PROCEDURE_EXTRA_SCOPES)) {+ const namespace = path.split('.')[0];+ expect(TRPC_NAMESPACE_API_KEY_RULES[namespace]).toBeDefined();+ expect(scopes.length).toBeGreaterThan(0);+ for (const scope of scopes) expect(isValidApiKeyScope(scope)).toBe(true);+ }+ });+});diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.tsnew file mode 100644index 00000000000..4da01347339--- /dev/null+++ b/packages/const/src/apiKeyScope.ts@@ -0,0 +1,418 @@+/**+ * API Key Scopes+ *+ * A scope describes what a signed API key is allowed to do. The effective+ * permission of a request is always the intersection of the issuer's own+ * permissions (RBAC / workspace role) and the key's scopes — scopes can only+ * narrow, never widen.+ *+ * Storage semantics on `api_keys.scopes`:+ * - `NULL` → full access (every key issued before scopes existed)+ * - `['*']` → full access, explicitly chosen at creation time+ * - list → restricted key; each entry must be a member of `API_KEY_SCOPES`+ *+ * Scopes are immutable after creation (same as GitHub tokens): re-issue the+ * key to change its powers.+ */++export const API_KEY_FULL_ACCESS_SCOPE = '*';++/**+ * The selectable scope catalog. `model:invoke` is its own tier because it is+ * the one that burns money (chat/completions, image, video, asr).+ *+ * Deliberately absent (a restricted key can never obtain them):+ * - `api_key:*` — keys must not mint keys (self-provisioning)+ * - `rbac:*`, member/role management — privilege escalation surface+ * - billing (spend / subscription / top-up / credits)+ */+export const API_KEY_SCOPES = [+ API_KEY_FULL_ACCESS_SCOPE,+ 'agent:read',+ 'agent:write',+ 'chat:read',+ 'chat:write',+ 'model:invoke',+ 'model:read',+ 'model:write',+ 'file:read',+ 'file:write',+ 'knowledge:read',+ 'knowledge:write',+ 'workspace:read',+ 'workspace:write',+ 'user:read',+ 'user:write',+] as const;++export type ApiKeyScope = (typeof API_KEY_SCOPES)[number];++const API_KEY_SCOPE_SET: ReadonlySet<string> = new Set(API_KEY_SCOPES);++export const isValidApiKeyScope = (scope: string): scope is ApiKeyScope =>+ API_KEY_SCOPE_SET.has(scope);++/**+ * `NULL` (legacy key) and `['*']` both mean full access.+ */+export const isFullAccessApiKey = (scopes?: string[] | null): boolean =>+ !scopes || scopes.includes(API_KEY_FULL_ACCESS_SCOPE);++/**+ * Does this scope list satisfy `required`? `x:write` implies `x:read` so a+ * write-capable key never has to double-select the read box.+ */+export const hasApiKeyScope = (+ scopes: string[] | null | undefined,+ required: ApiKeyScope,+): boolean => {+ if (isFullAccessApiKey(scopes)) return true;+ if (scopes!.includes(required)) return true;++ if (required.endsWith(':read')) {+ const writeTwin = required.replace(/:read$/, ':write');+ return scopes!.includes(writeTwin);+ }++ return false;+};++// ---------------------------------------------------------------------------+// OpenAPI (Hono) projection: RBAC permission action → required scope+// ---------------------------------------------------------------------------++/**+ * RBAC resource (the part before `:` in a permission action) → scope domain.+ * `null` means the resource is never reachable with a restricted key.+ */+const PERMISSION_RESOURCE_TO_SCOPE_DOMAIN: Record<string, string | null> = {+ agent: 'agent',+ agent_label: 'agent',+ ai_model: 'model',+ ai_provider: 'model',+ api_key: null,+ document: 'knowledge',+ file: 'file',+ knowledge_base: 'knowledge',+ message: 'chat',+ rbac: null,+ session: 'chat',+ session_group: 'chat',+ topic: 'chat',+ topic_comment: 'chat',+ translation: 'chat',+ user: 'user',+ workspace: 'workspace',+ workspace_audit: 'workspace',+ workspace_member: 'workspace',+ workspace_role: null,+};++const READ_ACTIONS = new Set(['read']);++/**+ * Map an RBAC permission action to the API key scope required to use it.+ * Accepts both the bare action form (`agent:create`) and the scope-suffixed+ * permission code form (`agent:create:owner`).+ *+ * Returns:+ * - an `ApiKeyScope` — restricted keys holding it may proceed+ * - `null` — the action is off-limits to restricted keys (fail closed)+ */+export const requiredApiKeyScopeForPermission = (permission: string): ApiKeyScope | null => {+ const [resource, action] = permission.split(':');+ if (!resource || !action) return null;++ // the single money-burning action gets its own tier+ if (resource === 'ai_model' && action === 'invoke') return 'model:invoke';++ const domain = PERMISSION_RESOURCE_TO_SCOPE_DOMAIN[resource];+ if (!domain) return null;++ const suffix = READ_ACTIONS.has(action) ? 'read' : 'write';+ const scope = `${domain}:${suffix}`;++ return isValidApiKeyScope(scope) ? scope : null;+};++// ---------------------------------------------------------------------------+// tRPC lambda projection: router namespace → required scope+// ---------------------------------------------------------------------------++/**+ * Per-namespace rule for the tRPC lambda surface (also covers the tools+ * router, which shares `authedProcedure`).+ *+ * - `'open'` → no scope required (bootstrap / public info)+ * - `'blocked'` → restricted keys can never call it (full-access keys can)+ * - `{ read, write }` → scope for queries / mutations; `null` blocks that half+ * - `{ any }` → same scope for queries and mutations+ */+export type TrpcNamespaceScopeRule =+ | 'open'+ | 'blocked'+ | { any: ApiKeyScope }+ | { read: ApiKeyScope | null; write: ApiKeyScope | null };++const rw = (read: ApiKeyScope | null, write: ApiKeyScope | null): TrpcNamespaceScopeRule => ({+ read,+ write,+});++/**+ * Every namespace mounted on the lambda (and tools) router MUST appear here —+ * the guard denies unknown namespaces, and a consistency test in+ * `apps/server` fails when a newly added router is left uncategorized.+ */+export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRule> = {+ accountDeletion: 'blocked',+ acceptance: 'blocked',+ agent: rw('agent:read', 'agent:write'),+ // bot channel wiring carries channel credentials+ agentBotProvider: 'blocked',+ agentDocument: rw('knowledge:read', 'knowledge:write'),+ agentEval: 'blocked',+ agentEvalExternal: 'blocked',+ agentLabel: rw('agent:read', 'agent:write'),+ agentNotify: rw('agent:read', 'agent:write'),+ agentQuota: rw('agent:read', null),+ agentSignal: rw('agent:read', 'agent:write'),+ agentSkills: rw('agent:read', 'agent:write'),+ aiAgent: rw('agent:read', 'agent:write'),+ aiChat: { any: 'model:invoke' },+ aiModel: rw('model:read', 'model:write'),+ aiProvider: rw('model:read', 'model:write'),+ // keys must not mint or manage keys+ apiKey: 'blocked',+ asr: { any: 'model:invoke' },+ // decrypts stored bot/messenger credentials and calls external channel APIs+ botMessage: 'blocked',+ brief: rw('chat:read', 'chat:write'),+ changelog: 'open',+ chunk: rw('knowledge:read', 'knowledge:write'),+ comfyui: rw('model:read', 'model:write'),+ // third-party integrations hold external credentials+ composio: 'blocked',+ config: 'open',+ connector: 'blocked',+ device: 'blocked',+ document: rw('knowledge:read', 'knowledge:write'),+ // whole-account backup dump (settings incl. market tokens, providers, agents)+ exporter: 'blocked',+ file: rw('file:read', 'file:write'),+ followUpAction: rw('chat:read', 'chat:write'),+ generation: { any: 'model:invoke' },+ generationBatch: { any: 'model:invoke' },+ generationTopic: { any: 'model:invoke' },+ group: rw('agent:read', 'agent:write'),+ healthcheck: 'open',+ home: rw('chat:read', 'chat:write'),+ image: { any: 'model:invoke' },+ // whole-account backup import can overwrite credential-bearing settings,+ // provider/model config and agents+ importer: 'blocked',+ klavis: 'blocked',+ knowledge: rw('knowledge:read', 'knowledge:write'),+ knowledgeBase: rw('knowledge:read', 'knowledge:write'),+ llmGenerationTracing: 'blocked',+ market: rw('agent:read', 'agent:write'),+ // tool execution inside a chat run+ mcp: { any: 'model:invoke' },+ message: rw('chat:read', 'chat:write'),+ // IM channel management carries channel credentials+ messenger: 'blocked',+ notebook: rw('knowledge:read', 'knowledge:write'),+ notification: rw('user:read', 'user:write'),+ oauthApp: 'blocked',+ oauthDeviceFlow: 'blocked',+ pageShare: rw('chat:read', 'chat:write'),+ plugin: rw('agent:read', 'agent:write'),+ project: rw('agent:read', 'agent:write'),+ pushToken: 'blocked',+ ragEval: 'blocked',+ recent: rw('chat:read', null),+ referral: 'blocked',+ resourcePermission: 'blocked',+ search: rw('chat:read', null),+ session: rw('chat:read', 'chat:write'),+ sessionGroup: rw('chat:read', 'chat:write'),+ share: rw('chat:read', 'chat:write'),+ spend: 'blocked',+ storageOverage: 'blocked',+ subscription: 'blocked',+ task: rw('agent:read', 'agent:write'),+ taskTemplate: rw('agent:read', 'agent:write'),+ thread: rw('chat:read', 'chat:write'),+ topUp: 'blocked',+ topic: rw('chat:read', 'chat:write'),+ topicComment: rw('chat:read', 'chat:write'),+ upload: rw('file:read', 'file:write'),+ usage: 'blocked',+ user: rw('user:read', 'user:write'),+ userMemories: rw('user:read', 'user:write'),+ userMemory: rw('user:read', 'user:write'),+ verify: 'blocked',+ video: { any: 'model:invoke' },+ waitlist: 'blocked',+ webBrowsing: { any: 'model:invoke' },+ work: rw('agent:read', 'agent:write'),+ workspace: rw('workspace:read', 'workspace:write'),+ workspaceAuditLog: rw('workspace:read', null),+ workspaceCredits: 'blocked',+ workspaceCreds: 'blocked',+ workspaceData: 'blocked',+ workspaceMember: rw('workspace:read', null),+ workspaceUsage: 'blocked',+ workspaceUserSettings: rw('workspace:read', 'workspace:write'),+};++/**+ * Procedure-level extra scope requirements, keyed by the full+ * `namespace.procedure` path. Applied ON TOP of the namespace rule — the key+ * must satisfy both. Use this when a procedure has a side effect its namespace+ * scope does not capture, e.g. a knowledge-write mutation that internally+ * invokes a model.+ */+/**+ * Boundary note: embedding calls (chunk semantic search / memory search /+ * re-embed) are deliberately NOT gated by `model:invoke`. They are+ * retrieval/indexing infrastructure owned by their domain scope, their+ * per-call cost is marginal, and file-upload pipelines trigger the same+ * embedding work outside this guard anyway. Whether embeddings deserve their+ * own scope (e.g. `model:embed`) is tracked in LOBE-12910.+ */+const AGENT_RUN_SCOPES: ApiKeyScope[] = ['chat:write', 'model:invoke'];++export const TRPC_PROCEDURE_EXTRA_SCOPES: Record<string, ApiKeyScope[]> = {+ // agent-run execution paths schedule model runs and write chat/topic state,+ // so `agent:write` alone must not start them+ 'aiAgent.execAgent': AGENT_RUN_SCOPES,+ 'aiAgent.execAgents': AGENT_RUN_SCOPES,+ 'aiAgent.execGroupAgent': AGENT_RUN_SCOPES,+ 'aiAgent.execSubAgentTask': AGENT_RUN_SCOPES,+ 'aiAgent.scheduleAgentRun': AGENT_RUN_SCOPES,+ 'aiAgent.startExecution': AGENT_RUN_SCOPES,+ // thread/message state writes without starting a run+ 'aiAgent.createClientGroupAgentTaskThread': ['chat:write'],+ 'aiAgent.createClientTaskThread': ['chat:write'],+ 'aiAgent.interruptTask': ['chat:write'],+ 'aiAgent.stopPendingApproval': ['chat:write'],+ 'aiAgent.updateClientTaskThreadStatus': ['chat:write'],+ // intervention responses write messages and resume model execution+ 'aiAgent.processHumanIntervention': AGENT_RUN_SCOPES,+ 'aiAgent.submitHeteroIntervention': AGENT_RUN_SCOPES,+ // lists the caller's whole knowledge-base/file inventory, not agent config+ 'agent.getKnowledgeBasesAndFiles': ['file:read', 'knowledge:read'],+ // notify's user/continue paths call `aiAgentService.execAgent` — another run entry+ 'agentNotify.notify': AGENT_RUN_SCOPES,+ // signal triggers enqueue analyze-intent workflows whose judges call+ // `generateObject` (and may dispatch self-iteration runs)+ 'agentSignal.emitSourceEvent': ['model:invoke'],+ 'agentSignal.triggerSourceEvent': ['model:invoke'],+ // persists tool results into the topic's message history+ 'aiChat.archiveToolResult': ['chat:write'],+ // creates user/assistant messages and topics alongside the model call+ 'aiChat.sendMessageInServer': ['chat:write'],+ // connectivity test sends a real (1-token) chat request to the provider+ 'aiProvider.checkProviderConnectivity': ['model:invoke'],+ // runs a ComfyUI image-generation workflow, not a config write+ 'comfyui.createImage': ['model:invoke'],+ // extracts follow-up actions via `AiGenerationService.generateObject`+ 'followUpAction.extract': ['model:invoke'],+ // asset cleanup/organization is file management, not model invocation —+ // a model-only key must not delete or reorganize generated assets+ 'generation.deleteGeneration': ['file:write'],+ 'generationBatch.deleteGenerationBatch': ['file:write'],+ 'generationTopic.deleteTopic': ['file:write'],+ // sharing/visibility control is asset management, not generation+ 'generationTopic.setTopicVisibility': ['file:write'],+ 'generationTopic.updateTopic': ['file:write'],+ // fetches caller-supplied image data and uploads a cover file+ 'generationTopic.updateTopicCover': ['file:write'],+ // Market tool-execution surface (mounted on the tools router): external+ // tool calls burn quota / cause side effects; file export writes files+ 'market.callCloudMcpEndpoint': ['model:invoke'],+ 'market.connectCallTool': ['model:invoke'],+ 'market.exportAndUploadFile': ['file:write'],+ // executes a server-side MCP tool call with caller-supplied endpoint/args —+ // a model-only key must not trigger arbitrary tool side effects+ 'mcp.callTool': ['agent:write'],+ // prefills the convert-to-skill form via an LLM call+ // (`SystemAgentService.generateSkillMeta` → `modelRuntime.generateObject`)+ 'agentDocument.generateSkillMeta': ['model:invoke'],+ // home sidebar procedures read/reorganize the agent inventory, not chat data+ 'home.getSidebarAgentList': ['agent:read'],+ 'home.searchAgents': ['agent:read'],+ 'home.updateAgentSessionGroupId': ['agent:write'],+ // task orchestration starts `execAgent` runs (run/runReadySubtasks) or calls+ // `generateObject` judges (runReview) — same boundary as `aiAgent.*`+ 'task.run': AGENT_RUN_SCOPES,+ 'task.runReadySubtasks': AGENT_RUN_SCOPES,+ 'task.runReview': ['model:invoke'],+ // deletes the whole settings row, including stored provider credentials —+ // same bar as the `updateSettings` keyVaults guard+ 'user.resetSettings': ['model:write'],+ // onboarding understanding triggers enqueue generation workflows+ // (persona / task-recommendation `generateObject` steps run async via QStash)+ 'user.retryOnboardingUnderstandingSource': ['model:invoke'],+ 'user.reviseOnboardingUnderstanding': ['model:invoke'],+ 'user.startOnboardingUnderstanding': ['model:invoke'],+ // schedules the full memory-extraction workflow (embeddings + per-layer+ // `generateObject`), unlike the accepted search/re-embed embedding tradeoff+ 'userMemory.requestMemoryFromChatTopic': ['model:invoke'],+ // persists crawled pages as `documents` rows — a knowledge write+ 'webBrowsing.upsertCrawledDocument': ['knowledge:write'],+};++/**+ * Nested sub-surfaces denied to restricted keys regardless of the parent+ * namespace rule. The namespace table only sees the first path segment, so+ * sensitive subrouters mounted inside an otherwise-scoped namespace must be+ * blocked here by path prefix.+ */+export const TRPC_BLOCKED_PATH_PREFIXES: string[] = [+ // returns an unrestricted user JWT that passes `oidcAuth` as non-API-key+ // auth and would bypass the scope guard entirely+ 'aiAgent.refreshGatewayToken',+ // sandbox execution mints a full LOBEHUB_JWT for `lh` commands+ // (`preprocessLhCommand`), which would bypass the key's scopes entirely+ 'market.callCodeInterpreterTool',+ 'market.execInSandbox',+ // marketplace credential management: list/decrypt/create/delete/share/inject+ // of external credentials — same class as the blocked connector/composio surfaces+ 'market.creds.',+ // marketplace OIDC auth flows carry tokens+ 'market.oidc.',+];++export type TrpcScopeDecision = { scopes: ApiKeyScope[] } | { open: true } | { blocked: true };++/**+ * Decide what a restricted API key needs to call `path` (`namespace.proc`).+ * Unknown namespaces are blocked — fail closed, so a newly added router is+ * never silently exposed to restricted keys.+ */+export const requiredApiKeyScopeForTrpc = (+ path: string,+ type: 'query' | 'mutation' | 'subscription',+): TrpcScopeDecision => {+ if (TRPC_BLOCKED_PATH_PREFIXES.some((prefix) => path.startsWith(prefix)))+ return { blocked: true };++ const namespace = path.split('.')[0];+ const rule = TRPC_NAMESPACE_API_KEY_RULES[namespace];++ if (!rule || rule === 'blocked') return { blocked: true };++ const base =+ rule === 'open' ? null : 'any' in rule ? rule.any : type === 'query' ? rule.read : rule.write;++ // a namespace half with no scope grants nothing to restricted keys+ if (rule !== 'open' && !base) return { blocked: true };++ const scopes = [+ ...new Set([base, ...(TRPC_PROCEDURE_EXTRA_SCOPES[path] ?? [])].filter(Boolean)),+ ] as ApiKeyScope[];++ return scopes.length > 0 ? { scopes } : { open: true };+};diff --git a/packages/const/src/index.ts b/packages/const/src/index.tsindex ad56c4e496e..420d0f9f54d 100644--- a/packages/const/src/index.ts+++ b/packages/const/src/index.ts@@ -1,5 +1,6 @@export * from './agentDocument';export * from './agentName';+export * from './apiKeyScope';export * from './bot';export * from './composio';export * from './currency';diff --git a/packages/const/src/rbac.test.ts b/packages/const/src/rbac.test.tsindex 106c813708c..b22865da296 100644--- a/packages/const/src/rbac.test.ts+++ b/packages/const/src/rbac.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';import {legacyRoleToWorkspaceRole,+ PERSONAL_DEFAULT_PERMISSIONS,WORKSPACE_ROLE_PERMISSIONS,WORKSPACE_SYSTEM_ROLES,} from './rbac';@@ -54,3 +55,42 @@ describe('workspace built-in roles', () => {}});});++describe('personal default permissions (LOBE-12892)', () => {+ it('grants only :owner codes plus the shared-registry :all resources', () => {+ for (const code of PERSONAL_DEFAULT_PERMISSIONS) {+ const [resource, , scope] = [code.split(':')[0], code.split(':')[1], code.split(':')[2]];+ if (scope === 'all') {+ // the only :all grants are user_id-bound shared registries+ expect(['agent_label', 'session_group']).toContain(resource);+ } else {+ expect(scope).toBe('owner');+ }+ }+ });++ it('never grants admin or workspace domains', () => {+ for (const code of PERSONAL_DEFAULT_PERMISSIONS) {+ expect(code.startsWith('rbac:')).toBe(false);+ expect(code.startsWith('workspace')).toBe(false);+ }+ expect(PERSONAL_DEFAULT_PERMISSIONS).not.toContain('user:create:all');+ expect(PERSONAL_DEFAULT_PERMISSIONS).not.toContain('user:delete:all');+ });++ it('covers the content actions the OpenAPI surface gates on', () => {+ for (const code of [+ 'agent:read:owner',+ 'session:read:owner',+ 'message:create:owner',+ 'topic:read:owner',+ 'file:upload:owner',+ 'knowledge_base:read:owner',+ 'ai_model:read:owner',+ 'ai_model:invoke:owner',+ 'translation:create:owner',+ ]) {+ expect(PERSONAL_DEFAULT_PERMISSIONS).toContain(code);+ }+ });+});diff --git a/packages/const/src/rbac.ts b/packages/const/src/rbac.tsindex bb6f19337f9..f9264f5dbc1 100644--- a/packages/const/src/rbac.ts+++ b/packages/const/src/rbac.ts@@ -618,3 +618,95 @@ export const getWorkspaceRolePermissionCodes = (role: string): readonly string[]const systemRole = legacyRoleToWorkspaceRole(role);return systemRole ? WORKSPACE_ROLE_PERMISSIONS[systemRole] : [];};++/**+ * Default permission codes every authenticated user holds over their OWN data+ * in personal (non-workspace) context.+ *+ * Why this exists (LOBE-12892): ordinary accounts have no `rbac_user_roles`+ * rows — roles are only assigned via the admin backend — so any personal-mode+ * check that consulted the DB alone returned 403 for every registered user,+ * making the OpenAPI surface admin-only in practice. Personal data is already+ * isolated by `user_id` at the resource layer, so the implicit baseline is the+ * `:owner` grant set (mirroring what `workspace_member` gets inside a+ * workspace).+ *+ * Scope notes:+ * - Content resources are granted `:owner` — resource queries stay pinned to+ * the caller, and `hasGlobalPermission`-style `:all` widenings still require+ * a real DB role.+ * - `agent_label` / `session_group` only define an `:all` scope (shared+ * registries — see `getAllowedScopesForAction`); in personal mode their data+ * is still `user_id`-bound, so the `:all` grant does not widen anything.+ * - Deliberately absent: `rbac:*`, `workspace*` domains, `user:create` /+ * `user:delete` — administration stays behind explicitly assigned DB roles.+ */+export const PERSONAL_DEFAULT_PERMISSIONS: readonly string[] = [+ // Agents+ `${action('AGENT_READ')}:owner`,+ `${action('AGENT_CREATE')}:owner`,+ `${action('AGENT_UPDATE')}:owner`,+ `${action('AGENT_DELETE')}:owner`,+ `${action('AGENT_FORK')}:owner`,+ `${action('AGENT_LABEL_READ')}:all`,+ `${action('AGENT_LABEL_CREATE')}:all`,+ `${action('AGENT_LABEL_UPDATE')}:all`,+ `${action('AGENT_LABEL_DELETE')}:all`,+ // Chat+ `${action('SESSION_READ')}:owner`,+ `${action('SESSION_CREATE')}:owner`,+ `${action('SESSION_UPDATE')}:owner`,+ `${action('SESSION_DELETE')}:owner`,+ `${action('SESSION_GROUP_READ')}:all`,+ `${action('SESSION_GROUP_CREATE')}:all`,+ `${action('SESSION_GROUP_UPDATE')}:all`,+ `${action('SESSION_GROUP_DELETE')}:all`,+ `${action('MESSAGE_READ')}:owner`,+ `${action('MESSAGE_CREATE')}:owner`,+ `${action('MESSAGE_UPDATE')}:owner`,+ `${action('MESSAGE_DELETE')}:owner`,+ `${action('TOPIC_READ')}:owner`,+ `${action('TOPIC_CREATE')}:owner`,+ `${action('TOPIC_UPDATE')}:owner`,+ `${action('TOPIC_DELETE')}:owner`,+ `${action('TOPIC_COMMENT_READ')}:owner`,+ `${action('TOPIC_COMMENT_CREATE')}:owner`,+ `${action('TOPIC_COMMENT_UPDATE')}:owner`,+ `${action('TOPIC_COMMENT_DELETE')}:owner`,+ `${action('TOPIC_COMMENT_RESTORE')}:owner`,+ `${action('TRANSLATION_READ')}:owner`,+ `${action('TRANSLATION_CREATE')}:owner`,+ `${action('TRANSLATION_UPDATE')}:owner`,+ `${action('TRANSLATION_DELETE')}:owner`,+ // Files / knowledge+ `${action('FILE_READ')}:owner`,+ `${action('FILE_UPLOAD')}:owner`,+ `${action('FILE_UPDATE')}:owner`,+ `${action('FILE_DELETE')}:owner`,+ `${action('DOCUMENT_READ')}:owner`,+ `${action('DOCUMENT_CREATE')}:owner`,+ `${action('DOCUMENT_UPDATE')}:owner`,+ `${action('DOCUMENT_DELETE')}:owner`,+ `${action('KNOWLEDGE_BASE_READ')}:owner`,+ `${action('KNOWLEDGE_BASE_CREATE')}:owner`,+ `${action('KNOWLEDGE_BASE_UPDATE')}:owner`,+ `${action('KNOWLEDGE_BASE_DELETE')}:owner`,+ // Model infrastructure (personal provider/model config + invocation)+ `${action('AI_MODEL_READ')}:owner`,+ `${action('AI_MODEL_CREATE')}:owner`,+ `${action('AI_MODEL_UPDATE')}:owner`,+ `${action('AI_MODEL_DELETE')}:owner`,+ `${action('AI_MODEL_INVOKE')}:owner`,+ `${action('AI_PROVIDER_READ')}:owner`,+ `${action('AI_PROVIDER_CREATE')}:owner`,+ `${action('AI_PROVIDER_UPDATE')}:owner`,+ `${action('AI_PROVIDER_DELETE')}:owner`,+ // API keys (personal keys are self-managed)+ `${action('API_KEY_READ')}:owner`,+ `${action('API_KEY_CREATE')}:owner`,+ `${action('API_KEY_UPDATE')}:owner`,+ `${action('API_KEY_DELETE')}:owner`,+ // Own profile+ `${action('USER_READ')}:owner`,+ `${action('USER_UPDATE')}:owner`,+];diff --git a/packages/database/src/models/__tests__/rbac.test.ts b/packages/database/src/models/__tests__/rbac.test.tsindex 93613b5d2b8..f8509aac2a0 100644--- a/packages/database/src/models/__tests__/rbac.test.ts+++ b/packages/database/src/models/__tests__/rbac.test.ts@@ -386,3 +386,52 @@ describe('RbacModel — back-compat: no workspaceId', () => {expect(details[0]).toMatchObject({ permissionCode: code, roleName: 'detail_role' });});});++describe('RbacModel — personal mode implicit baseline (LOBE-12892)', () => {+ it('grants the :owner content baseline to a user with NO rbac_user_roles rows', async () => {+ const rbac = new RbacModel(serverDB, userId);++ expect(await rbac.hasPermission(`${PERMISSION_ACTIONS.AGENT_READ}:owner`)).toBe(true);+ expect(await rbac.hasPermission(`${PERMISSION_ACTIONS.TOPIC_CREATE}:owner`)).toBe(true);+ expect(await rbac.hasPermission(`${PERMISSION_ACTIONS.AI_MODEL_INVOKE}:owner`)).toBe(true);+ // the OpenAPI routes OR the two scopes — the owner half must settle it+ expect(+ await rbac.hasAnyPermission([+ `${PERMISSION_ACTIONS.AGENT_READ}:all`,+ `${PERMISSION_ACTIONS.AGENT_READ}:owner`,+ ]),+ ).toBe(true);+ });++ it('does NOT grant :all widenings or admin domains', async () => {+ const rbac = new RbacModel(serverDB, userId);++ expect(await rbac.hasPermission(`${PERMISSION_ACTIONS.AGENT_READ}:all`)).toBe(false);+ expect(await rbac.hasPermission(`${PERMISSION_ACTIONS.RBAC_ROLE_READ}:all`)).toBe(false);+ expect(await rbac.hasPermission(`${PERMISSION_ACTIONS.USER_CREATE}:all`)).toBe(false);+ expect(await rbac.hasPermission(`${PERMISSION_ACTIONS.WORKSPACE_UPDATE}:all`)).toBe(false);+ });++ it('does NOT leak the personal baseline into workspace mode', async () => {+ // viewer in workspace A: read-only there, regardless of personal defaults+ await addMembership(userId, workspaceAId, 'viewer');+ const rbac = new RbacModel(serverDB, userId);++ expect(+ await rbac.hasAnyPermission(+ [`${PERMISSION_ACTIONS.AGENT_CREATE}:all`, `${PERMISSION_ACTIONS.AGENT_CREATE}:owner`],+ { workspaceId: workspaceAId },+ ),+ ).toBe(false);+ });++ it('getUserPermissions unions the baseline with DB grants', async () => {+ const dbCode = 'test:extra:all';+ await grantGlobalRole(userId, 'extra_role', [dbCode]);+ const rbac = new RbacModel(serverDB, userId);++ const codes = await rbac.getUserPermissions();+ expect(codes).toContain(`${PERMISSION_ACTIONS.AGENT_READ}:owner`);+ expect(codes).toContain(dbCode);+ });+});diff --git a/packages/database/src/models/rbac.ts b/packages/database/src/models/rbac.tsindex 981190a6ab0..7727a050bb5 100644--- a/packages/database/src/models/rbac.ts+++ b/packages/database/src/models/rbac.ts@@ -1,4 +1,7 @@-import { getWorkspaceRolePermissionCodes } from '@lobechat/const/rbac';+import {+ getWorkspaceRolePermissionCodes,+ PERSONAL_DEFAULT_PERMISSIONS,+} from '@lobechat/const/rbac';import { and, eq, inArray, isNull, sql } from 'drizzle-orm';import type { LobeChatDatabase } from '@/database/type';@@ -229,9 +232,15 @@ export class RbacModel {),);+ // Personal mode: every authenticated user implicitly holds the `:owner`+ // baseline over their own data (LOBE-12892) — ordinary accounts have no+ // `rbac_user_roles` rows, and resource queries are `user_id`-isolated+ // anyway. DB grants (super_admin etc.) union on top.// De-dupe — the same code can come from multiple roles (e.g. owner +// member if a user somehow ends up with both).- return [...new Set(result.map((row) => row.permissionCode))];+ return [+ ...new Set([...PERSONAL_DEFAULT_PERMISSIONS, ...result.map((row) => row.permissionCode)]),+ ];};/**@@ -305,6 +314,13 @@ export class RbacModel {return globalMatches.length > 0;}+ // Personal mode: the implicit `:owner` baseline settles most checks with+ // zero DB queries (LOBE-12892). Workspace mode above is untouched — the+ // membership-role matrix stays the single source of truth there.+ if (permissionCodes.some((code) => PERSONAL_DEFAULT_PERMISSIONS.includes(code))) {+ return true;+ }+const result = await this.db.select({ count: sql<number>`count(*)` }).from(userRoles)diff --git a/packages/locales/src/default/auth.ts b/packages/locales/src/default/auth.tsindex 0b38242f22a..93b5cbf0e23 100644--- a/packages/locales/src/default/auth.ts+++ b/packages/locales/src/default/auth.ts@@ -5,6 +5,8 @@ export default {'By selecting "Agree and continue", you confirm that you have read and agree to the <terms>Terms and Conditions</terms> and <privacy>Privacy Policy</privacy>.','agreement.confirm.ok': 'Agree and continue','agreement.confirm.title': 'Terms and Privacy Policy',+ 'apikey.detail.createdAt': 'Created',+ 'apikey.detail.title': 'API Key Details','apikey.display.autoGenerated': 'Auto-generated','apikey.display.copy': 'Copy','apikey.display.copyError': 'Copy failed',@@ -21,6 +23,11 @@ export default {'apikey.form.fields.expiresAt.placeholder': 'Never expires','apikey.form.fields.name.label': 'Name','apikey.form.fields.name.placeholder': 'Please enter API Key name',+ 'apikey.form.fields.scopes.fullAccess': 'Full access',+ 'apikey.form.fields.scopes.fullAccessDescription':+ 'This key can do everything your account can do',+ 'apikey.form.fields.scopes.label': 'Scope',+ 'apikey.form.fields.scopes.required': 'Select at least one scope','apikey.form.submit': 'Create','apikey.form.title': 'Create API Key','apikey.list.actions.create': 'Create API Key',@@ -30,7 +37,6 @@ export default {'apikey.list.actions.deleteConfirm.content': 'Are you sure you want to delete this API Key?','apikey.list.actions.deleteConfirm.title': 'Confirm Action','apikey.list.actions.viewDocs': 'API Docs',- 'apikey.list.columns.actions': 'Actions','apikey.list.columns.creator': 'Creator','apikey.list.columns.expiresAt': 'Expiration Date','apikey.list.columns.key': 'Key',@@ -39,6 +45,21 @@ export default {'apikey.list.columns.status': 'Enabled','apikey.list.empty': 'No API Keys yet','apikey.list.title': 'API Key List',+ 'apikey.scopes.fullAccess': 'Full access',+ 'apikey.scopes.grantJoin': ': ',+ 'apikey.scopes.groups.agent': 'Agents',+ 'apikey.scopes.groups.chat': 'Chat',+ 'apikey.scopes.groups.file': 'Files',+ 'apikey.scopes.groups.knowledge': 'Knowledge',+ 'apikey.scopes.groups.model': 'Models',+ 'apikey.scopes.groups.user': 'User',+ 'apikey.scopes.groups.workspace': 'Workspace',+ 'apikey.scopes.invoke': 'Invoke',+ 'apikey.scopes.modelInvoke': 'Invoke models',+ 'apikey.scopes.none': 'This key has no scopes',+ 'apikey.scopes.read': 'Read',+ 'apikey.scopes.separator': ', ',+ 'apikey.scopes.write': 'Write','apikey.validation.required': 'This field cannot be empty','authModal.description':'Your sign-in session has expired. Please sign in again to continue using cloud sync features.',diff --git a/packages/openapi/src/controllers/provider.controller.ts b/packages/openapi/src/controllers/provider.controller.tsindex d0d2afaf4a6..089183d0b29 100644--- a/packages/openapi/src/controllers/provider.controller.ts+++ b/packages/openapi/src/controllers/provider.controller.ts@@ -1,5 +1,7 @@import type { Context } from 'hono';+import { isFullAccessApiKey } from '@/const/apiKeyScope';+import { BaseController } from '../common/base.controller';import { ProviderService } from '../services/provider.service';import type {@@ -16,6 +18,16 @@ import type {* Provider controller, responsible for handling Provider-related HTTP requests*/export class ProviderController extends BaseController {+ /**+ * Restricted API keys must not exfiltrate decrypted provider credentials+ * through the read endpoints.+ */+ private isRestrictedApiKey(c: Context): boolean {+ if (c.get('authType') !== 'apikey') return false;++ return !isFullAccessApiKey(c.get('apiKeyScopes') as string[] | null | undefined);+ }+async handleGetProviders(c: Context): Promise<Response> {try {const query = this.getQuery<ProviderListQuery>(c);@@ -24,6 +36,13 @@ export class ProviderController extends BaseController {const result = await providerService.getProviders(query);+ if (result?.providers && this.isRestrictedApiKey(c)) {+ result.providers = result.providers.map((provider) => ({+ ...provider,+ keyVaults: undefined,+ }));+ }+return this.success(c, result, 'Provider list retrieved successfully');} catch (error) {return this.handleError(c, error);@@ -39,6 +58,14 @@ export class ProviderController extends BaseController {const providerService = new ProviderService(db, this.getUserId(c), this.getWorkspaceId(c));const provider = await providerService.getProviderDetail(request);+ if (provider && this.isRestrictedApiKey(c)) {+ return this.success(+ c,+ { ...provider, keyVaults: undefined },+ 'Provider details retrieved successfully',+ );+ }+return this.success(c, provider, 'Provider details retrieved successfully');} catch (error) {return this.handleError(c, error);@@ -53,7 +80,11 @@ export class ProviderController extends BaseController {const providerService = new ProviderService(db, this.getUserId(c), this.getWorkspaceId(c));const created = await providerService.createProvider({ ...body, source: 'custom' });- return this.success(c, created, 'Provider created successfully');+ return this.success(+ c,+ created && this.isRestrictedApiKey(c) ? { ...created, keyVaults: undefined } : created,+ 'Provider created successfully',+ );} catch (error) {return this.handleError(c, error);}@@ -73,7 +104,11 @@ export class ProviderController extends BaseController {const providerService = new ProviderService(db, this.getUserId(c), this.getWorkspaceId(c));const updated = await providerService.updateProvider(request);- return this.success(c, updated, 'Provider updated successfully');+ return this.success(+ c,+ updated && this.isRestrictedApiKey(c) ? { ...updated, keyVaults: undefined } : updated,+ 'Provider updated successfully',+ );} catch (error) {return this.handleError(c, error);}diff --git a/packages/openapi/src/middleware/auth.ts b/packages/openapi/src/middleware/auth.tsindex 01cf08a9053..5f8b382fbd3 100644--- a/packages/openapi/src/middleware/auth.ts+++ b/packages/openapi/src/middleware/auth.ts@@ -20,6 +20,7 @@ interface ApiKeyCacheEntry {apiKeyId: string;apiKeyName: string;expiresAt: Date | null;+ scopes: string[] | null;timestamp: number;userId: string;workspaceId?: string | null;@@ -69,6 +70,8 @@ export const userAuthMiddleware = async (c: Context, next: Next) => {let authType: string | null = null;let authData: any = null;let apiKeyWorkspaceId: string | null | undefined;+ // capability scopes of the API key (`null` = full-access key)+ let apiKeyScopes: string[] | null = null;// Try Bearer token authentication - check format first to determine typeif (bearerToken) {@@ -95,6 +98,7 @@ export const userAuthMiddleware = async (c: Context, next: Next) => {authType = 'apikey';authData = { apiKeyId: cachedEntry.apiKeyId, apiKeyName: cachedEntry.apiKeyName };apiKeyWorkspaceId = cachedEntry.workspaceId;+ apiKeyScopes = cachedEntry.scopes;log('API Key authentication successful (from cache), userId: %s, apiKeyId: %d',@@ -138,12 +142,14 @@ export const userAuthMiddleware = async (c: Context, next: Next) => {authType = 'apikey';authData = { apiKeyId: apiKeyRecord.id, apiKeyName: apiKeyRecord.name };apiKeyWorkspaceId = apiKeyRecord.workspaceId;+ apiKeyScopes = apiKeyRecord.scopes ?? null;// Cache the validated API KeyapiKeyCache.set(bearerToken, {apiKeyId: apiKeyRecord.id,apiKeyName: apiKeyRecord.name,expiresAt: apiKeyRecord.expiresAt,+ scopes: apiKeyRecord.scopes ?? null,timestamp: now,userId: apiKeyRecord.userId,workspaceId: apiKeyRecord.workspaceId,@@ -207,6 +213,8 @@ export const userAuthMiddleware = async (c: Context, next: Next) => {c.set('authData', authData);c.set('authorizationHeader', authorizationHeader);c.set('apiKeyWorkspaceId', authType === 'apikey' ? (apiKeyWorkspaceId ?? null) : undefined);+ // `undefined` = not API-key auth; `null` = full-access key+ c.set('apiKeyScopes', authType === 'apikey' ? apiKeyScopes : undefined);log('Authentication successful - userId: %s, authType: %s', userId, authType);} else {diff --git a/packages/openapi/src/middleware/permission-check.test.ts b/packages/openapi/src/middleware/permission-check.test.tsnew file mode 100644index 00000000000..bca081a235c--- /dev/null+++ b/packages/openapi/src/middleware/permission-check.test.ts@@ -0,0 +1,55 @@+import { Hono } from 'hono';+import { describe, expect, it, vi } from 'vitest';++import { requireApiKeyScope } from './permission-check';++// `requireApiKeyScope` never touches the database — stub the db imports pulled+// in by the sibling `requirePermission` middleware to keep this test light+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn() }));+vi.mock('@/database/models/rbac', () => ({ RbacModel: class {} }));++const buildApp = (auth: { authType?: string; scopes?: string[] | null }) => {+ const app = new Hono();++ app.use('*', async (c, next) => {+ if (auth.authType) c.set('authType' as never, auth.authType as never);+ c.set('apiKeyScopes' as never, auth.scopes as never);+ await next();+ });+ app.post('/replies', requireApiKeyScope('model:invoke'), (c) => c.json({ ok: true }));++ return app;+};++describe('requireApiKeyScope', () => {+ it('is a no-op for session/OIDC auth', async () => {+ const app = buildApp({ authType: 'oidc' });++ const res = await app.request('/replies', { method: 'POST' });+ expect(res.status).toBe(200);+ });++ it('lets full-access keys through (legacy NULL and explicit *)', async () => {+ for (const scopes of [null, ['*']]) {+ const app = buildApp({ authType: 'apikey', scopes });++ const res = await app.request('/replies', { method: 'POST' });+ expect(res.status).toBe(200);+ }+ });++ it('rejects restricted keys missing the scope', async () => {+ const app = buildApp({ authType: 'apikey', scopes: ['chat:write'] });++ const res = await app.request('/replies', { method: 'POST' });+ expect(res.status).toBe(403);+ expect(await res.text()).toContain('model:invoke');+ });++ it('allows restricted keys holding the scope', async () => {+ const app = buildApp({ authType: 'apikey', scopes: ['model:invoke'] });++ const res = await app.request('/replies', { method: 'POST' });+ expect(res.status).toBe(200);+ });+});diff --git a/packages/openapi/src/middleware/permission-check.ts b/packages/openapi/src/middleware/permission-check.tsindex 01545c42ab0..0a2009786f8 100644--- a/packages/openapi/src/middleware/permission-check.ts+++ b/packages/openapi/src/middleware/permission-check.ts@@ -2,6 +2,12 @@ import debug from 'debug';import type { Context, Next } from 'hono';import { HTTPException } from 'hono/http-exception';+import type { ApiKeyScope } from '@/const/apiKeyScope';+import {+ hasApiKeyScope,+ isFullAccessApiKey,+ requiredApiKeyScopeForPermission,+} from '@/const/apiKeyScope';import { getServerDB } from '@/database/core/db-adaptor';import { RbacModel } from '@/database/models/rbac';@@ -40,6 +46,40 @@ export interface PermissionCheckOptions {* @param options - Permission check configuration* @returns Hono middleware function*/+/**+ * Enforce the API key's capability scopes against the RBAC permissions a+ * route declares. Effective permission = issuer's RBAC ∩ key scopes: RBAC is+ * checked elsewhere; this narrows API-key-authenticated requests further.+ *+ * No-op for non-API-key auth and for full-access keys. For restricted keys,+ * `operator: 'OR'` needs at least one declared permission whose mapped scope+ * the key holds; `'AND'` needs all of them. Permissions that map to no scope+ * (api_key/rbac/roles) can never be satisfied by a restricted key.+ */+const assertApiKeyScopesAllow = (c: Context, permissionCodes: string[], operator: 'AND' | 'OR') => {+ if (c.get('authType') !== 'apikey') return;++ const scopes = c.get('apiKeyScopes') as string[] | null | undefined;+ if (isFullAccessApiKey(scopes)) return;++ const requiredScopes = permissionCodes.map((code) => requiredApiKeyScopeForPermission(code));+ const satisfies = (scope: ApiKeyScope | null) => !!scope && hasApiKeyScope(scopes, scope);+ const allowed =+ operator === 'AND' ? requiredScopes.every(satisfies) : requiredScopes.some(satisfies);++ if (!allowed) {+ const missing = [...new Set(requiredScopes.filter(Boolean) as string[])];++ throw new HTTPException(403, {+ cause: { missingScopes: missing, requiredPermissions: permissionCodes },+ message:+ missing.length > 0+ ? `insufficient_scope: this API key is missing required scope(s): ${missing.join(', ')}`+ : 'insufficient_scope: this operation is not available to restricted API keys',+ });+ }+};+const requirePermission = (options: PermissionCheckOptions) => {return async (c: Context, next: Next) => {// Development mode bypass if enabled@@ -103,6 +143,9 @@ const requirePermission = (options: PermissionCheckOptions) => {});}+ // RBAC passed — now narrow by the API key's capability scopes+ assertApiKeyScopesAllow(c, permissionCodes, operator);+log('Permission check passed for user %s', userId);// Store permission check result in context for potential use in handlers@@ -169,3 +212,24 @@ export const requireAnyPermission = (permissionCodes: string[], errorMessage?: spermissions: permissionCodes,});};++/**+ * Standalone API key scope gate for routes that declare no RBAC permissions+ * (e.g. `POST /responses`). No-op for session/OIDC auth and full-access keys;+ * restricted keys must hold the given scope.+ */+export const requireApiKeyScope = (scope: ApiKeyScope) => {+ return async (c: Context, next: Next) => {+ if (c.get('authType') !== 'apikey') return next();++ const scopes = c.get('apiKeyScopes') as string[] | null | undefined;+ if (!isFullAccessApiKey(scopes) && !hasApiKeyScope(scopes, scope)) {+ throw new HTTPException(403, {+ cause: { missingScopes: [scope] },+ message: `insufficient_scope: this API key is missing required scope '${scope}'`,+ });+ }++ return next();+ };+};diff --git a/packages/openapi/src/routes/message-translations.route.ts b/packages/openapi/src/routes/message-translations.route.tsindex 9b0803c36b2..9a3cb6b5350 100644--- a/packages/openapi/src/routes/message-translations.route.ts+++ b/packages/openapi/src/routes/message-translations.route.ts@@ -5,7 +5,7 @@ import { getAllScopePermissions } from '@/utils/rbac';import { zValidator } from '../common/validator';import { MessageTranslationController } from '../controllers';import { requireAuth } from '../middleware';-import { requireAnyPermission } from '../middleware/permission-check';+import { requireAnyPermission, requireApiKeyScope } from '../middleware/permission-check';import {MessageTranslateInfoUpdateSchema,MessageTranslateQueryRequestSchema,@@ -27,6 +27,8 @@ MessageTranslationRoutes.post(getAllScopePermissions('TRANSLATION_CREATE'),'You do not have permission to translate message',),+ // Translation invokes a model, so restricted API keys also need `model:invoke`+ requireApiKeyScope('model:invoke'),zValidator('param', MessageTranslateQueryRequestSchema),zValidator('json', MessageTranslateTriggerRequestSchema),(c) => {diff --git a/packages/openapi/src/routes/messages.route.ts b/packages/openapi/src/routes/messages.route.tsindex 0aa31652554..18323a41615 100644--- a/packages/openapi/src/routes/messages.route.ts+++ b/packages/openapi/src/routes/messages.route.ts@@ -5,7 +5,7 @@ import { getAllScopePermissions } from '@/utils/rbac';import { zValidator } from '../common/validator';import { MessageController } from '../controllers';import { requireAuth } from '../middleware';-import { requireAnyPermission } from '../middleware/permission-check';+import { requireAnyPermission, requireApiKeyScope } from '../middleware/permission-check';import {MessageIdParamSchema,MessagesCountQuerySchema,@@ -80,6 +80,7 @@ MessageRoutes.post();// POST /api/v1/messages/replies - Create a user message and generate an AI reply (requires message write permission)+// Generating the reply invokes a model, so restricted API keys also need `model:invoke`MessageRoutes.post('/replies',requireAuth,@@ -87,6 +88,7 @@ MessageRoutes.post(getAllScopePermissions('MESSAGE_CREATE'),'You do not have permission to create messages',),+ requireApiKeyScope('model:invoke'),zValidator('json', MessagesCreateWithReplyRequestSchema),(c) => {const controller = new MessageController();diff --git a/packages/openapi/src/routes/responses.route.ts b/packages/openapi/src/routes/responses.route.tsindex 59736c5bf7d..31e771506cb 100644--- a/packages/openapi/src/routes/responses.route.ts+++ b/packages/openapi/src/routes/responses.route.ts@@ -3,6 +3,7 @@ import { Hono } from 'hono';import { zValidator } from '../common/validator';import { ResponsesController } from '../controllers/responses.controller';import { requireAuth } from '../middleware/auth';+import { requireApiKeyScope } from '../middleware/permission-check';import { CreateResponseRequestSchema } from '../types/responses.type';const ResponsesRoutes = new Hono();@@ -10,10 +11,18 @@ const ResponsesRoutes = new Hono();/*** POST /api/v1/responses* Create a model response (OpenResponses protocol)+ *+ * Burns model quota AND runs through `AiAgentService.execAgent` (the request+ * `model` is an agent id), persisting topic/message state — so restricted+ * keys need the same `agent:write` + `chat:write` + `model:invoke` trio as+ * the tRPC agent-run entries.*/ResponsesRoutes.post('/',requireAuth,+ requireApiKeyScope('model:invoke'),+ requireApiKeyScope('chat:write'),+ requireApiKeyScope('agent:write'),zValidator('json', CreateResponseRequestSchema),async (c) => {const controller = new ResponsesController();diff --git a/packages/openapi/src/routes/users.route.ts b/packages/openapi/src/routes/users.route.tsindex fb79961c82e..82338d8a4b5 100644--- a/packages/openapi/src/routes/users.route.ts+++ b/packages/openapi/src/routes/users.route.ts@@ -6,7 +6,7 @@ import { getAllScopePermissions, getScopePermissions } from '@/utils/rbac';import { zValidator } from '../common/validator';import { UserController } from '../controllers';import { requireAuth } from '../middleware/auth';-import { requireAnyPermission } from '../middleware/permission-check';+import { requireAnyPermission, requireApiKeyScope } from '../middleware/permission-check';import {CreateUserRequestSchema,UpdateUserRequestSchema,@@ -26,6 +26,8 @@ UserRoutes.get('/me',describeRoute({ summary: 'Get current authenticated user', tags: ['users'] }),requireAuth,+ // no RBAC permission, but restricted API keys still need the user domain+ requireApiKeyScope('user:read'),async (c) => {const userController = new UserController();return await userController.getCurrentUser(c);diff --git a/packages/openapi/vitest.config.mts b/packages/openapi/vitest.config.mtsindex 654fb308627..7f44f70f149 100644--- a/packages/openapi/vitest.config.mts+++ b/packages/openapi/vitest.config.mts@@ -5,6 +5,9 @@ import { defineConfig } from 'vitest/config';export default defineConfig({resolve: {alias: {+ // mirror the root tsconfig paths: package sources first, app src as fallback+ '@/const/': resolve(__dirname, '../const/src') + '/',+ '@/database/': resolve(__dirname, '../database/src') + '/','@/': resolve(__dirname, '../../src') + '/',},},diff --git a/packages/trpc/src/lambda/context.ts b/packages/trpc/src/lambda/context.tsindex 683454ee86e..7d0a5bd0c77 100644--- a/packages/trpc/src/lambda/context.ts+++ b/packages/trpc/src/lambda/context.ts@@ -35,6 +35,7 @@ const extractClientIp = (request: NextRequest): string | undefined => {};interface ValidatedApiKey {+ scopes: string[] | null;userId: string;workspaceId: string | null;}@@ -60,7 +61,11 @@ const validateApiKey = async (apiKey: string): Promise<ValidatedApiKey | null> =console.error('Failed to update API key last used timestamp:', error);});- return { userId: apiKeyRecord.userId, workspaceId: apiKeyRecord.workspaceId ?? null };+ return {+ scopes: apiKeyRecord.scopes ?? null,+ userId: apiKeyRecord.userId,+ workspaceId: apiKeyRecord.workspaceId ?? null,+ };} catch (error) {log('API key authentication failed: %O', error);console.error('API key authentication failed, trying other methods:', error);@@ -78,6 +83,12 @@ export interface OIDCAuth {}export interface AuthContext {+ /**+ * Set only when the request authenticated via an API key: the key's+ * capability scopes (`null` = full-access key). `undefined` means the+ * request used another auth method and scope enforcement does not apply.+ */+ apiKeyScopes?: string[] | null;clientIp?: string | null;clientMetadata?: ClientMetadata;jwtPayload?: ClientSecretPayload | null;@@ -97,6 +108,7 @@ export interface AuthContext {* This is useful for testing when we don't want to mock Next.js' request/response*/export const createContextInner = async (params?: {+ apiKeyScopes?: string[] | null;clientMetadata?: ClientMetadata;clientIp?: string | null;marketAccessToken?: string;@@ -111,6 +123,7 @@ export const createContextInner = async (params?: {const responseHeaders = new Headers();return {+ apiKeyScopes: params?.apiKeyScopes,clientMetadata: params?.clientMetadata || { type: 'unknown' },clientIp: params?.clientIp,marketAccessToken: params?.marketAccessToken,@@ -249,6 +262,7 @@ export const createLambdaContext = async (request: NextRequest): Promise<LambdaCreturn createContextInner({...commonContext,+ apiKeyScopes: apiKeyAuth.scopes,traceContext,userId: apiKeyAuth.userId,workspaceId: apiKeyAuth.workspaceId ?? undefined,diff --git a/packages/trpc/src/lambda/index.ts b/packages/trpc/src/lambda/index.tsindex 6d03786ce4d..4ecb07afea1 100644--- a/packages/trpc/src/lambda/index.ts+++ b/packages/trpc/src/lambda/index.ts@@ -11,6 +11,7 @@import { openTelemetry } from '../middleware/openTelemetry';import { userAuth } from '../middleware/userAuth';import { trpc } from './init';+import { apiKeyScopeGuard } from './middleware/apiKeyScope';import { heteroOperationAuth } from './middleware/heteroOperationAuth';import { oidcAuth } from './middleware/oidcAuth';@@ -26,10 +27,16 @@ export const router = trpc.router;**/const baseProcedure = trpc.procedure.use(openTelemetry);-export const publicProcedure = baseProcedure;+// `apiKeyScopeGuard` also covers public procedures: `createLambdaContext`+// authenticates an `X-API-Key` before procedure selection, and several public+// procedures serve authenticated data off `ctx.userId`. The guard is a no-op+// without API-key auth, so anonymous access is untouched.+export const publicProcedure = baseProcedure.use(apiKeyScopeGuard);// procedure that asserts that the user is logged in-export const authedProcedure = baseProcedure.use(oidcAuth).use(userAuth);+// `apiKeyScopeGuard` narrows API-key-authenticated calls to the key's scopes;+// session/OIDC auth and full-access keys pass through untouched.+export const authedProcedure = baseProcedure.use(oidcAuth).use(userAuth).use(apiKeyScopeGuard);// procedure for hetero-agent ingest/finish endpoints — requires a `hetero-operation` JWTexport const heteroAuthedProcedure = baseProcedure.use(heteroOperationAuth).use(userAuth);diff --git a/packages/trpc/src/lambda/middleware/__tests__/apiKeyScope.test.ts b/packages/trpc/src/lambda/middleware/__tests__/apiKeyScope.test.tsnew file mode 100644index 00000000000..bbb601e5e84--- /dev/null+++ b/packages/trpc/src/lambda/middleware/__tests__/apiKeyScope.test.ts@@ -0,0 +1,150 @@+import { describe, expect, it } from 'vitest';++import { createCallerFactory, publicProcedure } from '@/libs/trpc/lambda';+import { trpc } from '@/libs/trpc/lambda/init';++import { apiKeyScopeGuard } from '../apiKeyScope';++// Routers whose namespaces map to real catalog rules — the guard derives the+// required scope from `path`, so the namespaces here must exist in+// TRPC_NAMESPACE_API_KEY_RULES.+const guarded = trpc.procedure.use(apiKeyScopeGuard);++const testRouter = trpc.router({+ agent: trpc.router({+ createAgent: guarded.mutation(() => 'created'),+ getAgents: guarded.query(() => 'agents'),+ }),+ agentDocument: trpc.router({+ // carries a procedure-level extra scope (model:invoke) on top of knowledge:write+ generateSkillMeta: guarded.mutation(() => 'meta'),+ }),+ aiChat: trpc.router({+ sendMessage: guarded.mutation(() => 'sent'),+ }),+ apiKey: trpc.router({+ createApiKey: guarded.mutation(() => 'minted'),+ }),+ healthcheck: guarded.query(() => 'ok'),+ // public procedures can still serve authenticated data off ctx.userId, so+ // the real `publicProcedure` must carry the guard as well+ message: trpc.router({+ getMessages: publicProcedure.query(() => 'messages'),+ }),+ unknownNamespace: trpc.router({+ doThing: guarded.mutation(() => 'done'),+ }),+});++const createCaller = createCallerFactory(testRouter);++describe('apiKeyScopeGuard', () => {+ describe('non-API-key auth', () => {+ it('is untouched by the guard', async () => {+ const caller = createCaller({ userId: 'user-1' } as any);++ await expect(caller.agent.createAgent()).resolves.toBe('created');+ await expect(caller.apiKey.createApiKey()).resolves.toBe('minted');+ });+ });++ describe('full-access keys', () => {+ it('legacy NULL scopes pass everywhere', async () => {+ const caller = createCaller({ apiKeyScopes: null, userId: 'user-1' } as any);++ await expect(caller.agent.createAgent()).resolves.toBe('created');+ await expect(caller.apiKey.createApiKey()).resolves.toBe('minted');+ });++ it("explicit ['*'] passes everywhere", async () => {+ const caller = createCaller({ apiKeyScopes: ['*'], userId: 'user-1' } as any);++ await expect(caller.aiChat.sendMessage()).resolves.toBe('sent');+ });+ });++ describe('restricted keys', () => {+ it('allows operations whose scope the key holds', async () => {+ const caller = createCaller({ apiKeyScopes: ['agent:write'], userId: 'user-1' } as any);++ await expect(caller.agent.createAgent()).resolves.toBe('created');+ // write implies read+ await expect(caller.agent.getAgents()).resolves.toBe('agents');+ });++ it('rejects operations whose scope is missing', async () => {+ const caller = createCaller({ apiKeyScopes: ['agent:read'], userId: 'user-1' } as any);++ await expect(caller.agent.createAgent()).rejects.toMatchObject({+ code: 'FORBIDDEN',+ message: expect.stringContaining('agent:write'),+ });+ });++ it('rejects money-burning calls without model:invoke', async () => {+ const caller = createCaller({ apiKeyScopes: ['chat:write'], userId: 'user-1' } as any);++ await expect(caller.aiChat.sendMessage()).rejects.toMatchObject({ code: 'FORBIDDEN' });+ });++ it('always rejects blocked namespaces (key minting)', async () => {+ const caller = createCaller({+ apiKeyScopes: [...(['agent:write', 'chat:write', 'model:invoke'] as string[])],+ userId: 'user-1',+ } as any);++ await expect(caller.apiKey.createApiKey()).rejects.toMatchObject({ code: 'FORBIDDEN' });+ });++ it('fails closed on unregistered namespaces', async () => {+ const caller = createCaller({ apiKeyScopes: ['agent:write'], userId: 'user-1' } as any);++ await expect(caller.unknownNamespace.doThing()).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ });++ it('requires procedure-level extra scopes on top of the namespace scope', async () => {+ const withoutInvoke = createCaller({ apiKeyScopes: ['knowledge:write'], userId: 'u' } as any);+ await expect(withoutInvoke.agentDocument.generateSkillMeta()).rejects.toMatchObject({+ code: 'FORBIDDEN',+ message: expect.stringContaining('model:invoke'),+ });++ const withBoth = createCaller({+ apiKeyScopes: ['knowledge:write', 'model:invoke'],+ userId: 'u',+ } as any);+ await expect(withBoth.agentDocument.generateSkillMeta()).resolves.toBe('meta');+ });++ it('keeps bootstrap namespaces open', async () => {+ const caller = createCaller({ apiKeyScopes: ['agent:read'], userId: 'user-1' } as any);++ await expect(caller.healthcheck()).resolves.toBe('ok');+ });+ });++ describe('publicProcedure', () => {+ it('anonymous access is untouched', async () => {+ const caller = createCaller({} as any);++ await expect(caller.message.getMessages()).resolves.toBe('messages');+ });++ it('enforces scopes for API-key-authenticated calls', async () => {+ const caller = createCaller({ apiKeyScopes: ['agent:read'], userId: 'user-1' } as any);++ await expect(caller.message.getMessages()).rejects.toMatchObject({+ code: 'FORBIDDEN',+ message: expect.stringContaining('chat:read'),+ });+ });++ it('allows API-key calls holding the required scope', async () => {+ const caller = createCaller({ apiKeyScopes: ['chat:read'], userId: 'user-1' } as any);++ await expect(caller.message.getMessages()).resolves.toBe('messages');+ });+ });+});diff --git a/packages/trpc/src/lambda/middleware/apiKeyScope.ts b/packages/trpc/src/lambda/middleware/apiKeyScope.tsnew file mode 100644index 00000000000..55a2e15a509--- /dev/null+++ b/packages/trpc/src/lambda/middleware/apiKeyScope.ts@@ -0,0 +1,49 @@+import {+ hasApiKeyScope,+ isFullAccessApiKey,+ requiredApiKeyScopeForTrpc,+} from '@lobechat/const/apiKeyScope';+import { TRPCError } from '@trpc/server';++import { trpc } from '../init';++/**+ * Global capability-scope guard for API-key-authenticated requests.+ *+ * Applies to every `authedProcedure` without touching individual routers: the+ * required scope is derived from the router namespace + operation type via+ * `TRPC_NAMESPACE_API_KEY_RULES`.+ *+ * - Session / OIDC auth (`ctx.apiKeyScopes === undefined`) → untouched.+ * - Full-access keys (legacy `NULL` scopes, or `['*']`) → untouched.+ * - Restricted keys → the namespace must be registered and grant a scope the+ * key holds; unknown namespaces are denied (fail closed), so newly added+ * routers are never silently exposed to restricted keys.+ */+export const apiKeyScopeGuard = trpc.middleware(async ({ ctx, path, type, next }) => {+ const scopes = ctx.apiKeyScopes;++ // not API-key auth, or a full-access key: scope enforcement does not apply+ if (scopes === undefined || isFullAccessApiKey(scopes)) return next();++ const decision = requiredApiKeyScopeForTrpc(path, type);++ if ('open' in decision) return next();++ if ('blocked' in decision) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: `This API key cannot access '${path}': the operation is not available to restricted API keys.`,+ });+ }++ const missing = decision.scopes.filter((scope) => !hasApiKeyScope(scopes, scope));+ if (missing.length > 0) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: `This API key cannot access '${path}': missing required scope '${missing.join("', '")}'.`,+ });+ }++ return next();+});diff --git a/packages/types/src/apiKey.ts b/packages/types/src/apiKey.tsindex 6f9d00117dd..df8814c0668 100644--- a/packages/types/src/apiKey.ts+++ b/packages/types/src/apiKey.ts@@ -16,6 +16,10 @@ export interface ApiKeyItem {keyDecryptionFailed?: boolean;lastUsedAt?: Date | null;name: string;+ // Capability scopes. `null`/absent = full access (legacy keys), `['*']` =+ // explicit full access, otherwise a restricted scope list. Immutable after+ // creation — re-issue the key to change its powers.+ scopes?: string[] | null;updatedAt: Date;userId: string;}@@ -23,6 +27,7 @@ export interface ApiKeyItem {export interface CreateApiKeyParams {expiresAt?: Date | null;name: string;+ scopes?: string[] | null;}export interface UpdateApiKeyParams {diff --git a/src/components/LiteTable/index.tsx b/src/components/LiteTable/index.tsxindex 5afc6c367b1..f470572e2b8 100644--- a/src/components/LiteTable/index.tsx+++ b/src/components/LiteTable/index.tsx@@ -12,6 +12,14 @@ const styles = createStaticStyles(({ css, cssVar }) => ({body: css`overflow-x: auto;`,+ clickableRow: css`+ cursor: pointer;++ &:focus-visible {+ outline: 2px solid ${cssVar.colorPrimary};+ outline-offset: -2px;+ }+ `,container: css`container-type: inline-size;`,@@ -146,6 +154,11 @@ export interface LiteTableProps<RecordType> {dataSource?: RecordType[];emptyText?: ReactNode;loading?: boolean;+ /**+ * Makes every data row clickable. Interactive cell content (buttons,+ * switches, editable cells) must stopPropagation to keep working.+ */+ onRowClick?: (record: RecordType) => void;rowKey: (record: RecordType) => string;}@@ -155,6 +168,7 @@ const LiteTableInner = <RecordType,>({dataSource,emptyText,loading,+ onRowClick,rowKey,}: LiteTableProps<RecordType>) => {const items = dataSource ?? [];@@ -203,7 +217,24 @@ const LiteTableInner = <RecordType,>({</tr>)): items.map((record, index) => (- <tr key={rowKey(record)}>+ <tr+ className={onRowClick ? styles.clickableRow : undefined}+ key={rowKey(record)}+ tabIndex={onRowClick ? 0 : undefined}+ onClick={onRowClick ? () => onRowClick(record) : undefined}+ onKeyDown={+ onRowClick+ ? (event) => {+ // only the row itself — a key pressed inside a cell+ // control (switch, button, input) belongs to it+ if (event.target !== event.currentTarget) return;+ if (event.key !== 'Enter' && event.key !== ' ') return;+ event.preventDefault();+ onRowClick(record);+ }+ : undefined+ }+ >{columns.map((column) => (<tddata-label={listLabelOf(column)}diff --git a/src/features/Settings/apikey/features/ApiKey.test.tsx b/src/features/Settings/apikey/features/ApiKey.test.tsxindex 28d4de335a8..71dd6568c45 100644--- a/src/features/Settings/apikey/features/ApiKey.test.tsx+++ b/src/features/Settings/apikey/features/ApiKey.test.tsx@@ -34,6 +34,26 @@ vi.mock('@lobehub/ui/base-ui', () => {Button: ({ children, ...props }: ButtonHTMLAttributes<HTMLButtonElement>) => (<button {...props}>{children}</button>),+ Drawer: ({+ children,+ onClose,+ open,+ title,+ }: {+ children?: ReactNode;+ onClose?: () => void;+ open?: boolean;+ title?: ReactNode;+ }) =>+ open ? (+ <div role="dialog">+ <div>{title}</div>+ <button type="button" onClick={onClose}>+ close-drawer+ </button>+ {children}+ </div>+ ) : null,Switch: ({checked,disabled,@@ -145,6 +165,11 @@ beforeEach(() => {hoisted.trpc.deleteApiKey.mockResolvedValue({});});+const openDetail = async (name: string) => {+ fireEvent.click(screen.getByText(name).closest('tr')!);+ return screen.findByRole('dialog');+};+describe('ApiKey', () => {it('shows loading, then empty state when the first fetch returns no keys', async () => {let resolveList!: (items: ApiKeyItem[]) => void;@@ -170,7 +195,8 @@ describe('ApiKey', () => {expect(await screen.findByText('My Key')).toBeInTheDocument();expect(screen.getByText('lb-plain-secret')).toBeInTheDocument();- expect(screen.getByRole('switch')).toBeChecked();+ // management controls live in the drawer, not on the row+ expect(screen.queryByRole('switch')).toBeNull();});it('creates a key through the modal and refreshes the list', async () => {@@ -194,7 +220,8 @@ describe('ApiKey', () => {renderPage();await screen.findByText('My Key');- fireEvent.click(screen.getByRole('button', { name: 'edit-text' }));+ const dialog = await openDetail('My Key');+ fireEvent.click(within(dialog).getByRole('button', { name: 'edit-text' }));await waitFor(() =>expect(hoisted.trpc.updateApiKey).toHaveBeenCalledWith({@@ -205,11 +232,12 @@ describe('ApiKey', () => {await waitFor(() => expect(hoisted.trpc.getApiKeys).toHaveBeenCalledTimes(2));});- it('toggles a key off and refreshes the list', async () => {+ it('toggles a key off from the detail drawer and refreshes the list', async () => {renderPage();await screen.findByText('My Key');- fireEvent.click(screen.getByRole('switch'));+ const dialog = await openDetail('My Key');+ fireEvent.click(within(dialog).getByRole('switch'));await waitFor(() =>expect(hoisted.trpc.updateApiKey).toHaveBeenCalledWith({@@ -220,11 +248,12 @@ describe('ApiKey', () => {await waitFor(() => expect(hoisted.trpc.getApiKeys).toHaveBeenCalledTimes(2));});- it('deletes a key after Popconfirm confirmation and refreshes the list', async () => {+ it('deletes a key from the detail drawer after Popconfirm confirmation', async () => {renderPage();await screen.findByText('My Key');- fireEvent.click(screen.getByRole('button', { name: 'apikey.list.actions.delete' }));+ const dialog = await openDetail('My Key');+ fireEvent.click(within(dialog).getByRole('button', { name: 'apikey.list.actions.delete' }));await screen.findByText('apikey.list.actions.deleteConfirm.title');fireEvent.click(@@ -240,7 +269,8 @@ describe('ApiKey', () => {renderPage();await screen.findByText('My Key');- fireEvent.click(screen.getByRole('switch'));+ const dialog = await openDetail('My Key');+ fireEvent.click(within(dialog).getByRole('switch'));await waitFor(() => expect(hoisted.toast.error).toHaveBeenCalledWith('manageOnlyCreator'));expect(hoisted.trpc.getApiKeys).toHaveBeenCalledTimes(1);@@ -251,7 +281,8 @@ describe('ApiKey', () => {renderPage();await screen.findByText('My Key');- fireEvent.click(screen.getByRole('switch'));+ const dialog = await openDetail('My Key');+ fireEvent.click(within(dialog).getByRole('switch'));await waitFor(() => expect(hoisted.toast.error).toHaveBeenCalledWith('operationFailed'));expect(hoisted.trpc.getApiKeys).toHaveBeenCalledTimes(1);@@ -264,10 +295,15 @@ describe('ApiKey', () => {await screen.findByText('My Key');expect(screen.getByRole('button', { name: 'apikey.list.actions.create' })).toBeDisabled();- expect(screen.getByRole('button', { name: 'edit-text' })).toBeDisabled();- expect(screen.getByRole('button', { name: 'edit-date' })).toBeDisabled();- expect(screen.getByRole('switch')).toBeDisabled();- expect(screen.getByRole('button', { name: 'no-permission' })).toBeDisabled();++ // the drawer carries the whole management surface, so it must be gated+ const dialog = await openDetail('My Key');+ expect(within(dialog).getByRole('button', { name: 'edit-text' })).toBeDisabled();+ expect(within(dialog).getByRole('button', { name: 'edit-date' })).toBeDisabled();+ expect(within(dialog).getByRole('switch')).toBeDisabled();+ expect(+ within(dialog).getByRole('button', { name: 'apikey.list.actions.delete' }),+ ).toBeDisabled();});it('allows a workspace admin to manage another member key while keeping its secret masked', async () => {@@ -280,17 +316,20 @@ describe('ApiKey', () => {await screen.findByText('Other Key');const otherRow = screen.getByText('Other Key').closest('tr')!;- expect(within(otherRow).getByText(`lb-${'*'.repeat(12)}`)).toBeInTheDocument();- expect(within(otherRow).getByRole('button', { name: 'edit-text' })).toBeEnabled();- expect(within(otherRow).getByRole('switch')).toBeEnabled();+ expect(within(otherRow).getByText(`sk-lh-${'*'.repeat(12)}`)).toBeInTheDocument();++ // an admin can manage another member's key from its drawer+ const dialog = await openDetail('Other Key');+ expect(within(dialog).getByRole('button', { name: 'edit-text' })).toBeEnabled();+ expect(within(dialog).getByRole('switch')).toBeEnabled();expect(- within(otherRow).getByRole('button', { name: 'apikey.list.actions.delete' }),+ within(dialog).getByRole('button', { name: 'apikey.list.actions.delete' }),).toBeEnabled();+ // ...but its secret stays masked there too+ expect(within(dialog).getByText(`sk-lh-${'*'.repeat(12)}`)).toBeInTheDocument();const mineRow = screen.getByText('My Key').closest('tr')!;expect(within(mineRow).getByText('lb-plain-secret')).toBeInTheDocument();- expect(within(mineRow).getByRole('button', { name: 'edit-text' })).toBeEnabled();- expect(within(mineRow).getByRole('switch')).toBeEnabled();});it('disables create and row actions for workspace members without settings permission', async () => {@@ -300,10 +339,13 @@ describe('ApiKey', () => {await screen.findByText('My Key');expect(screen.getByRole('button', { name: 'apikey.list.actions.create' })).toBeDisabled();- expect(screen.getByRole('button', { name: 'edit-text' })).toBeDisabled();- expect(screen.getByRole('button', { name: 'edit-date' })).toBeDisabled();- expect(screen.getByRole('switch')).toBeDisabled();- expect(screen.getByRole('button', { name: 'manageOnlyCreator' })).toBeDisabled();++ const dialog = await openDetail('My Key');+ expect(within(dialog).getByRole('button', { name: 'edit-text' })).toBeDisabled();+ expect(within(dialog).getByRole('switch')).toBeDisabled();+ expect(+ within(dialog).getByRole('button', { name: 'apikey.list.actions.delete' }),+ ).toBeDisabled();});it('shows the unavailable copy with tooltip when key decryption failed', async () => {@@ -333,4 +375,83 @@ describe('ApiKey', () => {expect(screen.queryByRole('columnheader', { name: 'apikey.list.columns.creator' })).toBeNull();});++ it('keeps scopes out of the list — they live in the detail drawer', async () => {+ hoisted.trpc.getApiKeys.mockResolvedValue([makeItem({ scopes: ['agent:read'] })]);+ renderPage();+ await screen.findByText('My Key');++ expect(screen.queryByRole('columnheader', { name: 'apikey.list.columns.scopes' })).toBeNull();+ expect(screen.getByText('My Key').closest('tr')!.textContent).not.toContain(+ 'apikey.scopes.groups.agent',+ );+ });++ it('opens the detail drawer on row click listing only the granted scopes', async () => {+ hoisted.trpc.getApiKeys.mockResolvedValue([+ makeItem({ scopes: ['model:read', 'model:invoke', 'agent:read'] }),+ ]);+ renderPage();+ await screen.findByText('My Key');++ fireEvent.click(screen.getByText('My Key').closest('tr')!);++ const dialog = await screen.findByRole('dialog');+ expect(within(dialog).getByText('apikey.detail.title')).toBeInTheDocument();+ // one row per granted domain, actions collapsed — ungranted domains absent+ expect(within(dialog).getByText('apikey.scopes.groups.agent')).toBeInTheDocument();+ expect(within(dialog).getByText('apikey.scopes.groups.model')).toBeInTheDocument();+ expect(within(dialog).queryByText('apikey.scopes.groups.chat')).toBeNull();+ expect(within(dialog).queryByText('apikey.scopes.groups.file')).toBeNull();+ // the model row collapses read + invoke onto one line (the `t` mock echoes+ // keys, so the join/separator appear as their key names)+ expect(dialog.textContent).toContain(+ [+ 'apikey.scopes.groups.model',+ 'apikey.scopes.grantJoin',+ 'apikey.scopes.read',+ 'apikey.scopes.separator',+ 'apikey.scopes.invoke',+ ].join(''),+ );+ // read-only: no editable scope controls in the detail view+ expect(within(dialog).queryAllByRole('checkbox')).toHaveLength(0);+ });++ it('shows the full-access copy instead of the grant list for a full-access key', async () => {+ renderPage();+ await screen.findByText('My Key');++ fireEvent.click(screen.getByText('My Key').closest('tr')!);++ const dialog = await screen.findByRole('dialog');+ expect(within(dialog).getByText('apikey.scopes.fullAccess')).toBeInTheDocument();+ expect(within(dialog).queryByText('apikey.scopes.groups.agent')).toBeNull();+ });++ it('does not open the drawer when clicking inside the key cell', async () => {+ renderPage();+ await screen.findByText('My Key');++ // the key cell keeps its own reveal/copy controls, so it must not navigate+ fireEvent.click(screen.getByText('lb-plain-secret'));++ expect(screen.queryByRole('dialog')).toBeNull();+ });++ it('deletes from the drawer and closes it', async () => {+ renderPage();+ await screen.findByText('My Key');++ const dialog = await openDetail('My Key');++ fireEvent.click(within(dialog).getByRole('button', { name: 'apikey.list.actions.delete' }));+ await screen.findByText('apikey.list.actions.deleteConfirm.title');+ fireEvent.click(+ screen.getByRole('button', { name: 'apikey.list.actions.deleteConfirm.actions.ok' }),+ );++ await waitFor(() => expect(hoisted.trpc.deleteApiKey).toHaveBeenCalledWith({ id: 'key-1' }));+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());+ });});diff --git a/src/features/Settings/apikey/features/ApiKey.tsx b/src/features/Settings/apikey/features/ApiKey.tsxindex b1dfaf9934b..9e5f852b6c4 100644--- a/src/features/Settings/apikey/features/ApiKey.tsx+++ b/src/features/Settings/apikey/features/ApiKey.tsx@@ -2,12 +2,11 @@import { isDesktop } from '@lobechat/const';import { Center, Empty, Flexbox, Text } from '@lobehub/ui';-import { Button, Switch, toast } from '@lobehub/ui/base-ui';+import { Button, toast } from '@lobehub/ui/base-ui';import { useMutation } from '@tanstack/react-query';-import { Popconfirm } from 'antd';import { createStaticStyles } from 'antd-style';-import { BookOpen, Trash } from 'lucide-react';-import { type FC } from 'react';+import { BookOpen, ChevronRight } from 'lucide-react';+import { type FC, useState } from 'react';import { useTranslation } from 'react-i18next';import urlJoin from 'url-join';@@ -23,7 +22,8 @@ import { electronSyncSelectors } from '@/store/electron/selectors';import { type ApiKeyItem, type CreateApiKeyParams, type UpdateApiKeyParams } from '@/types/apiKey';import { isForbiddenError } from '@/utils/forbiddenError';-import { ApiKeyDisplay, createApiKeyModal, EditableCell } from './index';+import ApiKeyDetail from './ApiKeyDetail';+import { ApiKeyDisplay, createApiKeyModal } from './index';const styles = createStaticStyles(({ css, cssVar }) => ({container: css`@@ -32,6 +32,17 @@ const styles = createStaticStyles(({ css, cssVar }) => ({border-radius: ${cssVar.borderRadius};background: ${cssVar.colorBgContainer};`,+ /* Always visible, not reveal-on-hover: the row's only job besides browsing is+ to lead into the detail drawer, and a marker you must hover to discover+ doesn't advertise that. Quiet by default, darker under the cursor. */+ enterIcon: css`+ color: ${cssVar.colorTextQuaternary};+ transition: color 0.2s ease;++ tr:hover & {+ color: ${cssVar.colorText};+ }+ `,header: css`display: flex;gap: 16px;@@ -41,6 +52,14 @@ const styles = createStaticStyles(({ css, cssVar }) => ({padding-block-end: 16px;padding-inline: 24px;`,+ /* The name doubles as the entry point into the detail drawer. */+ nameLink: css`+ font-weight: 500;++ tr:hover & {+ color: ${cssVar.colorLink};+ }+ `,}));const ApiKey: FC = () => {@@ -70,6 +89,11 @@ const ApiKey: FC = () => {lambdaClient.apiKey.getApiKeys.query(),);+ // Detail drawer holds only the id; the item is re-derived from SWR data so+ // in-drawer edits (rename / toggle) reflect immediately after revalidation.+ const [detailId, setDetailId] = useState<string>();+ const detailApiKey = detailId ? data?.find((item) => item.id === detailId) : undefined;+const notifyMutationError = (error: unknown) => {toast.error(isForbiddenError(error)@@ -115,46 +139,33 @@ const ApiKey: FC = () => {{key: 'name',listSlot: 'title',- render: (apiKey) => {- const canManage = checkManageable(apiKey.userId);- return (- <span title={canManage ? undefined : manageTooltip}>- <EditableCell- disabled={!canEdit || !canManage}- placeholder={t('apikey.display.enterPlaceholder')}- type="text"- value={apiKey.name}- onSubmit={(name) => {- if (!canEdit || !canManage) return;- if (!name || name === apiKey.name) {- return;- }-- updateMutation.mutate({ id: apiKey.id!, params: { name: name as string } });- }}- />- </span>- );- },+ // The name is the affordance into the detail drawer — styled as a link so+ // the row reads as navigable rather than inert.+ render: (apiKey) => <span className={styles.nameLink}>{apiKey.name}</span>,title: t('apikey.list.columns.name'),},{key: 'key',- render: (apiKey) =>+ render: (apiKey) => (// Plaintext is returned only for the caller's own keys; other members'// rows are masked (owners can manage them but never see the secret).- apiKey.isMine === false ? (- <span style={{ opacity: 0.5 }}>{`lb-${'*'.repeat(12)}`}</span>- ) : apiKey.keyDecryptionFailed ? (- <span title={t('apikey.display.unavailableDescription')}>- {t('apikey.display.unavailable')}- </span>- ) : (- <ApiKeyDisplay apiKey={apiKey.key} />- ),+ <span onClick={(e) => e.stopPropagation()}>+ {apiKey.isMine === false ? (+ <span style={{ opacity: 0.5 }}>{`sk-lh-${'*'.repeat(12)}`}</span>+ ) : apiKey.keyDecryptionFailed ? (+ <span title={t('apikey.display.unavailableDescription')}>+ {t('apikey.display.unavailable')}+ </span>+ ) : (+ <ApiKeyDisplay apiKey={apiKey.key} />+ )}+ </span>+ ),title: t('apikey.list.columns.key'),width: 230,},+ // Scopes are deliberately absent from the list: the column could only ever+ // truncate, and the detail drawer (row click) shows the full grant list....(activeWorkspaceId? [{@@ -165,53 +176,9 @@ const ApiKey: FC = () => {} satisfies LiteTableColumn<ApiKeyItem>,]: []),- {- key: 'enabled',- listSlot: 'extra',- render: (apiKey: ApiKeyItem) => {- const canManage = checkManageable(apiKey.userId);- return (- <span style={{ display: 'inline-flex' }} title={canManage ? undefined : manageTooltip}>- <Switch- checked={!!apiKey.enabled}- disabled={!canEdit || !canManage}- onChange={(checked) => {- if (!canEdit || !canManage) return;- updateMutation.mutate({ id: apiKey.id!, params: { enabled: checked } });- }}- />- </span>- );- },- title: t('apikey.list.columns.status'),- width: 100,- },{key: 'expiresAt',- render: (apiKey) => {- const canManage = checkManageable(apiKey.userId);- return (- <span title={canManage ? undefined : manageTooltip}>- <EditableCell- disabled={!canEdit || !canManage}- placeholder={t('apikey.display.neverExpires')}- type="date"- value={apiKey.expiresAt?.toLocaleString() || t('apikey.display.neverExpires')}- onSubmit={(expiresAt) => {- if (!canEdit || !canManage) return;- if (expiresAt === apiKey.expiresAt) {- return;- }-- updateMutation.mutate({- id: apiKey.id!,- params: { expiresAt: expiresAt ? new Date(expiresAt as string) : null },- });- }}- />- </span>- );- },+ render: (apiKey) => apiKey.expiresAt?.toLocaleString() || t('apikey.display.neverExpires'),title: t('apikey.list.columns.expiresAt'),width: 170,},@@ -221,42 +188,13 @@ const ApiKey: FC = () => {apiKey.lastUsedAt?.toLocaleString() || t('apikey.display.neverUsed'),title: t('apikey.list.columns.lastUsedAt'),},+ // Every management action (rename, expiry, enable/disable, delete) lives in+ // the detail drawer: the list browses, the drawer owns one key's surface.{- key: 'action',- listSlot: 'actions',- render: (apiKey: ApiKeyItem) => {- const canManage = checkManageable(apiKey.userId);- return (- <Popconfirm- cancelText={t('apikey.list.actions.deleteConfirm.actions.cancel')}- description={t('apikey.list.actions.deleteConfirm.content')}- okButtonProps={{ disabled: !canEdit || !canManage }}- okText={t('apikey.list.actions.deleteConfirm.actions.ok')}- title={t('apikey.list.actions.deleteConfirm.title')}- onConfirm={async () => {- if (!canEdit || !canManage) return;- await deleteMutation.mutateAsync(apiKey.id!);- }}- >- <Button- disabled={!canEdit || !canManage}- icon={Trash}- size="small"- style={{ verticalAlign: 'middle' }}- type="text"- title={- canEdit && canManage- ? t('apikey.list.actions.delete')- : canEdit- ? manageTooltip- : reason- }- />- </Popconfirm>- );- },- title: t('apikey.list.columns.actions'),- width: 100,+ key: 'enter',+ render: () => <ChevronRight className={styles.enterIcon} size={16} />,+ title: '',+ width: 40,},];@@ -290,6 +228,19 @@ const ApiKey: FC = () => {<Empty description={t('apikey.list.empty')} /></Center>}+ onRowClick={(apiKey) => setDetailId(apiKey.id)}+ />+ <ApiKeyDetail+ apiKey={detailApiKey}+ canManage={canEdit && (detailApiKey ? checkManageable(detailApiKey.userId) : false)}+ manageTooltip={canEdit ? manageTooltip : (reason ?? manageTooltip)}+ open={!!detailApiKey}+ onClose={() => setDetailId(undefined)}+ onUpdate={(id, params) => updateMutation.mutate({ id, params })}+ onDelete={async (id) => {+ await deleteMutation.mutateAsync(id);+ setDetailId(undefined);+ }}/></div>);diff --git a/src/features/Settings/apikey/features/ApiKeyDetail.tsx b/src/features/Settings/apikey/features/ApiKeyDetail.tsxnew file mode 100644index 00000000000..6bd39c6bdf9--- /dev/null+++ b/src/features/Settings/apikey/features/ApiKeyDetail.tsx@@ -0,0 +1,212 @@+'use client';++import { Flexbox, Text } from '@lobehub/ui';+import { Button, Drawer, Switch } from '@lobehub/ui/base-ui';+import { Popconfirm } from 'antd';+import { createStaticStyles } from 'antd-style';+import { Trash } from 'lucide-react';+import { type FC } from 'react';+import { useTranslation } from 'react-i18next';++import { isFullAccessApiKey } from '@/const/apiKeyScope';+import { type ApiKeyItem, type UpdateApiKeyParams } from '@/types/apiKey';++import { ScopeOverview } from './ApiKeyModal/ScopeSelector';+import { ApiKeyDisplay, EditableCell } from './index';++const styles = createStaticStyles(({ css, cssVar }) => ({+ fullAccessCard: css`+ padding: 12px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadius};+ `,+ label: css`+ flex: none;+ width: 96px;+ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ `,+ metaRow: css`+ display: flex;+ gap: 16px;+ align-items: center;+ min-height: 28px;+ `,+ sectionTitle: css`+ font-size: 13px;+ font-weight: 500;+ color: ${cssVar.colorTextSecondary};+ `,+ value: css`+ overflow: hidden;+ display: flex;+ align-items: center;+ font-size: 13px;+ `,+}));++export interface ApiKeyDetailProps {+ apiKey?: ApiKeyItem;+ canManage: boolean;+ manageTooltip: string;+ onClose: () => void;+ onDelete: (id: string) => Promise<void>;+ onUpdate: (id: string, params: UpdateApiKeyParams) => void;+ open: boolean;+}++/**+ * Full detail of one API key — the list's scopes column can only truncate.+ * Same management surface as the list rows (rename / toggle / delete), and+ * the scope grid mirrors the creation modal so create and inspect read as one+ * system. Scopes are immutable after creation, so that section is read-only.+ */+const ApiKeyDetail: FC<ApiKeyDetailProps> = ({+ apiKey,+ canManage,+ manageTooltip,+ onClose,+ onDelete,+ onUpdate,+ open,+}) => {+ const { t } = useTranslation('auth');++ return (+ <Drawer+ open={open}+ placement={'right'}+ title={t('apikey.detail.title')}+ width={'min(92vw, 520px)'}+ onClose={onClose}+ >+ {apiKey && (+ <Flexbox gap={24}>+ <Flexbox gap={4}>+ <div className={styles.metaRow}>+ <span className={styles.label}>{t('apikey.list.columns.name')}</span>+ <span className={styles.value}>+ <EditableCell+ disabled={!canManage}+ placeholder={t('apikey.display.enterPlaceholder')}+ type="text"+ value={apiKey.name}+ onSubmit={(name) => {+ if (!canManage || !name || name === apiKey.name) return;+ onUpdate(apiKey.id, { name: name as string });+ }}+ />+ </span>+ </div>++ <div className={styles.metaRow}>+ <span className={styles.label}>{t('apikey.list.columns.key')}</span>+ <span className={styles.value}>+ {apiKey.isMine === false ? (+ <span style={{ opacity: 0.5 }}>{`sk-lh-${'*'.repeat(12)}`}</span>+ ) : apiKey.keyDecryptionFailed ? (+ <span title={t('apikey.display.unavailableDescription')}>+ {t('apikey.display.unavailable')}+ </span>+ ) : (+ <ApiKeyDisplay apiKey={apiKey.key} />+ )}+ </span>+ </div>++ {apiKey.creator && (+ <div className={styles.metaRow}>+ <span className={styles.label}>{t('apikey.list.columns.creator')}</span>+ <span className={styles.value}>{apiKey.creator}</span>+ </div>+ )}++ <div className={styles.metaRow}>+ <span className={styles.label}>{t('apikey.detail.createdAt')}</span>+ <span className={styles.value}>{apiKey.createdAt.toLocaleString()}</span>+ </div>++ <div className={styles.metaRow}>+ <span className={styles.label}>{t('apikey.list.columns.lastUsedAt')}</span>+ <span className={styles.value}>+ {apiKey.lastUsedAt?.toLocaleString() || t('apikey.display.neverUsed')}+ </span>+ </div>++ <div className={styles.metaRow}>+ <span className={styles.label}>{t('apikey.list.columns.expiresAt')}</span>+ <span className={styles.value}>+ <EditableCell+ disabled={!canManage}+ placeholder={t('apikey.display.neverExpires')}+ type="date"+ value={apiKey.expiresAt?.toLocaleString() || t('apikey.display.neverExpires')}+ onSubmit={(expiresAt) => {+ if (!canManage || expiresAt === apiKey.expiresAt) return;+ onUpdate(apiKey.id, {+ expiresAt: expiresAt ? new Date(expiresAt as string) : null,+ });+ }}+ />+ </span>+ </div>++ <div className={styles.metaRow}>+ <span className={styles.label}>{t('apikey.list.columns.status')}</span>+ <span className={styles.value} title={canManage ? undefined : manageTooltip}>+ <Switch+ checked={!!apiKey.enabled}+ disabled={!canManage}+ onChange={(checked) => {+ if (!canManage) return;+ onUpdate(apiKey.id, { enabled: checked });+ }}+ />+ </span>+ </div>+ </Flexbox>++ <Flexbox gap={8}>+ <span className={styles.sectionTitle}>{t('apikey.form.fields.scopes.label')}</span>+ {isFullAccessApiKey(apiKey.scopes) ? (+ <Flexbox className={styles.fullAccessCard} gap={2}>+ <Text style={{ fontSize: 14 }}>{t('apikey.scopes.fullAccess')}</Text>+ <Text style={{ fontSize: 12 }} type={'secondary'}>+ {t('apikey.form.fields.scopes.fullAccessDescription')}+ </Text>+ </Flexbox>+ ) : (+ <ScopeOverview scopes={apiKey.scopes!} />+ )}+ </Flexbox>++ <Flexbox horizontal justify={'flex-end'}>+ <Popconfirm+ cancelText={t('apikey.list.actions.deleteConfirm.actions.cancel')}+ description={t('apikey.list.actions.deleteConfirm.content')}+ okButtonProps={{ disabled: !canManage }}+ okText={t('apikey.list.actions.deleteConfirm.actions.ok')}+ title={t('apikey.list.actions.deleteConfirm.title')}+ onConfirm={async () => {+ if (!canManage) return;+ await onDelete(apiKey.id);+ }}+ >+ <Button+ danger+ disabled={!canManage}+ icon={Trash}+ title={canManage ? t('apikey.list.actions.delete') : manageTooltip}+ type="text"+ >+ {t('apikey.list.actions.delete')}+ </Button>+ </Popconfirm>+ </Flexbox>+ </Flexbox>+ )}+ </Drawer>+ );+};++export default ApiKeyDetail;diff --git a/src/features/Settings/apikey/features/ApiKeyModal/Content.tsx b/src/features/Settings/apikey/features/ApiKeyModal/Content.tsxindex e2d18239e58..6fa35c2e8a3 100644--- a/src/features/Settings/apikey/features/ApiKeyModal/Content.tsx+++ b/src/features/Settings/apikey/features/ApiKeyModal/Content.tsx@@ -7,11 +7,13 @@ import { type Dayjs } from 'dayjs';import { type FC, useState } from 'react';import { useTranslation } from 'react-i18next';+import { API_KEY_FULL_ACCESS_SCOPE, type ApiKeyScope } from '@/const/apiKeyScope';import { type CreateApiKeyParams } from '@/types/apiKey';import ApiKeyDatePicker from '../ApiKeyDatePicker';+import ScopeSelector from './ScopeSelector';-type FormValues = Omit<CreateApiKeyParams, 'expiresAt'> & {+type FormValues = Omit<CreateApiKeyParams, 'expiresAt' | 'scopes'> & {expiresAt: Dayjs | null;};@@ -24,13 +26,21 @@ const ApiKeyModalContent: FC<ApiKeyModalContentProps> = ({ onSubmit }) => {const { close } = useModalContext();const [form] = Form.useForm<FormValues>();const [loading, setLoading] = useState(false);+ // scopes are immutable after creation, so the choice only exists here+ const [fullAccess, setFullAccess] = useState(true);+ const [selectedScopes, setSelectedScopes] = useState<ApiKeyScope[]>([]);++ const scopeMissing = !fullAccess && selectedScopes.length === 0;const handleFinish = async (values: FormValues) => {+ if (scopeMissing) return;+setLoading(true);try {await onSubmit({...values,expiresAt: values.expiresAt ? values.expiresAt.toDate() : null,+ scopes: fullAccess ? [API_KEY_FULL_ACCESS_SCOPE] : selectedScopes,} satisfies CreateApiKeyParams);close();} finally {@@ -60,7 +70,27 @@ const ApiKeyModalContent: FC<ApiKeyModalContentProps> = ({ onSubmit }) => {<ApiKeyDatePicker style={{ width: '100%' }} /></Form.Item>- <Button block htmlType={'submit'} loading={loading} type={'primary'}>+ <Form.Item+ help={scopeMissing ? t('apikey.form.fields.scopes.required') : undefined}+ label={t('apikey.form.fields.scopes.label')}+ style={itemStyle}+ validateStatus={scopeMissing ? 'error' : undefined}+ >+ <ScopeSelector+ fullAccess={fullAccess}+ selected={selectedScopes}+ onFullAccessChange={setFullAccess}+ onSelectedChange={setSelectedScopes}+ />+ </Form.Item>++ <Button+ block+ disabled={scopeMissing}+ htmlType={'submit'}+ loading={loading}+ type={'primary'}+ >{t('apikey.form.submit')}</Button></Flexbox>diff --git a/src/features/Settings/apikey/features/ApiKeyModal/ScopeSelector.tsx b/src/features/Settings/apikey/features/ApiKeyModal/ScopeSelector.tsxnew file mode 100644index 00000000000..39863b2e87c--- /dev/null+++ b/src/features/Settings/apikey/features/ApiKeyModal/ScopeSelector.tsx@@ -0,0 +1,238 @@+'use client';++import { Flexbox, Text } from '@lobehub/ui';+import { Switch } from '@lobehub/ui/base-ui';+import { Checkbox } from 'antd';+import { createStaticStyles } from 'antd-style';+import { Check } from 'lucide-react';+import { type FC } from 'react';+import { useTranslation } from 'react-i18next';++import { type ApiKeyScope } from '@/const/apiKeyScope';++const styles = createStaticStyles(({ css, cssVar }) => ({+ disabled: css`+ pointer-events: none;+ opacity: 0.45;+ `,+ fullAccessRow: css`+ display: flex;+ gap: 16px;+ align-items: center;+ justify-content: space-between;++ padding: 12px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadius};+ `,+ grid: css`+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 12px 16px;++ /* same card treatment as the full-access row so the whole Scope block+ reads as one system */+ padding: 12px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadius};+ `,+ grantCheck: css`+ flex: none;+ color: ${cssVar.colorSuccess};+ `,+ /* Granted-only list: one row per domain the key actually reaches. Hairline+ separators, no card-in-card — the surrounding card is the container. */+ grantList: css`+ padding-block: 4px;+ padding-inline: 12px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadius};+ `,+ grantRow: css`+ padding-block: 12px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};++ &:last-child {+ border-block-end: none;+ }+ `,+ groupTitle: css`+ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ `,+ scopeRow: css`+ flex-wrap: wrap;++ /* keep each label on one line; overflowing items wrap as a whole */+ .ant-checkbox-wrapper {+ align-items: center;+ white-space: nowrap;++ /* antd offsets the box against the first text line (top: 0.2em /+ flex-start); with this theme's box size that sinks it below the+ label's midline — pin it back to true center */+ .ant-checkbox {+ inset-block-start: 0;+ align-self: center;+ }+ }+ `,+}));++/**+ * Scope groups shown to the user. Each group carries a read and a write+ * scope; the model group additionally carries the money-burning+ * `model:invoke` tier.+ */+const SCOPE_GROUPS = [+ { key: 'agent', label: 'apikey.scopes.groups.agent', read: 'agent:read', write: 'agent:write' },+ { key: 'chat', label: 'apikey.scopes.groups.chat', read: 'chat:read', write: 'chat:write' },+ { key: 'model', label: 'apikey.scopes.groups.model', read: 'model:read', write: 'model:write' },+ { key: 'file', label: 'apikey.scopes.groups.file', read: 'file:read', write: 'file:write' },+ {+ key: 'knowledge',+ label: 'apikey.scopes.groups.knowledge',+ read: 'knowledge:read',+ write: 'knowledge:write',+ },+ {+ key: 'workspace',+ label: 'apikey.scopes.groups.workspace',+ read: 'workspace:read',+ write: 'workspace:write',+ },+ { key: 'user', label: 'apikey.scopes.groups.user', read: 'user:read', write: 'user:write' },+] as const satisfies { key: string; label: string; read: ApiKeyScope; write: ApiKeyScope }[];++export interface ScopeOverviewProps {+ scopes: string[];+}++/**+ * What the key can actually do, one row per granted domain.+ *+ * Deliberately NOT the creation grid frozen read-only: creation must offer+ * every option because you are choosing, but inspection answers "what does+ * this key reach", and a 15-cell grid with 4 ticks buries that answer in the+ * 11 it doesn't have. Granted scopes are rendered verbatim from storage (no+ * write→read derivation), so the list stays an honest mirror of the database.+ */+export const ScopeOverview: FC<ScopeOverviewProps> = ({ scopes }) => {+ const { t } = useTranslation('auth');+ const scopeSet = new Set(scopes);+ const separator = t('apikey.scopes.separator');++ const grants = SCOPE_GROUPS.flatMap((group) => {+ const actions = [+ scopeSet.has(group.read) && t('apikey.scopes.read'),+ scopeSet.has(group.write) && t('apikey.scopes.write'),+ group.key === 'model' && scopeSet.has('model:invoke') && t('apikey.scopes.invoke'),+ ].filter(Boolean) as string[];++ return actions.length > 0 ? [{ actions, key: group.key, label: t(group.label) }] : [];+ });++ // A restricted key always carries at least one scope, but never render an+ // empty bordered box if that invariant ever breaks.+ if (grants.length === 0) return <Text type={'secondary'}>{t('apikey.scopes.none')}</Text>;++ return (+ <Flexbox className={styles.grantList}>+ {grants.map((grant) => (+ <Flexbox horizontal align={'center'} className={styles.grantRow} gap={10} key={grant.key}>+ <Check className={styles.grantCheck} size={16} />+ <span style={{ fontSize: 13 }}>+ <strong>{grant.label}</strong>+ {t('apikey.scopes.grantJoin')}+ {grant.actions.join(separator)}+ </span>+ </Flexbox>+ ))}+ </Flexbox>+ );+};++export interface ScopeSelectorProps {+ fullAccess: boolean;+ onFullAccessChange: (fullAccess: boolean) => void;+ onSelectedChange: (selected: ApiKeyScope[]) => void;+ selected: ApiKeyScope[];+}++const ScopeSelector: FC<ScopeSelectorProps> = ({+ fullAccess,+ onFullAccessChange,+ onSelectedChange,+ selected,+}) => {+ const { t } = useTranslation('auth');+ const selectedSet = new Set(selected);++ const toggle = (scope: ApiKeyScope, checked: boolean) => {+ const next = new Set(selectedSet);+ if (checked) {+ next.add(scope);+ // write implies read — keep the UI honest about what the key can do+ if (scope.endsWith(':write')) next.add(scope.replace(/:write$/, ':read') as ApiKeyScope);+ } else {+ next.delete(scope);+ // dropping read also drops the write that implied it+ if (scope.endsWith(':read')) next.delete(scope.replace(/:read$/, ':write') as ApiKeyScope);+ }++ onSelectedChange([...next]);+ };++ return (+ <Flexbox gap={12}>+ <div className={styles.fullAccessRow}>+ <Flexbox gap={2}>+ <Text style={{ fontSize: 14 }}>{t('apikey.form.fields.scopes.fullAccess')}</Text>+ <Text style={{ fontSize: 12 }} type={'secondary'}>+ {t('apikey.form.fields.scopes.fullAccessDescription')}+ </Text>+ </Flexbox>+ <Switch checked={fullAccess} onChange={onFullAccessChange} />+ </div>++ <div className={fullAccess ? styles.disabled : undefined}>+ <Flexbox gap={10}>+ <div className={styles.grid}>+ {SCOPE_GROUPS.map((group) => (+ <Flexbox gap={4} key={group.key}>+ <span className={styles.groupTitle}>{t(group.label)}</span>+ <Flexbox horizontal className={styles.scopeRow} gap={12}>+ <Checkbox+ checked={selectedSet.has(group.read)}+ disabled={fullAccess}+ onChange={(e) => toggle(group.read, e.target.checked)}+ >+ {t('apikey.scopes.read')}+ </Checkbox>+ <Checkbox+ checked={selectedSet.has(group.write)}+ disabled={fullAccess}+ onChange={(e) => toggle(group.write, e.target.checked)}+ >+ {t('apikey.scopes.write')}+ </Checkbox>+ {group.key === 'model' && (+ <Checkbox+ checked={selectedSet.has('model:invoke')}+ disabled={fullAccess}+ onChange={(e) => toggle('model:invoke', e.target.checked)}+ >+ {t('apikey.scopes.modelInvoke')}+ </Checkbox>+ )}+ </Flexbox>+ </Flexbox>+ ))}+ </div>+ </Flexbox>+ </div>+ </Flexbox>+ );+};++export default ScopeSelector;