🤯 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(bot): stop a binding outside the active scope from being undeletable (#19446)
Arvin Xu85d4f3a79c2e
diff --git a/apps/cli/src/commands/bot.test.ts b/apps/cli/src/commands/bot.test.tsindex b9835228901..d77738bf71d 100644--- a/apps/cli/src/commands/bot.test.ts+++ b/apps/cli/src/commands/bot.test.ts@@ -269,13 +269,29 @@ describe('bot command', () => {describe('remove', () => {it('should remove with --yes', async () => {- mockTrpcClient.agentBotProvider.delete.mutate.mockResolvedValue({});+ mockTrpcClient.agentBotProvider.delete.mutate.mockResolvedValue([{ id: 'b1' }]);const program = createProgram();await program.parseAsync(['node', 'test', 'bot', 'remove', 'b1', '--yes']);expect(mockTrpcClient.agentBotProvider.delete.mutate).toHaveBeenCalledWith({ id: 'b1' });});++ it('fails loudly when the server removed nothing', async () => {+ // A delete that matched no row used to print the same checkmark as a real+ // one, which is what made an unreachable binding look deleted.+ mockTrpcClient.agentBotProvider.delete.mutate.mockResolvedValue([]);+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ const program = createProgram();+ await program.parseAsync(['node', 'test', 'bot', 'remove', 'b1', '--yes']);++ expect(errorSpy.mock.calls.flat().join(' ')).toContain('Nothing removed');+ expect(process.exitCode).toBe(1);++ process.exitCode = 0;+ errorSpy.mockRestore();+ });});describe('enable / disable', () => {diff --git a/apps/cli/src/commands/bot.ts b/apps/cli/src/commands/bot.tsindex 8a654e3d23f..4d45e6b7ebd 100644--- a/apps/cli/src/commands/bot.ts+++ b/apps/cli/src/commands/bot.ts@@ -830,7 +830,16 @@ export function registerBotCommand(program: Command) {}const client = await getTrpcClient();- await client.agentBotProvider.delete.mutate({ id: botId });+ const removed = await client.agentBotProvider.delete.mutate({ id: botId });++ // The server returns the rows it removed. Printing the checkmark without+ // reading it is how a delete that matched nothing used to read as done.+ if (Array.isArray(removed) && removed.length === 0) {+ console.error(`${pc.red('✗')} Nothing removed — bot ${pc.bold(botId)} still exists`);+ process.exitCode = 1;+ return;+ }+console.log(`${pc.green('✓')} Removed bot ${pc.bold(botId)}`);});diff --git a/apps/server/src/routers/lambda/__tests__/agentBotProvider.scope.test.ts b/apps/server/src/routers/lambda/__tests__/agentBotProvider.scope.test.tsnew file mode 100644index 00000000000..c67197e281b--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/agentBotProvider.scope.test.ts@@ -0,0 +1,248 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++// serverDatabase middleware calls getServerDB(); the model is mocked, so the+// handle it returns is never dereferenced.+vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return {};+ }),+}));++vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({+ withScopedPermission: vi.fn(function () {+ return (opts: any) => opts.next({ ctx: opts.ctx });+ }),+}));++vi.mock('@/business/server/bot/featureAccess', () => ({+ assertBotFeatureAccess: vi.fn(async () => {}),+ withBotPlatformAccessMeta: vi.fn((meta: any) => meta),+}));++vi.mock('@/server/services/bot/agentBotProviderSettings', () => ({+ assertBotAccessSettings: vi.fn(),+ assertWatchKeywordsWritable: vi.fn(async () => {}),+ invalidateBotAfterUpdate: vi.fn(async () => {}),+ mergeBotSettingsForPersist: vi.fn((_platform: string, settings: unknown) => settings ?? {}),+}));++vi.mock('@/server/services/bot/platforms', () => ({+ collectFieldFormatViolations: vi.fn(() => []),+ formatFieldFormatViolations: vi.fn(() => ''),+ mergeWithDefaults: vi.fn((_p: string, s: unknown) => s),+ platformRegistry: { getPlatform: vi.fn(() => undefined) },+}));++const mockStopClient = vi.fn(async () => {});+vi.mock('@/server/services/gateway', () => ({+ GatewayService: vi.fn(function () {+ return { stopClient: mockStopClient };+ }),+}));++const mockInvalidateBot = vi.fn(async () => {});+vi.mock('@/server/services/bot/BotMessageRouter', () => ({+ getBotMessageRouter: vi.fn(() => ({ invalidateBot: mockInvalidateBot })),+}));++vi.mock('@/server/services/gateway/runtimeStatus', () => ({+ getBotRuntimeStatus: vi.fn(async () => ({ status: 'disconnected' })),+}));++vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({+ KeyVaultsGateKeeper: { initWithEnvKey: vi.fn(async () => ({})) },+}));++const mockGetMember = vi.fn();+vi.mock('@/database/models/workspaceMember', () => ({+ WorkspaceMemberModel: vi.fn(function () {+ return { getMember: mockGetMember };+ }),+}));++const mockCreate = vi.fn();+const mockFindById = vi.fn();+const mockDelete = vi.fn();+const mockFindByIdAcrossScopes = vi.fn();+const mockDeleteAcrossScopes = vi.fn();+const mockFindByPlatformAndAppId = vi.fn();++vi.mock('@/database/models/agentBotProvider', () => {+ const AgentBotProviderModel: any = vi.fn(function () {+ return {+ create: mockCreate,+ delete: mockDelete,+ deleteAcrossScopes: mockDeleteAcrossScopes,+ findById: mockFindById,+ findByIdAcrossScopes: mockFindByIdAcrossScopes,+ };+ });+ AgentBotProviderModel.findByPlatformAndAppId = mockFindByPlatformAndAppId;+ return { AgentBotProviderModel };+});++const { agentBotProviderRouter } = await import('../agentBotProvider');++/** Shaped like the driver error drizzle surfaces, nested behind `cause`. */+const uniqueViolation = () => {+ const error = new Error('duplicate key value violates unique constraint');+ (error as any).cause = { code: '23505' };+ return error;+};++const BOT_ID = 'bot-1';+const ctx: any = { serverDB: {}, userId: 'user-1', workspaceId: 'ws-1', workspaceRole: 'owner' };++const strandedRow = {+ agentId: 'agt_other',+ applicationId: 'cli_app',+ id: BOT_ID,+ platform: 'feishu',+ userId: 'user-1',+ workspaceId: null,+};++/** Same row, but parked in a workspace instead of personal scope. */+const strandedInWorkspace = { ...strandedRow, workspaceId: 'ws-other' };++beforeEach(() => {+ vi.clearAllMocks();+ mockFindById.mockResolvedValue(undefined);+ mockDelete.mockResolvedValue([]);+ mockFindByIdAcrossScopes.mockResolvedValue(undefined);+ mockDeleteAcrossScopes.mockResolvedValue([{ id: BOT_ID }]);+ mockGetMember.mockResolvedValue({ role: 'member' });+});++describe('agentBotProviderRouter · bindings stranded outside the active scope', () => {+ describe('delete', () => {+ it('reclaims the caller’s own binding when the active scope cannot see it', async () => {+ // The row lives in personal scope while the session is in a workspace.+ // `list` hides it and the scoped delete misses it, yet it still holds the+ // global (platform, applicationId) key that blocks every re-bind.+ mockFindByIdAcrossScopes.mockResolvedValue(strandedRow);+ const caller = agentBotProviderRouter.createCaller(ctx);++ await expect(caller.delete({ id: BOT_ID })).resolves.toEqual([{ id: BOT_ID }]);++ expect(mockDeleteAcrossScopes).toHaveBeenCalledWith(BOT_ID);+ // The gateway still has to be told, using the stranded row's identifiers.+ expect(mockStopClient).toHaveBeenCalledWith('feishu', 'cli_app', 'user-1');+ expect(mockInvalidateBot).toHaveBeenCalledWith('feishu', 'cli_app');+ });++ it('refuses instead of reporting success when nothing was removed', async () => {+ const caller = agentBotProviderRouter.createCaller(ctx);++ await expect(caller.delete({ id: BOT_ID })).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(mockDeleteAcrossScopes).not.toHaveBeenCalled();+ });++ it('will not let one user delete another user’s binding', async () => {+ mockFindByIdAcrossScopes.mockResolvedValue({ ...strandedRow, userId: 'someone-else' });+ const caller = agentBotProviderRouter.createCaller(ctx);++ await expect(caller.delete({ id: BOT_ID })).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(mockDeleteAcrossScopes).not.toHaveBeenCalled();+ });++ it('does not consult workspace membership for a personal binding', async () => {+ mockFindByIdAcrossScopes.mockResolvedValue(strandedRow);+ const caller = agentBotProviderRouter.createCaller(ctx);++ await expect(caller.delete({ id: BOT_ID })).resolves.toEqual([{ id: BOT_ID }]);+ expect(mockGetMember).not.toHaveBeenCalled();+ });++ it('reclaims a workspace binding while the creator still has a seat there', async () => {+ mockFindByIdAcrossScopes.mockResolvedValue(strandedInWorkspace);+ const caller = agentBotProviderRouter.createCaller(ctx);++ await expect(caller.delete({ id: BOT_ID })).resolves.toEqual([{ id: BOT_ID }]);+ expect(mockGetMember).toHaveBeenCalledWith('ws-other', 'user-1');+ });++ it('refuses once the creator has left the workspace holding the binding', async () => {+ // Creating it once is not standing access: the procedure's agent:update+ // gate only covers the active scope, so a departed member could otherwise+ // kill an integration the workspace still runs.+ mockFindByIdAcrossScopes.mockResolvedValue(strandedInWorkspace);+ mockGetMember.mockResolvedValue(undefined);+ const caller = agentBotProviderRouter.createCaller(ctx);++ await expect(caller.delete({ id: BOT_ID })).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(mockDeleteAcrossScopes).not.toHaveBeenCalled();+ expect(mockStopClient).not.toHaveBeenCalled();+ });++ it('refuses a creator demoted to viewer in the workspace holding the binding', async () => {+ mockFindByIdAcrossScopes.mockResolvedValue(strandedInWorkspace);+ mockGetMember.mockResolvedValue({ role: 'viewer' });+ const caller = agentBotProviderRouter.createCaller(ctx);++ await expect(caller.delete({ id: BOT_ID })).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(mockDeleteAcrossScopes).not.toHaveBeenCalled();+ });++ it('leaves the ordinary in-scope delete alone', async () => {+ mockFindById.mockResolvedValue(strandedRow);+ mockDelete.mockResolvedValue([{ id: BOT_ID }]);+ const caller = agentBotProviderRouter.createCaller(ctx);++ await expect(caller.delete({ id: BOT_ID })).resolves.toEqual([{ id: BOT_ID }]);+ expect(mockFindByIdAcrossScopes).not.toHaveBeenCalled();+ expect(mockDeleteAcrossScopes).not.toHaveBeenCalled();+ });+ });++ describe('create conflict message', () => {+ const input = {+ agentId: 'agt_target',+ applicationId: 'cli_app',+ credentials: { appSecret: 's' },+ platform: 'feishu',+ };++ it('names the caller’s own holder and where it lives', async () => {+ mockCreate.mockRejectedValue(uniqueViolation());+ mockFindByPlatformAndAppId.mockResolvedValue(strandedRow);+ const caller = agentBotProviderRouter.createCaller(ctx);++ await expect(caller.create(input)).rejects.toMatchObject({+ code: 'CONFLICT',+ message: expect.stringContaining('agt_other'),+ });+ await expect(caller.create(input)).rejects.toMatchObject({+ message: expect.stringContaining('personal'),+ });+ });++ it('does not name another account’s agent or workspace', async () => {+ mockCreate.mockRejectedValue(uniqueViolation());+ mockFindByPlatformAndAppId.mockResolvedValue({+ ...strandedRow,+ userId: 'someone-else',+ workspaceId: 'ws-secret',+ });+ const caller = agentBotProviderRouter.createCaller(ctx);++ const error = await caller.create(input).catch((e) => e);++ expect(error.code).toBe('CONFLICT');+ expect(error.message).toContain('another account');+ expect(error.message).not.toContain('agt_other');+ expect(error.message).not.toContain('ws-secret');+ });++ it('tells the caller to retry when the holder is already gone', async () => {+ mockCreate.mockRejectedValue(uniqueViolation());+ mockFindByPlatformAndAppId.mockResolvedValue(undefined);+ const caller = agentBotProviderRouter.createCaller(ctx);++ await expect(caller.create(input)).rejects.toMatchObject({+ message: expect.stringContaining('Retry'),+ });+ });+ });+});diff --git a/apps/server/src/routers/lambda/agentBotProvider.ts b/apps/server/src/routers/lambda/agentBotProvider.tsindex 78b03578aa9..8d8dd35ff35 100644--- a/apps/server/src/routers/lambda/agentBotProvider.ts+++ b/apps/server/src/routers/lambda/agentBotProvider.ts@@ -11,6 +11,8 @@ import {import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';import { AgentBotProviderModel } from '@/database/models/agentBotProvider';+import { WorkspaceMemberModel } from '@/database/models/workspaceMember';+import type { LobeChatDatabase } from '@/database/type';import { authedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';@@ -52,6 +54,76 @@ const agentBotProviderProcedureWrite = agentBotProviderProcedure.use(withScopedPermission('agent:update'),);+const BOT_NOT_FOUND_MESSAGE = 'Bot integration not found';++/**+ * Gate the cross-scope reclaim on the workspace the binding actually lives in.+ *+ * The procedure's `agent:update` scope is evaluated against the caller's active+ * workspace, which by definition is not the one holding a stranded row. Being+ * its original creator says nothing about present access, so re-check+ * membership where it counts: an active, non-viewer seat in the owning+ * workspace. A binding with no workspace is personal, and the creator check+ * already settled it.+ */+async function assertStrandedWorkspaceStillManageable(+ ctx: { serverDB: LobeChatDatabase; userId: string },+ workspaceId: string | null,+): Promise<void> {+ if (!workspaceId) return;++ const member = await new WorkspaceMemberModel(ctx.serverDB, ctx.userId).getMember(+ workspaceId,+ ctx.userId,+ );++ if (member && member.role !== 'viewer') return;++ throw new TRPCError({+ code: 'FORBIDDEN',+ message: `This bot belongs to workspace ${workspaceId}, and you no longer have permission to manage it there. Ask a member of that workspace to remove the binding.`,+ });+}++/**+ * Turn a unique-index violation into something the caller can act on.+ *+ * `(platform, applicationId)` is unique across the whole deployment because it+ * is the webhook routing key, while `list` only ever shows the caller's active+ * scope. The old message asserted "already registered" without looking, so a+ * holder sitting in the caller's other scope — invisible to `list`, untouched+ * by `remove` — read as a phantom constraint with nothing behind it.+ *+ * Resolve the actual holder and say where it is. A binding the caller created+ * is theirs to know about in full; anyone else's is reported as taken without+ * naming the agent, the workspace or the owner.+ */+async function describeApplicationIdConflict(+ ctx: { serverDB: LobeChatDatabase; userId: string },+ platform: string,+ applicationId: string,+): Promise<string> {+ const head = `Application ID "${applicationId}" is already bound on ${platform}`;+ const holder = await AgentBotProviderModel.findByPlatformAndAppId(+ ctx.serverDB,+ platform,+ applicationId,+ );++ // Lost the race with a concurrent delete — the key is free again.+ if (!holder) return `${head}. Retry the request.`;++ if (holder.userId !== ctx.userId) {+ return `${head} by another account. An application ID can only be bound to one agent, so ask whoever set it up to remove their binding first.`;+ }++ const where = holder.workspaceId+ ? `workspace ${holder.workspaceId}`+ : 'your personal (non-workspace) scope';++ return `${head} to your agent ${holder.agentId} in ${where}. Remove that binding first: lh bot remove ${holder.id}. If it does not appear in \`lh bot list\`, you are listing a different scope — the binding is still there and still holds the ID.`;+}+/*** Wrap the shared access-policy validator so violations surface as* `TRPCError(BAD_REQUEST)` — keeps client forms able to highlight the@@ -147,7 +219,7 @@ export const agentBotProviderRouter = router({if (e?.cause?.code === '23505') {throw new TRPCError({code: 'CONFLICT',- message: `A bot with application ID "${input.applicationId}" is already registered on ${input.platform}. Each application ID can only be used once.`,+ message: await describeApplicationIdConflict(ctx, input.platform, input.applicationId),});}throw e;@@ -161,16 +233,46 @@ export const agentBotProviderRouter = router({const existing = await ctx.agentBotProviderModel.findById(input.id);if (existing) assertWorkspaceRowManageable(ctx, existing.userId, 'bot provider');- const result = await ctx.agentBotProviderModel.delete(input.id);+ let deleted = await ctx.agentBotProviderModel.delete(input.id);+ // Only the routing identifiers are needed downstream, so keep this+ // independent of whether the row came back decrypted or raw.+ let routing = existing && {+ applicationId: existing.applicationId,+ platform: existing.platform,+ };++ // Nothing matched in the caller's scope. The binding may still exist in+ // their other scope — a personal session cannot see a workspace row and+ // vice versa — where it stays invisible to `list` yet keeps holding the+ // global (platform, applicationId) key. Let the creator reclaim it from+ // either side rather than reporting a delete that never happened.+ if (deleted.length === 0) {+ const stranded = await ctx.agentBotProviderModel.findByIdAcrossScopes(input.id);++ // A binding owned by someone else is not the caller's to delete, and+ // saying so would confirm it exists — both answer NOT_FOUND.+ if (!stranded || stranded.userId !== ctx.userId) {+ throw new TRPCError({ code: 'NOT_FOUND', message: BOT_NOT_FOUND_MESSAGE });+ }++ // Having created it is not enough when it lives in a workspace: the+ // procedure's `agent:update` gate only covers the *active* scope, so+ // without this a creator who has since left that workspace could reach+ // in from personal scope and kill an integration the team still runs.+ await assertStrandedWorkspaceStillManageable(ctx, stranded.workspaceId);++ deleted = await ctx.agentBotProviderModel.deleteAcrossScopes(input.id);+ routing = { applicationId: stranded.applicationId, platform: stranded.platform };+ }// Stop running client and invalidate cached bot- if (existing) {+ if (routing) {const service = new GatewayService();- await service.stopClient(existing.platform, existing.applicationId, ctx.userId);- await getBotMessageRouter().invalidateBot(existing.platform, existing.applicationId);+ await service.stopClient(routing.platform, routing.applicationId, ctx.userId);+ await getBotMessageRouter().invalidateBot(routing.platform, routing.applicationId);}- return result;+ return deleted;}),getByAgentId: agentBotProviderProcedurediff --git a/packages/database/src/models/__tests__/agentBotProvider.test.ts b/packages/database/src/models/__tests__/agentBotProvider.test.tsindex ca80220e642..76be7ac37fb 100644--- a/packages/database/src/models/__tests__/agentBotProvider.test.ts+++ b/packages/database/src/models/__tests__/agentBotProvider.test.ts@@ -34,6 +34,15 @@ afterEach(async () => {vi.clearAllMocks();});+const seedWorkspace = async (id: string) => {+ await serverDB+ .insert(workspaces)+ .values({ id, name: id, primaryOwnerId: userId, slug: id })+ .onConflictDoNothing();++ return id;+};+describe('AgentBotProviderModel', () => {describe('create', () => {it('should create a bot provider without encryption', async () => {@@ -102,6 +111,60 @@ describe('AgentBotProviderModel', () => {const found = await model1.findById(created.id);expect(found).toBeDefined();});++ it('reports that it removed nothing when the row is outside the active scope', async () => {+ const workspaceId = await seedWorkspace('bot-provider-scope-gap-ws');+ const inWorkspace = new AgentBotProviderModel(serverDB, userId, undefined, workspaceId);+ const created = await inWorkspace.create({+ agentId,+ applicationId: 'app-scope-gap',+ credentials: { botToken: 'tok' },+ platform: 'discord',+ });++ // Same user, personal scope: the workspace row is invisible here, but it+ // keeps holding the global (platform, applicationId) key.+ const personal = new AgentBotProviderModel(serverDB, userId);+ const deleted = await personal.delete(created.id);++ expect(deleted).toHaveLength(0);+ expect(await inWorkspace.findById(created.id)).toBeDefined();+ });++ it('reports the rows it removed on a delete that matched', async () => {+ const model = new AgentBotProviderModel(serverDB, userId);+ const created = await model.create({+ agentId,+ applicationId: 'app-del-reported',+ credentials: { botToken: 'tok' },+ platform: 'discord',+ });++ await expect(model.delete(created.id)).resolves.toEqual([{ id: created.id }]);+ });+ });++ describe('findByIdAcrossScopes / deleteAcrossScopes', () => {+ it('reaches a row the active scope hides, so a creator can reclaim the application id', async () => {+ const workspaceId = await seedWorkspace('bot-provider-stranded-ws');+ const inWorkspace = new AgentBotProviderModel(serverDB, userId, undefined, workspaceId);+ const created = await inWorkspace.create({+ agentId,+ applicationId: 'app-stranded',+ credentials: { botToken: 'tok' },+ platform: 'discord',+ });++ const personal = new AgentBotProviderModel(serverDB, userId);+ expect(await personal.findById(created.id)).toBeUndefined();++ const stranded = await personal.findByIdAcrossScopes(created.id);+ expect(stranded?.userId).toBe(userId);+ expect(stranded?.workspaceId).toBe(workspaceId);++ await expect(personal.deleteAcrossScopes(created.id)).resolves.toEqual([{ id: created.id }]);+ expect(await inWorkspace.findById(created.id)).toBeUndefined();+ });});describe('query', () => {diff --git a/packages/database/src/models/agentBotProvider.ts b/packages/database/src/models/agentBotProvider.tsindex 436a5419a84..ea0b7fd4523 100644--- a/packages/database/src/models/agentBotProvider.ts+++ b/packages/database/src/models/agentBotProvider.ts@@ -54,10 +54,45 @@ export class AgentBotProviderModel {return result;};+ /**+ * Returns the rows it actually removed, so the caller can tell a real delete+ * from a no-op. The ownership filter and the `(platform, applicationId)`+ * unique index disagree about scope — the index is global, the filter is not+ * — so a binding that lives outside the caller's active scope matches+ * nothing here while still occupying the key that `create` collides with.+ * Silently returning "ok" in that case reads as "removed" and leaves the+ * application id permanently unbindable.+ */delete = async (id: string) => {return this.db.delete(agentBotProviders)- .where(and(eq(agentBotProviders.id, id), this.ownership()));+ .where(and(eq(agentBotProviders.id, id), this.ownership()))+ .returning({ id: agentBotProviders.id });+ };++ /**+ * Look a binding up by id with no scope filter, for the two cases where the+ * caller's active scope is the problem rather than a permission: explaining+ * which agent already holds an application id, and letting a creator delete+ * their own binding from the other scope. Authorization is the caller's job+ * — this returns rows belonging to anyone.+ */+ findByIdAcrossScopes = async (id: string) => {+ const [result] = await this.db+ .select()+ .from(agentBotProviders)+ .where(eq(agentBotProviders.id, id))+ .limit(1);++ return result;+ };++ /** Delete by id with no scope filter. Call only after authorizing the row. */+ deleteAcrossScopes = async (id: string) => {+ return this.db+ .delete(agentBotProviders)+ .where(eq(agentBotProviders.id, id))+ .returning({ id: agentBotProviders.id });};query = async (params?: { agentId?: string; platform?: string }) => {