π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(skill): scope skill-store imports to the active workspace (#16620)
LiJian8f089b1a1f24
diff --git a/apps/server/src/services/skill/importer.test.ts b/apps/server/src/services/skill/importer.test.tsindex 544b825113f..1fad7e9ac99 100644--- a/apps/server/src/services/skill/importer.test.ts+++ b/apps/server/src/services/skill/importer.test.ts@@ -1,10 +1,12 @@// @vitest-environment nodeimport type { LobeChatDatabase } from '@lobechat/database';-import { agentSkills, files, globalFiles, users } from '@lobechat/database/schemas';+import { agentSkills, files, globalFiles, users, workspaces } from '@lobechat/database/schemas';import { getTestDB } from '@lobechat/database/test-utils';import { and, eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { AgentSkillModel } from '@/database/models/agentSkill';+import { SkillImportError } from './errors';import { SkillImporter } from './importer';@@ -1163,4 +1165,131 @@ description: A nested skillawait db.delete(users).where(eq(users.id, otherUserId));});});++ // Regression for LOBE-10893: a skill imported while running inside a workspace+ // must be written with `workspace_id = <ws>`, not the importer's personal scope+ // (`workspace_id IS NULL`). Otherwise it is invisible to every workspace member+ // β including the creator whenever they operate in workspace mode β and a+ // re-import of a name that already exists personally hits a unique violation.+ describe('workspace scoping (LOBE-10893)', () => {+ let workspaceId: string;+ let wsImporter: SkillImporter;++ beforeEach(async () => {+ // agent_skills.workspace_id has an FK to workspaces.id, so the workspace+ // row must exist before a workspace-scoped skill can be inserted.+ const [ws] = await db+ .insert(workspaces)+ .values({ name: 'Test Workspace', primaryOwnerId: userId, slug: `ws-${userId}` })+ .returning();+ workspaceId = ws.id;+ wsImporter = new SkillImporter(db, userId, workspaceId);+ });++ it('createUserSkill writes workspace_id when running in a workspace', async () => {+ const result = await wsImporter.createUserSkill({+ content: '# WS content',+ description: 'A workspace skill',+ name: 'Workspace Skill',+ });++ const dbSkill = await db.query.agentSkills.findFirst({+ where: eq(agentSkills.id, result.id),+ });+ expect(dbSkill?.workspaceId).toBe(workspaceId);+ });++ it('personal import stays personal (workspace_id IS NULL)', async () => {+ const result = await importer.createUserSkill({+ content: '# personal',+ description: 'A personal skill',+ name: 'Personal Skill',+ });++ const dbSkill = await db.query.agentSkills.findFirst({+ where: eq(agentSkills.id, result.id),+ });+ expect(dbSkill?.workspaceId).toBeNull();+ });++ it('importFromUrl lands the skill in the workspace scope', async () => {+ mockSsrfSafeFetch.mockResolvedValue({+ ok: true,+ status: 200,+ text: async () => 'content',+ });+ mockParserInstance.parseSkillMd.mockReturnValue({+ content: '# Imported',+ manifest: { name: 'Imported Workspace Skill', description: 'from url' },+ raw: 'raw',+ });++ const result = await wsImporter.importFromUrl({+ url: 'https://example.com/ws-skill.md',+ });++ const dbSkill = await db.query.agentSkills.findFirst({+ where: eq(agentSkills.id, result.skill.id),+ });+ expect(dbSkill?.workspaceId).toBe(workspaceId);+ });++ it('is visible to other workspace members but hidden from personal scope', async () => {+ const created = await wsImporter.createUserSkill({+ content: '# shared',+ description: 'A shared workspace skill',+ identifier: 'shared-ws-skill',+ name: 'Shared Workspace Skill',+ });++ // Another member of the SAME workspace (different user, same workspaceId).+ // Workspace reads filter by workspace_id only, so a member must see it.+ const memberId = `member-${userId}`;+ await db.insert(users).values({ id: memberId });+ const memberView = await new AgentSkillModel(db, memberId, workspaceId).findById(created.id);+ expect(memberView?.id).toBe(created.id);++ // The importer's OWN personal scope (no workspaceId) must NOT see it.+ const personalView = await new AgentSkillModel(db, userId).findById(created.id);+ expect(personalView).toBeUndefined();++ await db.delete(users).where(eq(users.id, memberId));+ });++ it('does not collide with a same-named skill in the user personal scope', async () => {+ // The user already has a personal skill named "pdf" (a different identifier).+ await importer.createUserSkill({+ content: '# personal pdf',+ description: 'personal pdf skill',+ identifier: 'personal-pdf',+ name: 'pdf',+ });++ // Importing a market/URL skill also named "pdf" into the workspace must+ // succeed: the personal partial unique `(user_id, name) WHERE ws IS NULL`+ // and the workspace partial unique `(ws, name) WHERE ws IS NOT NULL` are+ // disjoint. Pre-fix this insert wrote workspace_id = NULL and blew up on+ // the personal unique index.+ mockSsrfSafeFetch.mockResolvedValue({+ ok: true,+ status: 200,+ text: async () => 'content',+ });+ mockParserInstance.parseSkillMd.mockReturnValue({+ content: '# workspace pdf',+ manifest: { name: 'pdf', description: 'workspace pdf skill' },+ raw: 'raw',+ });++ const result = await wsImporter.importFromUrl({+ url: 'https://example.com/anthropics-skills-pdf.md',+ });++ const dbSkill = await db.query.agentSkills.findFirst({+ where: eq(agentSkills.id, result.skill.id),+ });+ expect(dbSkill?.name).toBe('pdf');+ expect(dbSkill?.workspaceId).toBe(workspaceId);+ });+ });});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skillStore.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skillStore.test.tsnew file mode 100644index 00000000000..b2c3c0448f4--- /dev/null+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skillStore.test.ts@@ -0,0 +1,130 @@+import { RBAC_PERMISSIONS } from '@lobechat/const/rbac';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ getUserSettings: vi.fn(),+ hasAnyPermission: vi.fn(),+ SkillImporter: vi.fn(),+}));++vi.mock('@lobechat/builtin-tool-skill-store', () => ({+ SkillStoreIdentifier: 'lobe-skill-store',+}));++vi.mock('@lobechat/builtin-tool-skill-store/executionRuntime', () => ({+ // Minimal stub so the factory can wrap the service without pulling the real+ // package runtime; the test only cares about how SkillImporter is constructed.+ SkillStoreExecutionRuntime: vi.fn(function (this: any, opts: any) {+ this.service = opts.service;+ }),+}));++vi.mock('@/database/models/rbac', () => ({+ RbacModel: vi.fn(() => ({+ hasAnyPermission: mocks.hasAnyPermission,+ })),+}));++vi.mock('@/database/models/user', () => ({+ UserModel: vi.fn(() => ({+ getUserSettings: mocks.getUserSettings,+ })),+}));++vi.mock('@/server/services/market', () => ({+ MarketService: vi.fn(() => ({})),+}));++vi.mock('@/server/services/skill/importer', () => ({+ SkillImporter: mocks.SkillImporter,+}));++vi.mock('@/server/services/agentSignal/procedure', () => ({+ emitToolOutcomeSafely: vi.fn(),+ resolveToolOutcomeScope: vi.fn(() => ({ scope: 'user', scopeKey: 'user-1' })),+}));++vi.mock('@/server/services/agentSignal/store/adapters/redis/policyStateStore', () => ({+ redisPolicyStateStore: {},+}));++describe('skillStoreRuntime', () => {+ const serverDB = {} as never;+ const scopedSkillWritePermissions = [+ RBAC_PERMISSIONS.AGENT_UPDATE_ALL,+ RBAC_PERMISSIONS.AGENT_UPDATE_OWNER,+ ];++ beforeEach(() => {+ vi.clearAllMocks();+ mocks.getUserSettings.mockResolvedValue({ market: { accessToken: 'market-token' } });+ // Default: caller is allowed to manage workspace skills.+ mocks.hasAnyPermission.mockResolvedValue(true);+ });++ // Regression guard for LOBE-10893: importing a skill while running inside a+ // workspace must construct SkillImporter WITH the workspaceId, otherwise the+ // skill row is saved with `workspace_id = NULL` (the importer's personal+ // scope) and becomes invisible to the whole workspace β including the creator+ // whenever they operate in workspace mode.+ it('constructs SkillImporter with the workspaceId when the caller can manage workspace skills', async () => {+ const { skillStoreRuntime } = await import('../skillStore');++ await skillStoreRuntime.factory({+ serverDB,+ toolManifestMap: {},+ userId: 'user-1',+ workspaceId: 'workspace-1',+ });++ expect(mocks.hasAnyPermission).toHaveBeenCalledWith(scopedSkillWritePermissions, {+ workspaceId: 'workspace-1',+ });+ expect(mocks.SkillImporter).toHaveBeenCalledWith(serverDB, 'user-1', 'workspace-1');+ });++ // The skillStore runtime is reached via aiAgentWriteProcedure (message:create),+ // bypassing agentSkillsRouter's withScopedPermission('agent:update') gate. An+ // approve-only member must NOT be able to mutate the shared workspace skill+ // catalog by approving an import β it falls back to their personal scope.+ it('falls back to personal scope when the caller lacks the workspace skill-write permission', async () => {+ mocks.hasAnyPermission.mockResolvedValue(false);+ const { skillStoreRuntime } = await import('../skillStore');++ await skillStoreRuntime.factory({+ serverDB,+ toolManifestMap: {},+ userId: 'user-1',+ workspaceId: 'workspace-1',+ });++ expect(mocks.SkillImporter).toHaveBeenCalledWith(serverDB, 'user-1', undefined);+ });++ it('falls back to personal scope when the permission check throws', async () => {+ mocks.hasAnyPermission.mockRejectedValue(new Error('db down'));+ const { skillStoreRuntime } = await import('../skillStore');++ await skillStoreRuntime.factory({+ serverDB,+ toolManifestMap: {},+ userId: 'user-1',+ workspaceId: 'workspace-1',+ });++ expect(mocks.SkillImporter).toHaveBeenCalledWith(serverDB, 'user-1', undefined);+ });++ it('uses personal scope and skips the RBAC check outside a workspace', async () => {+ const { skillStoreRuntime } = await import('../skillStore');++ await skillStoreRuntime.factory({+ serverDB,+ toolManifestMap: {},+ userId: 'user-1',+ });++ expect(mocks.hasAnyPermission).not.toHaveBeenCalled();+ expect(mocks.SkillImporter).toHaveBeenCalledWith(serverDB, 'user-1', undefined);+ });+});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/skillStore.ts b/apps/server/src/services/toolExecution/serverRuntimes/skillStore.tsindex 0d2b4f6b349..41f7d82f87e 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/skillStore.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/skillStore.ts@@ -8,8 +8,10 @@ import {SkillStoreExecutionRuntime,type SkillStoreRuntimeService,} from '@lobechat/builtin-tool-skill-store/executionRuntime';+import { RBAC_PERMISSIONS } from '@lobechat/const/rbac';import debug from 'debug';+import { RbacModel } from '@/database/models/rbac';import { UserModel } from '@/database/models/user';import {emitToolOutcomeSafely,@@ -256,7 +258,43 @@ export const skillStoreRuntime: ServerRuntimeRegistration = {log('Failed to fetch market accessToken for user %s: %O', context.userId, error);}- const importer = new SkillImporter(context.serverDB, context.userId);+ // Importing inside a workspace writes the SHARED workspace skill catalog.+ // This server-runtime path is reached via aiAgentWriteProcedure+ // (message:create) and does NOT pass through agentSkillsRouter's+ // withScopedPermission('agent:update') write gate, so an approve-only member+ // (chat/tool-approval rights but no skill-management grant) could otherwise+ // mutate the shared catalog by approving an import. Gate the workspace scope+ // on the same permission; fall back to personal scope when the caller lacks+ // it (safe direction β mirrors the pre-workspace behavior for that member and+ // never touches the shared catalog without authorization).+ let importWorkspaceId = context.workspaceId;+ if (importWorkspaceId) {+ try {+ const rbac = new RbacModel(context.serverDB, context.userId);+ const canManageWorkspaceSkills = await rbac.hasAnyPermission(+ [RBAC_PERMISSIONS.AGENT_UPDATE_ALL, RBAC_PERMISSIONS.AGENT_UPDATE_OWNER],+ { workspaceId: importWorkspaceId },+ );+ if (!canManageWorkspaceSkills) {+ log(+ 'User %s lacks agent:update in workspace %s; importing skill into personal scope',+ context.userId,+ importWorkspaceId,+ );+ importWorkspaceId = undefined;+ }+ } catch (error) {+ // Fail safe: never write the shared workspace catalog on an unverified+ // permission check.+ log(+ 'Failed to verify workspace skill-write permission; falling back to personal scope: %O',+ error,+ );+ importWorkspaceId = undefined;+ }+ }++ const importer = new SkillImporter(context.serverDB, context.userId, importWorkspaceId);const marketService = new MarketService({accessToken: marketAccessToken,userInfo: { userId: context.userId },