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.

🐛 fix(channel): workspace owners and admins manage the group Channels they belong to (#23153)

Lobehub Coder7bf5425496f2
diff --git a/packages/database/src/repositories/channel/__tests__/workspaceManager.test.ts b/packages/database/src/repositories/channel/__tests__/workspaceManager.test.ts
new file mode 100644
index 00000000000..39f0e30285e
--- /dev/null
+++ b/packages/database/src/repositories/channel/__tests__/workspaceManager.test.ts
@@ -0,0 +1,101 @@
+// @vitest-environment node
+import { and, eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { channelMembers, workspaceMembers } from '../../../schemas';
+import { ChannelRepository } from '..';
+import { createChannelFixture } from './testUtils';
+
+const db = await getTestDB();
+const fixture = createChannelFixture(db, 'channel-workspace-manager');
+
+const setWorkspaceRole = (role: string) =>
+ db
+ .update(workspaceMembers)
+ .set({ role })
+ .where(
+ and(
+ eq(workspaceMembers.workspaceId, fixture.workspaceId),
+ eq(workspaceMembers.userId, fixture.memberId),
+ ),
+ );
+
+beforeEach(async () => {
+ await fixture.setup();
+ await db.insert(workspaceMembers).values([
+ { workspaceId: fixture.workspaceId, userId: fixture.ownerId, role: 'owner' },
+ { workspaceId: fixture.workspaceId, userId: fixture.memberId },
+ ]);
+});
+afterEach(fixture.cleanup);
+
+/** A group Channel `creatorId` created, which `joinerId` joined as a plain member. */
+const joinAsMember = async (creatorId = fixture.ownerId, joinerId = fixture.memberId) => {
+ const creator = new ChannelRepository(db, creatorId, fixture.workspaceId);
+ const { channel } = await creator.create({ title: 'Marketing', userIds: [joinerId] });
+ const member = new ChannelRepository(db, joinerId, fixture.workspaceId);
+ return { channel, member };
+};
+
+describe('workspace owners and admins in group Channels', () => {
+ it.each([
+ // Mia is promoted to workspace admin and joins Olivia's Channel.
+ { creatorId: fixture.ownerId, joinerId: fixture.memberId, role: 'admin' },
+ // Olivia owns the workspace and joins Mia's Channel.
+ { creatorId: fixture.memberId, joinerId: fixture.ownerId, role: 'owner' },
+ ])(
+ 'lets a workspace $role manage a Channel they joined as a member',
+ async ({ creatorId, joinerId, role }) => {
+ if (role === 'admin') await setWorkspaceRole('admin');
+ const { channel, member } = await joinAsMember(creatorId, joinerId);
+
+ expect(await member.list()).toEqual([
+ expect.objectContaining({ canDelete: true, id: channel.id }),
+ ]);
+ expect((await member.detail(channel.id)).channel.canDelete).toBe(true);
+ await member.rename(channel.id, 'Growth');
+ expect((await member.detail(channel.id)).channel.title).toBe('Growth');
+
+ // The Channel's own roster is untouched: the role comes from the workspace.
+ const [row] = await db
+ .select({ role: channelMembers.role })
+ .from(channelMembers)
+ .where(and(eq(channelMembers.channelId, channel.id), eq(channelMembers.userId, joinerId)));
+ expect(row.role).toBe('member');
+ },
+ );
+
+ it('keeps a plain workspace member a plain Channel member', async () => {
+ const { channel, member } = await joinAsMember();
+
+ expect((await member.detail(channel.id)).channel.canDelete).toBe(false);
+ await expect(member.rename(channel.id, 'Growth')).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ });
+ });
+
+ it('stops counting a workspace admin once they leave the workspace', async () => {
+ await setWorkspaceRole('admin');
+ const { channel, member } = await joinAsMember();
+ await db
+ .update(workspaceMembers)
+ .set({ deletedAt: new Date() })
+ .where(eq(workspaceMembers.userId, fixture.memberId));
+
+ expect((await member.detail(channel.id)).channel.canDelete).toBe(false);
+ await expect(member.rename(channel.id, 'Growth')).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ });
+ });
+
+ it('gives a workspace admin nothing in a Channel they are not in', async () => {
+ await setWorkspaceRole('admin');
+ const owner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);
+ const { channel } = await owner.create({ title: 'Private' });
+ const admin = new ChannelRepository(db, fixture.memberId, fixture.workspaceId);
+
+ expect(await admin.list()).toEqual([]);
+ await expect(admin.detail(channel.id)).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+});
diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.ts
index 7744b56d694..b89090d0966 100644
--- a/packages/database/src/repositories/channel/index.ts
+++ b/packages/database/src/repositories/channel/index.ts
@@ -18,6 +18,7 @@ import {
channelMessages,
channels,
channelThreads,
+ workspaceMembers,
} from '../../schemas';
import type { LobeChatDatabase, Transaction } from '../../type';
import { ilikeContains } from '../../utils/like';
@@ -84,6 +85,9 @@ const ROLE_RANK: Record<ChannelMemberRole, number> = { admin: 1, member: 0, owne
const hasRole = (role: ChannelMemberRole | null, minRole: ChannelMemberRole) =>
ROLE_RANK[role ?? 'member'] >= ROLE_RANK[minRole];
+/** Workspace roles that manage every group Channel they belong to in that workspace. */
+const WORKSPACE_MANAGER_ROLES = ['owner', 'admin'];
+
/**
* Membership-scoped access to channels.
*
@@ -589,7 +593,7 @@ export class ChannelRepository {
channel: channels,
lastReadSequence: channelMembers.lastReadSequence,
memberId: channelMembers.id,
- role: channelMembers.role,
+ role: this.callerRole(),
shareId: agentShares.id,
shareSlug: sql<string | null>`${agentShares.shareConfig} ->> 'slug'`,
})
@@ -893,13 +897,17 @@ export class ChannelRepository {
// Read membership only after the lock: a removal or demotion committed by the previous
// lock holder must be visible here, not the snapshot from before the wait.
- const [access] = await tx
- .select({ channel: channels, member: channelMembers })
+ const [row] = await tx
+ .select({ channel: channels, member: channelMembers, role: this.callerRole() })
.from(channels)
.innerJoin(channelMembers, eq(channelMembers.channelId, channels.id))
.where(and(eq(channels.id, channelId), this.membershipWhere()))
.limit(1);
- if (!access) throw new ChannelError('NOT_FOUND', 'Channel not found');
+ if (!row) throw new ChannelError('NOT_FOUND', 'Channel not found');
+ const access: ChannelAccess = {
+ channel: row.channel,
+ member: { ...row.member, role: row.role },
+ };
const minRole = options.minRole ?? 'member';
if (!hasRole(access.member.role, minRole))
@@ -1157,6 +1165,26 @@ export class ChannelRepository {
return row;
};
+ /**
+ * The caller's role as permission checks see it. A workspace owner or admin counts at least as
+ * an admin of the group Channels they belong to in that workspace; direct and peer
+ * conversations stay with their participants. The stored member row keeps its own role.
+ */
+ private callerRole() {
+ if (!this.workspaceId) return sql<ChannelMemberRole | null>`${channelMembers.role}`;
+ return sql<ChannelMemberRole | null>`CASE
+ WHEN ${channelMembers.role} = 'owner' THEN ${channelMembers.role}
+ WHEN ${channels.agentId} IS NULL AND ${channels.peerUserId} IS NULL AND EXISTS (
+ SELECT 1 FROM ${workspaceMembers}
+ WHERE ${workspaceMembers.workspaceId} = ${channels.workspaceId}
+ AND ${workspaceMembers.userId} = ${this.userId}
+ AND ${workspaceMembers.deletedAt} IS NULL
+ AND ${inArray(workspaceMembers.role, WORKSPACE_MANAGER_ROLES)}
+ ) THEN 'admin'
+ ELSE ${channelMembers.role}
+ END`;
+ }
+
private membershipWhere() {
return and(
eq(channelMembers.actorType, 'user'),