Skip to main content

djs_model/
permissions.rs

1//! [Permissions](https://docs.discord.com/developers/topics/permissions): what members and
2//! roles may do in a guild or channel.
3
4use core::fmt;
5
6use bitflags::bitflags;
7use serde::{
8    Deserialize, Deserializer, Serialize, Serializer,
9    de::{Error as DeError, Unexpected, Visitor},
10};
11
12use crate::{
13    channel::Overwrite,
14    id::{GuildId, RoleId, UserId},
15};
16
17bitflags! {
18    /// A set of [permission flags](https://docs.discord.com/developers/topics/permissions#permissions-bitwise-permission-flags).
19    ///
20    /// Permissions appear on roles, members (computed), channel permission overwrites,
21    /// interactions (`app_permissions`) and OAuth2 bot invites. Discord transmits them as a
22    /// **decimal string** because the value does not fit into a JavaScript number; this type
23    /// (de)serializes that representation and also accepts plain integers when deserializing.
24    ///
25    /// Unknown bits (permissions added by Discord after this release) are preserved, so values
26    /// can be round-tripped without losing information.
27    ///
28    /// Permissions marked **2FA** below require the guild owner to use two-factor
29    /// authentication when the guild has server-wide 2FA enabled.
30    ///
31    /// discord.js counterpart: `PermissionFlagsBits` / `PermissionsBitField`.
32    ///
33    /// # Examples
34    ///
35    /// ```
36    /// use djs_model::permissions::Permissions;
37    ///
38    /// let permissions = Permissions::VIEW_CHANNEL | Permissions::SEND_MESSAGES;
39    /// assert!(permissions.contains(Permissions::SEND_MESSAGES));
40    /// assert!(!permissions.contains(Permissions::ADMINISTRATOR));
41    ///
42    /// // Discord sends permissions as decimal strings.
43    /// assert_eq!(serde_json::to_string(&permissions).unwrap(), r#""3072""#);
44    /// let parsed: Permissions = serde_json::from_str(r#""3072""#).unwrap();
45    /// assert_eq!(parsed, permissions);
46    /// ```
47    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
48    pub struct Permissions: u64 {
49        /// Create instant invites. Text, voice and stage channels.
50        const CREATE_INSTANT_INVITE = 1 << 0;
51        /// Kick members. **2FA.**
52        const KICK_MEMBERS = 1 << 1;
53        /// Ban members. **2FA.**
54        const BAN_MEMBERS = 1 << 2;
55        /// Every permission, bypassing channel permission overwrites. **2FA.**
56        const ADMINISTRATOR = 1 << 3;
57        /// Create, edit and delete channels. Text, voice and stage channels. **2FA.**
58        const MANAGE_CHANNELS = 1 << 4;
59        /// Edit the guild's settings. **2FA.**
60        const MANAGE_GUILD = 1 << 5;
61        /// Add new reactions to messages (reacting with an existing reaction needs no
62        /// permission). Text, voice and stage channels.
63        const ADD_REACTIONS = 1 << 6;
64        /// View the guild's audit log.
65        const VIEW_AUDIT_LOG = 1 << 7;
66        /// Use priority speaker in voice channels.
67        const PRIORITY_SPEAKER = 1 << 8;
68        /// Go live (stream) in voice and stage channels.
69        const STREAM = 1 << 9;
70        /// See a channel: read messages in text channels, join voice channels. Text, voice and
71        /// stage channels.
72        const VIEW_CHANNEL = 1 << 10;
73        /// Send messages in a channel and create forum posts (not messages in threads, see
74        /// [`SEND_MESSAGES_IN_THREADS`](Self::SEND_MESSAGES_IN_THREADS)). Text, voice and stage
75        /// channels.
76        const SEND_MESSAGES = 1 << 11;
77        /// Send text-to-speech (`/tts`) messages. Text, voice and stage channels.
78        const SEND_TTS_MESSAGES = 1 << 12;
79        /// Delete other users' messages. Text, voice and stage channels. **2FA.**
80        const MANAGE_MESSAGES = 1 << 13;
81        /// Links sent by the member are embedded automatically. Text, voice and stage channels.
82        const EMBED_LINKS = 1 << 14;
83        /// Upload images and files. Text, voice and stage channels.
84        const ATTACH_FILES = 1 << 15;
85        /// Read the message history of a channel. Text, voice and stage channels.
86        const READ_MESSAGE_HISTORY = 1 << 16;
87        /// Mention `@everyone` (all members of the channel) and `@here` (online members). Text,
88        /// voice and stage channels.
89        const MENTION_EVERYONE = 1 << 17;
90        /// Use custom emojis from other guilds. Text, voice and stage channels.
91        const USE_EXTERNAL_EMOJIS = 1 << 18;
92        /// View guild insights.
93        const VIEW_GUILD_INSIGHTS = 1 << 19;
94        /// Join voice and stage channels.
95        const CONNECT = 1 << 20;
96        /// Speak in voice channels.
97        const SPEAK = 1 << 21;
98        /// Mute members in voice and stage channels.
99        const MUTE_MEMBERS = 1 << 22;
100        /// Deafen members in voice channels.
101        const DEAFEN_MEMBERS = 1 << 23;
102        /// Move members between voice and stage channels.
103        const MOVE_MEMBERS = 1 << 24;
104        /// Use voice activity detection ("Use Voice Activity" in the client) in voice channels.
105        const USE_VAD = 1 << 25;
106        /// Change one's own nickname.
107        const CHANGE_NICKNAME = 1 << 26;
108        /// Change other members' nicknames.
109        const MANAGE_NICKNAMES = 1 << 27;
110        /// Create, edit and delete roles and channel permission overwrites ("Manage
111        /// Permissions" in the client). Text, voice and stage channels. **2FA.**
112        const MANAGE_ROLES = 1 << 28;
113        /// Create, edit and delete webhooks. Text, voice and stage channels. **2FA.**
114        const MANAGE_WEBHOOKS = 1 << 29;
115        /// Edit and delete emojis, stickers and soundboard sounds created by anyone. **2FA.**
116        const MANAGE_GUILD_EXPRESSIONS = 1 << 30;
117        /// Use application commands (slash and context-menu commands). Text, voice and stage
118        /// channels.
119        const USE_APPLICATION_COMMANDS = 1 << 31;
120        /// Request to speak in stage channels.
121        const REQUEST_TO_SPEAK = 1 << 32;
122        /// Edit and delete scheduled events created by anyone. Voice and stage channels.
123        const MANAGE_EVENTS = 1 << 33;
124        /// Delete and archive threads and view all private threads. Text channels. **2FA.**
125        const MANAGE_THREADS = 1 << 34;
126        /// Create public and announcement threads. Text channels.
127        const CREATE_PUBLIC_THREADS = 1 << 35;
128        /// Create private threads. Text channels.
129        const CREATE_PRIVATE_THREADS = 1 << 36;
130        /// Use custom stickers from other guilds. Text, voice and stage channels.
131        const USE_EXTERNAL_STICKERS = 1 << 37;
132        /// Send messages in threads. Text channels.
133        const SEND_MESSAGES_IN_THREADS = 1 << 38;
134        /// Use Activities (applications with the `EMBEDDED` flag). Text and voice channels.
135        const USE_EMBEDDED_ACTIVITIES = 1 << 39;
136        /// Time out members ("Timeout Members" in the client), which stops them from chatting,
137        /// reacting and speaking. Timed-out members temporarily lose most permissions; see
138        /// [Permissions for Timed Out Members](https://docs.discord.com/developers/topics/permissions#permissions-for-timed-out-members).
139        const MODERATE_MEMBERS = 1 << 40;
140        /// View role subscription insights. **2FA.**
141        const VIEW_CREATOR_MONETIZATION_ANALYTICS = 1 << 41;
142        /// Use the soundboard in voice channels.
143        const USE_SOUNDBOARD = 1 << 42;
144        /// Create emojis, stickers and soundboard sounds, and edit or delete the ones created by
145        /// oneself.
146        const CREATE_GUILD_EXPRESSIONS = 1 << 43;
147        /// Create scheduled events, and edit or delete the ones created by oneself. Voice and
148        /// stage channels.
149        const CREATE_EVENTS = 1 << 44;
150        /// Use custom soundboard sounds from other guilds in voice channels.
151        const USE_EXTERNAL_SOUNDS = 1 << 45;
152        /// Send voice messages. Text, voice and stage channels.
153        const SEND_VOICE_MESSAGES = 1 << 46;
154        /// Set the status of voice channels.
155        const SET_VOICE_CHANNEL_STATUS = 1 << 48;
156        /// Send polls. Text, voice and stage channels.
157        const SEND_POLLS = 1 << 49;
158        /// Let user-installed apps send public responses; without it their responses are
159        /// ephemeral. Only applies to apps that are not also installed in the guild. Text,
160        /// voice and stage channels.
161        const USE_EXTERNAL_APPS = 1 << 50;
162        /// Pin and unpin messages. Text channels.
163        const PIN_MESSAGES = 1 << 51;
164        /// Bypass slowmode. Text, voice and stage channels.
165        const BYPASS_SLOWMODE = 1 << 52;
166    }
167}
168
169/// Computing a member's permissions, following [Discord's
170/// algorithm](https://docs.discord.com/developers/topics/permissions#permission-overwrites)
171/// (D-292). Three steps, each usable alone:
172///
173/// 1. [`guild_level`](Self::guild_level): the owner, `@everyone`, the member's roles and
174///    `ADMINISTRATOR`;
175/// 2. [`in_channel`](Self::in_channel): a channel's overwrites, then the implicit denials
176///    (D-295);
177/// 3. [`during_timeout`](Self::during_timeout): what a timed-out member keeps (D-294).
178///
179/// `djs_cache::Cache::member_permissions` and `member_permissions_in` run them on cached data.
180///
181/// # Examples
182///
183/// ```
184/// use djs_model::{
185///     channel::Overwrite,
186///     id::{GuildId, RoleId, UserId},
187///     permissions::Permissions,
188/// };
189///
190/// let (guild, moderator, user) = (GuildId::new(1), RoleId::new(2), UserId::new(3));
191/// let everyone = Permissions::VIEW_CHANNEL | Permissions::SEND_MESSAGES;
192/// let base = Permissions::guild_level(false, everyone, [Permissions::BAN_MEMBERS]);
193/// assert!(base.contains(Permissions::BAN_MEMBERS));
194///
195/// // A read-only channel for `@everyone` (its overwrite has the guild's ID).
196/// let overwrites = [Overwrite::role(guild.cast(), Permissions::empty(), Permissions::SEND_MESSAGES)];
197/// let in_channel = base.in_channel(guild, user, &[moderator], &overwrites);
198/// assert!(!in_channel.contains(Permissions::SEND_MESSAGES));
199///
200/// // Timed out: only viewing and reading the history remain.
201/// assert_eq!(in_channel.during_timeout(), Permissions::VIEW_CHANNEL);
202/// ```
203impl Permissions {
204    /// The permissions that implicitly depend on [`SEND_MESSAGES`](Self::SEND_MESSAGES): a
205    /// member without it cannot use them in that channel.
206    pub const NEEDS_SEND_MESSAGES: Self = Self::MENTION_EVERYONE
207        .union(Self::SEND_TTS_MESSAGES)
208        .union(Self::ATTACH_FILES)
209        .union(Self::EMBED_LINKS);
210
211    /// What a timed-out member keeps (D-294).
212    pub const DURING_TIMEOUT: Self = Self::VIEW_CHANNEL.union(Self::READ_MESSAGE_HISTORY);
213
214    /// A member's permissions in its guild: every permission for the guild's owner;
215    /// otherwise the permissions of the `@everyone` role and of the member's `roles` together,
216    /// and every permission when they include [`ADMINISTRATOR`](Self::ADMINISTRATOR).
217    ///
218    /// This is Discord's `compute_base_permissions`; a timeout is applied with
219    /// [`during_timeout`](Self::during_timeout).
220    ///
221    /// discord.js counterpart: `GuildMember#permissions` (which leaves `ADMINISTRATOR` to
222    /// `has`).
223    #[must_use]
224    pub fn guild_level(owner: bool, everyone: Self, roles: impl IntoIterator<Item = Self>) -> Self {
225        if owner {
226            return Self::all();
227        }
228        let permissions = roles.into_iter().fold(everyone, Self::union);
229        if permissions.contains(Self::ADMINISTRATOR) {
230            Self::all()
231        } else {
232            permissions
233        }
234    }
235
236    /// Applies a channel's `overwrites` to guild-level permissions (from
237    /// [`guild_level`](Self::guild_level)) of the member `user_id` of `guild_id`, who has the
238    /// roles `role_ids` (without `@everyone`): the `@everyone` overwrite, then the role
239    /// overwrites together, then the member's own; `ADMINISTRATOR` keeps every permission.
240    ///
241    /// Then the implicit denials (D-295): without [`VIEW_CHANNEL`](Self::VIEW_CHANNEL) the
242    /// member can do nothing in the channel (the result is empty), and without
243    /// [`SEND_MESSAGES`](Self::SEND_MESSAGES) the [`NEEDS_SEND_MESSAGES`](Self::NEEDS_SEND_MESSAGES)
244    /// permissions are removed. Discord also ignores some permissions in a voice channel
245    /// without [`CONNECT`](Self::CONNECT) (`MANAGE_CHANNELS`, for example) but gives no
246    /// complete list, so that rule is not applied.
247    ///
248    /// A thread has no overwrites of its own: pass its parent channel's.
249    ///
250    /// discord.js counterpart: `GuildChannel#permissionsFor(member)` (without the implicit
251    /// denials).
252    #[must_use]
253    pub fn in_channel(
254        self,
255        guild_id: GuildId,
256        user_id: UserId,
257        role_ids: &[RoleId],
258        overwrites: &[Overwrite],
259    ) -> Self {
260        if self.contains(Self::ADMINISTRATOR) {
261            return Self::all();
262        }
263        let mut everyone = None;
264        let mut member = None;
265        let (mut allow, mut deny) = (Self::empty(), Self::empty());
266        for overwrite in overwrites {
267            if let Some(role_id) = overwrite.role_id() {
268                if role_id.get() == guild_id.get() {
269                    everyone = Some(overwrite);
270                } else if role_ids.contains(&role_id) {
271                    allow |= overwrite.allow;
272                    deny |= overwrite.deny;
273                }
274            } else if overwrite.user_id() == Some(user_id) {
275                member = Some(overwrite);
276            }
277        }
278        let mut permissions = self;
279        if let Some(everyone) = everyone {
280            permissions = permissions.difference(everyone.deny).union(everyone.allow);
281        }
282        permissions = permissions.difference(deny).union(allow);
283        if let Some(member) = member {
284            permissions = permissions.difference(member.deny).union(member.allow);
285        }
286        // An overwrite cannot grant `ADMINISTRATOR`.
287        permissions.remove(Self::ADMINISTRATOR);
288        if !permissions.contains(Self::VIEW_CHANNEL) {
289            return Self::empty();
290        }
291        if !permissions.contains(Self::SEND_MESSAGES) {
292            permissions.remove(Self::NEEDS_SEND_MESSAGES);
293        }
294        permissions
295    }
296
297    /// What a timed-out member keeps of these permissions: only
298    /// [`VIEW_CHANNEL`](Self::VIEW_CHANNEL) and
299    /// [`READ_MESSAGE_HISTORY`](Self::READ_MESSAGE_HISTORY) (D-294). The owner and members
300    /// with [`ADMINISTRATOR`](Self::ADMINISTRATOR) are exempt (their permissions are
301    /// returned unchanged).
302    ///
303    /// See [Permissions for Timed Out
304    /// Members](https://docs.discord.com/developers/topics/permissions#permissions-for-timed-out-members).
305    ///
306    /// discord.js counterpart: none (discord.js applies the timeout inside `GuildMember#permissions`).
307    #[must_use]
308    pub const fn during_timeout(self) -> Self {
309        if self.contains(Self::ADMINISTRATOR) {
310            self
311        } else {
312            self.intersection(Self::DURING_TIMEOUT)
313        }
314    }
315}
316
317impl Serialize for Permissions {
318    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
319        // `collect_str` lets serde_json write the digits directly, without an allocation.
320        serializer.collect_str(&self.bits())
321    }
322}
323
324impl<'de> Deserialize<'de> for Permissions {
325    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
326        struct PermissionsVisitor;
327
328        impl Visitor<'_> for PermissionsVisitor {
329            type Value = Permissions;
330
331            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
332                f.write_str("a permissions bitfield as a decimal string or integer")
333            }
334
335            fn visit_str<E: DeError>(self, value: &str) -> Result<Permissions, E> {
336                value
337                    .parse()
338                    .map(Permissions::from_bits_retain)
339                    .map_err(|_| E::invalid_value(Unexpected::Str(value), &self))
340            }
341
342            fn visit_u64<E: DeError>(self, value: u64) -> Result<Permissions, E> {
343                Ok(Permissions::from_bits_retain(value))
344            }
345
346            fn visit_i64<E: DeError>(self, value: i64) -> Result<Permissions, E> {
347                u64::try_from(value)
348                    .map(Permissions::from_bits_retain)
349                    .map_err(|_| E::invalid_value(Unexpected::Signed(value), &self))
350            }
351        }
352
353        deserializer.deserialize_any(PermissionsVisitor)
354    }
355}
356
357#[cfg(test)]
358mod tests {
359    use super::*;
360
361    #[test]
362    fn known_bits_match_the_docs() {
363        // Bits 0..=46 and 48..=52 (bit 47 is unassigned); computed independently.
364        assert_eq!(Permissions::all().bits(), 8_866_461_766_385_663);
365        assert_eq!(Permissions::ADMINISTRATOR.bits(), 0x8);
366        assert_eq!(Permissions::BYPASS_SLOWMODE.bits(), 0x0010_0000_0000_0000);
367    }
368
369    #[test]
370    fn serializes_as_decimal_string() {
371        let check = |permissions: Permissions, json: &str| {
372            assert_eq!(serde_json::to_string(&permissions).unwrap(), json);
373        };
374        check(Permissions::empty(), r#""0""#);
375        check(
376            Permissions::VIEW_CHANNEL | Permissions::SEND_MESSAGES,
377            r#""3072""#,
378        );
379        check(
380            Permissions::from_bits_retain(u64::MAX),
381            r#""18446744073709551615""#,
382        );
383    }
384
385    #[test]
386    fn deserializes_strings_and_integers_keeping_unknown_bits() {
387        let unknown = (1 << 47) | (1 << 63) | (1 << 3);
388        let permissions: Permissions = serde_json::from_str(r#""9223512774343131144""#).unwrap();
389        assert_eq!(permissions.bits(), unknown);
390        assert!(permissions.contains(Permissions::ADMINISTRATOR));
391        assert_eq!(
392            serde_json::to_string(&permissions).unwrap(),
393            r#""9223512774343131144""#
394        );
395
396        let permissions: Permissions = serde_json::from_str("3072").unwrap();
397        assert_eq!(
398            permissions,
399            Permissions::VIEW_CHANNEL | Permissions::SEND_MESSAGES
400        );
401    }
402
403    #[test]
404    fn rejects_invalid_values() {
405        for json in [
406            r#""""#,
407            r#""-1""#,
408            r#""12a""#,
409            "-1",
410            r#""18446744073709551616""#,
411            "1.5",
412        ] {
413            assert!(
414                serde_json::from_str::<Permissions>(json).is_err(),
415                "{json} must be rejected"
416            );
417        }
418    }
419}