summary refs log tree commit diff
path: root/util/src/util/Permissions.ts
blob: 9d87253a56124bfb55582ba857ee7b32dc0a257f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
// https://github.com/discordjs/discord.js/blob/master/src/util/Permissions.js
// Apache License Version 2.0 Copyright 2015 - 2021 Amish Shah
import { Channel, ChannelPermissionOverwrite, Guild, Member, Role } from "../entities";
import { BitField } from "./BitField";
import "missing-native-js-functions";
// TODO: check role hierarchy permission

var HTTPError: any;

try {
	HTTPError = require("lambert-server").HTTPError;
} catch (e) {
	HTTPError = Error;
}

export type PermissionResolvable = bigint | number | Permissions | PermissionResolvable[] | PermissionString;

type PermissionString = keyof typeof Permissions.FLAGS;

const CUSTOM_PERMISSION_OFFSET = BigInt(1) << BigInt(48); // 16 free custom permission bits, and 11 for discord to add new ones

export class Permissions extends BitField {
	cache: PermissionCache = {};

	static FLAGS = {
		CREATE_INSTANT_INVITE: BigInt(1) << BigInt(0),
		KICK_MEMBERS: BigInt(1) << BigInt(1),
		BAN_MEMBERS: BigInt(1) << BigInt(2),
		ADMINISTRATOR: BigInt(1) << BigInt(3),
		MANAGE_CHANNELS: BigInt(1) << BigInt(4),
		MANAGE_GUILD: BigInt(1) << BigInt(5),
		ADD_REACTIONS: BigInt(1) << BigInt(6),
		VIEW_AUDIT_LOG: BigInt(1) << BigInt(7),
		PRIORITY_SPEAKER: BigInt(1) << BigInt(8),
		STREAM: BigInt(1) << BigInt(9),
		VIEW_CHANNEL: BigInt(1) << BigInt(10),
		SEND_MESSAGES: BigInt(1) << BigInt(11),
		SEND_TTS_MESSAGES: BigInt(1) << BigInt(12),
		MANAGE_MESSAGES: BigInt(1) << BigInt(13),
		EMBED_LINKS: BigInt(1) << BigInt(14),
		ATTACH_FILES: BigInt(1) << BigInt(15),
		READ_MESSAGE_HISTORY: BigInt(1) << BigInt(16),
		MENTION_EVERYONE: BigInt(1) << BigInt(17),
		USE_EXTERNAL_EMOJIS: BigInt(1) << BigInt(18),
		VIEW_GUILD_INSIGHTS: BigInt(1) << BigInt(19),
		CONNECT: BigInt(1) << BigInt(20),
		SPEAK: BigInt(1) << BigInt(21),
		MUTE_MEMBERS: BigInt(1) << BigInt(22),
		DEAFEN_MEMBERS: BigInt(1) << BigInt(23),
		MOVE_MEMBERS: BigInt(1) << BigInt(24),
		USE_VAD: BigInt(1) << BigInt(25),
		CHANGE_NICKNAME: BigInt(1) << BigInt(26),
		MANAGE_NICKNAMES: BigInt(1) << BigInt(27),
		MANAGE_ROLES: BigInt(1) << BigInt(28),
		MANAGE_WEBHOOKS: BigInt(1) << BigInt(29),
		MANAGE_EMOJIS_AND_STICKERS: BigInt(1) << BigInt(30),
		USE_APPLICATION_COMMANDS: BigInt(1) << BigInt(31),
		REQUEST_TO_SPEAK: BigInt(1) << BigInt(32),
		// TODO: what is permission 33?
		MANAGE_THREADS: BigInt(1) << BigInt(34),
		USE_PUBLIC_THREADS: BigInt(1) << BigInt(35),
		USE_PRIVATE_THREADS: BigInt(1) << BigInt(36),
		USE_EXTERNAL_STICKERS: BigInt(1) << BigInt(37),

		/**
		 * CUSTOM PERMISSIONS ideas:
		 * - allow user to dm members
		 * - allow user to pin messages (without MANAGE_MESSAGES)
		 * - allow user to publish messages (without MANAGE_MESSAGES)
		 */
		// CUSTOM_PERMISSION: BigInt(1) << BigInt(0) + CUSTOM_PERMISSION_OFFSET
	};

	any(permission: PermissionResolvable, checkAdmin = true) {
		return (checkAdmin && super.any(Permissions.FLAGS.ADMINISTRATOR)) || super.any(permission);
	}

	/**
	 * Checks whether the bitfield has a permission, or multiple permissions.
	 */
	has(permission: PermissionResolvable, checkAdmin = true) {
		return (checkAdmin && super.has(Permissions.FLAGS.ADMINISTRATOR)) || super.has(permission);
	}

	/**
	 * Checks whether the bitfield has a permission, or multiple permissions, but throws an Error if user fails to match auth criteria.
	 */
	hasThrow(permission: PermissionResolvable) {
		if (this.has(permission) && this.has("VIEW_CHANNEL")) return true;
		// @ts-ignore
		throw new HTTPError(`You are missing the following permissions ${permission}`, 403);
	}

