Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(apikey): scope workspace API keys to member permissions (#18136)

Rdmclin2a9bf96d95010
diff --git a/apps/server/src/routers/lambda/__tests__/apiKey.test.ts b/apps/server/src/routers/lambda/__tests__/apiKey.test.ts
new file mode 100644
index 00000000000..1cfb8023fb8
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/apiKey.test.ts
@@ -0,0 +1,191 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { apiKeyRouter } from '../apiKey';
+
+const {
+ mockApiKeyModel,
+ mockApiKeyModelConstructor,
+ mockAuditCreate,
+ mockCanUseWorkspaceApiKeys,
+ mockGetApiKeyMemberCreation,
+} = vi.hoisted(() => {
+ const apiKeyModel = {
+ create: vi.fn(),
+ delete: vi.fn(),
+ deleteAll: vi.fn(),
+ findById: vi.fn(),
+ findByKey: vi.fn(),
+ query: vi.fn(),
+ update: vi.fn(),
+ validateKey: vi.fn(),
+ };
+
+ return {
+ mockApiKeyModel: apiKeyModel,
+ mockApiKeyModelConstructor: vi.fn(() => apiKeyModel),
+ mockAuditCreate: vi.fn(),
+ mockCanUseWorkspaceApiKeys: vi.fn(),
+ mockGetApiKeyMemberCreation: vi.fn(),
+ };
+});
+
+vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({
+ withScopedPermission: vi.fn(() => (opts: any) => opts.next({ ctx: opts.ctx })),
+}));
+
+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {
+ const { authedProcedure } = await import('@/libs/trpc/lambda');
+ return { wsCompatProcedure: authedProcedure };
+});
+
+vi.mock('@/business/server/workspaceApiKey', () => ({
+ canUseWorkspaceApiKeys: mockCanUseWorkspaceApiKeys,
+}));
+
+vi.mock('@/database/models/apiKey', () => ({
+ ApiKeyModel: mockApiKeyModelConstructor,
+}));
+
+vi.mock('@/database/models/workspace', () => ({
+ WorkspaceModel: vi.fn(() => ({ getApiKeyMemberCreation: mockGetApiKeyMemberCreation })),
+}));
+
+vi.mock('@/database/models/workspaceAuditLog', () => ({
+ WorkspaceAuditLogModel: vi.fn(() => ({ create: mockAuditCreate })),
+}));
+
+vi.mock('@/libs/trpc/lambda/middleware', () => ({
+ serverDatabase: vi.fn((opts: any) => opts.next({ ctx: opts.ctx })),
+}));
+
+const createCaller = (workspaceRole: 'admin' | 'member' | 'owner' = 'member') =>
+ apiKeyRouter.createCaller({
+ clientIp: '127.0.0.1',
+ serverDB: {},
+ userId: `${workspaceRole}-user`,
+ workspaceId: 'workspace-1',
+ workspaceRole,
+ } as any);
+
+describe('apiKeyRouter workspace member access', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockCanUseWorkspaceApiKeys.mockResolvedValue(true);
+ mockGetApiKeyMemberCreation.mockResolvedValue('all_members');
+ mockAuditCreate.mockResolvedValue(undefined);
+ mockApiKeyModel.create.mockResolvedValue({
+ enabled: true,
+ expiresAt: null,
+ id: 'key-1',
+ name: 'Member integration',
+ scopes: ['*'],
+ userId: 'member-user',
+ });
+ mockApiKeyModel.delete.mockResolvedValue(undefined);
+ mockApiKeyModel.deleteAll.mockResolvedValue([]);
+ mockApiKeyModel.query.mockResolvedValue([]);
+ mockApiKeyModel.update.mockResolvedValue(undefined);
+ });
+
+ it('constructs an owner-scoped model for members and a workspace-wide model for admins', async () => {
+ await createCaller('member').getApiKeys();
+ expect(mockApiKeyModelConstructor).toHaveBeenLastCalledWith(
+ expect.anything(),
+ 'member-user',
+ 'workspace-1',
+ { canManageAll: false },
+ );
+
+ await createCaller('admin').getApiKeys();
+ expect(mockApiKeyModelConstructor).toHaveBeenLastCalledWith(
+ expect.anything(),
+ 'admin-user',
+ 'workspace-1',
+ { canManageAll: true },
+ );
+ });
+
+ it('allows members to create full-access keys when the workspace policy allows members', async () => {
+ await createCaller('member').createApiKey({
+ expiresAt: null,
+ name: 'Member integration',
+ scopes: ['*'],
+ });
+
+ expect(mockApiKeyModel.create).toHaveBeenCalledWith({
+ expiresAt: null,
+ name: 'Member integration',
+ scopes: ['*'],
+ });
+ expect(mockAuditCreate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ action: 'api_key.created',
+ resourceId: 'key-1',
+ workspaceId: 'workspace-1',
+ }),
+ );
+ });
+
+ it('rejects member creation when the workspace policy is admins only', async () => {
+ mockGetApiKeyMemberCreation.mockResolvedValueOnce('admins_only');
+
+ await expect(
+ createCaller('member').createApiKey({ name: 'Blocked', scopes: ['agent:read'] }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(mockApiKeyModel.create).not.toHaveBeenCalled();
+ });
+
+ it('lets the creator edit scopes in place and records before/after grants', async () => {
+ mockApiKeyModel.findById.mockResolvedValueOnce({
+ enabled: true,
+ expiresAt: null,
+ id: 'key-1',
+ name: 'Member integration',
+ scopes: ['agent:read'],
+ userId: 'member-user',
+ });
+
+ await createCaller('member').updateApiKey({
+ id: 'key-1',
+ value: { scopes: ['chat:read', 'chat:write'] },
+ });
+
+ expect(mockApiKeyModel.update).toHaveBeenCalledWith('key-1', {
+ scopes: ['chat:read', 'chat:write'],
+ });
+ expect(mockAuditCreate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ action: 'api_key.updated',
+ metadata: expect.objectContaining({
+ after: expect.objectContaining({ scopes: ['chat:read', 'chat:write'] }),
+ before: expect.objectContaining({ scopes: ['agent:read'] }),
+ }),
+ }),
+ );
+ });
+
+ it('prevents admins from editing another member key but still allows revocation', async () => {
+ mockApiKeyModel.findById.mockResolvedValue({
+ enabled: true,
+ expiresAt: null,
+ id: 'member-key',
+ name: 'Member key',
+ scopes: ['agent:read'],
+ userId: 'member-user',
+ });
+
+ await expect(
+ createCaller('admin').updateApiKey({
+ id: 'member-key',
+ value: { scopes: ['*'] },
+ }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+
+ await createCaller('admin').deleteApiKey({ id: 'member-key' });
+ expect(mockApiKeyModel.delete).toHaveBeenCalledWith('member-key');
+ expect(mockAuditCreate).toHaveBeenCalledWith(
+ expect.objectContaining({ action: 'api_key.revoked', resourceId: 'member-key' }),
+ );
+ });
+});
diff --git a/apps/server/src/routers/lambda/apiKey.ts b/apps/server/src/routers/lambda/apiKey.ts
index a7a022a16b1..7a190217da4 100644
--- a/apps/server/src/routers/lambda/apiKey.ts
+++ b/apps/server/src/routers/lambda/apiKey.ts
@@ -4,27 +4,71 @@ import { z } from 'zod';
import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
import {
- requireWorkspaceRoleWhenScoped,
+ type WorkspaceRole,
wsCompatProcedure,
} from '@/business/server/trpc-middlewares/workspaceAuth';
import { canUseWorkspaceApiKeys } from '@/business/server/workspaceApiKey';
import { ApiKeyModel } from '@/database/models/apiKey';
+import { WorkspaceModel } from '@/database/models/workspace';
+import { WorkspaceAuditLogModel } from '@/database/models/workspaceAuditLog';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-const apiKeyProcedure = wsCompatProcedure
- .use(requireWorkspaceRoleWhenScoped('admin'))
- .use(serverDatabase)
- .use(async (opts) => {
- const { ctx } = opts;
- const wsId = ctx.workspaceId ?? undefined;
-
- return opts.next({
- ctx: {
- apiKeyModel: new ApiKeyModel(ctx.serverDB, ctx.userId, wsId),
- },
- });
+const apiKeyScopesSchema = z
+ .array(z.string().refine(isValidApiKeyScope, { message: 'Unknown API key scope' }))
+ .min(1)
+ .nullish();
+
+const normalizeScopes = (scopes: string[] | null | undefined) =>
+ scopes?.includes(API_KEY_FULL_ACCESS_SCOPE) ? [API_KEY_FULL_ACCESS_SCOPE] : scopes;
+
+/**
+ * Reads `workspaceRole` as an optional context field: the cloud workspace-auth
+ * override injects it, while the OSS stub leaves it absent. Same shape as
+ * `_helpers/assertWorkspaceRowManageable`, keeping this router build-portable.
+ */
+const isWorkspaceAdmin = (ctx: { userId: string; workspaceRole?: WorkspaceRole }) =>
+ ctx.workspaceRole === 'owner' || ctx.workspaceRole === 'admin';
+
+const apiKeyProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+ const wsId = ctx.workspaceId ?? undefined;
+
+ return opts.next({
+ ctx: {
+ apiKeyModel: new ApiKeyModel(ctx.serverDB, ctx.userId, wsId, {
+ canManageAll: isWorkspaceAdmin(ctx),
+ }),
+ workspaceModel: new WorkspaceModel(ctx.serverDB, ctx.userId),
+ },
});
+});
+
+const recordApiKeyAudit = async (
+ ctx: {
+ clientIp?: string | null;
+ serverDB: ConstructorParameters<typeof WorkspaceAuditLogModel>[0];
+ userId: string;
+ workspaceId?: string | null;
+ },
+ params: {
+ action: 'api_key.created' | 'api_key.revoked' | 'api_key.updated';
+ metadata?: Record<string, unknown>;
+ resourceId: string;
+ },
+) => {
+ if (!ctx.workspaceId) return;
+
+ await new WorkspaceAuditLogModel(ctx.serverDB).create({
+ action: params.action,
+ ipAddress: ctx.clientIp ?? undefined,
+ metadata: params.metadata,
+ resourceId: params.resourceId,
+ resourceType: 'api_key',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+};
export const apiKeyRouter = router({
createApiKey: apiKeyProcedure
@@ -33,35 +77,54 @@ 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(),
+ scopes: apiKeyScopesSchema,
}),
)
.mutation(async ({ input, ctx }) => {
- if (ctx.workspaceId && !(await canUseWorkspaceApiKeys(ctx.workspaceId))) {
- throw new TRPCError({
- code: 'PRECONDITION_FAILED',
- message: 'Workspace API Key access is not available',
- });
+ if (ctx.workspaceId) {
+ if (!(await canUseWorkspaceApiKeys(ctx.workspaceId))) {
+ throw new TRPCError({
+ code: 'PRECONDITION_FAILED',
+ message: 'Workspace API Key access is not available',
+ });
+ }
+
+ const memberCreation = await ctx.workspaceModel.getApiKeyMemberCreation(ctx.workspaceId);
+ if (memberCreation === 'admins_only' && !isWorkspaceAdmin(ctx)) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'Workspace API Key creation is restricted to admins',
+ });
+ }
}
- // 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;
+ const scopes = normalizeScopes(input.scopes);
+ const result = await ctx.apiKeyModel.create({ ...input, scopes });
+ await recordApiKeyAudit(ctx, {
+ action: 'api_key.created',
+ metadata: { expiresAt: result.expiresAt, name: result.name, scopes: result.scopes ?? null },
+ resourceId: result.id,
+ });
- return await ctx.apiKeyModel.create({ ...input, scopes });
+ return result;
}),
deleteAllApiKeys: apiKeyProcedure
.use(withScopedPermission('api_key:delete'))
.mutation(async ({ ctx }) => {
- return ctx.apiKeyModel.deleteAll();
+ const deleted = await ctx.apiKeyModel.deleteAll();
+ await Promise.all(
+ deleted.map((item) =>
+ recordApiKeyAudit(ctx, {
+ action: 'api_key.revoked',
+ metadata: { name: item.name, scopes: item.scopes ?? null },
+ resourceId: item.id,
+ }),
+ ),
+ );
+ return deleted;
}),
deleteApiKey: apiKeyProcedure
@@ -71,14 +134,23 @@ export const apiKeyRouter = router({
const existing = await ctx.apiKeyModel.findById(input.id);
if (!existing) return;
- return ctx.apiKeyModel.delete(input.id);
+ const result = await ctx.apiKeyModel.delete(input.id);
+ await recordApiKeyAudit(ctx, {
+ action: 'api_key.revoked',
+ metadata: { name: existing.name, scopes: existing.scopes ?? null },
+ resourceId: existing.id,
+ });
+ return result;
}),
getApiKey: apiKeyProcedure
.use(withScopedPermission('api_key:read'))
.input(z.object({ apiKey: z.string() }))
.query(async ({ input, ctx }) => {
- return ctx.apiKeyModel.findByKey(input.apiKey);
+ const apiKey = await ctx.apiKeyModel.findByKey(input.apiKey);
+ if (!apiKey) return apiKey;
+ const { key: _, keyHash: __, ...safeApiKey } = apiKey;
+ return safeApiKey;
}),
getApiKeyById: apiKeyProcedure
@@ -88,7 +160,8 @@ export const apiKeyRouter = router({
const apiKey = await ctx.apiKeyModel.findById(input.id);
if (!apiKey) return apiKey;
- return apiKey;
+ const { key: _, keyHash: __, ...safeApiKey } = apiKey;
+ return safeApiKey;
}),
getApiKeys: apiKeyProcedure.use(withScopedPermission('api_key:read')).query(async ({ ctx }) => {
@@ -101,18 +174,48 @@ export const apiKeyRouter = router({
z.object({
id: z.string(),
value: z.object({
- description: z.string().optional(),
enabled: z.boolean().optional(),
expiresAt: z.date().nullish(),
name: z.string().optional(),
+ scopes: apiKeyScopesSchema,
}),
}),
)
.mutation(async ({ input, ctx }) => {
const existing = await ctx.apiKeyModel.findById(input.id);
if (!existing) return;
+ if (existing.userId !== ctx.userId) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'Only the API Key creator can edit this key',
+ });
+ }
- return ctx.apiKeyModel.update(input.id, input.value);
+ const nextValue = {
+ ...input.value,
+ scopes: input.value.scopes === undefined ? undefined : normalizeScopes(input.value.scopes),
+ };
+ const result = await ctx.apiKeyModel.update(input.id, nextValue);
+ await recordApiKeyAudit(ctx, {
+ action: 'api_key.updated',
+ metadata: {
+ after: {
+ enabled: nextValue.enabled ?? existing.enabled,
+ expiresAt: nextValue.expiresAt === undefined ? existing.expiresAt : nextValue.expiresAt,
+ name: nextValue.name ?? existing.name,
+ scopes: nextValue.scopes === undefined ? (existing.scopes ?? null) : nextValue.scopes,
+ },
+ before: {
+ enabled: existing.enabled,
+ expiresAt: existing.expiresAt,
+ name: existing.name,
+ scopes: existing.scopes ?? null,
+ },
+ },
+ resourceId: existing.id,
+ });
+
+ return result;
}),
validateApiKey: apiKeyProcedure
diff --git a/locales/ar/auth.json b/locales/ar/auth.json
index ebe9c14b0e7..7b1069692f5 100644
--- a/locales/ar/auth.json
+++ b/locales/ar/auth.json
@@ -4,6 +4,9 @@
"agreement.confirm.ok": "موافق ومتابعة",
"agreement.confirm.title": "الشروط وسياسة الخصوصية",
"apikey.detail.createdAt": "تم الإنشاء",
+ "apikey.detail.permissions.cancel": "إلغاء",
+ "apikey.detail.permissions.edit": "تعديل الأذونات",
+ "apikey.detail.permissions.save": "حفظ الأذونات",
"apikey.detail.title": "تفاصيل مفتاح API",
"apikey.display.autoGenerated": "تم إنشاؤه تلقائيًا",
"apikey.display.copy": "نسخ",
@@ -27,6 +30,7 @@
"apikey.form.submit": "إنشاء",
"apikey.form.title": "إنشاء مفتاح API",
"apikey.list.actions.create": "إنشاء مفتاح API",
+ "apikey.list.actions.creationRestricted": "قام مسؤول مساحة العمل بتقييد إنشاء مفاتيح API للمسؤولين فقط",
"apikey.list.actions.delete": "حذف",
"apikey.list.actions.deleteConfirm.actions.cancel": "إلغاء",
"apikey.list.actions.deleteConfirm.actions.ok": "تأكيد",
@@ -40,6 +44,8 @@
"apikey.list.columns.name": "الاسم",
"apikey.list.columns.status": "حالة التمكين",
"apikey.list.empty": "لا توجد مفاتيح API حتى الآن",
+ "apikey.list.restrictedEmpty.desc": "يمكن فقط لمسؤولي مساحة العمل إنشاء مفاتيح API. تواصل مع مسؤول مساحة العمل إذا كنت بحاجة إلى واحد.",
+ "apikey.list.restrictedEmpty.title": "تم تقييد إنشاء مفاتيح API",
"apikey.list.title": "قائمة مفاتيح API",
"apikey.scopes.fullAccess": "وصول كامل",
"apikey.scopes.grantJoin": ": ",
diff --git a/locales/ar/setting.json b/locales/ar/setting.json
index a509c526619..353c7e9a37f 100644
--- a/locales/ar/setting.json
+++ b/locales/ar/setting.json
@@ -1534,12 +1534,17 @@
"tools.tabs.all": "الكل",
"tools.tabs.installed": "مفعلة",
"tools.title": "أدوات التوسعة",
+ "workspace.apiKey.policy.desc": "اختر من يمكنه إنشاء مفاتيح API شخصية تعمل نيابة عنهم في مساحة العمل هذه.",
+ "workspace.apiKey.policy.options.allMembers": "جميع الأعضاء",
+ "workspace.apiKey.policy.options.onlyAdmins": "المسؤولون فقط",
+ "workspace.apiKey.policy.title": "إنشاء مفتاح API",
+ "workspace.apiKey.policy.updateFailed": "فشل في تحديث سياسة إنشاء مفتاح API",
"workspace.apiKey.upgrade.benefits.integration.desc": "قم باستدعاء وكلاء وموارد مساحة العمل من أنظمتك الخاصة عبر واجهة برمجة تطبيقات LobeHub.",
"workspace.apiKey.upgrade.benefits.integration.title": "الوصول البرمجي",
- "workspace.apiKey.upgrade.benefits.security.desc": "تعمل الطلبات تحت أدوار وأذونات مساحة العمل، ويمكن إلغاء المفاتيح مركزيًا.",
+ "workspace.apiKey.upgrade.benefits.security.desc": "تظل الطلبات مرتبطة بمساحة العمل ولا يمكنها أبدًا تجاوز أذونات المصدر الحالية.",
"workspace.apiKey.upgrade.benefits.security.title": "أمان مخصص لمساحة العمل",
- "workspace.apiKey.upgrade.benefits.shared.desc": "المفاتيح تنتمي إلى مساحة العمل بدلاً من شخص واحد، لذا تستمر الأتمتة حتى مع تغييرات الأعضاء.",
- "workspace.apiKey.upgrade.benefits.shared.title": "مفاتيح مشتركة للفريق",
+ "workspace.apiKey.upgrade.benefits.shared.desc": "يمكن للمسؤولين التحكم في إنشاء الأعضاء وإلغاء مفاتيح API النشطة مركزيًا.",
+ "workspace.apiKey.upgrade.benefits.shared.title": "حوكمة المسؤول",
"workspace.apiKey.upgrade.cta": "الترقية إلى برو",
"workspace.apiKey.upgrade.desc": "قم بإنشاء مفاتيح API مخصصة لمساحة العمل لدمج وكلاء وبيانات مساحة العمل في سير العمل والخدمات الخاصة بك.",
"workspace.apiKey.upgrade.title": "افتح مفاتيح API لمساحة العمل للوصول البرمجي",
@@ -1547,6 +1552,7 @@
"workspace.auditLog.actions.api_key.renamed": "تمت إعادة تسمية مفتاح API",
"workspace.auditLog.actions.api_key.revoked": "تم إلغاء مفتاح API",
"workspace.auditLog.actions.api_key.rotated": "تم تدوير مفتاح API",
+ "workspace.auditLog.actions.api_key.updated": "تم تحديث مفتاح API",
"workspace.auditLog.actions.auto_top_up.disabled": "تم تعطيل التعبئة التلقائية",
"workspace.auditLog.actions.auto_top_up.enabled": "تم تمكين التعبئة التلقائية",
"workspace.auditLog.actions.auto_top_up.failed": "فشلت التعبئة التلقائية",
diff --git a/locales/bg-BG/auth.json b/locales/bg-BG/auth.json
index 5ea2f1df2c5..d381c181330 100644
--- a/locales/bg-BG/auth.json
+++ b/locales/bg-BG/auth.json
@@ -4,6 +4,9 @@
"agreement.confirm.ok": "Съгласен съм и продължавам",
"agreement.confirm.title": "Условия и Политика за поверителност",
"apikey.detail.createdAt": "Създадено",
+ "apikey.detail.permissions.cancel": "Отказ",
+ "apikey.detail.permissions.edit": "Редактиране на разрешения",
+ "apikey.detail.permissions.save": "Запазване на разрешения",
"apikey.detail.title": "Детайли за API ключ",
"apikey.display.autoGenerated": "Автоматично генериран",
"apikey.display.copy": "Копирай",
@@ -27,6 +30,7 @@
"apikey.form.submit": "Създай",
"apikey.form.title": "Създаване на API ключ",
"apikey.list.actions.create": "Създай API ключ",
+ "apikey.list.actions.creationRestricted": "Администраторът на работното пространство е ограничил създаването на API ключове само за администратори",
"apikey.list.actions.delete": "Изтрий",
"apikey.list.actions.deleteConfirm.actions.cancel": "Отказ",
"apikey.list.actions.deleteConfirm.actions.ok": "Потвърди",
@@ -40,6 +44,8 @@
"apikey.list.columns.name": "Име",
"apikey.list.columns.status": "Статус",
"apikey.list.empty": "Все още няма API ключове",
+ "apikey.list.restrictedEmpty.desc": "Само администраторите на работното пространство могат да създават API ключове. Свържете се с администратор на работното пространство, ако имате нужда от такъв.",
+ "apikey.list.restrictedEmpty.title": "Създаването на API ключове е ограничено",
"apikey.list.title": "Списък с API ключове",
"apikey.scopes.fullAccess": "Пълен достъп",
"apikey.scopes.grantJoin": ": ",
diff --git a/locales/bg-BG/setting.json b/locales/bg-BG/setting.json
index 3985275213a..658776f2e06 100644
--- a/locales/bg-BG/setting.json
+++ b/locales/bg-BG/setting.json
@@ -1534,12 +1534,17 @@
"tools.tabs.all": "Всички",
"tools.tabs.installed": "Активирани",
"tools.title": "Разширения и инструменти",
+ "workspace.apiKey.policy.desc": "Изберете кой може да създава лични API ключове, които действат от тяхно име в това работно пространство.",
+ "workspace.apiKey.policy.options.allMembers": "Всички членове",
+ "workspace.apiKey.policy.options.onlyAdmins": "Само администратори",
+ "workspace.apiKey.policy.title": "Създаване на API ключ",
+ "workspace.apiKey.policy.updateFailed": "Неуспешно актуализиране на политиката за създаване на API ключове",
"workspace.apiKey.upgrade.benefits.integration.desc": "Извиквайте агенти и ресурси на работното пространство от вашите собствени системи чрез LobeHub API.",
"workspace.apiKey.upgrade.benefits.integration.title": "Програматичен достъп",
- "workspace.apiKey.upgrade.benefits.security.desc": "Заявките се изпълняват под роли и разрешения на работното пространство, а ключовете могат да бъдат оттеглени централно.",
+ "workspace.apiKey.upgrade.benefits.security.desc": "Заявките остават свързани с работното пространство и никога не могат да надвишат текущите разрешения на издателя.",
"workspace.apiKey.upgrade.benefits.security.title": "Сигурност, обвързана с работното пространство",
- "workspace.apiKey.upgrade.benefits.shared.desc": "Ключовете принадлежат на работното пространство, а не на един човек, така че автоматизацията оцелява при промени в членовете.",
- "workspace.apiKey.upgrade.benefits.shared.title": "Ключове, споделени в екипа",
+ "workspace.apiKey.upgrade.benefits.shared.desc": "Администраторите могат да контролират създаването от членове и централно да анулират активни API ключове.",
+ "workspace.apiKey.upgrade.benefits.shared.title": "Управление от администратор",
"workspace.apiKey.upgrade.cta": "Надградете до Pro",
"workspace.apiKey.upgrade.desc": "Създайте API ключове, обвързани с работното пространство, за да интегрирате агенти и данни на работното пространство във вашите собствени работни потоци и услуги.",
"workspace.apiKey.upgrade.title": "Отключете API ключове за работното пространство за програматичен достъп",
@@ -1547,6 +1552,7 @@
"workspace.auditLog.actions.api_key.renamed": "Преименуван API ключ",
"workspace.auditLog.actions.api_key.revoked": "Отменен API ключ",
"workspace.auditLog.actions.api_key.rotated": "Завъртян API ключ",
+ "workspace.auditLog.actions.api_key.updated": "API ключът е актуализиран",
"workspace.auditLog.actions.auto_top_up.disabled": "Автоматичното зареждане е деактивирано",
"workspace.auditLog.actions.auto_top_up.enabled": "Автоматичното зареждане е активирано",
"workspace.auditLog.actions.auto_top_up.failed": "Автоматичното зареждане е неуспешно",
diff --git a/locales/de-DE/auth.json b/locales/de-DE/auth.json
index a1f8ff4749b..98b3505f5ac 100644
--- a/locales/de-DE/auth.json
+++ b/locales/de-DE/auth.json
@@ -4,6 +4,9 @@
"agreement.confirm.ok": "Zustimmen und fortfahren",
"agreement.confirm.title": "Allgemeine Geschäftsbedingungen und Datenschutzrichtlinie",
"apikey.detail.createdAt": "Erstellt",
+ "apikey.detail.permissions.cancel": "Abbrechen",
+ "apikey.detail.permissions.edit": "Berechtigungen bearbeiten",
+ "apikey.detail.permissions.save": "Berechtigungen speichern",
"apikey.detail.title": "API-Schlüsseldetails",
"apikey.display.autoGenerated": "Automatisch generiert",
"apikey.display.copy": "Kopieren",
@@ -27,6 +30,7 @@
"apikey.form.submit": "Erstellen",
"apikey.form.title": "API-Schlüssel erstellen",
"apikey.list.actions.create": "API-Schlüssel erstellen",
+ "apikey.list.actions.creationRestricted": "Ihr Workspace-Administrator hat die Erstellung von API-Schlüsseln auf Administratoren beschränkt",
"apikey.list.actions.delete": "Löschen",
"apikey.list.actions.deleteConfirm.actions.cancel": "Abbrechen",
"apikey.list.actions.deleteConfirm.actions.ok": "Bestätigen",
@@ -40,6 +44,8 @@
"apikey.list.columns.name": "Name",
"apikey.list.columns.status": "Status aktiviert",
"apikey.list.empty": "Noch keine API-Schlüssel",
+ "apikey.list.restrictedEmpty.desc": "Nur Workspace-Administratoren können API-Schlüssel erstellen. Wenden Sie sich an einen Workspace-Administrator, wenn Sie einen benötigen.",
+ "apikey.list.restrictedEmpty.title": "Die Erstellung von API-Schlüsseln ist eingeschränkt",
"apikey.list.title": "API-Schlüsselliste",
"apikey.scopes.fullAccess": "Vollzugriff",
"apikey.scopes.grantJoin": ": ",
diff --git a/locales/de-DE/setting.json b/locales/de-DE/setting.json
index 4d6899cf3c1..d1774d6a2e0 100644
--- a/locales/de-DE/setting.json
+++ b/locales/de-DE/setting.json
@@ -1534,12 +1534,17 @@
"tools.tabs.all": "Alle",
"tools.tabs.installed": "Aktiviert",
"tools.title": "Erweiterungswerkzeuge",
+ "workspace.apiKey.policy.desc": "Wählen Sie aus, wer persönliche API-Schlüssel erstellen kann, die in diesem Arbeitsbereich in ihrem Namen agieren.",
+ "workspace.apiKey.policy.options.allMembers": "Alle Mitglieder",
+ "workspace.apiKey.policy.options.onlyAdmins": "Nur Administratoren",
+ "workspace.apiKey.policy.title": "API-Schlüssel-Erstellung",
+ "workspace.apiKey.policy.updateFailed": "Die Aktualisierung der API-Schlüssel-Erstellungsrichtlinie ist fehlgeschlagen",
"workspace.apiKey.upgrade.benefits.integration.desc": "Rufen Sie Workspace-Agenten und -Ressourcen über die LobeHub-API aus Ihren eigenen Systemen auf.",
"workspace.apiKey.upgrade.benefits.integration.title": "Programmatischer Zugriff",
- "workspace.apiKey.upgrade.benefits.security.desc": "Anfragen werden unter Workspace-Rollen und -Berechtigungen ausgeführt, und Schlüssel können zentral widerrufen werden.",
+ "workspace.apiKey.upgrade.benefits.security.desc": "Anfragen bleiben an den Arbeitsbereich gebunden und können die aktuellen Berechtigungen des Ausstellers niemals überschreiten.",
"workspace.apiKey.upgrade.benefits.security.title": "Workspace-gebundene Sicherheit",
- "workspace.apiKey.upgrade.benefits.shared.desc": "Schlüssel gehören zum Workspace statt zu einer Person, sodass die Automatisierung Mitgliederänderungen überdauert.",
- "workspace.apiKey.upgrade.benefits.shared.title": "Team-geteilte Schlüssel",
+ "workspace.apiKey.upgrade.benefits.shared.desc": "Administratoren können die Erstellung durch Mitglieder steuern und zentral aktive API-Schlüssel widerrufen.",
+ "workspace.apiKey.upgrade.benefits.shared.title": "Verwaltung durch Administratoren",
"workspace.apiKey.upgrade.cta": "Auf Pro upgraden",
"workspace.apiKey.upgrade.desc": "Erstellen Sie Workspace-gebundene API-Schlüssel, um Workspace-Agenten und -Daten in Ihre eigenen Workflows und Dienste zu integrieren.",
"workspace.apiKey.upgrade.title": "Workspace-API-Schlüssel für programmatischen Zugriff freischalten",
@@ -1547,6 +1552,7 @@
"workspace.auditLog.actions.api_key.renamed": "API-Schlüssel umbenannt",
"workspace.auditLog.actions.api_key.revoked": "API-Schlüssel widerrufen",
"workspace.auditLog.actions.api_key.rotated": "API-Schlüssel rotiert",
+ "workspace.auditLog.actions.api_key.updated": "API-Schlüssel aktualisiert",
"workspace.auditLog.actions.auto_top_up.disabled": "Automatische Aufladung deaktiviert",
"workspace.auditLog.actions.auto_top_up.enabled": "Automatische Aufladung aktiviert",
"workspace.auditLog.actions.auto_top_up.failed": "Automatische Aufladung fehlgeschlagen",
diff --git a/locales/en-US/auth.json b/locales/en-US/auth.json
index e5be7b9e2c2..ef917cae8a8 100644
--- a/locales/en-US/auth.json
+++ b/locales/en-US/auth.json
@@ -4,6 +4,9 @@
"agreement.confirm.ok": "Agree and continue",
"agreement.confirm.title": "Terms and Privacy Policy",
"apikey.detail.createdAt": "Created",
+ "apikey.detail.permissions.cancel": "Cancel",
+ "apikey.detail.permissions.edit": "Edit permissions",
+ "apikey.detail.permissions.save": "Save permissions",
"apikey.detail.title": "API Key Details",
"apikey.display.autoGenerated": "Auto-generated",
"apikey.display.copy": "Copy",
@@ -27,6 +30,7 @@
"apikey.form.submit": "Create",
"apikey.form.title": "Create API Key",
"apikey.list.actions.create": "Create API Key",
+ "apikey.list.actions.creationRestricted": "Your workspace administrator has restricted API Key creation to admins",
"apikey.list.actions.delete": "Delete",
"apikey.list.actions.deleteConfirm.actions.cancel": "Cancel",
"apikey.list.actions.deleteConfirm.actions.ok": "Confirm",
@@ -40,6 +44,8 @@
"apikey.list.columns.name": "Name",
"apikey.list.columns.status": "Enabled",
"apikey.list.empty": "No API Keys yet",
+ "apikey.list.restrictedEmpty.desc": "Only workspace admins can create API Keys. Contact a workspace admin if you need one.",
+ "apikey.list.restrictedEmpty.title": "API Key creation is restricted",
"apikey.list.title": "API Key List",
"apikey.scopes.fullAccess": "Full access",
"apikey.scopes.grantJoin": ": ",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 1332ea7691a..afacbbbcaf2 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -1534,12 +1534,17 @@
"tools.tabs.all": "All",
"tools.tabs.installed": "Enabled",
"tools.title": "Skills",
+ "workspace.apiKey.policy.desc": "Choose who can create personal API Keys that act on their behalf in this workspace.",
+ "workspace.apiKey.policy.options.allMembers": "All members",
+ "workspace.apiKey.policy.options.onlyAdmins": "Only admins",
+ "workspace.apiKey.policy.title": "API Key creation",
+ "workspace.apiKey.policy.updateFailed": "Failed to update the API Key creation policy",
"workspace.apiKey.upgrade.benefits.integration.desc": "Call workspace agents and resources from your own systems via the LobeHub API.",
"workspace.apiKey.upgrade.benefits.integration.title": "Programmatic access",
- "workspace.apiKey.upgrade.benefits.security.desc": "Requests stay bound to this workspace and require an active owner account.",
+ "workspace.apiKey.upgrade.benefits.security.desc": "Requests stay bound to the workspace and can never exceed the issuer’s current permissions.",
"workspace.apiKey.upgrade.benefits.security.title": "Workspace-scoped security",
- "workspace.apiKey.upgrade.benefits.shared.desc": "Only workspace owners can create, view, manage, and revoke workspace API keys.",
- "workspace.apiKey.upgrade.benefits.shared.title": "Owner-managed keys",
+ "workspace.apiKey.upgrade.benefits.shared.desc": "Admins can control member creation and centrally revoke active API Keys.",
+ "workspace.apiKey.upgrade.benefits.shared.title": "Admin governance",
"workspace.apiKey.upgrade.cta": "Upgrade to Pro",
"workspace.apiKey.upgrade.desc": "Create workspace-scoped API keys to integrate workspace agents and data into your own workflows and services.",
"workspace.apiKey.upgrade.title": "Unlock workspace API keys for programmatic access",
@@ -1547,6 +1552,7 @@
"workspace.auditLog.actions.api_key.renamed": "API key renamed",
"workspace.auditLog.actions.api_key.revoked": "API key revoked",
"workspace.auditLog.actions.api_key.rotated": "API key rotated",
+ "workspace.auditLog.actions.api_key.updated": "API key updated",
"workspace.auditLog.actions.auto_top_up.disabled": "Auto top-up disabled",
"workspace.auditLog.actions.auto_top_up.enabled": "Auto top-up enabled",
"workspace.auditLog.actions.auto_top_up.failed": "Auto top-up failed",
diff --git a/locales/es-ES/auth.json b/locales/es-ES/auth.json
index a1301aa0c79..a1340d0d63f 100644
--- a/locales/es-ES/auth.json
+++ b/locales/es-ES/auth.json
@@ -4,6 +4,9 @@
"agreement.confirm.ok": "Aceptar y continuar",
"agreement.confirm.title": "Términos y Política de Privacidad",
"apikey.detail.createdAt": "Creado",
+ "apikey.detail.permissions.cancel": "Cancelar",
+ "apikey.detail.permissions.edit": "Editar permisos",
+ "apikey.detail.permissions.save": "Guardar permisos",
"apikey.detail.title": "Detalles de la Clave API",
"apikey.display.autoGenerated": "Generado automáticamente",
"apikey.display.copy": "Copiar",
@@ -27,6 +30,7 @@
"apikey.form.submit": "Crear",
"apikey.form.title": "Crear clave API",
"apikey.list.actions.create": "Crear clave API",
+ "apikey.list.actions.creationRestricted": "El administrador de tu espacio de trabajo ha restringido la creación de claves API a los administradores",
"apikey.list.actions.delete": "Eliminar",
"apikey.list.actions.deleteConfirm.actions.cancel": "Cancelar",
"apikey.list.actions.deleteConfirm.actions.ok": "Confirmar",
@@ -40,6 +44,8 @@
"apikey.list.columns.name": "Nombre",
"apikey.list.columns.status": "Estado habilitado",
"apikey.list.empty": "Aún no hay claves API",
+ "apikey.list.restrictedEmpty.desc": "Solo los administradores del espacio de trabajo pueden crear claves API. Contacta a un administrador del espacio de trabajo si necesitas una.",
+ "apikey.list.restrictedEmpty.title": "La creación de claves API está restringida",
"apikey.list.title": "Lista de claves API",
"apikey.scopes.fullAccess": "Acceso completo",
"apikey.scopes.grantJoin": ": ",
diff --git a/locales/es-ES/setting.json b/locales/es-ES/setting.json
index d67641fd3d7..9b516529040 100644
--- a/locales/es-ES/setting.json
+++ b/locales/es-ES/setting.json
@@ -1534,12 +1534,17 @@
"tools.tabs.all": "Todas",
"tools.tabs.installed": "Habilitadas",
"tools.title": "Herramientas de Extensión",
+ "workspace.apiKey.policy.desc": "Elige quién puede crear claves API personales que actúen en su nombre dentro de este espacio de trabajo.",
+ "workspace.apiKey.policy.options.allMembers": "Todos los miembros",
+ "workspace.apiKey.policy.options.onlyAdmins": "Solo administradores",
+ "workspace.apiKey.policy.title": "Creación de claves API",
+ "workspace.apiKey.policy.updateFailed": "No se pudo actualizar la política de creación de claves API",
"workspace.apiKey.upgrade.benefits.integration.desc": "Llama a agentes y recursos del espacio de trabajo desde tus propios sistemas a través de la API de LobeHub.",
"workspace.apiKey.upgrade.benefits.integration.title": "Acceso programático",
- "workspace.apiKey.upgrade.benefits.security.desc": "Las solicitudes se ejecutan bajo roles y permisos del espacio de trabajo, y las claves pueden ser revocadas de forma centralizada.",
+ "workspace.apiKey.upgrade.benefits.security.desc": "Las solicitudes permanecen vinculadas al espacio de trabajo y nunca pueden exceder los permisos actuales del emisor.",
"workspace.apiKey.upgrade.benefits.security.title": "Seguridad con alcance al espacio de trabajo",
- "workspace.apiKey.upgrade.benefits.shared.desc": "Las claves pertenecen al espacio de trabajo en lugar de a una persona, por lo que la automatización sobrevive a los cambios de miembros.",
- "workspace.apiKey.upgrade.benefits.shared.title": "Claves compartidas por el equipo",
+ "workspace.apiKey.upgrade.benefits.shared.desc": "Los administradores pueden controlar la creación de miembros y revocar centralmente las claves API activas.",
+ "workspace.apiKey.upgrade.benefits.shared.title": "Gobernanza administrativa",
"workspace.apiKey.upgrade.cta": "Actualizar a Pro",
"workspace.apiKey.upgrade.desc": "Crea claves API con alcance al espacio de trabajo para integrar agentes y datos del espacio de trabajo en tus propios flujos de trabajo y servicios.",
"workspace.apiKey.upgrade.title": "Desbloquea claves API del espacio de trabajo para acceso programático",
@@ -1547,6 +1552,7 @@
"workspace.auditLog.actions.api_key.renamed": "Clave API renombrada",
"workspace.auditLog.actions.api_key.revoked": "Clave API revocada",
"workspace.auditLog.actions.api_key.rotated": "Clave API rotada",
+ "workspace.auditLog.actions.api_key.updated": "Clave API actualizada",
"workspace.auditLog.actions.auto_top_up.disabled": "Recarga automática desactivada",
"workspace.auditLog.actions.auto_top_up.enabled": "Recarga automática activada",
"workspace.auditLog.actions.auto_top_up.failed": "Recarga automática fallida",
diff --git a/locales/fa-IR/auth.json b/locales/fa-IR/auth.json
index 1dd2798f5ae..9ecf6b241a6 100644
--- a/locales/fa-IR/auth.json
+++ b/locales/fa-IR/auth.json
@@ -4,6 +4,9 @@
"agreement.confirm.ok": "موافقت و ادامه",
"agreement.confirm.title": "شرایط و سیاست حفظ حریم خصوصی",
"apikey.detail.createdAt": "ایجاد شده",
+ "apikey.detail.permissions.cancel": "لغو",
+ "apikey.detail.permissions.edit": "ویرایش مجوزها",
+ "apikey.detail.permissions.save": "ذخیره مجوزها",
"apikey.detail.title": "جزئیات کلید API",
"apikey.display.autoGenerated": "به‌صورت خودکار تولید شده",
"apikey.display.copy": "کپی",
@@ -27,6 +30,7 @@
"apikey.form.submit": "ایجاد",
"apikey.form.title": "ایجاد کلید API",
"apikey.list.actions.create": "ایجاد کلید API",
+ "apikey.list.actions.creationRestricted": "مدیر فضای کاری شما ایجاد کلید API را به مدیران محدود کرده است",
"apikey.list.actions.delete": "حذف",
"apikey.list.actions.deleteConfirm.actions.cancel": "لغو",
"apikey.list.actions.deleteConfirm.actions.ok": "تأیید",
@@ -40,6 +44,8 @@
"apikey.list.columns.name": "نام",
"apikey.list.columns.status": "وضعیت فعال بودن",
"apikey.list.empty": "هنوز هیچ کلید API وجود ندارد",
+ "apikey.list.restrictedEmpty.desc": "تنها مدیران فضای کاری می‌توانند کلیدهای API ایجاد کنند. اگر به یکی نیاز دارید، با مدیر فضای کاری تماس بگیرید.",
+ "apikey.list.restrictedEmpty.title": "ایجاد کلید API محدود شده است",
"apikey.list.title": "فهرست کلیدهای API",
"apikey.scopes.fullAccess": "دسترسی کامل",
"apikey.scopes.grantJoin": ": ",
diff --git a/locales/fa-IR/setting.json b/locales/fa-IR/setting.json
index bde59e5861e..8e4fa20a728 100644
--- a/locales/fa-IR/setting.json
+++ b/locales/fa-IR/setting.json
@@ -1534,12 +1534,17 @@
"tools.tabs.all": "همه",
"tools.tabs.installed": "فعال‌شده",
"tools.title": "ابزارهای افزونه",
+ "workspace.apiKey.policy.desc": "انتخاب کنید چه کسی می‌تواند کلیدهای API شخصی ایجاد کند که به نمایندگی از آنها در این فضای کاری عمل کند.",
+ "workspace.apiKey.policy.options.allMembers": "همه اعضا",
+ "workspace.apiKey.policy.options.onlyAdmins": "فقط مدیران",
+ "workspace.apiKey.policy.title": "ایجاد کلید API",
+ "workspace.apiKey.policy.updateFailed": "به‌روزرسانی سیاست ایجاد کلید API ناموفق بود",
"workspace.apiKey.upgrade.benefits.integration.desc": "از طریق API لاب‌هاب، عوامل و منابع فضای کاری را از سیستم‌های خود فراخوانی کنید.",
"workspace.apiKey.upgrade.benefits.integration.title": "دسترسی برنامه‌نویسی",
- "workspace.apiKey.upgrade.benefits.security.desc": "درخواست‌ها تحت نقش‌ها و مجوزهای فضای کاری اجرا می‌شوند و کلیدها می‌توانند به صورت مرکزی لغو شوند.",
+ "workspace.apiKey.upgrade.benefits.security.desc": "درخواست‌ها به فضای کاری متصل می‌مانند و هرگز نمی‌توانند از مجوزهای فعلی صادرکننده فراتر روند.",
"workspace.apiKey.upgrade.benefits.security.title": "امنیت محدود به فضای کاری",
- "workspace.apiKey.upgrade.benefits.shared.desc": "کلیدها متعلق به فضای کاری هستند نه یک فرد، بنابراین اتوماسیون با تغییر اعضا باقی می‌ماند.",
- "workspace.apiKey.upgrade.benefits.shared.title": "کلیدهای مشترک تیمی",
+ "workspace.apiKey.upgrade.benefits.shared.desc": "مدیران می‌توانند ایجاد کلید توسط اعضا را کنترل کرده و کلیدهای API فعال را به صورت مرکزی لغو کنند.",
+ "workspace.apiKey.upgrade.benefits.shared.title": "حاکمیت مدیر",
"workspace.apiKey.upgrade.cta": "ارتقاء به نسخه حرفه‌ای",
"workspace.apiKey.upgrade.desc": "کلیدهای API محدود به فضای کاری ایجاد کنید تا عوامل و داده‌های فضای کاری را در جریان‌های کاری و خدمات خود یکپارچه کنید.",
"workspace.apiKey.upgrade.title": "کلیدهای API فضای کاری را برای دسترسی برنامه‌نویسی باز کنید",
@@ -1547,6 +1552,7 @@
"workspace.auditLog.actions.api_key.renamed": "کلید API تغییر نام یافت",
"workspace.auditLog.actions.api_key.revoked": "کلید API لغو شد",
"workspace.auditLog.actions.api_key.rotated": "کلید API چرخانده شد",
+ "workspace.auditLog.actions.api_key.updated": "کلید API به‌روزرسانی شد",
"workspace.auditLog.actions.auto_top_up.disabled": "شارژ خودکار غیرفعال شد",
"workspace.auditLog.actions.auto_top_up.enabled": "شارژ خودکار فعال شد",
"workspace.auditLog.actions.auto_top_up.failed": "شارژ خودکار ناموفق بود",
diff --git a/locales/fr-FR/auth.json b/locales/fr-FR/auth.json
index 4d77e70079d..a64d7445f98 100644
--- a/locales/fr-FR/auth.json
+++ b/locales/fr-FR/auth.json
@@ -4,6 +4,9 @@
"agreement.confirm.ok": "Accepter et continuer",
"agreement.confirm.title": "Conditions générales et Politique de confidentialité",
"apikey.detail.createdAt": "Créé",
+ "apikey.detail.permissions.cancel": "Annuler",
+ "apikey.detail.permissions.edit": "Modifier les autorisations",
+ "apikey.detail.permissions.save": "Enregistrer les autorisations",
"apikey.detail.title": "Détails de la clé API",
"apikey.display.autoGenerated": "Généré automatiquement",
"apikey.display.copy": "Copier",
@@ -27,6 +30,7 @@
"apikey.form.submit": "Créer",
"apikey.form.title": "Créer une clé API",
"apikey.list.actions.create": "Créer une clé API",
+ "apikey.list.actions.creationRestricted": "L'administrateur de votre espace de travail a limité la création de clés API aux administrateurs",
"apikey.list.actions.delete": "Supprimer",
"apikey.list.actions.deleteConfirm.actions.cancel": "Annuler",
"apikey.list.actions.deleteConfirm.actions.ok": "Confirmer",
@@ -40,6 +44,8 @@
"apikey.list.columns.name": "Nom",
"apikey.list.columns.status": "Statut activé",
"apikey.list.empty": "Aucune clé API pour le moment",
+ "apikey.list.restrictedEmpty.desc": "Seuls les administrateurs de l'espace de travail peuvent créer des clés API. Contactez un administrateur de l'espace de travail si vous en avez besoin.",
+ "apikey.list.restrictedEmpty.title": "La création de clés API est restreinte",
"apikey.list.title": "Liste des clés API",
"apikey.scopes.fullAccess": "Accès complet",
"apikey.scopes.grantJoin": ": ",
diff --git a/locales/fr-FR/setting.json b/locales/fr-FR/setting.json
index 1c4f3e76d92..aba8ad9c574 100644
--- a/locales/fr-FR/setting.json
+++ b/locales/fr-FR/setting.json
@@ -1534,12 +1534,17 @@
"tools.tabs.all": "Toutes",
"tools.tabs.installed": "Activées",
"tools.title": "Outils d’extension",
+ "workspace.apiKey.policy.desc": "Choisissez qui peut créer des clés API personnelles agissant en leur nom dans cet espace de travail.",
+ "workspace.apiKey.policy.options.allMembers": "Tous les membres",
+ "workspace.apiKey.policy.options.onlyAdmins": "Seuls les administrateurs",
+ "workspace.apiKey.policy.title": "Création de clé API",
+ "workspace.apiKey.policy.updateFailed": "Échec de la mise à jour de la politique de création de clé API",
"workspace.apiKey.upgrade.benefits.integration.desc": "Appelez les agents et ressources de l'espace de travail depuis vos propres systèmes via l'API LobeHub.",
"workspace.apiKey.upgrade.benefits.integration.title": "Accès programmatique",
- "workspace.apiKey.upgrade.benefits.security.desc": "Les requêtes s'exécutent sous les rôles et permissions de l'espace de travail, et les clés peuvent être révoquées de manière centralisée.",
+ "workspace.apiKey.upgrade.benefits.security.desc": "Les requêtes restent liées à l'espace de travail et ne peuvent jamais dépasser les autorisations actuelles de l'émetteur.",
"workspace.apiKey.upgrade.benefits.security.title": "Sécurité à l'échelle de l'espace de travail",
- "workspace.apiKey.upgrade.benefits.shared.desc": "Les clés appartiennent à l'espace de travail plutôt qu'à une seule personne, ce qui permet à l'automatisation de survivre aux changements de membres.",
- "workspace.apiKey.upgrade.benefits.shared.title": "Clés partagées par l'équipe",
+ "workspace.apiKey.upgrade.benefits.shared.desc": "Les administrateurs peuvent contrôler la création par les membres et révoquer centralement les clés API actives.",
+ "workspace.apiKey.upgrade.benefits.shared.title": "Gouvernance administrative",
"workspace.apiKey.upgrade.cta": "Passer à Pro",
"workspace.apiKey.upgrade.desc": "Créez des clés API à l'échelle de l'espace de travail pour intégrer les agents et les données de l'espace de travail dans vos propres flux de travail et services.",
"workspace.apiKey.upgrade.title": "Débloquez les clés API de l'espace de travail pour un accès programmatique",
@@ -1547,6 +1552,7 @@
"workspace.auditLog.actions.api_key.renamed": "Clé API renommée",
"workspace.auditLog.actions.api_key.revoked": "Clé API révoquée",
"workspace.auditLog.actions.api_key.rotated": "Clé API renouvelée",
+ "workspace.auditLog.actions.api_key.updated": "Clé API mise à jour",
"workspace.auditLog.actions.auto_top_up.disabled": "Recharge automatique désactivée",
"workspace.auditLog.actions.auto_top_up.enabled": "Recharge automatique activée",
"workspace.auditLog.actions.auto_top_up.failed": "Échec de la recharge automatique",
diff --git a/locales/it-IT/auth.json b/locales/it-IT/auth.json
index 5ab6f97aed0..9c9be1ca271 100644
--- a/locales/it-IT/auth.json
+++ b/locales/it-IT/auth.json
@@ -4,6 +4,9 @@
"agreement.confirm.ok": "Accetta e continua",
"agreement.confirm.title": "Termini e Informativa sulla Privacy",
"apikey.detail.createdAt": "Creato",
+ "apikey.detail.permissions.cancel": "Annulla",
+ "apikey.detail.permissions.edit": "Modifica permessi",
+ "apikey.detail.permissions.save": "Salva permessi",
"apikey.detail.title": "Dettagli Chiave API",
"apikey.display.autoGenerated": "Generata automaticamente",
"apikey.display.copy": "Copia",
@@ -27,6 +30,7 @@
"apikey.form.submit": "Crea",
"apikey.form.title": "Crea Chiave API",
"apikey.list.actions.create": "Crea Chiave API",
+ "apikey.list.actions.creationRestricted": "L'amministratore dello spazio di lavoro ha limitato la creazione delle chiavi API agli amministratori",
"apikey.list.actions.delete": "Elimina",
"apikey.list.actions.deleteConfirm.actions.cancel": "Annulla",
"apikey.list.actions.deleteConfirm.actions.ok": "Conferma",
@@ -40,6 +44,8 @@
"apikey.list.columns.name": "Nome",
"apikey.list.columns.status": "Stato abilitazione",
"apikey.list.empty": "Nessuna chiave API disponibile",
+ "apikey.list.restrictedEmpty.desc": "Solo gli amministratori dello spazio di lavoro possono creare chiavi API. Contatta un amministratore dello spazio di lavoro se ne hai bisogno.",
+ "apikey.list.restrictedEmpty.title": "La creazione delle chiavi API è limitata",
"apikey.list.title": "Elenco Chiavi API",
"apikey.scopes.fullAccess": "Accesso completo",
"apikey.scopes.grantJoin": ": ",
diff --git a/locales/it-IT/setting.json b/locales/it-IT/setting.json
index 29646ddc4a4..7bb87923354 100644
--- a/locales/it-IT/setting.json
+++ b/locales/it-IT/setting.json
@@ -1534,12 +1534,17 @@
"tools.tabs.all": "Tutti",
"tools.tabs.installed": "Abilitati",
"tools.title": "Strumenti Estensione",
+ "workspace.apiKey.policy.desc": "Scegli chi può creare chiavi API personali che agiscono per loro conto in questo workspace.",
+ "workspace.apiKey.policy.options.allMembers": "Tutti i membri",
+ "workspace.apiKey.policy.options.onlyAdmins": "Solo amministratori",
+ "workspace.apiKey.policy.title": "Creazione chiavi API",
+ "workspace.apiKey.policy.updateFailed": "Impossibile aggiornare la politica di creazione delle chiavi API",
"workspace.apiKey.upgrade.benefits.integration.desc": "Chiama agenti e risorse del workspace dai tuoi sistemi tramite l'API di LobeHub.",
"workspace.apiKey.upgrade.benefits.integration.title": "Accesso programmatico",
- "workspace.apiKey.upgrade.benefits.security.desc": "Le richieste vengono eseguite sotto ruoli e permessi del workspace, e le chiavi possono essere revocate centralmente.",
+ "workspace.apiKey.upgrade.benefits.security.desc": "Le richieste rimangono vincolate al workspace e non possono mai superare i permessi attuali dell'emittente.",
"workspace.apiKey.upgrade.benefits.security.title": "Sicurezza a livello di workspace",
- "workspace.apiKey.upgrade.benefits.shared.desc": "Le chiavi appartengono al workspace invece che a una singola persona, quindi l'automazione sopravvive ai cambiamenti dei membri.",
- "workspace.apiKey.upgrade.benefits.shared.title": "Chiavi condivise dal team",
+ "workspace.apiKey.upgrade.benefits.shared.desc": "Gli amministratori possono controllare la creazione da parte dei membri e revocare centralmente le chiavi API attive.",
+ "workspace.apiKey.upgrade.benefits.shared.title": "Governance amministrativa",
"workspace.apiKey.upgrade.cta": "Passa a Pro",
"workspace.apiKey.upgrade.desc": "Crea chiavi API a livello di workspace per integrare agenti e dati del workspace nei tuoi flussi di lavoro e servizi.",
"workspace.apiKey.upgrade.title": "Sblocca le chiavi API del workspace per l'accesso programmatico",
@@ -1547,6 +1552,7 @@
"workspace.auditLog.actions.api_key.renamed": "Chiave API rinominata",
"workspace.auditLog.actions.api_key.revoked": "Chiave API revocata",
"workspace.auditLog.actions.api_key.rotated": "Chiave API ruotata",
+ "workspace.auditLog.actions.api_key.updated": "Chiave API aggiornata",
"workspace.auditLog.actions.auto_top_up.disabled": "Ricarica automatica disattivata",
"workspace.auditLog.actions.auto_top_up.enabled": "Ricarica automatica attivata",
"workspace.auditLog.actions.auto_top_up.failed": "Ricarica automatica fallita",
diff --git a/locales/ja-JP/auth.json b/locales/ja-JP/auth.json
index 8d54bf7ffe7..e51a880e70d 100644
--- a/locales/ja-JP/auth.json
+++ b/locales/ja-JP/auth.json
@@ -4,6 +4,9 @@
"agreement.confirm.ok": "同意して続行",
"agreement.confirm.title": "利用規約とプライバシーポリシー",
"apikey.detail.createdAt": "作成日",
+ "apikey.detail.permissions.cancel": "キャンセル",
+ "apikey.detail.permissions.edit": "権限を編集",
+ "apikey.detail.permissions.save": "権限を保存",
"apikey.detail.title": "APIキーの詳細",
"apikey.display.autoGenerated": "自動生成",
"apikey.display.copy": "コピー",
@@ -27,6 +30,7 @@
"apikey.form.submit": "作成",
"apikey.form.title": "APIキーを作成",
"apikey.list.actions.create": "APIキーを作成",
+ "apikey.list.actions.creationRestricted": "ワークスペース管理者がAPIキーの作成を管理者に制限しています",
"apikey.list.actions.delete": "削除",
"apikey.list.actions.deleteConfirm.actions.cancel": "キャンセル",
"apikey.list.actions.deleteConfirm.actions.ok": "確認",
@@ -40,6 +44,8 @@
"apikey.list.columns.name": "名前",
"apikey.list.columns.status": "有効状態",
"apikey.list.empty": "APIキーはまだありません",
+ "apikey.list.restrictedEmpty.desc": "APIキーはワークスペース管理者のみが作成できます。必要な場合はワークスペース管理者に連絡してください。",
+ "apikey.list.restrictedEmpty.title": "APIキーの作成が制限されています",
"apikey.list.title": "APIキー一覧",
"apikey.scopes.fullAccess": "フルアクセス",
"apikey.scopes.grantJoin": ":",
diff --git a/locales/ja-JP/setting.json b/locales/ja-JP/setting.json
index c84066cf0c8..374a4b1bd57 100644
--- a/locales/ja-JP/setting.json
+++ b/locales/ja-JP/setting.json
@@ -1534,12 +1534,17 @@
"tools.tabs.all": "すべて",
"tools.tabs.installed": "有効化済み",
"tools.title": "拡張ツール",
+ "workspace.apiKey.policy.desc": "このワークスペースで個人のAPIキーを作成し、自分の代わりに操作できる権限を持つ人を選択してください。",
+ "workspace.apiKey.policy.options.allMembers": "すべてのメンバー",
+ "workspace.apiKey.policy.options.onlyAdmins": "管理者のみ",
+ "workspace.apiKey.policy.title": "APIキーの作成",
+ "workspace.apiKey.policy.updateFailed": "APIキー作成ポリシーの更新に失敗しました",
"workspace.apiKey.upgrade.benefits.integration.desc": "LobeHub APIを介して独自のシステムからワークスペースエージェントやリソースを呼び出します。",
"workspace.apiKey.upgrade.benefits.integration.title": "プログラムによるアクセス",
- "workspace.apiKey.upgrade.benefits.security.desc": "リクエストはワークスペースの役割と権限の下で実行され、キーは中央で取り消すことができます。",
+ "workspace.apiKey.upgrade.benefits.security.desc": "リクエストはワークスペースに限定され、発行者の現在の権限を超えることはありません。",
"workspace.apiKey.upgrade.benefits.security.title": "ワークスペース範囲のセキュリティ",
- "workspace.apiKey.upgrade.benefits.shared.desc": "キーは個人ではなくワークスペースに属するため、メンバー変更後も自動化が維持されます。",
- "workspace.apiKey.upgrade.benefits.shared.title": "チーム共有キー",
+ "workspace.apiKey.upgrade.benefits.shared.desc": "管理者はメンバーの作成を管理し、アクティブなAPIキーを中央で取り消すことができます。",
+ "workspace.apiKey.upgrade.benefits.shared.title": "管理者の統制",
"workspace.apiKey.upgrade.cta": "Proにアップグレード",
"workspace.apiKey.upgrade.desc": "ワークスペース範囲のAPIキーを作成して、ワークスペースエージェントやデータを独自のワークフローやサービスに統合します。",
"workspace.apiKey.upgrade.title": "プログラムによるアクセスのためのワークスペースAPIキーを解放",
@@ -1547,6 +1552,7 @@
"workspace.auditLog.actions.api_key.renamed": "APIキーが名前変更されました",
"workspace.auditLog.actions.api_key.revoked": "APIキーが無効化されました",
"workspace.auditLog.actions.api_key.rotated": "APIキーがローテーションされました",
+ "workspace.auditLog.actions.api_key.updated": "APIキーが更新されました",
"workspace.auditLog.actions.auto_top_up.disabled": "自動チャージが無効化されました",
"workspace.auditLog.actions.auto_top_up.enabled": "自動チャージが有効化されました",
"workspace.auditLog.actions.auto_top_up.failed": "自動チャージが失敗しました",
diff --git a/locales/ko-KR/auth.json b/locales/ko-KR/auth.json
index 3a621822821..fcb5725358a 100644
--- a/locales/ko-KR/auth.json
+++ b/locales/ko-KR/auth.json
@@ -4,6 +4,9 @@
"agreement.confirm.ok": "동의하고 계속하기",
"agreement.confirm.title": "이용 약관 및 개인정보 처리방침",
"apikey.detail.createdAt": "생성됨",
+ "apikey.detail.permissions.cancel": "취소",
+ "apikey.detail.permissions.edit": "권한 편집",
+ "apikey.detail.permissions.save": "권한 저장",
"apikey.detail.title": "API 키 세부정보",
"apikey.display.autoGenerated": "자동 생성됨",
"apikey.display.copy": "복사",
@@ -27,6 +30,7 @@
"apikey.form.submit": "생성",
"apikey.form.title": "API 키 생성",
"apikey.list.actions.create": "API 키 생성",
+ "apikey.list.actions.creationRestricted": "워크스페이스 관리자가 API 키 생성 권한을 관리자에게만 제한했습니다",
"apikey.list.actions.delete": "삭제",
"apikey.list.actions.deleteConfirm.actions.cancel": "취소",
"apikey.list.actions.deleteConfirm.actions.ok": "확인",
@@ -40,6 +44,8 @@
"apikey.list.columns.name": "이름",
"apikey.list.columns.status": "활성 상태",
"apikey.list.empty": "API 키가 아직 없습니다",
+ "apikey.list.restrictedEmpty.desc": "API 키는 워크스페이스 관리자만 생성할 수 있습니다. 필요할 경우 워크스페이스 관리자에게 문의하세요.",
+ "apikey.list.restrictedEmpty.title": "API 키 생성이 제한됨",
"apikey.list.title": "API 키 목록",
"apikey.scopes.fullAccess": "전체 액세스",
"apikey.scopes.grantJoin": ": ",
diff --git a/locales/ko-KR/setting.json b/locales/ko-KR/setting.json
index 0085f95d9fc..a30a445907d 100644
--- a/locales/ko-KR/setting.json
+++ b/locales/ko-KR/setting.json
@@ -1534,12 +1534,17 @@
"tools.tabs.all": "전체",
"tools.tabs.installed": "활성화됨",
"tools.title": "확장 도구",
+ "workspace.apiKey.policy.desc": "이 워크스페이스에서 개인 API 키를 생성하여 본인을 대신해 작동할 수 있는 권한을 부여할 대상을 선택하세요.",
+ "workspace.apiKey.policy.options.allMembers": "모든 멤버",
+ "workspace.apiKey.policy.options.onlyAdmins": "관리자만",
+ "workspace.apiKey.policy.title": "API 키 생성",
+ "workspace.apiKey.policy.updateFailed": "API 키 생성 정책 업데이트 실패",
"workspace.apiKey.upgrade.benefits.integration.desc": "LobeHub API를 통해 자체 시스템에서 워크스페이스 에이전트와 리소스를 호출하세요.",
"workspace.apiKey.upgrade.benefits.integration.title": "프로그래밍 액세스",
- "workspace.apiKey.upgrade.benefits.security.desc": "요청은 워크스페이스 역할과 권한 하에서 실행되며, 키는 중앙에서 취소할 수 있습니다.",
+ "workspace.apiKey.upgrade.benefits.security.desc": "요청은 워크스페이스에 묶여 있으며 발급자의 현재 권한을 초과할 수 없습니다.",
"workspace.apiKey.upgrade.benefits.security.title": "워크스페이스 범위 보안",
- "workspace.apiKey.upgrade.benefits.shared.desc": "키는 개인이 아닌 워크스페이스에 속하므로 멤버 변경에도 자동화가 유지됩니다.",
- "workspace.apiKey.upgrade.benefits.shared.title": "팀 공유 키",
+ "workspace.apiKey.upgrade.benefits.shared.desc": "관리자는 멤버 생성 권한을 제어하고 활성 API 키를 중앙에서 해제할 수 있습니다.",
+ "workspace.apiKey.upgrade.benefits.shared.title": "관리자 거버넌스",
"workspace.apiKey.upgrade.cta": "Pro로 업그레이드",
"workspace.apiKey.upgrade.desc": "워크스페이스 범위 API 키를 생성하여 워크스페이스 에이전트와 데이터를 자체 워크플로 및 서비스에 통합하세요.",
"workspace.apiKey.upgrade.title": "프로그래밍 액세스를 위한 워크스페이스 API 키 잠금 해제",
@@ -1547,6 +1552,7 @@
"workspace.auditLog.actions.api_key.renamed": "API 키 이름 변경됨",
"workspace.auditLog.actions.api_key.revoked": "API 키 취소됨",
"workspace.auditLog.actions.api_key.rotated": "API 키 교체됨",
+ "workspace.auditLog.actions.api_key.updated": "API 키 업데이트됨",
"workspace.auditLog.actions.auto_top_up.disabled": "자동 충전 비활성화됨",
"workspace.auditLog.actions.auto_top_up.enabled": "자동 충전 활성화됨",
"workspace.auditLog.actions.auto_top_up.failed": "자동 충전 실패",
diff --git a/locales/nl-NL/auth.json b/locales/nl-NL/auth.json
index 5f001647b3e..ba7324350ce 100644
--- a/locales/nl-NL/auth.json
+++ b/locales/nl-NL/auth.json
@@ -4,6 +4,9 @@
"agreement.confirm.ok": "Akkoord en doorgaan",
"agreement.confirm.title": "Algemene Voorwaarden en Privacybeleid",
"apikey.detail.createdAt": "Gemaakt",
+ "apikey.detail.permissions.cancel": "Annuleren",
+ "apikey.detail.permissions.edit": "Bewerk machtigingen",
+ "apikey.detail.permissions.save": "Sla machtigingen op",
"apikey.detail.title": "API-sleutel Details",
"apikey.display.autoGenerated": "Automatisch gegenereerd",
"apikey.display.copy": "Kopiëren",
@@ -27,6 +30,7 @@
"apikey.form.submit": "Aanmaken",
"apikey.form.title": "API-sleutel aanmaken",
"apikey.list.actions.create": "API-sleutel aanmaken",
+ "apikey.list.actions.creationRestricted": "Uw werkruimtebeheerder heeft het maken van API-sleutels beperkt tot beheerders",
"apikey.list.actions.delete": "Verwijderen",
"apikey.list.actions.deleteConfirm.actions.cancel": "Annuleren",
"apikey.list.actions.deleteConfirm.actions.ok": "Bevestigen",
@@ -40,6 +44,8 @@
"apikey.list.columns.name": "Naam",
"apikey.list.columns.status": "Status ingeschakeld",
"apikey.list.empty": "Nog geen API-sleutels",
+ "apikey.list.restrictedEmpty.desc": "Alleen werkruimtebeheerders kunnen API-sleutels maken. Neem contact op met een werkruimtebeheerder als u er een nodig heeft.",
+ "apikey.list.restrictedEmpty.title": "Het maken van API-sleutels is beperkt",
"apikey.list.title": "Lijst van API-sleutels",
"apikey.scopes.fullAccess": "Volledige toegang",
"apikey.scopes.grantJoin": ": ",
diff --git a/locales/nl-NL/setting.json b/locales/nl-NL/setting.json
index 04d70efff90..3d85604ef1f 100644
--- a/locales/nl-NL/setting.json
+++ b/locales/nl-NL/setting.json
@@ -1534,12 +1534,17 @@
"tools.tabs.all": "Alles",
"tools.tabs.installed": "Ingeschakeld",
"tools.title": "Extensietools",
+ "workspace.apiKey.policy.desc": "Kies wie persoonlijke API-sleutels kan maken die namens hen in deze werkruimte werken.",
+ "workspace.apiKey.policy.options.allMembers": "Alle leden",
+ "workspace.apiKey.policy.options.onlyAdmins": "Alleen beheerders",
+ "workspace.apiKey.policy.title": "API-sleutel aanmaken",
+ "workspace.apiKey.policy.updateFailed": "Het bijwerken van het beleid voor het aanmaken van API-sleutels is mislukt",
"workspace.apiKey.upgrade.benefits.integration.desc": "Roep werkruimte-agenten en -bronnen aan vanuit je eigen systemen via de LobeHub API.",
"workspace.apiKey.upgrade.benefits.integration.title": "Programmatische toegang",
- "workspace.apiKey.upgrade.benefits.security.desc": "Verzoeken worden uitgevoerd onder werkruimte-rollen en -machtigingen, en sleutels kunnen centraal worden ingetrokken.",
+ "workspace.apiKey.upgrade.benefits.security.desc": "Verzoeken blijven gebonden aan de werkruimte en kunnen nooit de huidige machtigingen van de uitgever overschrijden.",
"workspace.apiKey.upgrade.benefits.security.title": "Werkruimte-specifieke beveiliging",
- "workspace.apiKey.upgrade.benefits.shared.desc": "Sleutels behoren tot de werkruimte in plaats van tot één persoon, zodat automatisering blijft werken bij wijzigingen in het team.",
- "workspace.apiKey.upgrade.benefits.shared.title": "Teamgedeelde sleutels",
+ "workspace.apiKey.upgrade.benefits.shared.desc": "Beheerders kunnen het aanmaken door leden beheren en centraal actieve API-sleutels intrekken.",
+ "workspace.apiKey.upgrade.benefits.shared.title": "Beheerdersbeheer",
"workspace.apiKey.upgrade.cta": "Upgrade naar Pro",
"workspace.apiKey.upgrade.desc": "Maak werkruimte-specifieke API-sleutels om werkruimte-agenten en -gegevens te integreren in je eigen workflows en diensten.",
"workspace.apiKey.upgrade.title": "Ontgrendel werkruimte API-sleutels voor programmatische toegang",
@@ -1547,6 +1552,7 @@
"workspace.auditLog.actions.api_key.renamed": "API-sleutel hernoemd",
"workspace.auditLog.actions.api_key.revoked": "API-sleutel ingetrokken",
"workspace.auditLog.actions.api_key.rotated": "API-sleutel vernieuwd",
+ "workspace.auditLog.actions.api_key.updated": "API-sleutel bijgewerkt",
"workspace.auditLog.actions.auto_top_up.disabled": "Automatisch opwaarderen uitgeschakeld",
"workspace.auditLog.actions.auto_top_up.enabled": "Automatisch opwaarderen ingeschakeld",
"workspace.auditLog.actions.auto_top_up.failed": "Automatisch opwaarderen mislukt",
diff --git a/locales/pl-PL/auth.json b/locales/pl-PL/auth.json
index 346012c823f..8ff983fd33f 100644
--- a/locales/pl-PL/auth.json
+++ b/locales/pl-PL/auth.json
@@ -4,6 +4,9 @@
"agreement.confirm.ok": "Zgadzam się i kontynuuję",
"agreement.confirm.title": "Warunki i Polityka prywatności",
"apikey.detail.createdAt": "Utworzono",
+ "apikey.detail.permissions.cancel": "Anuluj",
+ "apikey.detail.permissions.edit": "Edytuj uprawnienia",
+ "apikey.detail.permissions.save": "Zapisz uprawnienia",
"apikey.detail.title": "Szczegóły Klucza API",
"apikey.display.autoGenerated": "Wygenerowany automatycznie",
"apikey.display.copy": "Kopiuj",
@@ -27,6 +30,7 @@
"apikey.form.submit": "Utwórz",
"apikey.form.title": "Utwórz klucz API",
"apikey.list.actions.create": "Utwórz klucz API",
+ "apikey.list.actions.creationRestricted": "Administrator Twojego obszaru roboczego ograniczył tworzenie kluczy API do administratorów",
"apikey.list.actions.delete": "Usuń",
"apikey.list.actions.deleteConfirm.actions.cancel": "Anuluj",
"apikey.list.actions.deleteConfirm.actions.ok": "Potwierdź",
@@ -40,6 +44,8 @@
"apikey.list.columns.name": "Nazwa",
"apikey.list.columns.status": "Status włączenia",
"apikey.list.empty": "Brak kluczy API",
+ "apikey.list.restrictedEmpty.desc": "Tylko administratorzy obszaru roboczego mogą tworzyć klucze API. Skontaktuj się z administratorem obszaru roboczego, jeśli potrzebujesz klucza.",
+ "apikey.list.restrictedEmpty.title": "Tworzenie kluczy API jest ograniczone",
"apikey.list.title": "Lista kluczy API",
"apikey.scopes.fullAccess": "Pełny dostęp",
"apikey.scopes.grantJoin": ": ",
diff --git a/locales/pl-PL/setting.json b/locales/pl-PL/setting.json
index 1bcac50188d..a54fe20f082 100644
--- a/locales/pl-PL/setting.json
+++ b/locales/pl-PL/setting.json
@@ -1534,12 +1534,17 @@
"tools.tabs.all": "Wszystkie",
"tools.tabs.installed": "Włączone",
"tools.title": "Narzędzia rozszerzeń",
+ "workspace.apiKey.policy.desc": "Wybierz, kto może tworzyć osobiste klucze API działające w ich imieniu w tej przestrzeni roboczej.",
+ "workspace.apiKey.policy.options.allMembers": "Wszyscy członkowie",
+ "workspace.apiKey.policy.options.onlyAdmins": "Tylko administratorzy",
+ "workspace.apiKey.policy.title": "Tworzenie kluczy API",
+ "workspace.apiKey.policy.updateFailed": "Nie udało się zaktualizować polityki tworzenia kluczy API",
"workspace.apiKey.upgrade.benefits.integration.desc": "Wywołuj agentów i zasoby przestrzeni roboczej z własnych systemów za pomocą API LobeHub.",
"workspace.apiKey.upgrade.benefits.integration.title": "Dostęp programowy",
- "workspace.apiKey.upgrade.benefits.security.desc": "Żądania działają w ramach ról i uprawnień przestrzeni roboczej, a klucze mogą być centralnie odwoływane.",
+ "workspace.apiKey.upgrade.benefits.security.desc": "Żądania pozostają powiązane z przestrzenią roboczą i nigdy nie mogą przekroczyć bieżących uprawnień wystawcy.",
"workspace.apiKey.upgrade.benefits.security.title": "Bezpieczeństwo w zakresie przestrzeni roboczej",
- "workspace.apiKey.upgrade.benefits.shared.desc": "Klucze należą do przestrzeni roboczej, a nie do jednej osoby, dzięki czemu automatyzacja przetrwa zmiany członków.",
- "workspace.apiKey.upgrade.benefits.shared.title": "Klucze współdzielone przez zespół",
+ "workspace.apiKey.upgrade.benefits.shared.desc": "Administratorzy mogą kontrolować tworzenie kluczy przez członków i centralnie unieważniać aktywne klucze API.",
+ "workspace.apiKey.upgrade.benefits.shared.title": "Zarządzanie przez administratora",
"workspace.apiKey.upgrade.cta": "Ulepsz do wersji Pro",
"workspace.apiKey.upgrade.desc": "Twórz klucze API przypisane do przestrzeni roboczej, aby integrować agentów i dane przestrzeni roboczej z własnymi przepływami pracy i usługami.",
"workspace.apiKey.upgrade.title": "Odblokuj klucze API przestrzeni roboczej dla dostępu programowego",
@@ -1547,6 +1552,7 @@
"workspace.auditLog.actions.api_key.renamed": "Zmieniono nazwę klucza API",
"workspace.auditLog.actions.api_key.revoked": "Odwołano klucz API",
"workspace.auditLog.actions.api_key.rotated": "Obrócono klucz API",
+ "workspace.auditLog.actions.api_key.updated": "Klucz API zaktualizowany",
"workspace.auditLog.actions.auto_top_up.disabled": "Automatyczne doładowanie wyłączone",
"workspace.auditLog.actions.auto_top_up.enabled": "Automatyczne doładowanie włączone",
"workspace.auditLog.actions.auto_top_up.failed": "Automatyczne doładowanie nie powiodło się",
diff --git a/locales/pt-BR/auth.json b/locales/pt-BR/auth.json
index d9891285238..e447df9bbb9 100644
--- a/locales/pt-BR/auth.json
+++ b/locales/pt-BR/auth.json
@@ -4,6 +4,9 @@
"agreement.confirm.ok": "Concordar e continuar",
"agreement.confirm.title": "Termos e Política de Privacidade",
"apikey.detail.createdAt": "Criado",
+ "apikey.detail.permissions.cancel": "Cancelar",
+ "apikey.detail.permissions.edit": "Editar permissões",
+ "apikey.detail.permissions.save": "Salvar permissões",
"apikey.detail.title": "Detalhes da Chave de API",
"apikey.display.autoGenerated": "Gerado automaticamente",
"apikey.display.copy": "Copiar",
@@ -27,6 +30,7 @@
"apikey.form.submit": "Criar",
"apikey.form.title": "Criar Chave de API",
"apikey.list.actions.create": "Criar Chave de API",
+ "apikey.list.actions.creationRestricted": "O administrador do espaço de trabalho restringiu a criação de Chaves de API apenas para administradores",
"apikey.list.actions.delete": "Excluir",
"apikey.list.actions.deleteConfirm.actions.cancel": "Cancelar",
"apikey.list.actions.deleteConfirm.actions.ok": "Confirmar",
@@ -40,6 +44,8 @@
"apikey.list.columns.name": "Nome",
"apikey.list.columns.status": "Status Ativado",
"apikey.list.empty": "Nenhuma chave de API ainda",
+ "apikey.list.restrictedEmpty.desc": "Somente administradores do espaço de trabalho podem criar Chaves de API. Entre em contato com um administrador do espaço de trabalho se precisar de uma.",
+ "apikey.list.restrictedEmpty.title": "A criação de Chaves de API está restrita",
"apikey.list.title": "Lista de Chaves de API",
"apikey.scopes.fullAccess": "Acesso total",
"apikey.scopes.grantJoin": ": ",
diff --git a/locales/pt-BR/setting.json b/locales/pt-BR/setting.json
index 096e0855dff..23b6ce70453 100644
--- a/locales/pt-BR/setting.json
+++ b/locales/pt-BR/setting.json
@@ -1534,12 +1534,17 @@
"tools.tabs.all": "Todas",
"tools.tabs.installed": "Ativadas",
"tools.title": "Ferramentas de Extensão",
+ "workspace.apiKey.policy.desc": "Escolha quem pode criar chaves de API pessoais que atuam em seu nome neste espaço de trabalho.",
+ "workspace.apiKey.policy.options.allMembers": "Todos os membros",
+ "workspace.apiKey.policy.options.onlyAdmins": "Somente administradores",
+ "workspace.apiKey.policy.title": "Criação de chave de API",
+ "workspace.apiKey.policy.updateFailed": "Falha ao atualizar a política de criação de chave de API",
"workspace.apiKey.upgrade.benefits.integration.desc": "Chame agentes e recursos do workspace a partir de seus próprios sistemas via a API LobeHub.",
"workspace.apiKey.upgrade.benefits.integration.title": "Acesso programático",
- "workspace.apiKey.upgrade.benefits.security.desc": "As solicitações são executadas sob funções e permissões do workspace, e as chaves podem ser revogadas centralmente.",
+ "workspace.apiKey.upgrade.benefits.security.desc": "As solicitações permanecem vinculadas ao espaço de trabalho e nunca podem exceder as permissões atuais do emissor.",
"workspace.apiKey.upgrade.benefits.security.title": "Segurança com escopo de workspace",
- "workspace.apiKey.upgrade.benefits.shared.desc": "As chaves pertencem ao workspace em vez de a uma pessoa, permitindo que a automação sobreviva a mudanças de membros.",
- "workspace.apiKey.upgrade.benefits.shared.title": "Chaves compartilhadas pela equipe",
+ "workspace.apiKey.upgrade.benefits.shared.desc": "Os administradores podem controlar a criação de membros e revogar centralmente chaves de API ativas.",
+ "workspace.apiKey.upgrade.benefits.shared.title": "Governança administrativa",
"workspace.apiKey.upgrade.cta": "Faça upgrade para Pro",
"workspace.apiKey.upgrade.desc": "Crie chaves de API com escopo de workspace para integrar agentes e dados do workspace em seus próprios fluxos de trabalho e serviços.",
"workspace.apiKey.upgrade.title": "Desbloqueie chaves de API do workspace para acesso programático",
@@ -1547,6 +1552,7 @@
"workspace.auditLog.actions.api_key.renamed": "Chave de API renomeada",
"workspace.auditLog.actions.api_key.revoked": "Chave de API revogada",
"workspace.auditLog.actions.api_key.rotated": "Chave de API rotacionada",
+ "workspace.auditLog.actions.api_key.updated": "Chave de API atualizada",
"workspace.auditLog.actions.auto_top_up.disabled": "Recarga automática desativada",
"workspace.auditLog.actions.auto_top_up.enabled": "Recarga automática ativada",
"workspace.auditLog.actions.auto_top_up.failed": "Falha na recarga automática",
diff --git a/locales/ru-RU/auth.json b/locales/ru-RU/auth.json
index 5ea56e6349c..45972a72bbc 100644
--- a/locales/ru-RU/auth.json
+++ b/locales/ru-RU/auth.json
@@ -4,6 +4,9 @@
"agreement.confirm.ok": "Согласиться и продолжить",
"agreement.confirm.title": "Условия и Политика конфиденциальности",
"apikey.detail.createdAt": "Создано",
+ "apikey.detail.permissions.cancel": "Отменить",
+ "apikey.detail.permissions.edit": "Редактировать разрешения",
+ "apikey.detail.permissions.save": "Сохранить разрешения",
"apikey.detail.title": "Детали API-ключа",
"apikey.display.autoGenerated": "Автоматически сгенерировано",
"apikey.display.copy": "Копировать",
@@ -27,6 +30,7 @@
"apikey.form.submit": "Создать",
"apikey.form.title": "Создание API-ключа",
"apikey.list.actions.create": "Создать API-ключ",
+ "apikey.list.actions.creationRestricted": "Администратор вашего рабочего пространства ограничил создание API-ключей только для администраторов",
"apikey.list.actions.delete": "Удалить",
"apikey.list.actions.deleteConfirm.actions.cancel": "Отмена",
"apikey.list.actions.deleteConfirm.actions.ok": "Подтвердить",
@@ -40,6 +44,8 @@
"apikey.list.columns.name": "Имя",
"apikey.list.columns.status": "Статус",
"apikey.list.empty": "API-ключи отсутствуют",
+ "apikey.list.restrictedEmpty.desc": "Только администраторы рабочего пространства могут создавать API-ключи. Свяжитесь с администратором рабочего пространства, если вам нужен ключ.",
+ "apikey.list.restrictedEmpty.title": "Создание API-ключей ограничено",
"apikey.list.title": "Список API-ключей",
"apikey.scopes.fullAccess": "Полный доступ",
"apikey.scopes.grantJoin": ": ",
diff --git a/locales/ru-RU/setting.json b/locales/ru-RU/setting.json
index f72b42db532..be91a2123dd 100644
--- a/locales/ru-RU/setting.json
+++ b/locales/ru-RU/setting.json
@@ -1534,12 +1534,17 @@
"tools.tabs.all": "Все",
"tools.tabs.installed": "Включено",
"tools.title": "Расширения",
+ "workspace.apiKey.policy.desc": "Выберите, кто может создавать персональные API-ключи, которые действуют от их имени в этом рабочем пространстве.",
+ "workspace.apiKey.policy.options.allMembers": "Все участники",
+ "workspace.apiKey.policy.options.onlyAdmins": "Только администраторы",
+ "workspace.apiKey.policy.title": "Создание API-ключей",
+ "workspace.apiKey.policy.updateFailed": "Не удалось обновить политику создания API-ключей",
"workspace.apiKey.upgrade.benefits.integration.desc": "Вызывайте агентов и ресурсы рабочего пространства из ваших собственных систем через API LobeHub.",
"workspace.apiKey.upgrade.benefits.integration.title": "Программный доступ",
- "workspace.apiKey.upgrade.benefits.security.desc": "Запросы выполняются в рамках ролей и разрешений рабочего пространства, а ключи могут быть отозваны централизованно.",
+ "workspace.apiKey.upgrade.benefits.security.desc": "Запросы остаются привязанными к рабочему пространству и никогда не могут превышать текущие разрешения издателя.",
"workspace.apiKey.upgrade.benefits.security.title": "Безопасность в рамках рабочего пространства",
- "workspace.apiKey.upgrade.benefits.shared.desc": "Ключи принадлежат рабочему пространству, а не одному человеку, поэтому автоматизация сохраняется при изменении участников.",
- "workspace.apiKey.upgrade.benefits.shared.title": "Ключи, общие для команды",
+ "workspace.apiKey.upgrade.benefits.shared.desc": "Администраторы могут контролировать создание ключей участниками и централизованно отзывать активные API-ключи.",
+ "workspace.apiKey.upgrade.benefits.shared.title": "Управление администраторами",
"workspace.apiKey.upgrade.cta": "Обновить до Pro",
"workspace.apiKey.upgrade.desc": "Создавайте ключи API, привязанные к рабочему пространству, чтобы интегрировать агентов и данные рабочего пространства в ваши собственные рабочие процессы и сервисы.",
"workspace.apiKey.upgrade.title": "Разблокируйте ключи API рабочего пространства для программного доступа",
@@ -1547,6 +1552,7 @@
"workspace.auditLog.actions.api_key.renamed": "Переименован ключ API",
"workspace.auditLog.actions.api_key.revoked": "Отозван ключ API",
"workspace.auditLog.actions.api_key.rotated": "Обновлен ключ API",
+ "workspace.auditLog.actions.api_key.updated": "API-ключ обновлен",
"workspace.auditLog.actions.auto_top_up.disabled": "Автоматическое пополнение отключено",
"workspace.auditLog.actions.auto_top_up.enabled": "Автоматическое пополнение включено",
"workspace.auditLog.actions.auto_top_up.failed": "Ошибка автоматического пополнения",
diff --git a/locales/tr-TR/auth.json b/locales/tr-TR/auth.json
index f2dd681064b..badcbafed8e 100644
--- a/locales/tr-TR/auth.json
+++ b/locales/tr-TR/auth.json
@@ -4,6 +4,9 @@
"agreement.confirm.ok": "Kabul et ve devam et",
"agreement.confirm.title": "Şartlar ve Gizlilik Politikası",
"apikey.detail.createdAt": "Oluşturulma Tarihi",
+ "apikey.detail.permissions.cancel": "İptal",
+ "apikey.detail.permissions.edit": "İzinleri düzenle",
+ "apikey.detail.permissions.save": "İzinleri kaydet",
"apikey.detail.title": "API Anahtarı Detayları",
"apikey.display.autoGenerated": "Otomatik oluşturuldu",
"apikey.display.copy": "Kopyala",
@@ -27,6 +30,7 @@
"apikey.form.submit": "Oluştur",
"apikey.form.title": "API Anahtarı Oluştur",
"apikey.list.actions.create": "API Anahtarı Oluştur",
+ "apikey.list.actions.creationRestricted": "Çalışma alanı yöneticiniz API Anahtarı oluşturmayı yöneticilerle sınırlandırdı",
"apikey.list.actions.delete": "Sil",
"apikey.list.actions.deleteConfirm.actions.cancel": "İptal",
"apikey.list.actions.deleteConfirm.actions.ok": "Onayla",
@@ -40,6 +44,8 @@
"apikey.list.columns.name": "Ad",
"apikey.list.columns.status": "Etkinlik Durumu",
"apikey.list.empty": "Henüz API Anahtarı yok",
+ "apikey.list.restrictedEmpty.desc": "Sadece çalışma alanı yöneticileri API Anahtarları oluşturabilir. Bir API Anahtarına ihtiyacınız varsa bir çalışma alanı yöneticisiyle iletişime geçin.",
+ "apikey.list.restrictedEmpty.title": "API Anahtarı oluşturma sınırlandırıldı",
"apikey.list.title": "API Anahtarı Listesi",
"apikey.scopes.fullAccess": "Tam erişim",
"apikey.scopes.grantJoin": ": ",
diff --git a/locales/tr-TR/setting.json b/locales/tr-TR/setting.json
index 6bff6b28b93..ca8e1d33de8 100644
--- a/locales/tr-TR/setting.json
+++ b/locales/tr-TR/setting.json
@@ -1534,12 +1534,17 @@
"tools.tabs.all": "Tümü",
"tools.tabs.installed": "Etkin",
"tools.title": "Eklenti Araçları",
+ "workspace.apiKey.policy.desc": "Bu çalışma alanında kendi adlarına hareket eden kişisel API Anahtarlarını kimlerin oluşturabileceğini seçin.",
+ "workspace.apiKey.policy.options.allMembers": "Tüm üyeler",
+ "workspace.apiKey.policy.options.onlyAdmins": "Sadece yöneticiler",
+ "workspace.apiKey.policy.title": "API Anahtarı oluşturma",
+ "workspace.apiKey.policy.updateFailed": "API Anahtarı oluşturma politikası güncellenemedi",
"workspace.apiKey.upgrade.benefits.integration.desc": "LobeHub API aracılığıyla kendi sistemlerinizden çalışma alanı ajanlarını ve kaynaklarını çağırın.",
"workspace.apiKey.upgrade.benefits.integration.title": "Programatik erişim",
- "workspace.apiKey.upgrade.benefits.security.desc": "İstekler çalışma alanı rolleri ve izinleri altında çalışır ve anahtarlar merkezi olarak iptal edilebilir.",
+ "workspace.apiKey.upgrade.benefits.security.desc": "İstekler çalışma alanına bağlı kalır ve hiçbir zaman verenin mevcut izinlerini aşamaz.",
"workspace.apiKey.upgrade.benefits.security.title": "Çalışma alanı kapsamlı güvenlik",
- "workspace.apiKey.upgrade.benefits.shared.desc": "Anahtarlar bir kişiye değil çalışma alanına ait olduğundan, otomasyon üye değişikliklerinden etkilenmez.",
- "workspace.apiKey.upgrade.benefits.shared.title": "Takım tarafından paylaşılan anahtarlar",
+ "workspace.apiKey.upgrade.benefits.shared.desc": "Yöneticiler, üye oluşturmayı kontrol edebilir ve aktif API Anahtarlarını merkezi olarak iptal edebilir.",
+ "workspace.apiKey.upgrade.benefits.shared.title": "Yönetici yönetimi",
"workspace.apiKey.upgrade.cta": "Pro'ya Yükselt",
"workspace.apiKey.upgrade.desc": "Çalışma alanı kapsamlı API anahtarları oluşturun ve çalışma alanı ajanlarını ve verilerini kendi iş akışlarınıza ve hizmetlerinize entegre edin.",
"workspace.apiKey.upgrade.title": "Programatik erişim için çalışma alanı API anahtarlarını açın",
@@ -1547,6 +1552,7 @@
"workspace.auditLog.actions.api_key.renamed": "API anahtarı yeniden adlandırıldı",
"workspace.auditLog.actions.api_key.revoked": "API anahtarı iptal edildi",
"workspace.auditLog.actions.api_key.rotated": "API anahtarı döndürüldü",
+ "workspace.auditLog.actions.api_key.updated": "API anahtarı güncellendi",
"workspace.auditLog.actions.auto_top_up.disabled": "Otomatik bakiye yükleme devre dışı bırakıldı",
"workspace.auditLog.actions.auto_top_up.enabled": "Otomatik bakiye yükleme etkinleştirildi",
"workspace.auditLog.actions.auto_top_up.failed": "Otomatik bakiye yükleme başarısız oldu",
diff --git a/locales/vi-VN/auth.json b/locales/vi-VN/auth.json
index 3ee61b27da2..edf9b966c5f 100644
--- a/locales/vi-VN/auth.json
+++ b/locales/vi-VN/auth.json
@@ -4,6 +4,9 @@
"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.permissions.cancel": "Hủy",
+ "apikey.detail.permissions.edit": "Chỉnh sửa quyền",
+ "apikey.detail.permissions.save": "Lưu quyền",
"apikey.detail.title": "Chi tiết API Key",
"apikey.display.autoGenerated": "Tự động tạo",
"apikey.display.copy": "Sao chép",
@@ -27,6 +30,7 @@
"apikey.form.submit": "Tạo",
"apikey.form.title": "Tạo API Key",
"apikey.list.actions.create": "Tạo API Key",
+ "apikey.list.actions.creationRestricted": "Quản trị viên không gian làm việc của bạn đã giới hạn việc tạo API Key chỉ dành cho quản trị viên",
"apikey.list.actions.delete": "Xóa",
"apikey.list.actions.deleteConfirm.actions.cancel": "Hủy",
"apikey.list.actions.deleteConfirm.actions.ok": "Xác nhận",
@@ -40,6 +44,8 @@
"apikey.list.columns.name": "Tên",
"apikey.list.columns.status": "Trạng thái kích hoạt",
"apikey.list.empty": "Chưa có API Key nào",
+ "apikey.list.restrictedEmpty.desc": "Chỉ quản trị viên không gian làm việc mới có thể tạo API Key. Liên hệ với quản trị viên không gian làm việc nếu bạn cần một API Key.",
+ "apikey.list.restrictedEmpty.title": "Việc tạo API Key bị giới hạn",
"apikey.list.title": "Danh sách API Key",
"apikey.scopes.fullAccess": "Quyền truy cập đầy đủ",
"apikey.scopes.grantJoin": ": ",
diff --git a/locales/vi-VN/setting.json b/locales/vi-VN/setting.json
index 951a0751203..fb7e07bd878 100644
--- a/locales/vi-VN/setting.json
+++ b/locales/vi-VN/setting.json
@@ -1534,12 +1534,17 @@
"tools.tabs.all": "Tất Cả",
"tools.tabs.installed": "Đã Bật",
"tools.title": "Công Cụ Mở Rộng",
+ "workspace.apiKey.policy.desc": "Chọn ai có thể tạo API Key cá nhân để hoạt động thay mặt họ trong không gian làm việc này.",
+ "workspace.apiKey.policy.options.allMembers": "Tất cả thành viên",
+ "workspace.apiKey.policy.options.onlyAdmins": "Chỉ quản trị viên",
+ "workspace.apiKey.policy.title": "Tạo API Key",
+ "workspace.apiKey.policy.updateFailed": "Không thể cập nhật chính sách tạo API Key",
"workspace.apiKey.upgrade.benefits.integration.desc": "Gọi các tác nhân và tài nguyên của không gian làm việc từ hệ thống của bạn thông qua API LobeHub.",
"workspace.apiKey.upgrade.benefits.integration.title": "Truy cập lập trình",
- "workspace.apiKey.upgrade.benefits.security.desc": "Các yêu cầu được thực hiện dưới vai trò và quyền của không gian làm việc, và các khóa có thể bị thu hồi tập trung.",
+ "workspace.apiKey.upgrade.benefits.security.desc": "Yêu cầu luôn gắn liền với không gian làm việc và không bao giờ vượt quá quyền hiện tại của người phát hành.",
"workspace.apiKey.upgrade.benefits.security.title": "Bảo mật theo phạm vi không gian làm việc",
- "workspace.apiKey.upgrade.benefits.shared.desc": "Các khóa thuộc về không gian làm việc thay vì một cá nhân, do đó tự động hóa vẫn hoạt động khi thành viên thay đổi.",
- "workspace.apiKey.upgrade.benefits.shared.title": "Khóa chia sẻ nhóm",
+ "workspace.apiKey.upgrade.benefits.shared.desc": "Quản trị viên có thể kiểm soát việc tạo của thành viên và thu hồi API Key đang hoạt động từ trung tâm.",
+ "workspace.apiKey.upgrade.benefits.shared.title": "Quản trị bởi quản trị viên",
"workspace.apiKey.upgrade.cta": "Nâng cấp lên Pro",
"workspace.apiKey.upgrade.desc": "Tạo các khóa API theo phạm vi không gian làm việc để tích hợp các tác nhân và dữ liệu của không gian làm việc vào quy trình và dịch vụ của bạn.",
"workspace.apiKey.upgrade.title": "Mở khóa các khóa API không gian làm việc để truy cập lập trình",
@@ -1547,6 +1552,7 @@
"workspace.auditLog.actions.api_key.renamed": "Đã đổi tên khóa API",
"workspace.auditLog.actions.api_key.revoked": "Đã thu hồi khóa API",
"workspace.auditLog.actions.api_key.rotated": "Đã xoay vòng khóa API",
+ "workspace.auditLog.actions.api_key.updated": "API Key đã được cập nhật",
"workspace.auditLog.actions.auto_top_up.disabled": "Đã tắt tự động nạp tiền",
"workspace.auditLog.actions.auto_top_up.enabled": "Đã bật tự động nạp tiền",
"workspace.auditLog.actions.auto_top_up.failed": "Tự động nạp tiền thất bại",
diff --git a/locales/zh-CN/auth.json b/locales/zh-CN/auth.json
index 29e9f708551..56dd93059e5 100644
--- a/locales/zh-CN/auth.json
+++ b/locales/zh-CN/auth.json
@@ -4,6 +4,9 @@
"agreement.confirm.ok": "同意并继续",
"agreement.confirm.title": "确认服务条款与隐私政策",
"apikey.detail.createdAt": "创建时间",
+ "apikey.detail.permissions.cancel": "取消",
+ "apikey.detail.permissions.edit": "编辑权限",
+ "apikey.detail.permissions.save": "保存权限",
"apikey.detail.title": "API Key 详情",
"apikey.display.autoGenerated": "自动生成",
"apikey.display.copy": "复制",
@@ -27,6 +30,7 @@
"apikey.form.submit": "创建",
"apikey.form.title": "创建 API Key",
"apikey.list.actions.create": "创建 API Key",
+ "apikey.list.actions.creationRestricted": "工作区管理员已将 API Key 创建权限限制为仅管理员",
"apikey.list.actions.delete": "删除",
"apikey.list.actions.deleteConfirm.actions.cancel": "取消",
"apikey.list.actions.deleteConfirm.actions.ok": "确认",
@@ -40,6 +44,8 @@
"apikey.list.columns.name": "名称",
"apikey.list.columns.status": "启用",
"apikey.list.empty": "暂无 API Key",
+ "apikey.list.restrictedEmpty.desc": "仅工作区管理员可以创建 API Key。如有需要,请联系工作区管理员。",
+ "apikey.list.restrictedEmpty.title": "API Key 创建权限已受限",
"apikey.list.title": "API Key 列表",
"apikey.scopes.fullAccess": "完全访问",
"apikey.scopes.grantJoin": ":",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 179a1e0dac2..1cb4b97313e 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -1534,12 +1534,17 @@
"tools.tabs.all": "全部",
"tools.tabs.installed": "已启用",
"tools.title": "技能",
+ "workspace.apiKey.policy.desc": "选择哪些成员可以创建代表自己访问此工作区的个人 API Key。",
+ "workspace.apiKey.policy.options.allMembers": "所有成员",
+ "workspace.apiKey.policy.options.onlyAdmins": "仅管理员",
+ "workspace.apiKey.policy.title": "API Key 创建权限",
+ "workspace.apiKey.policy.updateFailed": "更新 API Key 创建策略失败",
"workspace.apiKey.upgrade.benefits.integration.desc": "通过 LobeHub API 在您自己的系统中调用工作区的助理与资源。",
"workspace.apiKey.upgrade.benefits.integration.title": "编程化访问",
- "workspace.apiKey.upgrade.benefits.security.desc": "请求始终绑定当前工作区,并要求签发者保持所有者身份。",
+ "workspace.apiKey.upgrade.benefits.security.desc": "请求始终绑定工作区,且权限不会超过签发者当前拥有的权限。",
"workspace.apiKey.upgrade.benefits.security.title": "工作区级安全",
- "workspace.apiKey.upgrade.benefits.shared.desc": "只有工作区所有者可以创建、查看、管理和吊销工作区 API 密钥。",
- "workspace.apiKey.upgrade.benefits.shared.title": "所有者管理",
+ "workspace.apiKey.upgrade.benefits.shared.desc": "管理员可以控制成员创建权限,并集中吊销活动中的 API Key。",
+ "workspace.apiKey.upgrade.benefits.shared.title": "管理员治理",
"workspace.apiKey.upgrade.cta": "升级到 Pro",
"workspace.apiKey.upgrade.desc": "创建工作区级 API 密钥,将工作区的助理与数据集成到您自己的工作流和服务中。",
"workspace.apiKey.upgrade.title": "解锁工作区 API 密钥,开启编程化访问",
@@ -1547,6 +1552,7 @@
"workspace.auditLog.actions.api_key.renamed": "重命名 API Key",
"workspace.auditLog.actions.api_key.revoked": "撤销 API Key",
"workspace.auditLog.actions.api_key.rotated": "轮换 API Key",
+ "workspace.auditLog.actions.api_key.updated": "更新 API Key",
"workspace.auditLog.actions.auto_top_up.disabled": "关闭自动充值",
"workspace.auditLog.actions.auto_top_up.enabled": "开启自动充值",
"workspace.auditLog.actions.auto_top_up.failed": "自动充值失败",
diff --git a/locales/zh-TW/auth.json b/locales/zh-TW/auth.json
index 78e94a3b340..f20b1ab905f 100644
--- a/locales/zh-TW/auth.json
+++ b/locales/zh-TW/auth.json
@@ -4,6 +4,9 @@
"agreement.confirm.ok": "同意並繼續",
"agreement.confirm.title": "條款與隱私政策",
"apikey.detail.createdAt": "建立時間",
+ "apikey.detail.permissions.cancel": "取消",
+ "apikey.detail.permissions.edit": "編輯權限",
+ "apikey.detail.permissions.save": "保存權限",
"apikey.detail.title": "API 金鑰詳細資訊",
"apikey.display.autoGenerated": "自動生成",
"apikey.display.copy": "複製",
@@ -27,6 +30,7 @@
"apikey.form.submit": "建立",
"apikey.form.title": "建立 API Key",
"apikey.list.actions.create": "建立 API Key",
+ "apikey.list.actions.creationRestricted": "您的工作區管理員已限制僅由管理員創建 API 金鑰",
"apikey.list.actions.delete": "刪除",
"apikey.list.actions.deleteConfirm.actions.cancel": "取消",
"apikey.list.actions.deleteConfirm.actions.ok": "確認",
@@ -40,6 +44,8 @@
"apikey.list.columns.name": "名稱",
"apikey.list.columns.status": "啟用狀態",
"apikey.list.empty": "尚未有 API 密鑰",
+ "apikey.list.restrictedEmpty.desc": "只有工作區管理員可以創建 API 金鑰。如需 API 金鑰,請聯繫工作區管理員。",
+ "apikey.list.restrictedEmpty.title": "API 金鑰創建已被限制",
"apikey.list.title": "API Key 列表",
"apikey.scopes.fullAccess": "完全存取",
"apikey.scopes.grantJoin": ":",
diff --git a/locales/zh-TW/setting.json b/locales/zh-TW/setting.json
index bbd8138656b..ea444bf7c6e 100644
--- a/locales/zh-TW/setting.json
+++ b/locales/zh-TW/setting.json
@@ -1534,12 +1534,17 @@
"tools.tabs.all": "全部",
"tools.tabs.installed": "已啟用",
"tools.title": "擴展工具",
+ "workspace.apiKey.policy.desc": "選擇誰可以在此工作區中創建代表他們的個人 API 金鑰。",
+ "workspace.apiKey.policy.options.allMembers": "所有成員",
+ "workspace.apiKey.policy.options.onlyAdmins": "僅限管理員",
+ "workspace.apiKey.policy.title": "API 金鑰創建",
+ "workspace.apiKey.policy.updateFailed": "無法更新 API 金鑰創建政策",
"workspace.apiKey.upgrade.benefits.integration.desc": "透過 LobeHub API 從您的系統調用工作區代理和資源。",
"workspace.apiKey.upgrade.benefits.integration.title": "程式化存取",
- "workspace.apiKey.upgrade.benefits.security.desc": "請求在工作區角色和權限下運行,並且金鑰可以集中撤銷。",
+ "workspace.apiKey.upgrade.benefits.security.desc": "請求保持綁定於工作區,且永遠無法超出發行者的當前權限。",
"workspace.apiKey.upgrade.benefits.security.title": "工作區範圍的安全性",
- "workspace.apiKey.upgrade.benefits.shared.desc": "金鑰屬於工作區而非個人,因此自動化能在成員變更時保持運作。",
- "workspace.apiKey.upgrade.benefits.shared.title": "團隊共享金鑰",
+ "workspace.apiKey.upgrade.benefits.shared.desc": "管理員可以控制成員創建並集中撤銷活動的 API 金鑰。",
+ "workspace.apiKey.upgrade.benefits.shared.title": "管理員治理",
"workspace.apiKey.upgrade.cta": "升級到 Pro",
"workspace.apiKey.upgrade.desc": "創建工作區範圍的 API 金鑰,將工作區代理和數據整合到您的工作流程和服務中。",
"workspace.apiKey.upgrade.title": "解鎖工作區 API 金鑰以進行程式化存取",
@@ -1547,6 +1552,7 @@
"workspace.auditLog.actions.api_key.renamed": "API 金鑰已重新命名",
"workspace.auditLog.actions.api_key.revoked": "API 金鑰已撤銷",
"workspace.auditLog.actions.api_key.rotated": "API 金鑰已輪替",
+ "workspace.auditLog.actions.api_key.updated": "API 金鑰已更新",
"workspace.auditLog.actions.auto_top_up.disabled": "自動加值已停用",
"workspace.auditLog.actions.auto_top_up.enabled": "自動加值已啟用",
"workspace.auditLog.actions.auto_top_up.failed": "自動加值失敗",
diff --git a/packages/const/src/rbac.ts b/packages/const/src/rbac.ts
index f9264f5dbc1..7869c81b230 100644
--- a/packages/const/src/rbac.ts
+++ b/packages/const/src/rbac.ts
@@ -548,6 +548,11 @@ export const WORKSPACE_ROLE_PERMISSIONS: Record<WorkspaceSystemRoleName, readonl
`${action('AI_MODEL_READ')}:all`,
`${action('AI_MODEL_INVOKE')}:all`,
`${action('AI_PROVIDER_READ')}:all`,
+ // API keys — members manage only the credentials they issued themselves.
+ `${action('API_KEY_READ')}:owner`,
+ `${action('API_KEY_CREATE')}:owner`,
+ `${action('API_KEY_UPDATE')}:owner`,
+ `${action('API_KEY_DELETE')}:owner`,
],
[WORKSPACE_SYSTEM_ROLES.VIEWER]: [
// Read-only across the board
diff --git a/packages/database/src/models/__tests__/apiKey.test.ts b/packages/database/src/models/__tests__/apiKey.test.ts
index c64a5157c29..0c2e14c8e7d 100644
--- a/packages/database/src/models/__tests__/apiKey.test.ts
+++ b/packages/database/src/models/__tests__/apiKey.test.ts
@@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { hashApiKey } from '@/utils/server/apiKeyHash';
import { getTestDB } from '../../core/getTestDB';
-import { apiKeys, users } from '../../schemas';
+import { apiKeys, users, workspaces } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { ApiKeyModel } from '../apiKey';
@@ -187,6 +187,55 @@ describe('ApiKeyModel', () => {
expect(freshResult).toMatchObject({ keyDecryptionFailed: false });
expect(freshResult?.key).toMatch(/^sk-lh-[\da-z]{16}$/);
});
+
+ it('lets workspace admins list all keys while members only see their own', async () => {
+ const workspaceId = 'api-key-model-workspace';
+ await serverDB.insert(workspaces).values({
+ id: workspaceId,
+ name: 'API Key Test Workspace',
+ primaryOwnerId: userId,
+ slug: workspaceId,
+ });
+
+ const adminModel = new ApiKeyModel(serverDB, userId, workspaceId, { canManageAll: true });
+ const memberModel = new ApiKeyModel(serverDB, 'user2', workspaceId, {
+ canManageAll: false,
+ });
+ await adminModel.create({ enabled: true, name: 'Admin Key' });
+ await memberModel.create({ enabled: true, name: 'Member Key' });
+
+ const memberKeys = await memberModel.query();
+ const adminKeys = await adminModel.query();
+
+ expect(memberKeys.map(({ name }) => name)).toEqual(['Member Key']);
+ expect(adminKeys.map(({ name }) => name).sort()).toEqual(['Admin Key', 'Member Key']);
+ expect(adminKeys.find(({ name }) => name === 'Member Key')).toMatchObject({
+ isMine: false,
+ key: '',
+ });
+ });
+
+ it('prevents workspace members from reading, updating, or deleting another member key', async () => {
+ const workspaceId = 'api-key-model-ownership-workspace';
+ await serverDB.insert(workspaces).values({
+ id: workspaceId,
+ name: 'API Key Ownership Workspace',
+ primaryOwnerId: userId,
+ slug: workspaceId,
+ });
+
+ const adminModel = new ApiKeyModel(serverDB, userId, workspaceId, { canManageAll: true });
+ const memberModel = new ApiKeyModel(serverDB, 'user2', workspaceId, {
+ canManageAll: false,
+ });
+ const adminKey = await adminModel.create({ enabled: true, name: 'Admin Key' });
+
+ expect(await memberModel.findById(adminKey.id)).toBeUndefined();
+ await memberModel.update(adminKey.id, { name: 'Hijacked' });
+ await memberModel.delete(adminKey.id);
+
+ expect(await adminModel.findById(adminKey.id)).toMatchObject({ name: 'Admin Key' });
+ });
});
describe('findByKey', () => {
@@ -335,7 +384,7 @@ describe('ApiKeyModel', () => {
});
it('should only update API keys for the current user', async () => {
- const { id: key1 } = await apiKeyModel.create({ name: 'User 1 Key', enabled: true });
+ await apiKeyModel.create({ name: 'User 1 Key', enabled: true });
const anotherApiKeyModel = new ApiKeyModel(serverDB, 'user2');
const { id: key2 } = await anotherApiKeyModel.create({
diff --git a/packages/database/src/models/__tests__/workspace.test.ts b/packages/database/src/models/__tests__/workspace.test.ts
index dde32eb8993..de7dcf94a5b 100644
--- a/packages/database/src/models/__tests__/workspace.test.ts
+++ b/packages/database/src/models/__tests__/workspace.test.ts
@@ -272,6 +272,21 @@ describe('WorkspaceModel', () => {
await expect(model.getSettings(workspaceId)).resolves.toEqual({ keep: true });
});
+ it('defaults API Key member creation to all members and updates it without replacing settings', async () => {
+ const workspaceId = await createWorkspace();
+ const model = new WorkspaceModel(serverDB, ownerId);
+
+ await expect(model.getApiKeyMemberCreation(workspaceId)).resolves.toBe('all_members');
+ await model.updateApiKeyMemberCreation(workspaceId, 'admins_only');
+
+ await expect(model.getApiKeyMemberCreation(workspaceId)).resolves.toBe('admins_only');
+ await expect(model.getSettings(workspaceId)).resolves.toEqual({
+ apiKey: { memberCreation: 'admins_only' },
+ gracePeriodUntil: 123,
+ keep: true,
+ });
+ });
+
it('finds a workspace by id and by slug, and returns undefined when missing', async () => {
const workspaceId = await createWorkspace();
const model = new WorkspaceModel(serverDB, ownerId);
diff --git a/packages/database/src/models/apiKey.ts b/packages/database/src/models/apiKey.ts
index 97a90fb2036..cbded382698 100644
--- a/packages/database/src/models/apiKey.ts
+++ b/packages/database/src/models/apiKey.ts
@@ -16,20 +16,26 @@ export class ApiKeyModel {
}
const keyHash = hashApiKey(key);
- return db.query.apiKeys.findFirst({
- where: eq(apiKeys.keyHash, keyHash),
- });
+ const [row] = await db.select().from(apiKeys).where(eq(apiKeys.keyHash, keyHash)).limit(1);
+ return row;
};
private userId: string;
private db: LobeChatDatabase;
private workspaceId?: string;
+ private canManageAll: boolean;
private gateKeeperPromise: Promise<KeyVaultsGateKeeper> | null = null;
- constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ constructor(
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId?: string,
+ options?: { canManageAll?: boolean },
+ ) {
this.userId = userId;
this.db = db;
this.workspaceId = workspaceId;
+ this.canManageAll = options?.canManageAll ?? true;
}
private ownership = () =>
@@ -42,6 +48,9 @@ export class ApiKeyModel {
*/
private mine = () => and(this.ownership(), eq(apiKeys.userId, this.userId));
+ private manageable = () =>
+ this.workspaceId && !this.canManageAll ? this.mine() : this.ownership();
+
private async getGateKeeper() {
if (!this.gateKeeperPromise) {
this.gateKeeperPromise = KeyVaultsGateKeeper.initWithEnvKey();
@@ -70,18 +79,21 @@ export class ApiKeyModel {
};
delete = async (id: string) => {
- return this.db.delete(apiKeys).where(and(eq(apiKeys.id, id), this.ownership()));
+ return this.db.delete(apiKeys).where(and(eq(apiKeys.id, id), this.manageable()));
};
deleteAll = async () => {
- return this.db.delete(apiKeys).where(this.mine());
+ return this.db
+ .delete(apiKeys)
+ .where(this.mine())
+ .returning({ id: apiKeys.id, name: apiKeys.name, scopes: apiKeys.scopes });
};
/**
* List keys visible in the current scope. In workspace mode the caller sees
- * every key row (with its creator), but the decrypted plaintext is returned
- * only for the caller's own keys. Other owners' rows come back with an empty
- * `key`; the router owns the workspace authorization policy.
+ * every key row (with its creator) only when `canManageAll` is enabled.
+ * Members see only their own keys. The decrypted plaintext is returned only
+ * for the caller's own keys in either mode.
*/
query = async () => {
const rows = await this.db
@@ -93,43 +105,53 @@ export class ApiKeyModel {
})
.from(apiKeys)
.leftJoin(users, eq(users.id, apiKeys.userId))
- .where(this.ownership())
+ .where(this.manageable())
.orderBy(desc(apiKeys.updatedAt));
const gateKeeper = await this.getGateKeeper();
return Promise.all(
- rows.map(async ({ creatorEmail, creatorFullName, creatorUsername, ...apiKey }) => {
- const isMine = apiKey.userId === this.userId;
-
- let key = '';
- let keyDecryptionFailed = false;
- if (isMine) {
- const decrypted = await gateKeeper.decrypt(apiKey.key);
-
- if (!decrypted.wasAuthentic) {
- keyDecryptionFailed = true;
- console.error('Failed to decrypt API key; returning the key as unavailable', {
- apiKeyId: apiKey.id,
- });
- } else {
- key = decrypted.plaintext;
+ rows.map(
+ async ({ creatorEmail, creatorFullName, creatorUsername, keyHash: _, ...apiKey }) => {
+ const isMine = apiKey.userId === this.userId;
+
+ let key = '';
+ let keyDecryptionFailed = false;
+ if (isMine) {
+ const decrypted = await gateKeeper.decrypt(apiKey.key);
+
+ if (!decrypted.wasAuthentic) {
+ keyDecryptionFailed = true;
+ console.error('Failed to decrypt API key; returning the key as unavailable', {
+ apiKeyId: apiKey.id,
+ });
+ } else {
+ key = decrypted.plaintext;
+ }
}
- }
-
- return {
- ...apiKey,
- creator: creatorFullName || creatorUsername || creatorEmail || null,
- isMine,
- key,
- keyDecryptionFailed,
- };
- }),
+
+ return {
+ ...apiKey,
+ creator: creatorFullName || creatorUsername || creatorEmail || null,
+ isMine,
+ key,
+ keyDecryptionFailed,
+ };
+ },
+ ),
);
};
findByKey = async (key: string) => {
- return ApiKeyModel.findByKey(this.db, key);
+ if (!validateApiKeyFormat(key)) return null;
+
+ const keyHash = hashApiKey(key);
+ const [row] = await this.db
+ .select()
+ .from(apiKeys)
+ .where(and(eq(apiKeys.keyHash, keyHash), this.manageable()))
+ .limit(1);
+ return row;
};
validateKey = async (key: string) => {
@@ -146,19 +168,22 @@ export class ApiKeyModel {
return this.db
.update(apiKeys)
.set({ ...value, updatedAt: new Date() })
- .where(and(eq(apiKeys.id, id), this.ownership()));
+ .where(and(eq(apiKeys.id, id), this.manageable()));
};
findById = async (id: string) => {
- return this.db.query.apiKeys.findFirst({
- where: and(eq(apiKeys.id, id), this.ownership()),
- });
+ const [row] = await this.db
+ .select()
+ .from(apiKeys)
+ .where(and(eq(apiKeys.id, id), this.manageable()))
+ .limit(1);
+ return row;
};
updateLastUsed = async (id: string) => {
return this.db
.update(apiKeys)
.set({ lastUsedAt: new Date() })
- .where(and(eq(apiKeys.id, id), this.ownership()));
+ .where(and(eq(apiKeys.id, id), this.mine()));
};
}
diff --git a/packages/database/src/models/workspace.ts b/packages/database/src/models/workspace.ts
index 33e7468e72e..9529b202d16 100644
--- a/packages/database/src/models/workspace.ts
+++ b/packages/database/src/models/workspace.ts
@@ -1,4 +1,5 @@
-import { and, count, desc, eq, isNull } from 'drizzle-orm';
+import type { WorkspaceApiKeyMemberCreation } from '@lobechat/types';
+import { and, count, desc, eq, isNull, sql } from 'drizzle-orm';
import {
type NewWorkspace,
@@ -9,7 +10,7 @@ import {
import type { LobeChatDatabase } from '../type';
import { AGENT_TRANSFER_PENDING_OWNER_DELETE, AgentTransferJobModel } from './agentTransferJob';
-const getActiveMembershipRole = async (
+export const getActiveWorkspaceMembershipRole = async (
db: LobeChatDatabase,
params: { userId: string; workspaceId: string },
): Promise<string | null> => {
@@ -42,7 +43,7 @@ export const hasWorkspaceOwnerAccess = async (
db: LobeChatDatabase,
params: { userId: string; workspaceId: string },
): Promise<boolean> => {
- return (await getActiveMembershipRole(db, params)) === 'owner';
+ return (await getActiveWorkspaceMembershipRole(db, params)) === 'owner';
};
/**
@@ -53,10 +54,30 @@ export const hasWorkspaceAdminAccess = async (
db: LobeChatDatabase,
params: { userId: string; workspaceId: string },
): Promise<boolean> => {
- const role = await getActiveMembershipRole(db, params);
+ const role = await getActiveWorkspaceMembershipRole(db, params);
return role === 'owner' || role === 'admin';
};
+export const hasActiveWorkspaceMembership = async (
+ db: LobeChatDatabase,
+ params: { userId: string; workspaceId: string },
+): Promise<boolean> => {
+ return (await getActiveWorkspaceMembershipRole(db, params)) !== null;
+};
+
+export const getWorkspaceApiKeyMemberCreation = (
+ settings: unknown,
+): WorkspaceApiKeyMemberCreation => {
+ if (!settings || typeof settings !== 'object') return 'all_members';
+
+ const apiKey = (settings as { apiKey?: unknown }).apiKey;
+ if (!apiKey || typeof apiKey !== 'object') return 'all_members';
+
+ return (apiKey as { memberCreation?: unknown }).memberCreation === 'admins_only'
+ ? 'admins_only'
+ : 'all_members';
+};
+
export class WorkspaceModel {
protected readonly db: LobeChatDatabase;
protected readonly userId: string;
@@ -143,6 +164,10 @@ export class WorkspaceModel {
return workspace?.settings ?? {};
};
+ getApiKeyMemberCreation = async (id: string): Promise<WorkspaceApiKeyMemberCreation> => {
+ return getWorkspaceApiKeyMemberCreation(await this.getSettings(id));
+ };
+
/**
* Count every workspace this user belongs to — owned + joined. Reads the
* membership table directly because owners are always inserted as members on
@@ -193,6 +218,22 @@ export class WorkspaceModel {
.where(eq(workspaces.id, id));
};
+ updateApiKeyMemberCreation = async (
+ id: string,
+ memberCreation: WorkspaceApiKeyMemberCreation,
+ ) => {
+ return this.db
+ .update(workspaces)
+ .set({
+ settings: sql`coalesce(${workspaces.settings}, '{}'::jsonb) || jsonb_build_object(
+ 'apiKey',
+ coalesce(${workspaces.settings}->'apiKey', '{}'::jsonb) || jsonb_build_object('memberCreation', ${memberCreation}::text)
+ )`,
+ updatedAt: new Date(),
+ })
+ .where(eq(workspaces.id, id));
+ };
+
/**
* Transfer the unique Owner role and Stripe binding to an existing Admin.
* The previous Owner becomes Admin in the same transaction, keeping
diff --git a/packages/database/src/models/workspaceAuditLog.ts b/packages/database/src/models/workspaceAuditLog.ts
index fb3d942c68b..aa1feda7a12 100644
--- a/packages/database/src/models/workspaceAuditLog.ts
+++ b/packages/database/src/models/workspaceAuditLog.ts
@@ -47,6 +47,7 @@ export type WorkspaceAuditAction =
| 'credential.deleted'
| 'credential.tested'
| 'api_key.created'
+ | 'api_key.updated'
| 'api_key.renamed'
| 'api_key.rotated'
| 'api_key.revoked'
diff --git a/packages/locales/src/default/auth.ts b/packages/locales/src/default/auth.ts
index 93b5cbf0e23..1dd478e4205 100644
--- a/packages/locales/src/default/auth.ts
+++ b/packages/locales/src/default/auth.ts
@@ -6,6 +6,9 @@ export default {
'agreement.confirm.ok': 'Agree and continue',
'agreement.confirm.title': 'Terms and Privacy Policy',
'apikey.detail.createdAt': 'Created',
+ 'apikey.detail.permissions.cancel': 'Cancel',
+ 'apikey.detail.permissions.edit': 'Edit permissions',
+ 'apikey.detail.permissions.save': 'Save permissions',
'apikey.detail.title': 'API Key Details',
'apikey.display.autoGenerated': 'Auto-generated',
'apikey.display.copy': 'Copy',
@@ -31,6 +34,8 @@ export default {
'apikey.form.submit': 'Create',
'apikey.form.title': 'Create API Key',
'apikey.list.actions.create': 'Create API Key',
+ 'apikey.list.actions.creationRestricted':
+ 'Your workspace administrator has restricted API Key creation to admins',
'apikey.list.actions.delete': 'Delete',
'apikey.list.actions.deleteConfirm.actions.cancel': 'Cancel',
'apikey.list.actions.deleteConfirm.actions.ok': 'Confirm',
@@ -44,6 +49,9 @@ export default {
'apikey.list.columns.name': 'Name',
'apikey.list.columns.status': 'Enabled',
'apikey.list.empty': 'No API Keys yet',
+ 'apikey.list.restrictedEmpty.desc':
+ 'Only workspace admins can create API Keys. Contact a workspace admin if you need one.',
+ 'apikey.list.restrictedEmpty.title': 'API Key creation is restricted',
'apikey.list.title': 'API Key List',
'apikey.scopes.fullAccess': 'Full access',
'apikey.scopes.grantJoin': ': ',
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 836fea95431..3c78610c515 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -2092,15 +2092,21 @@ When I am ___, I need ___
'workspace.billingPage.usage.spend': 'Spend',
'workspace.billingPage.usage.summaryTitle': 'Usage',
'workspace.billingPage.usage.type': 'Type',
+ 'workspace.apiKey.policy.desc':
+ 'Choose who can create personal API Keys that act on their behalf in this workspace.',
+ 'workspace.apiKey.policy.options.allMembers': 'All members',
+ 'workspace.apiKey.policy.options.onlyAdmins': 'Only admins',
+ 'workspace.apiKey.policy.title': 'API Key creation',
+ 'workspace.apiKey.policy.updateFailed': 'Failed to update the API Key creation policy',
'workspace.apiKey.upgrade.benefits.integration.desc':
'Call workspace agents and resources from your own systems via the LobeHub API.',
'workspace.apiKey.upgrade.benefits.integration.title': 'Programmatic access',
'workspace.apiKey.upgrade.benefits.security.desc':
- 'Requests stay bound to this workspace and require an active owner account.',
+ 'Requests stay bound to the workspace and can never exceed the issuer’s current permissions.',
'workspace.apiKey.upgrade.benefits.security.title': 'Workspace-scoped security',
'workspace.apiKey.upgrade.benefits.shared.desc':
- 'Only workspace owners can create, view, manage, and revoke workspace API keys.',
- 'workspace.apiKey.upgrade.benefits.shared.title': 'Owner-managed keys',
+ 'Admins can control member creation and centrally revoke active API Keys.',
+ 'workspace.apiKey.upgrade.benefits.shared.title': 'Admin governance',
'workspace.apiKey.upgrade.cta': 'Upgrade to Pro',
'workspace.apiKey.upgrade.desc':
'Create workspace-scoped API keys to integrate workspace agents and data into your own workflows and services.',
@@ -2127,6 +2133,7 @@ When I am ___, I need ___
'workspace.auditLog.actions.api_key.renamed': 'API key renamed',
'workspace.auditLog.actions.api_key.revoked': 'API key revoked',
'workspace.auditLog.actions.api_key.rotated': 'API key rotated',
+ 'workspace.auditLog.actions.api_key.updated': 'API key updated',
'workspace.auditLog.actions.credential.created': 'Credential created',
'workspace.auditLog.actions.credential.deleted': 'Credential deleted',
'workspace.auditLog.actions.credential.tested': 'Credential tested',
diff --git a/packages/openapi/src/middleware/auth.test.ts b/packages/openapi/src/middleware/auth.test.ts
index 5a59125aa47..3ebe52e9738 100644
--- a/packages/openapi/src/middleware/auth.test.ts
+++ b/packages/openapi/src/middleware/auth.test.ts
@@ -42,7 +42,7 @@ vi.mock('@/database/core/db-adaptor', () => ({
vi.mock('@/database/models/apiKey', () => ({
ApiKeyModel: class {
- findByKey = mockApiKeyFindByKey;
+ static findByKey = mockApiKeyFindByKey;
updateLastUsed = mockApiKeyUpdateLastUsed;
},
}));
@@ -187,4 +187,45 @@ describe('OpenAPI auth middleware', () => {
});
expect(response.status).toBe(200);
});
+
+ it('should re-read API Key authorization changes on every request', async () => {
+ mockExtractBearerToken.mockReturnValue('sk-lh-workspacekey01');
+ mockValidateApiKeyFormat.mockReturnValue(true);
+ mockApiKeyFindByKey
+ .mockResolvedValueOnce({
+ enabled: true,
+ expiresAt: null,
+ id: 'api-key-1',
+ name: 'Workspace key',
+ scopes: ['agent:read'],
+ userId: 'user-1',
+ workspaceId: 'workspace-1',
+ })
+ .mockResolvedValueOnce({
+ enabled: false,
+ expiresAt: null,
+ id: 'api-key-1',
+ name: 'Workspace key',
+ scopes: ['agent:read'],
+ userId: 'user-1',
+ workspaceId: 'workspace-1',
+ });
+ const app = createApp();
+
+ expect(
+ (
+ await app.request('/protected', {
+ headers: { Authorization: 'Bearer sk-lh-workspacekey01' },
+ })
+ ).status,
+ ).toBe(200);
+ expect(
+ (
+ await app.request('/protected', {
+ headers: { Authorization: 'Bearer sk-lh-workspacekey01' },
+ })
+ ).status,
+ ).toBe(401);
+ expect(mockApiKeyFindByKey).toHaveBeenCalledTimes(2);
+ });
});
diff --git a/packages/openapi/src/middleware/auth.ts b/packages/openapi/src/middleware/auth.ts
index 5f8b382fbd3..2a3da098d71 100644
--- a/packages/openapi/src/middleware/auth.ts
+++ b/packages/openapi/src/middleware/auth.ts
@@ -13,38 +13,6 @@ import { extractBearerToken } from '@/utils/server/auth';
// Create context logger namespace
const log = debug('lobe-hono:auth-middleware');
-// API Key cache configuration
-const API_KEY_CACHE_TTL = 5 * 60 * 1000; // 5 minutes in milliseconds
-
-interface ApiKeyCacheEntry {
- apiKeyId: string;
- apiKeyName: string;
- expiresAt: Date | null;
- scopes: string[] | null;
- timestamp: number;
- userId: string;
- workspaceId?: string | null;
-}
-
-// In-memory cache for API Key validation results
-const apiKeyCache = new Map<string, ApiKeyCacheEntry>();
-
-/**
- * Clean up expired cache entries periodically
- */
-const cleanupApiKeyCache = () => {
- const now = Date.now();
- for (const [key, entry] of apiKeyCache.entries()) {
- if (now - entry.timestamp > API_KEY_CACHE_TTL) {
- apiKeyCache.delete(key);
- log('Removed expired API Key from cache: %s', key.slice(0, 10) + '...');
- }
- }
-};
-
-// Run cache cleanup every 10 minutes
-setInterval(cleanupApiKeyCache, 10 * 60 * 1000);
-
/**
* Standard Hono authentication middleware
* Supports both OIDC tokens and API keys via Bearer token
@@ -85,103 +53,47 @@ export const userAuthMiddleware = async (c: Context, next: Next) => {
// Try API Key authentication
log('Bearer token matches API Key format, attempting API Key authentication');
- // Check cache first
- const cachedEntry = apiKeyCache.get(bearerToken);
- const now = Date.now();
-
- if (cachedEntry && now - cachedEntry.timestamp < API_KEY_CACHE_TTL) {
- // Check if cached API Key is expired
- const isExpired = cachedEntry.expiresAt && new Date() > new Date(cachedEntry.expiresAt);
-
- if (!isExpired) {
- userId = cachedEntry.userId;
- 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',
- userId,
- cachedEntry.apiKeyId,
- );
- } else {
- log('Cached API Key is expired, removing from cache');
- apiKeyCache.delete(bearerToken);
- }
- } else {
- // Cache miss or expired, query database
- log('API Key cache miss, querying database');
-
- try {
- // Get database instance
- const db = await getServerDB();
- log('Database connection established');
+ // Always read the current row. Scope edits, disable and revoke are
+ // authorization changes, so a process-local TTL cache would preserve
+ // stale privileges across requests and server instances.
+ try {
+ const db = await getServerDB();
+ const apiKeyRecord = await ApiKeyModel.findByKey(db, bearerToken);
- // Find API Key in database
- const apiKeyModel = new ApiKeyModel(db, ''); // userId is not needed for findByKey
- log('Searching for API Key in database...');
- const apiKeyRecord = await apiKeyModel.findByKey(bearerToken);
+ if (apiKeyRecord?.enabled) {
+ const isExpired = apiKeyRecord.expiresAt && new Date() > new Date(apiKeyRecord.expiresAt);
- log('API Key database query result: %s', apiKeyRecord ? 'found' : 'not found');
+ if (!isExpired) {
+ userId = apiKeyRecord.userId;
+ authType = 'apikey';
+ authData = { apiKeyId: apiKeyRecord.id, apiKeyName: apiKeyRecord.name };
+ apiKeyWorkspaceId = apiKeyRecord.workspaceId;
+ apiKeyScopes = apiKeyRecord.scopes ?? null;
- if (apiKeyRecord) {
log(
- 'API Key record - enabled: %s, userId: %s, expiresAt: %s',
- apiKeyRecord.enabled,
+ 'API Key authentication successful, userId: %s, apiKeyId: %s',
+ userId,
+ apiKeyRecord.id,
+ );
+
+ const userApiKeyModel = new ApiKeyModel(
+ db,
apiKeyRecord.userId,
- apiKeyRecord.expiresAt,
+ apiKeyRecord.workspaceId ?? undefined,
);
- // Validate API Key is enabled and not expired
- if (apiKeyRecord.enabled) {
- const isExpired =
- apiKeyRecord.expiresAt && new Date() > new Date(apiKeyRecord.expiresAt);
-
- if (!isExpired) {
- userId = apiKeyRecord.userId;
- authType = 'apikey';
- authData = { apiKeyId: apiKeyRecord.id, apiKeyName: apiKeyRecord.name };
- apiKeyWorkspaceId = apiKeyRecord.workspaceId;
- apiKeyScopes = apiKeyRecord.scopes ?? null;
-
- // Cache the validated API Key
- apiKeyCache.set(bearerToken, {
- apiKeyId: apiKeyRecord.id,
- apiKeyName: apiKeyRecord.name,
- expiresAt: apiKeyRecord.expiresAt,
- scopes: apiKeyRecord.scopes ?? null,
- timestamp: now,
- userId: apiKeyRecord.userId,
- workspaceId: apiKeyRecord.workspaceId,
- });
-
- log(
- 'API Key authentication successful, userId: %s, apiKeyId: %d (cached)',
- userId,
- apiKeyRecord.id,
- );
-
- // Update last used timestamp (fire and forget)
- const userApiKeyModel = new ApiKeyModel(
- db,
- apiKeyRecord.userId,
- apiKeyRecord.workspaceId ?? undefined,
- );
- userApiKeyModel.updateLastUsed(apiKeyRecord.id).catch((err) => {
- log('Failed to update API Key last used timestamp: %O', err);
- });
- } else {
- log('API Key is expired');
- }
- } else {
- log('API Key is disabled');
- }
+ void userApiKeyModel.updateLastUsed(apiKeyRecord.id).catch((error) => {
+ log('Failed to update API Key last used timestamp: %O', error);
+ });
} else {
- log('API Key not found in database');
+ log('API Key is expired');
}
- } catch (error) {
- log('API Key authentication failed: %O', error);
+ } else if (apiKeyRecord) {
+ log('API Key is disabled');
+ } else {
+ log('API Key not found in database');
}
+ } catch (error) {
+ log('API Key authentication failed: %O', error);
}
} else if (authEnv.ENABLE_OIDC) {
// Try OIDC authentication
diff --git a/packages/openapi/src/middleware/workspace.test.ts b/packages/openapi/src/middleware/workspace.test.ts
index d3ca6c63685..b032898f7eb 100644
--- a/packages/openapi/src/middleware/workspace.test.ts
+++ b/packages/openapi/src/middleware/workspace.test.ts
@@ -215,13 +215,17 @@ describe('OpenAPI workspace middleware', () => {
expect(response.status).toBe(200);
});
- it('rejects a workspace API Key after its issuer is demoted below Admin', async () => {
+ it('keeps a workspace API Key active after its issuer becomes a member', async () => {
const app = createApp({ apiKeyWorkspaceId: 'workspace-1', authType: 'apikey' });
mockWorkspaceMembersFindFirst.mockResolvedValueOnce({ role: 'member' });
const response = await app.request('/workspace');
- expect(response.status).toBe(403);
+ await expect(response.json()).resolves.toEqual({
+ workspaceId: 'workspace-1',
+ workspaceRole: 'member',
+ });
+ expect(response.status).toBe(200);
});
it('rejects a different workspace header for a workspace API Key', async () => {
diff --git a/packages/openapi/src/middleware/workspace.ts b/packages/openapi/src/middleware/workspace.ts
index 198bb0979fc..913e75c3c53 100644
--- a/packages/openapi/src/middleware/workspace.ts
+++ b/packages/openapi/src/middleware/workspace.ts
@@ -81,22 +81,10 @@ export const workspaceAuthMiddleware = async (c: Context, next: Next) => {
});
}
- if (c.get('authType') === 'apikey') {
- // `workspace_members.role` is the single source of truth for built-in
- // workspace roles.
- const isWorkspaceAdmin = membership.role === 'owner' || membership.role === 'admin';
-
- if (!isWorkspaceAdmin) {
- throw new HTTPException(403, {
- message: 'Workspace API Key requires an admin account',
- });
- }
-
- if (!(await canUseWorkspaceApiKeys(workspaceId))) {
- throw new HTTPException(403, {
- message: 'Workspace API Key access is not available',
- });
- }
+ if (c.get('authType') === 'apikey' && !(await canUseWorkspaceApiKeys(workspaceId))) {
+ throw new HTTPException(403, {
+ message: 'Workspace API Key access is not available',
+ });
}
c.set('workspaceId', workspaceId);
diff --git a/packages/trpc/src/lambda/context.test.ts b/packages/trpc/src/lambda/context.test.ts
index 222edee0a94..e1fe3f6ff7c 100644
--- a/packages/trpc/src/lambda/context.test.ts
+++ b/packages/trpc/src/lambda/context.test.ts
@@ -81,10 +81,10 @@ vi.mock('@/business/server/workspaceApiKey', () => ({
canUseWorkspaceApiKeys: mockCanUseWorkspaceApiKeys,
}));
-const mockHasWorkspaceAdminAccess = vi.hoisted(() => vi.fn(async () => true));
+const mockHasActiveWorkspaceMembership = vi.hoisted(() => vi.fn(async () => true));
vi.mock('@/database/models/workspace', () => ({
- hasWorkspaceAdminAccess: mockHasWorkspaceAdminAccess,
+ hasActiveWorkspaceMembership: mockHasActiveWorkspaceMembership,
}));
describe('createContextInner', () => {
@@ -326,9 +326,9 @@ describe('createLambdaContext', () => {
expect(context.workspaceId).toBe('ws-1');
});
- it('should reject a workspace API key whose issuer is no longer an admin', async () => {
+ it('should reject a workspace API key whose issuer is no longer an active member', async () => {
vi.mocked(ApiKeyModel.findByKey).mockResolvedValue(makeApiKeyRecord('ws-1'));
- mockHasWorkspaceAdminAccess.mockResolvedValueOnce(false);
+ mockHasActiveWorkspaceMembership.mockResolvedValueOnce(false);
const request = new NextRequest('https://example.com/trpc/lambda', {
headers: {
@@ -341,7 +341,7 @@ describe('createLambdaContext', () => {
expect(context.userId).toBeNull();
expect(context.workspaceId).toBeUndefined();
- expect(mockHasWorkspaceAdminAccess).toHaveBeenCalledWith(expect.anything(), {
+ expect(mockHasActiveWorkspaceMembership).toHaveBeenCalledWith(expect.anything(), {
userId: 'api-user',
workspaceId: 'ws-1',
});
diff --git a/packages/trpc/src/lambda/context.ts b/packages/trpc/src/lambda/context.ts
index 7d0a5bd0c77..07fb8282deb 100644
--- a/packages/trpc/src/lambda/context.ts
+++ b/packages/trpc/src/lambda/context.ts
@@ -10,7 +10,7 @@ import { auth } from '@/auth';
import { canUseWorkspaceApiKeys } from '@/business/server/workspaceApiKey';
import { getServerDB } from '@/database/core/db-adaptor';
import { ApiKeyModel } from '@/database/models/apiKey';
-import { hasWorkspaceAdminAccess } from '@/database/models/workspace';
+import { hasActiveWorkspaceMembership } from '@/database/models/workspace';
import { authEnv, LOBE_CHAT_OIDC_AUTH_HEADER } from '@/envs/auth';
import { extractTraceContext } from '@/libs/observability/traceparent';
import { assertOIDCUserActive, isOIDCUserInactiveError } from '@/libs/oidc-provider/access-control';
@@ -224,19 +224,19 @@ export const createLambdaContext = async (request: NextRequest): Promise<LambdaC
});
}
- // Same gates as the OpenAPI workspace middleware: workspace API keys are
- // Admin-or-higher, so the issuer must still hold admin status (a demoted or
- // removed admin's key stops working), and a workspace that loses the
- // workspace-API-key entitlement must not keep serving already-issued keys.
+ // Same gates as the OpenAPI workspace middleware: the issuer must remain
+ // an active member, and the workspace must retain its API-key entitlement.
+ // Current RBAC is evaluated later and intersects with the key's scopes, so
+ // a role downgrade automatically narrows even a full-access key.
if (apiKeyAuth.workspaceId) {
const db = await getServerDB();
- const isAdmin = await hasWorkspaceAdminAccess(db, {
+ const isActiveMember = await hasActiveWorkspaceMembership(db, {
userId: apiKeyAuth.userId,
workspaceId: apiKeyAuth.workspaceId,
});
- if (!isAdmin) {
- log('Workspace API key issuer is no longer a workspace admin; rejecting request');
+ if (!isActiveMember) {
+ log('Workspace API key issuer is no longer an active member; rejecting request');
return createContextInner({
...commonContext,
diff --git a/packages/types/src/apiKey.ts b/packages/types/src/apiKey.ts
index df8814c0668..bf6b777080f 100644
--- a/packages/types/src/apiKey.ts
+++ b/packages/types/src/apiKey.ts
@@ -17,8 +17,7 @@ export interface ApiKeyItem {
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.
+ // explicit full access, otherwise a restricted scope list.
scopes?: string[] | null;
updatedAt: Date;
userId: string;
@@ -34,4 +33,7 @@ export interface UpdateApiKeyParams {
enabled?: boolean;
expiresAt?: Date | null;
name?: string;
+ scopes?: string[] | null;
}
+
+export type WorkspaceApiKeyMemberCreation = 'admins_only' | 'all_members';
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index f6e451e357d..e23922850aa 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -4,6 +4,7 @@ export * from './agentGroup';
export * from './agentHook';
export * from './aiChat';
export * from './aiProvider';
+export * from './apiKey';
export * from './artifact';
export * from './asyncTask';
export * from './auth';
diff --git a/src/business/client/BusinessSettingPages/WorkspaceApiKeyGuard.tsx b/src/business/client/BusinessSettingPages/WorkspaceApiKeyGuard.tsx
index 7c566d8bac2..94a4299654e 100644
--- a/src/business/client/BusinessSettingPages/WorkspaceApiKeyGuard.tsx
+++ b/src/business/client/BusinessSettingPages/WorkspaceApiKeyGuard.tsx
@@ -1,5 +1,5 @@
import type { PropsWithChildren, ReactNode } from 'react';
-export default function WorkspaceApiKeyGuard({ children }: PropsWithChildren): ReactNode {
+export function WorkspaceApiKeyGuard({ children }: PropsWithChildren): ReactNode {
return children;
}
diff --git a/src/features/Settings/apikey/WorkspaceApiKeyPolicyContext.ts b/src/features/Settings/apikey/WorkspaceApiKeyPolicyContext.ts
new file mode 100644
index 00000000000..60f9557d5e5
--- /dev/null
+++ b/src/features/Settings/apikey/WorkspaceApiKeyPolicyContext.ts
@@ -0,0 +1,23 @@
+import type { WorkspaceApiKeyMemberCreation } from '@lobechat/types';
+import { createContext, useContext } from 'react';
+
+export interface WorkspaceApiKeyPolicy {
+ canCreate: boolean;
+ isAdmin: boolean;
+ memberCreation: WorkspaceApiKeyMemberCreation;
+}
+
+/**
+ * Defaults describe a plain workspace member, matching what the server assumes
+ * when no deployment resolves workspace roles: admin-only affordances (the
+ * creator column, other members' keys) stay hidden, while creation stays open
+ * because `all_members` is also the server-side default policy. A deployment
+ * that resolves real roles provides this context instead.
+ */
+export const WorkspaceApiKeyPolicyContext = createContext<WorkspaceApiKeyPolicy>({
+ canCreate: true,
+ isAdmin: false,
+ memberCreation: 'all_members',
+});
+
+export const useWorkspaceApiKeyPolicy = () => useContext(WorkspaceApiKeyPolicyContext);
diff --git a/src/features/Settings/apikey/features/ApiKey.test.tsx b/src/features/Settings/apikey/features/ApiKey.test.tsx
index 71dd6568c45..36da6dbe2f4 100644
--- a/src/features/Settings/apikey/features/ApiKey.test.tsx
+++ b/src/features/Settings/apikey/features/ApiKey.test.tsx
@@ -6,6 +6,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { type ApiKeyItem, type CreateApiKeyParams } from '@/types/apiKey';
+import { WorkspaceApiKeyPolicyContext } from '../WorkspaceApiKeyPolicyContext';
import ApiKey from './ApiKey';
const hoisted = vi.hoisted(() => ({
@@ -13,6 +14,8 @@ const hoisted = vi.hoisted(() => ({
state: {
activeWorkspaceId: null as string | null,
allowed: true,
+ canCreateWorkspaceKey: true,
+ isWorkspaceAdmin: true,
manageSettingsAllowed: true,
reason: '',
},
@@ -147,7 +150,15 @@ const renderPage = () => {
return render(
<SWRConfig value={{ dedupingInterval: 0, provider: () => new Map() }}>
<QueryClientProvider client={queryClient}>
- <ApiKey />
+ <WorkspaceApiKeyPolicyContext
+ value={{
+ canCreate: hoisted.state.canCreateWorkspaceKey,
+ isAdmin: hoisted.state.isWorkspaceAdmin,
+ memberCreation: hoisted.state.canCreateWorkspaceKey ? 'all_members' : 'admins_only',
+ }}
+ >
+ <ApiKey />
+ </WorkspaceApiKeyPolicyContext>
</QueryClientProvider>
</SWRConfig>,
);
@@ -157,6 +168,8 @@ beforeEach(() => {
vi.clearAllMocks();
hoisted.state.activeWorkspaceId = null;
hoisted.state.allowed = true;
+ hoisted.state.canCreateWorkspaceKey = true;
+ hoisted.state.isWorkspaceAdmin = true;
hoisted.state.manageSettingsAllowed = true;
hoisted.state.reason = '';
hoisted.trpc.getApiKeys.mockResolvedValue([makeItem()]);
@@ -190,6 +203,20 @@ describe('ApiKey', () => {
expect(await screen.findByText('apikey.list.empty')).toBeInTheDocument();
});
+ it('explains the creation restriction when a workspace member has no keys', async () => {
+ hoisted.state.activeWorkspaceId = 'ws-1';
+ hoisted.state.canCreateWorkspaceKey = false;
+ hoisted.state.isWorkspaceAdmin = false;
+ hoisted.trpc.getApiKeys.mockResolvedValue([]);
+
+ renderPage();
+
+ expect(await screen.findByText('apikey.list.restrictedEmpty.title')).toBeInTheDocument();
+ expect(screen.getByText('apikey.list.restrictedEmpty.desc')).toBeInTheDocument();
+ expect(screen.queryByText('apikey.list.empty')).toBeNull();
+ expect(screen.getByRole('button', { name: 'apikey.list.actions.create' })).toBeDisabled();
+ });
+
it('renders fetched keys with their plaintext for the owner', async () => {
renderPage();
@@ -306,7 +333,7 @@ describe('ApiKey', () => {
).toBeDisabled();
});
- it('allows a workspace admin to manage another member key while keeping its secret masked', async () => {
+ it('allows a workspace admin to revoke another member key while keeping it read-only and masked', async () => {
hoisted.state.activeWorkspaceId = 'ws-1';
hoisted.trpc.getApiKeys.mockResolvedValue([
makeItem(),
@@ -318,10 +345,14 @@ describe('ApiKey', () => {
const otherRow = screen.getByText('Other Key').closest('tr')!;
expect(within(otherRow).getByText(`sk-lh-${'*'.repeat(12)}`)).toBeInTheDocument();
- // an admin can manage another member's key from its drawer
+ // an admin can centrally revoke another member's key, but only its creator
+ // can rename, disable, or edit the grants.
const dialog = await openDetail('Other Key');
- expect(within(dialog).getByRole('button', { name: 'edit-text' })).toBeEnabled();
- expect(within(dialog).getByRole('switch')).toBeEnabled();
+ expect(within(dialog).getByRole('button', { name: 'edit-text' })).toBeDisabled();
+ expect(within(dialog).getByRole('switch')).toBeDisabled();
+ expect(
+ within(dialog).queryByRole('button', { name: 'apikey.detail.permissions.edit' }),
+ ).toBeNull();
expect(
within(dialog).getByRole('button', { name: 'apikey.list.actions.delete' }),
).toBeEnabled();
@@ -332,20 +363,33 @@ describe('ApiKey', () => {
expect(within(mineRow).getByText('lb-plain-secret')).toBeInTheDocument();
});
- it('disables create and row actions for workspace members without settings permission', async () => {
+ it('allows workspace members to create and manage their own keys', async () => {
hoisted.state.activeWorkspaceId = 'ws-1';
hoisted.state.manageSettingsAllowed = false;
+ hoisted.state.isWorkspaceAdmin = false;
renderPage();
await screen.findByText('My Key');
- expect(screen.getByRole('button', { name: 'apikey.list.actions.create' })).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'apikey.list.actions.create' })).toBeEnabled();
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: 'edit-text' })).toBeEnabled();
+ expect(within(dialog).getByRole('switch')).toBeEnabled();
expect(
within(dialog).getByRole('button', { name: 'apikey.list.actions.delete' }),
- ).toBeDisabled();
+ ).toBeEnabled();
+ });
+
+ it('disables member creation when the workspace policy is admins only', async () => {
+ hoisted.state.activeWorkspaceId = 'ws-1';
+ hoisted.state.canCreateWorkspaceKey = false;
+ hoisted.state.isWorkspaceAdmin = false;
+ renderPage();
+ await screen.findByText('My Key');
+
+ const createButton = screen.getByRole('button', { name: 'apikey.list.actions.create' });
+ expect(createButton).toBeDisabled();
+ expect(createButton).toHaveAttribute('title', 'apikey.list.actions.creationRestricted');
});
it('shows the unavailable copy with tooltip when key decryption failed', async () => {
@@ -369,6 +413,15 @@ describe('ApiKey', () => {
expect(screen.getByText('Bob')).toBeInTheDocument();
});
+ it('hides the creator column from workspace members', async () => {
+ hoisted.state.activeWorkspaceId = 'ws-1';
+ hoisted.state.isWorkspaceAdmin = false;
+ renderPage();
+ await screen.findByText('My Key');
+
+ expect(screen.queryByRole('columnheader', { name: 'apikey.list.columns.creator' })).toBeNull();
+ });
+
it('hides the creator column in personal mode', async () => {
renderPage();
await screen.findByText('My Key');
@@ -414,8 +467,32 @@ describe('ApiKey', () => {
'apikey.scopes.invoke',
].join(''),
);
- // read-only: no editable scope controls in the detail view
+ // the grant summary stays compact until the creator explicitly edits it
expect(within(dialog).queryAllByRole('checkbox')).toHaveLength(0);
+ expect(
+ within(dialog).getByRole('button', { name: 'apikey.detail.permissions.edit' }),
+ ).toBeEnabled();
+ });
+
+ it('edits a key scope in place and refreshes the list', async () => {
+ hoisted.trpc.getApiKeys.mockResolvedValue([makeItem({ scopes: ['agent:read'] })]);
+ renderPage();
+ await screen.findByText('My Key');
+
+ const dialog = await openDetail('My Key');
+ fireEvent.click(within(dialog).getByRole('button', { name: 'apikey.detail.permissions.edit' }));
+ const scopeCheckboxes = within(dialog).getAllByRole('checkbox');
+ fireEvent.click(scopeCheckboxes[0]);
+ fireEvent.click(scopeCheckboxes[2]);
+ fireEvent.click(within(dialog).getByRole('button', { name: 'apikey.detail.permissions.save' }));
+
+ await waitFor(() =>
+ expect(hoisted.trpc.updateApiKey).toHaveBeenCalledWith({
+ id: 'key-1',
+ value: { scopes: ['chat:read'] },
+ }),
+ );
+ await waitFor(() => expect(hoisted.trpc.getApiKeys).toHaveBeenCalledTimes(2));
});
it('shows the full-access copy instead of the grant list for a full-access key', async () => {
diff --git a/src/features/Settings/apikey/features/ApiKey.tsx b/src/features/Settings/apikey/features/ApiKey.tsx
index 9e5f852b6c4..ac7bab3fcef 100644
--- a/src/features/Settings/apikey/features/ApiKey.tsx
+++ b/src/features/Settings/apikey/features/ApiKey.tsx
@@ -22,6 +22,7 @@ import { electronSyncSelectors } from '@/store/electron/selectors';
import { type ApiKeyItem, type CreateApiKeyParams, type UpdateApiKeyParams } from '@/types/apiKey';
import { isForbiddenError } from '@/utils/forbiddenError';
+import { useWorkspaceApiKeyPolicy } from '../WorkspaceApiKeyPolicyContext';
import ApiKeyDetail from './ApiKeyDetail';
import { ApiKeyDisplay, createApiKeyModal } from './index';
@@ -66,24 +67,23 @@ const ApiKey: FC = () => {
const { t } = useTranslation('auth');
const { t: tc } = useTranslation('common');
const activeWorkspaceId = useActiveWorkspaceId();
+ const workspacePolicy = useWorkspaceApiKeyPolicy();
const { allowed: canEdit, reason } = usePermission('create_content');
// Desktop renders from app://renderer, where a relative href is denied by the
// window-open handler — resolve the docs link against the active server origin.
const remoteServerUrl = useElectronStore(electronSyncSelectors.remoteServerUrl);
const docsHref = isDesktop ? urlJoin(remoteServerUrl, '/api/v1/docs') : '/api/v1/docs';
- // Workspace API keys are shared admin config: the server gates every
- // mutation (create included) at Admin-or-higher
- // (`requireWorkspaceRoleWhenScoped('admin')`), with no per-row creator
- // check — mirror that here so Admins can manage keys created by other
- // members and Members don't get an enabled create flow that always 403s.
- const { allowed: canManageKeys } = usePermission('manage_settings');
- const canCreate = canEdit && (!activeWorkspaceId || canManageKeys);
- const checkManageable = (_creatorUserId?: string | null) => !activeWorkspaceId || canManageKeys;
+ const canCreate = canEdit && (!activeWorkspaceId || workspacePolicy.canCreate);
+ const isMemberCreationRestricted =
+ !!activeWorkspaceId && !workspacePolicy.isAdmin && !workspacePolicy.canCreate;
const manageTooltip = tc(
'manageOnlyCreator',
'Only the creator or a workspace owner can do this',
);
+ const createTooltip = workspacePolicy.canCreate
+ ? reason
+ : t('apikey.list.actions.creationRestricted');
const { data, isLoading, mutate } = useClientDataSWR<ApiKeyItem[]>(apiKeyKeys.list(), () =>
lambdaClient.apiKey.getApiKeys.query(),
@@ -104,6 +104,7 @@ const ApiKey: FC = () => {
const createMutation = useMutation({
mutationFn: (params: CreateApiKeyParams) => lambdaClient.apiKey.createApiKey.mutate(params),
+ onError: notifyMutationError,
onSuccess: () => {
mutate();
},
@@ -166,7 +167,7 @@ const ApiKey: FC = () => {
},
// 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
+ ...(activeWorkspaceId && workspacePolicy.isAdmin
? [
{
key: 'creator',
@@ -210,7 +211,7 @@ const ApiKey: FC = () => {
</Button>
<Button
disabled={!canCreate}
- title={canCreate ? undefined : canEdit ? manageTooltip : reason}
+ title={canCreate ? undefined : createTooltip}
type="primary"
onClick={handleCreate}
>
@@ -225,22 +226,41 @@ const ApiKey: FC = () => {
rowKey={(apiKey) => apiKey.id}
emptyText={
<Center height={240} width={'100%'}>
- <Empty description={t('apikey.list.empty')} />
+ <Empty
+ description={t(
+ isMemberCreationRestricted
+ ? 'apikey.list.restrictedEmpty.desc'
+ : 'apikey.list.empty',
+ )}
+ title={
+ isMemberCreationRestricted ? t('apikey.list.restrictedEmpty.title') : undefined
+ }
+ />
</Center>
}
onRowClick={(apiKey) => setDetailId(apiKey.id)}
/>
<ApiKeyDetail
apiKey={detailApiKey}
- canManage={canEdit && (detailApiKey ? checkManageable(detailApiKey.userId) : false)}
+ canEdit={canEdit && !!detailApiKey && detailApiKey.isMine !== false}
manageTooltip={canEdit ? manageTooltip : (reason ?? manageTooltip)}
open={!!detailApiKey}
+ canDelete={
+ canEdit && !!detailApiKey && (detailApiKey.isMine !== false || workspacePolicy.isAdmin)
+ }
onClose={() => setDetailId(undefined)}
- onUpdate={(id, params) => updateMutation.mutate({ id, params })}
onDelete={async (id) => {
await deleteMutation.mutateAsync(id);
setDetailId(undefined);
}}
+ onUpdate={async (id, params) => {
+ try {
+ await updateMutation.mutateAsync({ id, params });
+ return true;
+ } catch {
+ return false;
+ }
+ }}
/>
</div>
);
diff --git a/src/features/Settings/apikey/features/ApiKeyDetail.tsx b/src/features/Settings/apikey/features/ApiKeyDetail.tsx
index 6bd39c6bdf9..afb6eb0e8e1 100644
--- a/src/features/Settings/apikey/features/ApiKeyDetail.tsx
+++ b/src/features/Settings/apikey/features/ApiKeyDetail.tsx
@@ -4,14 +4,18 @@ 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 { Pencil, Trash } from 'lucide-react';
+import { type FC, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { isFullAccessApiKey } from '@/const/apiKeyScope';
+import {
+ API_KEY_FULL_ACCESS_SCOPE,
+ type ApiKeyScope,
+ isFullAccessApiKey,
+} from '@/const/apiKeyScope';
import { type ApiKeyItem, type UpdateApiKeyParams } from '@/types/apiKey';
-import { ScopeOverview } from './ApiKeyModal/ScopeSelector';
+import ScopeSelector, { ScopeOverview } from './ApiKeyModal/ScopeSelector';
import { ApiKeyDisplay, EditableCell } from './index';
const styles = createStaticStyles(({ css, cssVar }) => ({
@@ -47,23 +51,112 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
export interface ApiKeyDetailProps {
apiKey?: ApiKeyItem;
- canManage: boolean;
+ canDelete: boolean;
+ canEdit: boolean;
manageTooltip: string;
onClose: () => void;
onDelete: (id: string) => Promise<void>;
- onUpdate: (id: string, params: UpdateApiKeyParams) => void;
+ onUpdate: (id: string, params: UpdateApiKeyParams) => Promise<boolean>;
open: boolean;
}
+interface ApiKeyScopeEditorProps {
+ apiKey: ApiKeyItem;
+ canEdit: boolean;
+ onUpdate: (id: string, params: UpdateApiKeyParams) => Promise<boolean>;
+}
+
+const ApiKeyScopeEditor: FC<ApiKeyScopeEditorProps> = ({ apiKey, canEdit, onUpdate }) => {
+ const { t } = useTranslation('auth');
+ const initialFullAccess = isFullAccessApiKey(apiKey.scopes);
+ const [editing, setEditing] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [fullAccess, setFullAccess] = useState(initialFullAccess);
+ const [selected, setSelected] = useState<ApiKeyScope[]>(
+ initialFullAccess ? [] : (apiKey.scopes as ApiKeyScope[]),
+ );
+ const scopeMissing = !fullAccess && selected.length === 0;
+
+ if (editing) {
+ return (
+ <Flexbox gap={12}>
+ <ScopeSelector
+ fullAccess={fullAccess}
+ selected={selected}
+ onFullAccessChange={setFullAccess}
+ onSelectedChange={setSelected}
+ />
+ <Flexbox horizontal gap={8} justify={'flex-end'}>
+ <Button
+ type="text"
+ onClick={() => {
+ setFullAccess(initialFullAccess);
+ setSelected(initialFullAccess ? [] : (apiKey.scopes as ApiKeyScope[]));
+ setEditing(false);
+ }}
+ >
+ {t('apikey.detail.permissions.cancel')}
+ </Button>
+ <Button
+ disabled={scopeMissing}
+ loading={saving}
+ type="primary"
+ onClick={async () => {
+ setSaving(true);
+ try {
+ const success = await onUpdate(apiKey.id, {
+ scopes: fullAccess ? [API_KEY_FULL_ACCESS_SCOPE] : selected,
+ });
+ if (success) setEditing(false);
+ } catch {
+ // The mutation owns user-facing error feedback. Keep the
+ // editor open so the selected grants are not lost.
+ } finally {
+ setSaving(false);
+ }
+ }}
+ >
+ {t('apikey.detail.permissions.save')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+ }
+
+ return (
+ <Flexbox gap={8}>
+ {initialFullAccess ? (
+ <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!} />
+ )}
+ {canEdit && (
+ <Flexbox horizontal justify={'flex-end'}>
+ <Button icon={Pencil} type="text" onClick={() => setEditing(true)}>
+ {t('apikey.detail.permissions.edit')}
+ </Button>
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+};
+
/**
* 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.
+ * system. The creator may edit scopes in place; admins may revoke other
+ * members' keys but cannot change their grants.
*/
const ApiKeyDetail: FC<ApiKeyDetailProps> = ({
apiKey,
- canManage,
+ canDelete,
+ canEdit,
manageTooltip,
onClose,
onDelete,
@@ -87,13 +180,13 @@ const ApiKeyDetail: FC<ApiKeyDetailProps> = ({
<span className={styles.label}>{t('apikey.list.columns.name')}</span>
<span className={styles.value}>
<EditableCell
- disabled={!canManage}
+ disabled={!canEdit}
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 });
+ if (!canEdit || !name || name === apiKey.name) return;
+ void onUpdate(apiKey.id, { name: name as string });
}}
/>
</span>
@@ -137,13 +230,13 @@ const ApiKeyDetail: FC<ApiKeyDetailProps> = ({
<span className={styles.label}>{t('apikey.list.columns.expiresAt')}</span>
<span className={styles.value}>
<EditableCell
- disabled={!canManage}
+ disabled={!canEdit}
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, {
+ if (!canEdit || expiresAt === apiKey.expiresAt) return;
+ void onUpdate(apiKey.id, {
expiresAt: expiresAt ? new Date(expiresAt as string) : null,
});
}}
@@ -153,13 +246,13 @@ const ApiKeyDetail: FC<ApiKeyDetailProps> = ({
<div className={styles.metaRow}>
<span className={styles.label}>{t('apikey.list.columns.status')}</span>
- <span className={styles.value} title={canManage ? undefined : manageTooltip}>
+ <span className={styles.value} title={canEdit ? undefined : manageTooltip}>
<Switch
checked={!!apiKey.enabled}
- disabled={!canManage}
+ disabled={!canEdit}
onChange={(checked) => {
- if (!canManage) return;
- onUpdate(apiKey.id, { enabled: checked });
+ if (!canEdit) return;
+ void onUpdate(apiKey.id, { enabled: checked });
}}
/>
</span>
@@ -168,35 +261,31 @@ const ApiKeyDetail: FC<ApiKeyDetailProps> = ({
<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!} />
- )}
+ <ApiKeyScopeEditor
+ apiKey={apiKey}
+ canEdit={canEdit}
+ key={`${apiKey.id}-${apiKey.updatedAt.toISOString()}`}
+ onUpdate={onUpdate}
+ />
</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 }}
+ okButtonProps={{ disabled: !canDelete }}
okText={t('apikey.list.actions.deleteConfirm.actions.ok')}
title={t('apikey.list.actions.deleteConfirm.title')}
onConfirm={async () => {
- if (!canManage) return;
+ if (!canDelete) return;
await onDelete(apiKey.id);
}}
>
<Button
danger
- disabled={!canManage}
+ disabled={!canDelete}
icon={Trash}
- title={canManage ? t('apikey.list.actions.delete') : manageTooltip}
+ title={canDelete ? t('apikey.list.actions.delete') : manageTooltip}
type="text"
>
{t('apikey.list.actions.delete')}
diff --git a/src/features/Settings/apikey/features/ApiKeyModal/Content.tsx b/src/features/Settings/apikey/features/ApiKeyModal/Content.tsx
index 6fa35c2e8a3..86de5f96cf8 100644
--- a/src/features/Settings/apikey/features/ApiKeyModal/Content.tsx
+++ b/src/features/Settings/apikey/features/ApiKeyModal/Content.tsx
@@ -26,7 +26,6 @@ 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[]>([]);
diff --git a/src/features/WorkspaceSetting/hooks/useCategory.test.tsx b/src/features/WorkspaceSetting/hooks/useCategory.test.tsx
index 20c3d93e1b5..4cf9a640f4b 100644
--- a/src/features/WorkspaceSetting/hooks/useCategory.test.tsx
+++ b/src/features/WorkspaceSetting/hooks/useCategory.test.tsx
@@ -18,6 +18,7 @@ vi.hoisted(() => {
});
const mocks = vi.hoisted(() => ({
+ canCreateContent: true,
canManageWorkspace: true,
canViewBilling: true,
}));
@@ -28,9 +29,14 @@ vi.mock('react-i18next', () => ({
}),
}));
+const permissionFlags: Record<string, () => boolean> = {
+ create_content: () => mocks.canCreateContent,
+ view_billing: () => mocks.canViewBilling,
+};
+
vi.mock('@/hooks/usePermission', () => ({
usePermission: (action: string) => ({
- allowed: action === 'view_billing' ? mocks.canViewBilling : mocks.canManageWorkspace,
+ allowed: permissionFlags[action]?.() ?? mocks.canManageWorkspace,
reason: '',
}),
}));
@@ -44,6 +50,7 @@ const getItemKeys = () => {
};
beforeEach(() => {
+ mocks.canCreateContent = true;
mocks.canManageWorkspace = true;
mocks.canViewBilling = true;
});
@@ -82,20 +89,20 @@ describe('workspace settings useCategory', () => {
);
});
- it('places API Key in the Admin-or-higher group', () => {
+ it('places API Key in the Developer group', () => {
const { result } = renderHook(() => useWorkspaceSettingCategory());
const adminGroup = result.current.find(
(group) => group.key === WorkspaceSettingsGroupKey.Admin,
);
- const agentGroup = result.current.find(
- (group) => group.key === WorkspaceSettingsGroupKey.Agent,
+ const developerGroup = result.current.find(
+ (group) => group.key === WorkspaceSettingsGroupKey.Developer,
);
- expect(adminGroup?.items.map((item) => item.key)).toContain(WorkspaceSettingsTabs.APIKey);
- expect(agentGroup?.items.map((item) => item.key)).not.toContain(WorkspaceSettingsTabs.APIKey);
+ expect(developerGroup?.items.map((item) => item.key)).toContain(WorkspaceSettingsTabs.APIKey);
+ expect(adminGroup?.items.map((item) => item.key)).not.toContain(WorkspaceSettingsTabs.APIKey);
});
- it('does not expose API Key settings below Admin', () => {
+ it('exposes API Key settings to members', () => {
mocks.canManageWorkspace = false;
const itemKeys = getItemKeys();
@@ -104,7 +111,43 @@ describe('workspace settings useCategory', () => {
expect(result.current.some((group) => group.key === WorkspaceSettingsGroupKey.Admin)).toBe(
false,
);
- expect(itemKeys).not.toContain(WorkspaceSettingsTabs.APIKey);
+ expect(itemKeys).toContain(WorkspaceSettingsTabs.APIKey);
+ });
+
+ // Viewers hold no `API_KEY_*` grant, so the tab would open onto a list
+ // request that immediately 403s.
+ it('hides API Key from viewers, and drops the empty Developer group', () => {
+ mocks.canCreateContent = false;
+ mocks.canManageWorkspace = false;
+
+ const { result } = renderHook(() => useWorkspaceSettingCategory());
+
+ expect(result.current.flatMap((group) => group.items.map((item) => item.key))).not.toContain(
+ WorkspaceSettingsTabs.APIKey,
+ );
+ expect(result.current.some((group) => group.key === WorkspaceSettingsGroupKey.Developer)).toBe(
+ false,
+ );
+ });
+
+ it('keeps the Developer group for viewers when OAuth Apps is enabled', () => {
+ mocks.canCreateContent = false;
+ mocks.canManageWorkspace = false;
+ useUserStore.setState({
+ preference: {
+ ...initialUserStoreState.preference,
+ lab: { ...initialUserStoreState.preference.lab, enableOAuthApps: true },
+ },
+ });
+
+ const { result } = renderHook(() => useWorkspaceSettingCategory());
+ const developerGroup = result.current.find(
+ (group) => group.key === WorkspaceSettingsGroupKey.Developer,
+ );
+
+ expect(developerGroup?.items.map((item) => item.key)).toEqual([
+ WorkspaceSettingsTabs.OAuthApps,
+ ]);
});
// Admin-or-higher reads the billing numbers; the pages keep the
diff --git a/src/features/WorkspaceSetting/hooks/useCategory.tsx b/src/features/WorkspaceSetting/hooks/useCategory.tsx
index 81c20aab006..2818f38e9bf 100644
--- a/src/features/WorkspaceSetting/hooks/useCategory.tsx
+++ b/src/features/WorkspaceSetting/hooks/useCategory.tsx
@@ -53,6 +53,11 @@ export const useWorkspaceSettingCategory = (): WorkspaceSettingCategoryGroup[] =
const { t: tSubscription } = useTranslation('subscription');
const { allowed: canManageWorkspace } = usePermission('manage_settings');
const { allowed: canViewBilling } = usePermission('view_billing');
+ // API keys act as the member who issued them, so the tab follows the same
+ // member-level gate the server enforces: `API_KEY_*` is granted from Member
+ // up, never to Viewer. Without this the tab leads to a list request that
+ // immediately 403s.
+ const { allowed: canCreateContent } = usePermission('create_content');
const enableOAuthApps = useUserStore(labPreferSelectors.enableOAuthApps);
return useMemo(
@@ -172,14 +177,19 @@ export const useWorkspaceSettingCategory = (): WorkspaceSettingCategoryGroup[] =
key: WorkspaceSettingsGroupKey.Agent,
title: t('workspaceSetting.group.agent'),
},
- enableOAuthApps && {
+ (canCreateContent || enableOAuthApps) && {
items: [
- {
+ canCreateContent && {
+ icon: KeyIcon,
+ key: WorkspaceSettingsTabs.APIKey,
+ label: tAuth('tab.apikey'),
+ },
+ enableOAuthApps && {
icon: AppWindowIcon,
key: WorkspaceSettingsTabs.OAuthApps,
label: tAuth('tab.oauthApps'),
},
- ],
+ ].filter(Boolean) as WorkspaceSettingCategoryItem[],
key: WorkspaceSettingsGroupKey.Developer,
title: t('group.developer'),
},
@@ -191,11 +201,6 @@ export const useWorkspaceSettingCategory = (): WorkspaceSettingCategoryGroup[] =
key: WorkspaceSettingsTabs.Storage,
label: t('tab.storage'),
},
- {
- icon: KeyIcon,
- key: WorkspaceSettingsTabs.APIKey,
- label: tAuth('tab.apikey'),
- },
{
icon: ScrollText,
key: WorkspaceSettingsTabs.AuditLog,
@@ -206,6 +211,14 @@ export const useWorkspaceSettingCategory = (): WorkspaceSettingCategoryGroup[] =
title: t('workspaceSetting.group.admin'),
},
].filter(Boolean) as WorkspaceSettingCategoryGroup[],
- [t, tAuth, tSubscription, enableOAuthApps, canManageWorkspace, canViewBilling],
+ [
+ t,
+ tAuth,
+ tSubscription,
+ enableOAuthApps,
+ canManageWorkspace,
+ canViewBilling,
+ canCreateContent,
+ ],
);
};
diff --git a/src/routes/(main)/[workspaceSlug]/settings/apikey/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/apikey/index.tsx
index a073f2acaf6..3e13fa7e206 100644
--- a/src/routes/(main)/[workspaceSlug]/settings/apikey/index.tsx
+++ b/src/routes/(main)/[workspaceSlug]/settings/apikey/index.tsx
@@ -1,15 +1,12 @@
'use client';
-import WorkspaceApiKeyGuard from '@/business/client/BusinessSettingPages/WorkspaceApiKeyGuard';
+import { WorkspaceApiKeyGuard } from '@/business/client/BusinessSettingPages/WorkspaceApiKeyGuard';
import Page from '@/features/Settings/apikey';
-import { WorkspaceAdminOnly } from '@/features/WorkspaceSetting';
const WorkspaceApiKeySetting = () => (
- <WorkspaceAdminOnly>
- <WorkspaceApiKeyGuard>
- <Page showSettingHeader={false} />
- </WorkspaceApiKeyGuard>
- </WorkspaceAdminOnly>
+ <WorkspaceApiKeyGuard>
+ <Page showSettingHeader={false} />
+ </WorkspaceApiKeyGuard>
);
WorkspaceApiKeySetting.displayName = 'WorkspaceApiKeySetting';