this repo has no description
1interface SlackChannel {
2 id: string;
3 created: number;
4 creator: string;
5 name: string;
6 is_channel: boolean;
7 is_private: boolean;
8 is_archived: boolean;
9 [key: string]: unknown;
10}
11
12interface ConversationsInfoResponse {
13 ok: boolean;
14 channel?: SlackChannel;
15 error?: string;
16}
17
18interface RoleAssignmentsResponse {
19 ok: boolean;
20 role_assignments?: Array<{
21 users: string[];
22 }>;
23 error?: string;
24}
25
26/**
27 * Check if a user has permission to manage a Slack channel
28 * Returns true if the user is:
29 * - A global admin (in ADMINS env var)
30 * - The channel creator
31 * - A channel manager
32 */
33export async function canManageChannel(
34 userId: string,
35 channelId: string,
36): Promise<boolean> {
37 // Check if user is a global admin
38 const admins = process.env.ADMINS?.split(",").map((id) => id.trim()) || [];
39 if (admins.includes(userId)) {
40 return true;
41 }
42
43 try {
44 // Check if user is channel creator
45 const formdata = new FormData();
46 formdata.append("channel", channelId);
47
48 const channelInfo: ConversationsInfoResponse = (await fetch(
49 "https://slack.com/api/conversations.info",
50 {
51 method: "POST",
52 headers: {
53 Authorization: `Bearer ${process.env.SLACK_BOT_TOKEN}`,
54 },
55 body: formdata,
56 },
57 ).then((res) => res.json())) as ConversationsInfoResponse;
58
59 if (channelInfo.ok && channelInfo.channel?.creator === userId) {
60 return true;
61 }
62
63 // Check if user is a channel manager
64 if (
65 process.env.SLACK_USER_COOKIE &&
66 process.env.SLACK_USER_TOKEN &&
67 process.env.SLACK_API_URL
68 ) {
69 const formdata = new FormData();
70 formdata.append("token", process.env.SLACK_USER_TOKEN);
71 formdata.append("entity_id", channelId);
72
73 const response = await fetch(
74 `${process.env.SLACK_API_URL}/api/admin.roles.entity.listAssignments`,
75 {
76 method: "POST",
77 headers: {
78 Cookie: process.env.SLACK_USER_COOKIE,
79 },
80 body: formdata,
81 },
82 );
83
84 const json: RoleAssignmentsResponse =
85 (await response.json()) as RoleAssignmentsResponse;
86
87 if (json.ok) {
88 const managers = json.role_assignments?.[0]?.users || [];
89 if (managers.includes(userId)) {
90 return true;
91 }
92 }
93 }
94 } catch (error) {
95 console.error("Error checking channel permissions:", error);
96 }
97
98 return false;
99}