	overwriteChannel(overwrites: ChannelPermissionOverwrite[]) {
		if (!this.cache) throw new Error("permission chache not available");
		overwrites = overwrites.filter((x) => {
			if (x.type === 0 && this.cache.roles?.some((r) => r.id === x.id)) return true;
			if (x.type === 1 && x.id == this.cache.user_id) return true;
			return false;
		});
		return new Permissions(Permissions.channelPermission(overwrites, this.bitfield));
	}

	static channelPermission(overwrites: ChannelPermissionOverwrite[], init?: bigint) {
		// TODO: do not deny any permissions if admin
		return overwrites.reduce((permission, overwrite) => {
			// apply disallowed permission
			// * permission: current calculated permission (e.g. 010)
			// * deny contains all denied permissions (e.g. 011)
			// * allow contains all explicitly allowed permisions (e.g. 100)
			return (permission & ~BigInt(overwrite.deny)) | BigInt(overwrite.allow);
			// ~ operator inverts deny (e.g. 011 -> 100)
			// & operator only allows 1 for both ~deny and permission (e.g. 010 & 100 -> 000)
			// | operators adds both together (e.g. 000 + 100 -> 100)
		}, init || BigInt(0));
	}

	static rolePermission(roles: Role[]) {
		// adds all permissions of all roles together (Bit OR)
		return roles.reduce((permission, role) => permission | BigInt(role.permissions), BigInt(0));
	}

	static finalPermission({
		user,
		guild,
		channel,
	}: {
		user: { id: string; roles: string[] };
		guild: { roles: Role[] };
		channel?: {
			overwrites?: ChannelPermissionOverwrite[];
			recipient_ids?: string[] | null;
			owner_id?: string;
		};
	}) {
		if (user.id === "0") return new Permissions("ADMINISTRATOR"); // system user id

		let roles = guild.roles.filter((x) => user.roles.includes(x.id));
		let permission = Permissions.rolePermission(roles);

		if (channel?.overwrites) {
			let overwrites = channel.overwrites.filter((x) => {
				if (x.type === 0 && user.roles.includes(x.id)) return true;
				if (x.type === 1 && x.id == user.id) return true;
				return false;
			});
			permission = Permissions.channelPermission(overwrites, permission);
		}

		if (channel?.recipient_ids) {
			if (channel?.owner_id === user.id) return new Permissions("ADMINISTRATOR");
			if (channel.recipient_ids.includes(user.id)) {
				// Default dm permissions
				return new Permissions([
					"VIEW_CHANNEL",
					"SEND_MESSAGES",
					"STREAM",
					"ADD_REACTIONS",
					"EMBED_LINKS",
					"ATTACH_FILES",
					"READ_MESSAGE_HISTORY",
					"MENTION_EVERYONE",
					"USE_EXTERNAL_EMOJIS",
					"CONNECT",
					"SPEAK",
					"MANAGE_CHANNELS",
				]);
			}

			return new Permissions();
		}

		return new Permissions(permission);
	}
}

export type PermissionCache = {
	channel?: Channel | undefined;
	member?: Member | undefined;
	guild?: Guild | undefined;
	roles?: Role[] | undefined;
	user_id?: string;
};

export async function getPermission(
	user_id?: string,
	guild_id?: string,
	channel_id?: string,
	opts: {
		guild_select?: (keyof Guild)[];
		guild_relations?: string[];
		channel_select?: (keyof Channel)[];
		channel_relations?: string[];
		member_select?: (keyof Member)[];
		member_relations?: string[];
	} = {}
) {
	if (!user_id) throw new HTTPError("User not found");
	var channel: Channel | undefined;
	var member: Member | undefined;
	var guild: Guild | undefined;

	if (channel_id) {
		channel = await Channel.findOneOrFail({
			where: { id: channel_id },
			relations: ["recipients", ...(opts.channel_relations || [])],
			select: [
				"id",
				"recipients",
				"permission_overwrites",
				"owner_id",
				"guild_id",
				// @ts-ignore
				...(opts.channel_select || []),
			],
		});
		if (channel.guild_id) guild_id = channel.guild_id; // derive guild_id from the channel
	}

	if (guild_id) {
		guild = await Guild.findOneOrFail({
			where: { id: guild_id },
			select: [
				"id",
				"owner_id",
				// @ts-ignore
				...(opts.guild_select || []),
			],
			relations: opts.guild_relations,
		});
		if (guild.owner_id === user_id) return new Permissions(Permissions.FLAGS.ADMINISTRATOR);

		member = await Member.findOneOrFail({
			where: { guild_id, id: user_id },
			relations: ["roles", ...(opts.member_relations || [])],
			select: [
				"id",
				"roles",
				// @ts-ignore
				...(opts.member_select || []),
			],
		});
	}

	let recipient_ids: any = channel?.recipients?.map((x) => x.user_id);
	if (!recipient_ids?.length) recipient_ids = null;

	// TODO: remove guild.roles and convert recipient_ids to recipients
	var permission = Permissions.finalPermission({
		user: {
			id: user_id,
			roles: member?.roles.map((x) => x.id) || [],
		},
		guild: {
			roles: member?.roles || [],
		},
		channel: {
			overwrites: channel?.permission_overwrites,
			owner_id: channel?.owner_id,
			recipient_ids,
		},
	});

	const obj = new Permissions(permission);

	// pass cache to permission for possible future getPermission calls
	obj.cache = { guild, member, channel, roles: member?.roles, user_id };

	return obj;
}