Skip to main content

zaun_community_protocol/command/object/
bot.rs

1//! Bot manifests, grants and the public bot card (specification §8.13).
2
3mod check;
4pub mod events;
5
6pub use check::{config_key_ok, host_pattern_ok, local_address_ok};
7
8use std::collections::BTreeMap;
9
10use serde::{Deserialize, Serialize};
11
12use crate::bits::Permissions;
13use crate::ids::{BotId, MemberId, PublisherId};
14
15/// What a bot may do beyond its permission bits. Every field defaults to "no".
16#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
17pub struct Capabilities {
18    /// Read the content of messages that do not mention it.
19    #[serde(default)]
20    pub message_content: bool,
21    /// List and read members beyond the authors it sees.
22    #[serde(default)]
23    pub members: bool,
24    /// Receive presence signals.
25    #[serde(default)]
26    pub presence: bool,
27    /// Schedule timers.
28    #[serde(default)]
29    pub timers: bool,
30    /// Upload files for its messages.
31    #[serde(default)]
32    pub attachments: bool,
33    /// Join voice channels and play audio (ADR-0020); `CONNECT` and `SPEAK` still apply.
34    #[serde(default)]
35    pub voice: bool,
36    /// Open direct messages with members and take theirs (§8.15).
37    #[serde(default)]
38    pub dms: bool,
39    /// Key-value storage quota, bytes (≤ 1 GiB).
40    #[serde(default)]
41    pub storage_bytes: u64,
42    /// DNS names it may request over https (≤ 32; a leading `*.` matches subdomains).
43    #[serde(default)]
44    pub network: Vec<String>,
45    /// Exact `host:port` addresses next to the host it may reach over http or https, private
46    /// addresses included (≤ 8): a media server on the same machine, say. Only the operator's
47    /// ceiling (`[bots] local_network_allow_list`) lets any be granted.
48    #[serde(default, skip_serializing_if = "Vec::is_empty")]
49    pub local_network: Vec<String>,
50}
51
52impl Capabilities {
53    /// Whether every capability of `self` is also in `other`.
54    #[must_use]
55    pub fn within(&self, other: &Self) -> bool {
56        let flag = |a: bool, b: bool| !a || b;
57        flag(self.message_content, other.message_content)
58            && flag(self.members, other.members)
59            && flag(self.presence, other.presence)
60            && flag(self.timers, other.timers)
61            && flag(self.attachments, other.attachments)
62            && flag(self.voice, other.voice)
63            && flag(self.dms, other.dms)
64            && self.storage_bytes <= other.storage_bytes
65            && self.network.iter().all(|h| other.network.contains(h))
66            && self
67                .local_network
68                .iter()
69                .all(|a| other.local_network.contains(a))
70    }
71
72    /// What both allow.
73    #[must_use]
74    pub fn intersect(&self, other: &Self) -> Self {
75        Self {
76            message_content: self.message_content && other.message_content,
77            members: self.members && other.members,
78            presence: self.presence && other.presence,
79            timers: self.timers && other.timers,
80            attachments: self.attachments && other.attachments,
81            voice: self.voice && other.voice,
82            dms: self.dms && other.dms,
83            storage_bytes: self.storage_bytes.min(other.storage_bytes),
84            network: self
85                .network
86                .iter()
87                .filter(|h| other.network.contains(h))
88                .cloned()
89                .collect(),
90            local_network: self
91                .local_network
92                .iter()
93                .filter(|a| other.local_network.contains(a))
94                .cloned()
95                .collect(),
96        }
97    }
98}
99
100/// A bot's grants: permission bits (its managed role) and capabilities.
101#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
102pub struct Grants {
103    /// The managed role's bits.
104    pub permissions: Permissions,
105    /// Capabilities.
106    pub capabilities: Capabilities,
107}
108
109impl Grants {
110    /// Whether `self` asks for nothing beyond `other`.
111    #[must_use]
112    pub fn within(&self, other: &Self) -> bool {
113        other.permissions.contains(self.permissions)
114            && self.capabilities.within(&other.capabilities)
115    }
116
117    /// What both allow.
118    #[must_use]
119    pub fn intersect(&self, other: &Self) -> Self {
120        Self {
121            permissions: self.permissions & other.permissions,
122            capabilities: self.capabilities.intersect(&other.capabilities),
123        }
124    }
125}
126
127/// Resource limits a manifest asks for; the host may lower them.
128#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
129pub struct ManifestLimits {
130    /// Memory, bytes.
131    #[serde(default, skip_serializing_if = "Option::is_none")]
132    pub memory_bytes: Option<u64>,
133    /// CPU per call, ms.
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    pub cpu_ms: Option<u32>,
136}
137
138/// One setting a bot declares in its manifest's `config` table; the owner sets its value.
139#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
140pub struct ConfigKey {
141    /// What it is, shown to the owner (1-200 scalars).
142    pub description: String,
143    /// Used while the owner has set nothing (≤ 4 KiB); never for a secret.
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub default: Option<String>,
146    /// Masked wherever it is shown, and never logged.
147    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
148    pub secret: bool,
149}
150
151/// The manifest inside a bot package (§8.13).
152#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
153pub struct Manifest {
154    /// Lowercase reverse-DNS, equal to the signed header.
155    pub app_id: String,
156    /// Semantic version, equal to the signed header.
157    pub version: String,
158    /// The bot member's display name, 1–32 scalars.
159    pub name: String,
160    /// ≤ 400 scalars.
161    #[serde(default, skip_serializing_if = "Option::is_none")]
162    pub description: Option<String>,
163    /// Permission bits it asks for.
164    #[serde(default)]
165    pub permissions: Permissions,
166    /// Capabilities it asks for.
167    #[serde(default)]
168    pub capabilities: Capabilities,
169    /// Event types it wants delivered.
170    #[serde(default, skip_serializing_if = "Vec::is_empty")]
171    pub events: Vec<String>,
172    /// Requested limits.
173    #[serde(default, skip_serializing_if = "Option::is_none")]
174    pub limits: Option<ManifestLimits>,
175    /// Where newer packages are published.
176    #[serde(default, skip_serializing_if = "Option::is_none")]
177    pub update_url: Option<String>,
178    /// Settings the owner sets (`bot.configure`): key (`[a-z][a-z0-9_]{0,63}`, ≤ 32) to
179    /// description, default and whether it is secret.
180    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
181    pub config: BTreeMap<String, ConfigKey>,
182}
183
184impl Manifest {
185    /// What the manifest asks for.
186    #[must_use]
187    pub fn request(&self) -> Grants {
188        Grants {
189            permissions: self.permissions,
190            capabilities: self.capabilities.clone(),
191        }
192    }
193}
194
195/// `state` of an installed bot.
196#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
197#[serde(rename_all = "snake_case")]
198pub enum BotState {
199    /// Running.
200    Enabled,
201    /// Stopped by the owner or the operator.
202    Disabled,
203    /// An update waits for the owner to grant more.
204    PendingApproval,
205    /// Stopped after repeated crashes.
206    Crashed,
207}
208
209/// `kind` of a bot.
210#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
211#[serde(rename_all = "snake_case")]
212pub enum BotKind {
213    /// A WebAssembly component the host runs.
214    Hosted,
215    /// A member connecting over SimpleX that the owner marked as a bot.
216    External,
217}
218
219/// The public description of an installed bot, visible to every member (§8.13).
220#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
221pub struct BotCard {
222    /// The installation.
223    pub bot_id: BotId,
224    /// Its member.
225    pub member_id: MemberId,
226    /// From the package; for an external bot, its `name`.
227    pub app_id: String,
228    /// Display name.
229    pub name: String,
230    /// ≤ 400 scalars.
231    #[serde(default, skip_serializing_if = "Option::is_none")]
232    pub description: Option<String>,
233    /// Package version; `""` for an external bot.
234    pub version: String,
235    /// The package signer; none for an external bot.
236    pub publisher: Option<PublisherId>,
237    /// False for an unsigned development package.
238    pub signed: bool,
239    /// Hosted or external.
240    pub kind: BotKind,
241    /// Running state.
242    pub state: BotState,
243    /// The managed role's bits.
244    pub permissions: Permissions,
245    /// Effective capabilities.
246    pub capabilities: Capabilities,
247    /// While `pending_approval`: what the waiting update asks for.
248    #[serde(default, skip_serializing_if = "Option::is_none")]
249    pub requested: Option<Grants>,
250    /// Event types delivered to it.
251    #[serde(default)]
252    pub events: Vec<String>,
253    /// The settings it declares (never their values): a member can see that it is configured
254    /// with, say, an API key.
255    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
256    pub config: BTreeMap<String, ConfigKey>,
257    /// Install time, ms.
258    pub installed_at: u64,
259    /// The owner who installed it; none when the operator did.
260    pub installed_by: Option<MemberId>,
261    /// Last package change, ms.
262    pub updated_at: u64,
263    /// Last grant change, ms.
264    pub granted_at: u64,
265}