Compare commits

..
20 Commits
Author SHA1 Message Date
izzy aab1734615 chore: bump version to 0.8.8 2025-06-08 11:57:57 +01:00
Paul Makles 40a41ffd64 merge: pull request #418 from revoltchat/feat/role-ranks-v2 2025-06-08 11:46:00 +01:00
izzy d30ceea373 test: complete test for editing role positions 2025-06-08 11:32:42 +01:00
izzy 3e8a401077 test: begin writing test for role editing 2025-06-08 11:18:47 +01:00
izzy 99f400bc7b fix: logic error in initial data check 2025-06-08 11:18:47 +01:00
izzy 73b576a75f fix: ensure server ID is fanned out with role ranks update
fix: ensure original order is correctly sorted on edit route
2025-06-08 11:18:47 +01:00
izzy 4e4e598daf refactor: minor formatting changes 2025-06-08 11:18:47 +01:00
Zomatree 77daf82b94 chore: refactor new role rankings code 2025-06-08 11:18:47 +01:00
Zomatree e00603f276 fix: route ranking 2025-06-08 11:18:47 +01:00
Zomatree 1b2c7b2fa1 feat: add roles migration 2025-06-08 11:18:47 +01:00
Zomatree c526095d4f feat: initial bulk role reorder route 2025-06-08 11:18:47 +01:00
izzy 8cc4bbea4d refactor: clean up clippy warnings 2025-06-07 17:50:11 +01:00
izzy 911ffc767e merge: remote-tracking branch 'origin/feat/store-session-hello-new' 2025-06-07 17:31:15 +01:00
izzy 1690df998d fix: local tests with overrides were missing prerequisites 2025-06-07 17:30:16 +01:00
izzy 519d3c08a8 chore: correct dependency order in justfile 2025-06-07 16:51:09 +01:00
IAmTomahawkx 9846d8aac2 fix(tests): add policy change value to text fixtures 2025-06-06 21:06:18 -07:00
IAmTomahawkx c74b6255dd don't use local authifier 2025-06-06 20:13:14 -07:00
IAmTomahawkx df91b8c990 store last login time of session
Signed-off-by: IAmTomahawkx <iamtomahawkx@gmail.com>
2025-06-06 20:10:37 -07:00
izzy c4728c696d feat: policy changes API
chore: bump version to 0.8.7
2025-05-30 13:12:57 +01:00
IAmTomahawkx 8153f5f17a Don't panic on empty message list
... even though it shouldn't be possible.
2025-05-15 03:20:32 -07:00
65 changed files with 2350 additions and 1202 deletions
Generated
+1498 -1052
View File
File diff suppressed because it is too large Load Diff
+2
View File
@@ -11,6 +11,8 @@ members = [
[patch.crates-io] [patch.crates-io]
redis23 = { package = "redis", version = "0.23.3", git = "https://github.com/revoltchat/redis-rs", rev = "523b2937367e17bd0073722bf6e23d06042cb4e4" } redis23 = { package = "redis", version = "0.23.3", git = "https://github.com/revoltchat/redis-rs", rev = "523b2937367e17bd0073722bf6e23d06042cb4e4" }
#authifier = { package = "authifier", version = "1.0.10", path = "../authifier/crates/authifier" }
#rocket_authifier = { package = "rocket_authifier", version = "1.0.10", path = "../authifier/crates/rocket_authifier" }
# I'm 99% sure this is overloading the GitHub worker # I'm 99% sure this is overloading the GitHub worker
# hence builds have been failing since, let's just # hence builds have been failing since, let's just
+2 -1
View File
@@ -114,7 +114,8 @@ If you'd like to change anything, create a `Revolt.overrides.toml` file and spec
> And corresponding Revolt configuration: > And corresponding Revolt configuration:
> >
> ```toml > ```toml
> # Revolt.overrides.toml > # Revolt.overrides.toml
> # and Revolt.test-overrides.toml
> [database] > [database]
> mongodb = "mongodb://127.0.0.1:14017" > mongodb = "mongodb://127.0.0.1:14017"
> redis = "redis://127.0.0.1:14079/" > redis = "redis://127.0.0.1:14079/"
+2 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "revolt-bonfire" name = "revolt-bonfire"
version = "0.8.6" version = "0.8.8"
license = "AGPL-3.0-or-later" license = "AGPL-3.0-or-later"
edition = "2021" edition = "2021"
@@ -41,7 +41,7 @@ revolt-result = { path = "../core/result" }
revolt-models = { path = "../core/models" } revolt-models = { path = "../core/models" }
revolt-config = { path = "../core/config" } revolt-config = { path = "../core/config" }
revolt-database = { path = "../core/database" } revolt-database = { path = "../core/database" }
revolt-permissions = { version = "0.8.6", path = "../core/permissions" } revolt-permissions = { version = "0.8.8", path = "../core/permissions" }
revolt-presence = { path = "../core/presence", features = ["redis-is-patched"] } revolt-presence = { path = "../core/presence", features = ["redis-is-patched"] }
# redis # redis
+15
View File
@@ -100,6 +100,18 @@ impl State {
let user = self.clone_user(); let user = self.clone_user();
self.cache.is_bot = user.bot.is_some(); self.cache.is_bot = user.bot.is_some();
// Fetch pending policy changes.
let policy_changes = if user.bot.is_some() {
vec![]
} else {
db.fetch_policy_changes()
.await?
.into_iter()
.filter(|policy| policy.created_time > user.last_acknowledged_policy_change)
.map(Into::into)
.collect()
};
// Find all relationships to the user. // Find all relationships to the user.
let mut user_ids: HashSet<String> = user let mut user_ids: HashSet<String> = user
.relations .relations
@@ -227,6 +239,7 @@ impl State {
for channel in &channels { for channel in &channels {
self.insert_subscription(channel.id().to_string()).await; self.insert_subscription(channel.id().to_string()).await;
} }
Ok(EventV1::Ready { Ok(EventV1::Ready {
users: if fields.contains(&ReadyPayloadFields::Users) { users: if fields.contains(&ReadyPayloadFields::Users) {
Some(users) Some(users)
@@ -252,6 +265,8 @@ impl State {
user_settings, user_settings,
channel_unreads: channel_unreads.map(|vec| vec.into_iter().map(Into::into).collect()), channel_unreads: channel_unreads.map(|vec| vec.into_iter().map(Into::into).collect()),
policy_changes,
}) })
} }
+5
View File
@@ -17,6 +17,7 @@ use redis_kiss::{PayloadType, REDIS_PAYLOAD_TYPE, REDIS_URI};
use revolt_config::report_internal_error; use revolt_config::report_internal_error;
use revolt_database::{ use revolt_database::{
events::{client::EventV1, server::ClientMessage}, events::{client::EventV1, server::ClientMessage},
iso8601_timestamp::Timestamp,
Database, User, UserHint, Database, User, UserHint,
}; };
use revolt_presence::{create_session, delete_session}; use revolt_presence::{create_session, delete_session};
@@ -100,6 +101,10 @@ pub async fn client(db: &'static Database, stream: TcpStream, addr: SocketAddr)
info!("User {addr:?} authenticated as @{}", user.username); info!("User {addr:?} authenticated as @{}", user.username);
db.update_session_last_seen(&session_id, Timestamp::now_utc())
.await
.ok();
// Create local state. // Create local state.
let mut state = State::from(user, session_id); let mut state = State::from(user, session_id);
let user_id = state.cache.user_id.clone(); let user_id = state.cache.user_id.clone();
+2 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "revolt-config" name = "revolt-config"
version = "0.8.6" version = "0.8.8"
edition = "2021" edition = "2021"
license = "MIT" license = "MIT"
authors = ["Paul Makles <me@insrt.uk>"] authors = ["Paul Makles <me@insrt.uk>"]
@@ -36,4 +36,4 @@ sentry = "0.31.5"
sentry-anyhow = { version = "0.38.1", optional = true } sentry-anyhow = { version = "0.38.1", optional = true }
# Core # Core
revolt-result = { version = "0.8.6", path = "../result", optional = true } revolt-result = { version = "0.8.8", path = "../result", optional = true }
+22 -6
View File
@@ -60,6 +60,9 @@ static CONFIG_SEARCH_PATHS: [&str; 3] = [
"/Revolt.toml", "/Revolt.toml",
]; ];
/// Path to search for test overrides
static TEST_OVERRIDE_PATH: &str = "Revolt.test-overrides.toml";
/// Configuration builder /// Configuration builder
static CONFIG_BUILDER: Lazy<RwLock<Config>> = Lazy::new(|| { static CONFIG_BUILDER: Lazy<RwLock<Config>> = Lazy::new(|| {
RwLock::new({ RwLock::new({
@@ -73,6 +76,20 @@ static CONFIG_BUILDER: Lazy<RwLock<Config>> = Lazy::new(|| {
include_str!("../Revolt.test.toml"), include_str!("../Revolt.test.toml"),
FileFormat::Toml, FileFormat::Toml,
)); ));
// recursively search upwards for an overrides file (if there is one)
if let Ok(cwd) = std::env::current_dir() {
let mut path = Some(cwd.as_path());
while let Some(current_path) = path {
let target_path = current_path.join(TEST_OVERRIDE_PATH);
if target_path.exists() {
builder = builder
.add_source(File::new(target_path.to_str().unwrap(), FileFormat::Toml));
}
path = current_path.parent();
}
}
} }
for path in CONFIG_SEARCH_PATHS { for path in CONFIG_SEARCH_PATHS {
@@ -388,6 +405,11 @@ pub async fn read() -> Config {
pub async fn config() -> Settings { pub async fn config() -> Settings {
let mut config = read().await.try_deserialize::<Settings>().unwrap(); let mut config = read().await.try_deserialize::<Settings>().unwrap();
// inject REDIS_URI for redis-kiss library
if std::env::var("REDIS_URL").is_err() {
std::env::set_var("REDIS_URI", config.database.redis.clone());
}
// auto-detect production nodes // auto-detect production nodes
if config.hosts.api.contains("https") && config.hosts.api.contains("revolt.chat") { if config.hosts.api.contains("https") && config.hosts.api.contains("revolt.chat") {
config.production = true; config.production = true;
@@ -406,12 +428,6 @@ pub async fn setup_logging(release: &'static str, dsn: String) -> Option<sentry:
std::env::set_var("ROCKET_ADDRESS", "0.0.0.0"); std::env::set_var("ROCKET_ADDRESS", "0.0.0.0");
} }
if std::env::var("REDIS_URL").is_err() {
// Configure redis-kiss library
let config = config().await;
std::env::set_var("REDIS_URI", config.database.redis);
}
pretty_env_logger::init(); pretty_env_logger::init();
log::info!("Starting {release}"); log::info!("Starting {release}");
+7 -7
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "revolt-database" name = "revolt-database"
version = "0.8.6" version = "0.8.8"
edition = "2021" edition = "2021"
license = "AGPL-3.0-or-later" license = "AGPL-3.0-or-later"
authors = ["Paul Makles <me@insrt.uk>"] authors = ["Paul Makles <me@insrt.uk>"]
@@ -24,19 +24,19 @@ default = ["mongodb", "async-std-runtime", "tasks"]
[dependencies] [dependencies]
# Core # Core
revolt-config = { version = "0.8.6", path = "../config", features = [ revolt-config = { version = "0.8.8", path = "../config", features = [
"report-macros", "report-macros",
] } ] }
revolt-result = { version = "0.8.6", path = "../result" } revolt-result = { version = "0.8.8", path = "../result" }
revolt-models = { version = "0.8.6", path = "../models", features = [ revolt-models = { version = "0.8.8", path = "../models", features = [
"validator", "validator",
] } ] }
revolt-presence = { version = "0.8.6", path = "../presence" } revolt-presence = { version = "0.8.8", path = "../presence" }
revolt-permissions = { version = "0.8.6", path = "../permissions", features = [ revolt-permissions = { version = "0.8.8", path = "../permissions", features = [
"serde", "serde",
"bson", "bson",
] } ] }
revolt-parser = { version = "0.8.6", path = "../parser" } revolt-parser = { version = "0.8.8", path = "../parser" }
# Utility # Utility
log = "0.4" log = "0.4"
@@ -3,18 +3,21 @@
"_object_type": "User", "_object_type": "User",
"_id": "__ID:0__", "_id": "__ID:0__",
"username": "Owner", "username": "Owner",
"last_acknowledged_policy_change": "2025-06-07T04:04:48+0000",
"discriminator": "0001" "discriminator": "0001"
}, },
{ {
"_object_type": "User", "_object_type": "User",
"_id": "__ID:1__", "_id": "__ID:1__",
"username": "Member", "username": "Member",
"last_acknowledged_policy_change": "2025-06-07T04:04:48+0000",
"discriminator": "0001" "discriminator": "0001"
}, },
{ {
"_object_type": "User", "_object_type": "User",
"_id": "__ID:2__", "_id": "__ID:2__",
"username": "Member", "username": "Member",
"last_acknowledged_policy_change": "2025-06-07T04:04:48+0000",
"discriminator": "0002" "discriminator": "0002"
}, },
{ {
@@ -23,6 +26,9 @@
"channel_type": "Group", "channel_type": "Group",
"name": "My Group", "name": "My Group",
"owner": "__ID:0__", "owner": "__ID:0__",
"recipients": ["__ID:0__", "__ID:1__"] "recipients": [
"__ID:0__",
"__ID:1__"
]
} }
] ]
@@ -3,18 +3,21 @@
"_object_type": "User", "_object_type": "User",
"_id": "__ID:0__", "_id": "__ID:0__",
"username": "Owner", "username": "Owner",
"last_acknowledged_policy_change": "2025-06-07T04:04:48+0000",
"discriminator": "0001" "discriminator": "0001"
}, },
{ {
"_object_type": "User", "_object_type": "User",
"_id": "__ID:1__", "_id": "__ID:1__",
"username": "Moderator", "username": "Moderator",
"last_acknowledged_policy_change": "2025-06-07T04:04:48+0000",
"discriminator": "0001" "discriminator": "0001"
}, },
{ {
"_object_type": "User", "_object_type": "User",
"_id": "__ID:2__", "_id": "__ID:2__",
"username": "User", "username": "User",
"last_acknowledged_policy_change": "2025-06-07T04:04:48+0000",
"discriminator": "0001" "discriminator": "0001"
}, },
{ {
@@ -39,7 +42,9 @@
"_id": "__ID:4__", "_id": "__ID:4__",
"owner": "__ID:0__", "owner": "__ID:0__",
"name": "Server", "name": "Server",
"channels": ["__ID:3__"], "channels": [
"__ID:3__"
],
"roles": { "roles": {
"__ID:5__": { "__ID:5__": {
"name": "Moderator", "name": "Moderator",
@@ -47,7 +52,7 @@
"a": 545270208, "a": 545270208,
"d": 0 "d": 0
}, },
"rank": 3 "rank": 1
}, },
"__ID:6__": { "__ID:6__": {
"name": "Owner", "name": "Owner",
@@ -66,7 +71,9 @@
"user": "__ID:0__", "user": "__ID:0__",
"server": "__ID:4__" "server": "__ID:4__"
}, },
"roles": ["__ID:6__"], "roles": [
"__ID:6__"
],
"joined_at": 1698318340195 "joined_at": 1698318340195
}, },
{ {
@@ -75,7 +82,9 @@
"user": "__ID:1__", "user": "__ID:1__",
"server": "__ID:4__" "server": "__ID:4__"
}, },
"roles": ["__ID:5__"], "roles": [
"__ID:5__"
],
"joined_at": 1698318340195 "joined_at": 1698318340195
}, },
{ {
@@ -86,4 +95,4 @@
}, },
"joined_at": 1698318340195 "joined_at": 1698318340195
} }
] ]
@@ -4,8 +4,8 @@ use futures::lock::Mutex;
use crate::{ use crate::{
Bot, Channel, ChannelCompositeKey, ChannelUnread, Emoji, File, FileHash, Invite, Member, Bot, Channel, ChannelCompositeKey, ChannelUnread, Emoji, File, FileHash, Invite, Member,
MemberCompositeKey, Message, RatelimitEvent, Report, Server, ServerBan, Snapshot, User, MemberCompositeKey, Message, PolicyChange, RatelimitEvent, Report, Server, ServerBan, Snapshot,
UserSettings, Webhook, User, UserSettings, Webhook,
}; };
database_derived!( database_derived!(
@@ -21,6 +21,7 @@ database_derived!(
pub file_hashes: Arc<Mutex<HashMap<String, FileHash>>>, pub file_hashes: Arc<Mutex<HashMap<String, FileHash>>>,
pub files: Arc<Mutex<HashMap<String, File>>>, pub files: Arc<Mutex<HashMap<String, File>>>,
pub messages: Arc<Mutex<HashMap<String, Message>>>, pub messages: Arc<Mutex<HashMap<String, Message>>>,
pub policy_changes: Arc<Mutex<HashMap<String, PolicyChange>>>,
pub ratelimit_events: Arc<Mutex<HashMap<String, RatelimitEvent>>>, pub ratelimit_events: Arc<Mutex<HashMap<String, RatelimitEvent>>>,
pub user_settings: Arc<Mutex<HashMap<String, UserSettings>>>, pub user_settings: Arc<Mutex<HashMap<String, UserSettings>>>,
pub users: Arc<Mutex<HashMap<String, User>>>, pub users: Arc<Mutex<HashMap<String, User>>>,
+6 -1
View File
@@ -6,7 +6,7 @@ use revolt_models::v0::{
AppendMessage, Channel, ChannelUnread, Emoji, FieldsChannel, FieldsMember, FieldsMessage, AppendMessage, Channel, ChannelUnread, Emoji, FieldsChannel, FieldsMember, FieldsMessage,
FieldsRole, FieldsServer, FieldsUser, FieldsWebhook, Member, MemberCompositeKey, Message, FieldsRole, FieldsServer, FieldsUser, FieldsWebhook, Member, MemberCompositeKey, Message,
PartialChannel, PartialMember, PartialMessage, PartialRole, PartialServer, PartialUser, PartialChannel, PartialMember, PartialMessage, PartialRole, PartialServer, PartialUser,
PartialWebhook, RemovalIntention, Report, Server, User, UserSettings, Webhook, PartialWebhook, PolicyChange, RemovalIntention, Report, Server, User, UserSettings, Webhook,
}; };
use crate::Database; use crate::Database;
@@ -62,6 +62,8 @@ pub enum EventV1 {
user_settings: Option<UserSettings>, user_settings: Option<UserSettings>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
channel_unreads: Option<Vec<ChannelUnread>>, channel_unreads: Option<Vec<ChannelUnread>>,
policy_changes: Vec<PolicyChange>,
}, },
/// Ping response /// Ping response
@@ -163,6 +165,9 @@ pub enum EventV1 {
/// Server role deleted /// Server role deleted
ServerRoleDelete { id: String, role_id: String }, ServerRoleDelete { id: String, role_id: String },
/// Server roles ranks updated
ServerRoleRanksUpdate { id: String, ranks: Vec<String> },
/// Update existing user /// Update existing user
UserUpdate { UserUpdate {
id: String, id: String,
@@ -64,6 +64,10 @@ pub async fn create_database(db: &MongoDb) {
.await .await
.expect("Failed to create user_settings collection."); .expect("Failed to create user_settings collection.");
db.create_collection("policy_changes")
.await
.expect("Failed to create policy_changes collection.");
db.create_collection("safety_reports") db.create_collection("safety_reports")
.await .await
.expect("Failed to create safety_reports collection."); .expect("Failed to create safety_reports collection.");
@@ -1,14 +1,19 @@
use std::{collections::HashSet, ops::BitXor, time::Duration}; use std::{
collections::{HashMap, HashSet},
ops::BitXor,
time::Duration,
};
use crate::{ use crate::{
mongodb::{ mongodb::{
bson::{doc, from_bson, from_document, to_document, Bson, DateTime, Document}, bson::{doc, from_bson, from_document, to_document, Bson, DateTime, Document},
options::FindOptions, options::FindOptions,
}, },
AbstractChannels, AbstractServers, Channel, Invite, MongoDb, DISCRIMINATOR_SEARCH_SPACE, AbstractChannels, AbstractServers, Channel, Invite, MongoDb, User, DISCRIMINATOR_SEARCH_SPACE,
}; };
use bson::oid::ObjectId; use bson::{oid::ObjectId, to_bson};
use futures::StreamExt; use futures::StreamExt;
use iso8601_timestamp::Timestamp;
use rand::seq::SliceRandom; use rand::seq::SliceRandom;
use revolt_permissions::DEFAULT_WEBHOOK_PERMISSIONS; use revolt_permissions::DEFAULT_WEBHOOK_PERMISSIONS;
use revolt_result::{Error, ErrorType}; use revolt_result::{Error, ErrorType};
@@ -21,7 +26,7 @@ struct MigrationInfo {
revision: i32, revision: i32,
} }
pub const LATEST_REVISION: i32 = 33; // MUST BE +1 to last migration pub const LATEST_REVISION: i32 = 42; // MUST BE +1 to last migration
pub async fn migrate_database(db: &MongoDb) { pub async fn migrate_database(db: &MongoDb) {
let migrations = db.col::<Document>("migrations"); let migrations = db.col::<Document>("migrations");
@@ -1139,6 +1144,88 @@ pub async fn run_migrations(db: &MongoDb, revision: i32) -> i32 {
.unwrap(); .unwrap();
} }
if revision <= 40 {
info!(
"Running migration [revision |> 40 / 30-05-2025]: Set last policy acknowlegement date to now and create policy changes collection."
);
db.db()
.create_collection("policy_changes")
.await
.expect("Failed to create policy_changes collection.");
db.db()
.collection::<User>("users")
.update_many(
doc! {},
doc! {
"$set": {
"last_acknowledged_policy_change": to_bson(&Timestamp::now_utc())
.expect("failed to serialise timestamp")
}
},
)
.await
.expect("failed to update users");
}
if revision <= 41 {
info!(
"Running migration [revision 41 / 05-06-2025]: convert role ranks to uniform numbers."
);
#[derive(Serialize, Deserialize, Clone)]
struct Role {
pub rank: i64,
}
#[derive(Serialize, Deserialize, Clone)]
struct Server {
#[serde(rename = "_id")]
pub id: String,
#[serde(default = "HashMap::<String, Role>::new")]
pub roles: HashMap<String, Role>,
}
let mut servers = db
.db()
.collection::<Server>("servers")
.find(doc! {
"roles": {
"$exists": true,
"$ne": []
}
})
.await
.unwrap()
.filter_map(|s| async { s.ok() })
.boxed();
while let Some(server) = servers.next().await {
let mut ordered_roles = server.roles.clone().into_iter().collect::<Vec<_>>();
ordered_roles.sort_by(|(_, role_a), (_, role_b)| role_a.rank.cmp(&role_b.rank));
let ordered_roles = ordered_roles
.into_iter()
.map(|(id, _)| id)
.collect::<Vec<_>>();
let mut doc = doc! {};
for id in server.roles.keys() {
doc.insert(
format!("roles.{id}.rank"),
ordered_roles.iter().position(|x| id == x).unwrap() as i64,
);
}
db.db()
.collection::<Server>("servers")
.update_one(doc! { "_id": &server.id }, doc! { "$set": doc })
.await
.unwrap();
}
}
// Reminder to update LATEST_REVISION when adding new migrations. // Reminder to update LATEST_REVISION when adding new migrations.
LATEST_REVISION.max(revision) LATEST_REVISION.max(revision)
} }
+3
View File
@@ -8,6 +8,7 @@ mod emojis;
mod file_hashes; mod file_hashes;
mod files; mod files;
mod messages; mod messages;
mod policy_changes;
mod ratelimit_events; mod ratelimit_events;
mod safety_reports; mod safety_reports;
mod safety_snapshots; mod safety_snapshots;
@@ -27,6 +28,7 @@ pub use emojis::*;
pub use file_hashes::*; pub use file_hashes::*;
pub use files::*; pub use files::*;
pub use messages::*; pub use messages::*;
pub use policy_changes::*;
pub use ratelimit_events::*; pub use ratelimit_events::*;
pub use safety_reports::*; pub use safety_reports::*;
pub use safety_snapshots::*; pub use safety_snapshots::*;
@@ -51,6 +53,7 @@ pub trait AbstractDatabase:
+ file_hashes::AbstractAttachmentHashes + file_hashes::AbstractAttachmentHashes
+ files::AbstractAttachments + files::AbstractAttachments
+ messages::AbstractMessages + messages::AbstractMessages
+ policy_changes::AbstractPolicyChange
+ ratelimit_events::AbstractRatelimitEvents + ratelimit_events::AbstractRatelimitEvents
+ safety_reports::AbstractReport + safety_reports::AbstractReport
+ safety_snapshots::AbstractSnapshot + safety_snapshots::AbstractSnapshot
@@ -0,0 +1,5 @@
mod model;
mod ops;
pub use model::*;
pub use ops::*;
@@ -0,0 +1,20 @@
use iso8601_timestamp::Timestamp;
auto_derived!(
/// Platform policy change
pub struct PolicyChange {
/// Unique Id
#[serde(rename = "_id")]
pub id: String,
/// Time at which this policy was created
pub created_time: Timestamp,
/// Time at which this policy is effective
pub effective_time: Timestamp,
/// Message shown to users
pub description: String,
/// URL with details about changes
pub url: String,
}
);
@@ -0,0 +1,15 @@
use revolt_result::Result;
use crate::PolicyChange;
mod mongodb;
mod reference;
#[async_trait]
pub trait AbstractPolicyChange: Sync + Send {
/// Fetch all policy changes
async fn fetch_policy_changes(&self) -> Result<Vec<PolicyChange>>;
/// Acknowledge policy changes
async fn acknowledge_policy_changes(&self, user_id: &str) -> Result<()>;
}
@@ -0,0 +1,46 @@
use bson::to_bson;
use iso8601_timestamp::Timestamp;
use revolt_result::Result;
use crate::MongoDb;
use crate::PolicyChange;
use crate::User;
use super::AbstractPolicyChange;
static COL: &str = "policy_changes";
#[async_trait]
impl AbstractPolicyChange for MongoDb {
/// Fetch all policy changes
async fn fetch_policy_changes(&self) -> Result<Vec<PolicyChange>> {
query!(self, find, COL, doc! {})
}
/// Acknowledge policy changes
async fn acknowledge_policy_changes(&self, user_id: &str) -> Result<()> {
let latest_policy = self
.fetch_policy_changes()
.await?
.into_iter()
.map(|policy| policy.created_time)
.max()
.unwrap_or(Timestamp::UNIX_EPOCH);
self.col::<User>("users")
.update_one(
doc! {
"_id": user_id
},
doc! {
"$set": {
"last_acknowledged_policy_change": to_bson(&latest_policy)
.map_err(|_| create_database_error!("to_bson", "timestamp"))?
}
},
)
.await
.map(|_| ())
.map_err(|_| create_database_error!("update_one", COL))
}
}
@@ -0,0 +1,31 @@
use iso8601_timestamp::Timestamp;
use revolt_result::Result;
use crate::PolicyChange;
use crate::ReferenceDb;
use super::AbstractPolicyChange;
#[async_trait]
impl AbstractPolicyChange for ReferenceDb {
/// Fetch all policy changes
async fn fetch_policy_changes(&self) -> Result<Vec<PolicyChange>> {
let policy_changes = self.policy_changes.lock().await;
Ok(policy_changes.values().cloned().collect())
}
/// Acknowledge policy changes
async fn acknowledge_policy_changes(&self, user_id: &str) -> Result<()> {
let mut users = self.users.lock().await;
let user = users.get_mut(user_id).expect("user doesn't exist");
user.last_acknowledged_policy_change = self
.fetch_policy_changes()
.await?
.into_iter()
.map(|policy| policy.created_time)
.max()
.unwrap_or(Timestamp::UNIX_EPOCH);
Ok(())
}
}
@@ -181,7 +181,7 @@ impl Server {
} }
/// Update server data /// Update server data
pub async fn update<'a>( pub async fn update(
&mut self, &mut self,
db: &Database, db: &Database,
partial: PartialServer, partial: PartialServer,
@@ -228,6 +228,13 @@ impl Server {
} }
} }
/// Ordered roles list
pub fn ordered_roles(&self) -> Vec<(String, Role)> {
let mut ordered_roles = self.roles.clone().into_iter().collect::<Vec<_>>();
ordered_roles.sort_by(|(_, role_a), (_, role_b)| role_a.rank.cmp(&role_b.rank));
ordered_roles
}
/// Set role permission on a server /// Set role permission on a server
pub async fn set_role_permission( pub async fn set_role_permission(
&mut self, &mut self,
@@ -253,6 +260,37 @@ impl Server {
Err(create_error!(NotFound)) Err(create_error!(NotFound))
} }
} }
/// Reorders the server's roles rankings
pub async fn set_role_ordering(&mut self, db: &Database, new_order: Vec<String>) -> Result<()> {
// New order must always contain every role
debug_assert_eq!(self.roles.len(), new_order.len());
// Set the role's ranks to the positions in the vec
for (rank, id) in new_order.iter().enumerate() {
self.roles.get_mut(id).unwrap().rank = rank as i64;
}
db.update_server(
&self.id,
&PartialServer {
roles: Some(self.roles.clone()),
..Default::default()
},
Vec::new(),
)
.await?;
// Publish bulk update event
EventV1::ServerRoleRanksUpdate {
id: self.id.clone(),
ranks: new_order,
}
.p(self.id.clone())
.await;
Ok(())
}
} }
impl Role { impl Role {
@@ -7,11 +7,5 @@ mod rocket;
#[cfg(feature = "rocket-impl")] #[cfg(feature = "rocket-impl")]
mod schema; mod schema;
#[cfg(feature = "axum-impl")]
pub use self::axum::*;
#[cfg(feature = "rocket-impl")]
pub use self::rocket::*;
#[cfg(feature = "rocket-impl")]
pub use self::schema::*;
pub use model::*; pub use model::*;
pub use ops::*; pub use ops::*;
@@ -57,6 +57,8 @@ auto_derived_partial!(
/// Time until user is unsuspended /// Time until user is unsuspended
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub suspended_until: Option<Timestamp>, pub suspended_until: Option<Timestamp>,
/// Last acknowledged policy change
pub last_acknowledged_policy_change: Timestamp,
}, },
"PartialUser" "PartialUser"
); );
@@ -178,6 +180,7 @@ impl Default for User {
privileged: Default::default(), privileged: Default::default(),
bot: Default::default(), bot: Default::default(),
suspended_until: Default::default(), suspended_until: Default::default(),
last_acknowledged_policy_change: Timestamp::UNIX_EPOCH,
} }
} }
} }
@@ -200,6 +203,7 @@ impl User {
id: account_id.into().unwrap_or_else(|| Ulid::new().to_string()), id: account_id.into().unwrap_or_else(|| Ulid::new().to_string()),
discriminator: User::find_discriminator(db, &username, None).await?, discriminator: User::find_discriminator(db, &username, None).await?,
username, username,
last_acknowledged_policy_change: Timestamp::now_utc(),
..Default::default() ..Default::default()
}; };
@@ -1,4 +1,5 @@
use authifier::models::Session; use authifier::models::Session;
use iso8601_timestamp::Timestamp;
use revolt_result::Result; use revolt_result::Result;
use crate::{FieldsUser, PartialUser, RelationshipStatus, User}; use crate::{FieldsUser, PartialUser, RelationshipStatus, User};
@@ -61,4 +62,6 @@ pub trait AbstractUsers: Sync + Send {
/// Remove push subscription for a session by session id (TODO: remove) /// Remove push subscription for a session by session id (TODO: remove)
async fn remove_push_subscription_by_session_id(&self, session_id: &str) -> Result<()>; async fn remove_push_subscription_by_session_id(&self, session_id: &str) -> Result<()>;
async fn update_session_last_seen(&self, session_id: &str, when: Timestamp) -> Result<()>;
} }
@@ -1,6 +1,7 @@
use ::mongodb::options::{Collation, CollationStrength, FindOneOptions, FindOptions}; use ::mongodb::options::{Collation, CollationStrength, FindOneOptions, FindOptions};
use authifier::models::Session; use authifier::models::Session;
use futures::StreamExt; use futures::StreamExt;
use iso8601_timestamp::Timestamp;
use revolt_result::Result; use revolt_result::Result;
use crate::DocumentId; use crate::DocumentId;
@@ -317,7 +318,26 @@ impl AbstractUsers for MongoDb {
) )
.await .await
.map(|_| ()) .map(|_| ())
.map_err(|_| create_database_error!("update_one", COL)) .map_err(|_| create_database_error!("update_one", "sessions"))
}
async fn update_session_last_seen(&self, session_id: &str, when: Timestamp) -> Result<()> {
let formatted: &str = &when.format();
self.col::<Session>("sessions")
.update_one(
doc! {
"_id": session_id
},
doc! {
"$set": {
"last_seen": formatted
}
},
)
.await
.map(|_| ())
.map_err(|_| create_database_error!("update_one", "sessions"))
} }
} }
@@ -1,4 +1,5 @@
use authifier::models::Session; use authifier::models::Session;
use iso8601_timestamp::Timestamp;
use revolt_result::Result; use revolt_result::Result;
use crate::{FieldsUser, PartialUser, RelationshipStatus, User}; use crate::{FieldsUser, PartialUser, RelationshipStatus, User};
@@ -168,4 +169,8 @@ impl AbstractUsers for ReferenceDb {
async fn remove_push_subscription_by_session_id(&self, _session_id: &str) -> Result<()> { async fn remove_push_subscription_by_session_id(&self, _session_id: &str) -> Result<()> {
todo!() todo!()
} }
async fn update_session_last_seen(&self, _session_id: &str, _when: Timestamp) -> Result<()> {
todo!()
}
} }
+25 -16
View File
@@ -3,6 +3,7 @@ use crate::{Database, Message, AMQP};
use deadqueue::limited::Queue; use deadqueue::limited::Queue;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use revolt_config::capture_message;
use revolt_models::v0::PushNotification; use revolt_models::v0::PushNotification;
use std::{ use std::{
collections::{HashMap, HashSet}, collections::{HashMap, HashSet},
@@ -64,6 +65,7 @@ pub async fn queue_ack(channel: String, user: String, event: AckEvent) {
); );
} }
/// Do not add more than one message per event.
pub async fn queue_message(channel: String, event: AckEvent) { pub async fn queue_message(channel: String, event: AckEvent) {
Q.try_push(Data { Q.try_push(Data {
channel, channel,
@@ -262,24 +264,31 @@ pub async fn worker(db: Database, amqp: AMQP) {
if let AckEvent::ProcessMessage { messages: existing } = if let AckEvent::ProcessMessage { messages: existing } =
&mut task.data.event &mut task.data.event
{ {
// add the new message to the list of messages to be processed. if let Some(new_event) = new_data.pop() {
existing.append(new_data); // if the message contains a mass mention, do not delay it any further.
if new_event.1.contains_mass_push_mention() {
// add the new message to the list of messages to be processed.
existing.push(new_event);
task.run_immediately();
continue;
}
// if the message contains a mass mention, do not delay it any further. existing.push(new_event);
if new_data[0].1.contains_mass_push_mention() {
task.run_immediately();
continue;
}
// put a cap on the amount of messages that can be queued, for particularly active channels // put a cap on the amount of messages that can be queued, for particularly active channels
if (existing.length() as u16) if (existing.length() as u16)
< revolt_config::config() < revolt_config::config()
.await .await
.features .features
.advanced .advanced
.process_message_delay_limit .process_message_delay_limit
{ {
task.delay(); task.delay();
}
} else {
let err_msg = format!("Got zero-length message event: {event:?}");
capture_message(&err_msg, revolt_config::Level::Warning);
info!("{err_msg}")
} }
} else { } else {
panic!("Somehow got an ack message in the add mention arm"); panic!("Somehow got an ack message in the add mention arm");
@@ -4,7 +4,7 @@ use once_cell::sync::Lazy;
use crate::events::client::EventV1; use crate::events::client::EventV1;
static Q: Lazy<(Sender<AuthifierEvent>, Receiver<AuthifierEvent>)> = Lazy::new(|| unbounded()); static Q: Lazy<(Sender<AuthifierEvent>, Receiver<AuthifierEvent>)> = Lazy::new(unbounded);
/// Get sender /// Get sender
pub fn sender() -> Sender<AuthifierEvent> { pub fn sender() -> Sender<AuthifierEvent> {
+15 -3
View File
@@ -1,3 +1,4 @@
use iso8601_timestamp::Timestamp;
use revolt_models::v0::*; use revolt_models::v0::*;
use revolt_permissions::{calculate_user_permissions, UserPermission}; use revolt_permissions::{calculate_user_permissions, UserPermission};
@@ -14,8 +15,7 @@ impl crate::Bot {
avatar: user.avatar.map(|x| x.id).unwrap_or_default(), avatar: user.avatar.map(|x| x.id).unwrap_or_default(),
description: user description: user
.profile .profile
.map(|profile| profile.content) .and_then(|profile| profile.content)
.flatten()
.unwrap_or_default(), .unwrap_or_default(),
} }
} }
@@ -597,6 +597,17 @@ impl From<Masquerade> for crate::Masquerade {
} }
} }
impl From<crate::PolicyChange> for PolicyChange {
fn from(value: crate::PolicyChange) -> Self {
PolicyChange {
created_time: value.created_time,
effective_time: value.effective_time,
description: value.description,
url: value.url,
}
}
}
impl From<crate::Report> for Report { impl From<crate::Report> for Report {
fn from(value: crate::Report) -> Self { fn from(value: crate::Report) -> Self {
Report { Report {
@@ -1102,7 +1113,7 @@ impl crate::User {
} }
/// Convert user object into user model without presence information /// Convert user object into user model without presence information
pub async fn into_known_static<'a>(self, is_online: bool) -> User { pub async fn into_known_static(self, is_online: bool) -> User {
let badges = self.get_badges().await; let badges = self.get_badges().await;
User { User {
@@ -1188,6 +1199,7 @@ impl From<User> for crate::User {
privileged: value.privileged, privileged: value.privileged,
bot: value.bot.map(Into::into), bot: value.bot.map(Into::into),
suspended_until: None, suspended_until: None,
last_acknowledged_policy_change: Timestamp::UNIX_EPOCH,
} }
} }
} }
+1 -1
View File
@@ -54,7 +54,7 @@ use revolt_rocket_okapi::{
use schemars::schema::{InstanceType, SchemaObject, SingleOrVec}; use schemars::schema::{InstanceType, SchemaObject, SingleOrVec};
#[cfg(feature = "rocket-impl")] #[cfg(feature = "rocket-impl")]
impl<'r> OpenApiFromRequest<'r> for IdempotencyKey { impl OpenApiFromRequest<'_> for IdempotencyKey {
fn from_request_input( fn from_request_input(
_gen: &mut OpenApiGenerator, _gen: &mut OpenApiGenerator,
_name: String, _name: String,
+1 -1
View File
@@ -104,7 +104,7 @@ impl PermissionQuery for DatabasePermissionQuery<'_> {
.unwrap_or_default(); .unwrap_or_default();
self.cached_mutual_connection = Some(value); self.cached_mutual_connection = Some(value);
matches!(value, true) value
} else { } else {
false false
} }
+3 -3
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "revolt-files" name = "revolt-files"
version = "0.8.6" version = "0.8.8"
edition = "2021" edition = "2021"
license = "AGPL-3.0-or-later" license = "AGPL-3.0-or-later"
authors = ["Paul Makles <me@insrt.uk>"] authors = ["Paul Makles <me@insrt.uk>"]
@@ -20,10 +20,10 @@ typenum = "1.17.0"
aws-config = "1.5.5" aws-config = "1.5.5"
aws-sdk-s3 = { version = "1.46.0", features = ["behavior-version-latest"] } aws-sdk-s3 = { version = "1.46.0", features = ["behavior-version-latest"] }
revolt-config = { version = "0.8.6", path = "../config", features = [ revolt-config = { version = "0.8.8", path = "../config", features = [
"report-macros", "report-macros",
] } ] }
revolt-result = { version = "0.8.6", path = "../result" } revolt-result = { version = "0.8.8", path = "../result" }
# image processing # image processing
jxl-oxide = "0.8.1" jxl-oxide = "0.8.1"
+3 -3
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "revolt-models" name = "revolt-models"
version = "0.8.6" version = "0.8.8"
edition = "2021" edition = "2021"
license = "MIT" license = "MIT"
authors = ["Paul Makles <me@insrt.uk>"] authors = ["Paul Makles <me@insrt.uk>"]
@@ -20,8 +20,8 @@ default = ["serde", "partials", "rocket"]
[dependencies] [dependencies]
# Core # Core
revolt-config = { version = "0.8.6", path = "../config" } revolt-config = { version = "0.8.8", path = "../config" }
revolt-permissions = { version = "0.8.6", path = "../permissions" } revolt-permissions = { version = "0.8.8", path = "../permissions" }
# Utility # Utility
regex = "1.11" regex = "1.11"
+5 -5
View File
@@ -310,14 +310,14 @@ impl Channel {
/// This returns a Result because the recipient name can't be determined here without a db call, /// This returns a Result because the recipient name can't be determined here without a db call,
/// which can't be done since this is models, which can't reference the database crate. /// which can't be done since this is models, which can't reference the database crate.
/// ///
/// If it returns Err, you need to fetch the name from the db. /// If it returns None, you need to fetch the name from the db.
pub fn name(&self) -> Result<&str, ()> { pub fn name(&self) -> Option<&str> {
match self { match self {
Channel::DirectMessage { .. } => Err(()), Channel::DirectMessage { .. } => None,
Channel::SavedMessages { .. } => Ok("Saved Messages"), Channel::SavedMessages { .. } => Some("Saved Messages"),
Channel::TextChannel { name, .. } Channel::TextChannel { name, .. }
| Channel::Group { name, .. } | Channel::Group { name, .. }
| Channel::VoiceChannel { name, .. } => Ok(name), | Channel::VoiceChannel { name, .. } => Some(name),
} }
} }
} }
+2
View File
@@ -7,6 +7,7 @@ mod embeds;
mod emojis; mod emojis;
mod files; mod files;
mod messages; mod messages;
mod policy_changes;
mod safety_reports; mod safety_reports;
mod server_bans; mod server_bans;
mod server_members; mod server_members;
@@ -23,6 +24,7 @@ pub use embeds::*;
pub use emojis::*; pub use emojis::*;
pub use files::*; pub use files::*;
pub use messages::*; pub use messages::*;
pub use policy_changes::*;
pub use safety_reports::*; pub use safety_reports::*;
pub use server_bans::*; pub use server_bans::*;
pub use server_members::*; pub use server_members::*;
@@ -0,0 +1,16 @@
use iso8601_timestamp::Timestamp;
auto_derived!(
/// Platform policy change
pub struct PolicyChange {
/// Time at which this policy was created
pub created_time: Timestamp,
/// Time at which this policy is effective
pub effective_time: Timestamp,
/// Message shown to users
pub description: String,
/// URL with details about changes
pub url: String,
}
);
+6 -1
View File
@@ -267,7 +267,7 @@ auto_derived!(
pub hoist: Option<bool>, pub hoist: Option<bool>,
/// Ranking position /// Ranking position
/// ///
/// Smaller values take priority. /// **Removed** - no effect, use the edit server role positions route
pub rank: Option<i64>, pub rank: Option<i64>,
/// Fields to remove from role object /// Fields to remove from role object
#[cfg_attr(feature = "validator", validate(length(min = 1)))] #[cfg_attr(feature = "validator", validate(length(min = 1)))]
@@ -286,4 +286,9 @@ auto_derived!(
/// Whether to not send a leave message /// Whether to not send a leave message
pub leave_silently: Option<bool>, pub leave_silently: Option<bool>,
} }
/// New role positions
pub struct DataEditRoleRanks {
pub ranks: Vec<String>,
}
); );
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "revolt-parser" name = "revolt-parser"
version = "0.8.6" version = "0.8.8"
edition = "2021" edition = "2021"
license = "AGPL-3.0-or-later" license = "AGPL-3.0-or-later"
description = "Revolt Backend: Message Parser" description = "Revolt Backend: Message Parser"
+2 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "revolt-permissions" name = "revolt-permissions"
version = "0.8.6" version = "0.8.8"
edition = "2021" edition = "2021"
license = "MIT" license = "MIT"
authors = ["Paul Makles <me@insrt.uk>"] authors = ["Paul Makles <me@insrt.uk>"]
@@ -21,7 +21,7 @@ async-std = { version = "1.8.0", features = ["attributes"] }
[dependencies] [dependencies]
# Core # Core
revolt-result = { version = "0.8.6", path = "../result" } revolt-result = { version = "0.8.8", path = "../result" }
# Utility # Utility
auto_ops = "0.3.0" auto_ops = "0.3.0"
+4 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "revolt-presence" name = "revolt-presence"
version = "0.8.6" version = "0.8.8"
edition = "2021" edition = "2021"
license = "AGPL-3.0-or-later" license = "AGPL-3.0-or-later"
authors = ["Paul Makles <me@insrt.uk>"] authors = ["Paul Makles <me@insrt.uk>"]
@@ -15,6 +15,9 @@ redis-is-patched = []
# Async # Async
async-std = { version = "1.8.0", features = ["attributes"] } async-std = { version = "1.8.0", features = ["attributes"] }
# Config for loading Redis URI
revolt-config = { version = "0.8.8", path = "../config" }
[dependencies] [dependencies]
# Utility # Utility
log = "0.4.17" log = "0.4.17"
+2
View File
@@ -197,6 +197,8 @@ mod tests {
#[async_std::test] #[async_std::test]
async fn it_works() { async fn it_works() {
revolt_config::config().await;
// Clear the region before we start the tests: // Clear the region before we start the tests:
clear_region(None).await; clear_region(None).await;
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "revolt-result" name = "revolt-result"
version = "0.8.6" version = "0.8.8"
edition = "2021" edition = "2021"
license = "MIT" license = "MIT"
authors = ["Paul Makles <me@insrt.uk>"] authors = ["Paul Makles <me@insrt.uk>"]
+5 -5
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "revolt-crond" name = "revolt-crond"
version = "0.8.6" version = "0.8.8"
license = "AGPL-3.0-or-later" license = "AGPL-3.0-or-later"
authors = ["Paul Makles <me@insrt.uk>"] authors = ["Paul Makles <me@insrt.uk>"]
edition = "2021" edition = "2021"
@@ -16,7 +16,7 @@ log = "0.4"
tokio = { version = "1" } tokio = { version = "1" }
# Core # Core
revolt-database = { version = "0.8.6", path = "../../core/database" } revolt-database = { version = "0.8.8", path = "../../core/database" }
revolt-result = { version = "0.8.6", path = "../../core/result" } revolt-result = { version = "0.8.8", path = "../../core/result" }
revolt-config = { version = "0.8.6", path = "../../core/config" } revolt-config = { version = "0.8.8", path = "../../core/config" }
revolt-files = { version = "0.8.6", path = "../../core/files" } revolt-files = { version = "0.8.8", path = "../../core/files" }
+6 -6
View File
@@ -1,19 +1,19 @@
[package] [package]
name = "revolt-pushd" name = "revolt-pushd"
version = "0.8.6" version = "0.8.8"
edition = "2021" edition = "2021"
license = "AGPL-3.0-or-later" license = "AGPL-3.0-or-later"
[dependencies] [dependencies]
revolt-result = { version = "0.8.6", path = "../../core/result" } revolt-result = { version = "0.8.8", path = "../../core/result" }
revolt-config = { version = "0.8.6", path = "../../core/config", features = [ revolt-config = { version = "0.8.8", path = "../../core/config", features = [
"report-macros", "report-macros",
] } ] }
revolt-database = { version = "0.8.6", path = "../../core/database" } revolt-database = { version = "0.8.8", path = "../../core/database" }
revolt-models = { version = "0.8.6", path = "../../core/models", features = [ revolt-models = { version = "0.8.8", path = "../../core/models", features = [
"validator", "validator",
] } ] }
revolt-presence = { version = "0.8.6", path = "../../core/presence", features = [ revolt-presence = { version = "0.8.8", path = "../../core/presence", features = [
"redis-is-patched", "redis-is-patched",
] } ] }
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "revolt-delta" name = "revolt-delta"
version = "0.8.6" version = "0.8.8"
license = "AGPL-3.0-or-later" license = "AGPL-3.0-or-later"
authors = ["Paul Makles <paulmakles@gmail.com>"] authors = ["Paul Makles <paulmakles@gmail.com>"]
edition = "2018" edition = "2018"
@@ -0,0 +1,114 @@
[
{
"_object_type": "User",
"_id": "__ID:0__",
"username": "Owner",
"last_acknowledged_policy_change": "2025-06-07T04:04:48+0000",
"discriminator": "0001"
},
{
"_object_type": "User",
"_id": "__ID:1__",
"username": "Moderator",
"last_acknowledged_policy_change": "2025-06-07T04:04:48+0000",
"discriminator": "0001"
},
{
"_object_type": "User",
"_id": "__ID:2__",
"username": "User",
"last_acknowledged_policy_change": "2025-06-07T04:04:48+0000",
"discriminator": "0001"
},
{
"_object_type": "Channel",
"_id": "__ID:3__",
"channel_type": "TextChannel",
"name": "General",
"server": "__ID:4__",
"default_permissions": {
"a": 0,
"d": 1048576
},
"role_permissions": {
"__ID:5__": {
"a": 1048576,
"d": 0
}
}
},
{
"_object_type": "Server",
"_id": "__ID:4__",
"owner": "__ID:0__",
"name": "Server",
"channels": [
"__ID:3__"
],
"roles": {
"__ID:5__": {
"name": "Moderator",
"permissions": {
"a": 545270216,
"d": 0
},
"rank": 1
},
"__ID:6__": {
"name": "Owner",
"permissions": {
"a": 0,
"d": 0
},
"rank": 0
},
"__ID:7__": {
"name": "Lower Rank 1",
"permissions": {
"a": 0,
"d": 0
},
"rank": 2
},
"__ID:8__": {
"name": "Lower Rank 2",
"permissions": {
"a": 0,
"d": 0
},
"rank": 2
}
},
"default_permissions": 4000322560
},
{
"_object_type": "ServerMember",
"_id": {
"user": "__ID:0__",
"server": "__ID:4__"
},
"roles": [
"__ID:6__"
],
"joined_at": 1698318340195
},
{
"_object_type": "ServerMember",
"_id": {
"user": "__ID:1__",
"server": "__ID:4__"
},
"roles": [
"__ID:5__"
],
"joined_at": 1698318340195
},
{
"_object_type": "ServerMember",
"_id": {
"user": "__ID:2__",
"server": "__ID:4__"
},
"joined_at": 1698318340195
}
]
+1 -1
View File
@@ -16,7 +16,7 @@ pub async fn fetch_public_bot(
target: Reference, target: Reference,
) -> Result<Json<PublicBot>> { ) -> Result<Json<PublicBot>> {
let bot = db.fetch_bot(&target.id).await?; let bot = db.fetch_bot(&target.id).await?;
if !bot.public && user.map_or(true, |x| x.id != bot.owner) { if !bot.public && user.is_none_or(|x| x.id != bot.owner) {
return Err(create_error!(NotFound)); return Err(create_error!(NotFound));
} }
@@ -84,7 +84,8 @@ pub async fn message_send(
// Create model user / members // Create model user / members
let model_user = user let model_user = user
.clone() .clone()
.into_known_static(revolt_presence::is_online(&user.id).await).await; .into_known_static(revolt_presence::is_online(&user.id).await)
.await;
let model_member: Option<v0::Member> = query let model_member: Option<v0::Member> = query
.member_ref() .member_ref()
@@ -491,7 +492,7 @@ mod test {
let (_, _, other_user) = harness.new_user().await; let (_, _, other_user) = harness.new_user().await;
let (server, _) = harness.new_server(&user).await; let (server, _) = harness.new_server(&user).await;
let channel = harness.new_channel(&server).await; let channel = harness.new_channel(&server).await;
let (role_id, mut role) = harness let (role_id, _role) = harness
.new_role( .new_role(
&server, &server,
1, 1,
@@ -41,7 +41,7 @@ pub async fn call(
// - If not, create it. // - If not, create it.
let client = reqwest::Client::new(); let client = reqwest::Client::new();
let result = client let result = client
.get(&format!( .get(format!(
"{}/room/{}", "{}/room/{}",
config.hosts.voso_legacy, config.hosts.voso_legacy,
channel.id() channel.id()
@@ -59,7 +59,7 @@ pub async fn call(
reqwest::StatusCode::OK => (), reqwest::StatusCode::OK => (),
reqwest::StatusCode::NOT_FOUND => { reqwest::StatusCode::NOT_FOUND => {
if (client if (client
.post(&format!( .post(format!(
"{}/room/{}", "{}/room/{}",
config.hosts.voso_legacy, config.hosts.voso_legacy,
channel.id() channel.id()
@@ -81,7 +81,7 @@ pub async fn call(
// Then create a user for the room. // Then create a user for the room.
if let Ok(response) = client if let Ok(response) = client
.post(&format!( .post(format!(
"{}/room/{}/user/{}", "{}/room/{}/user/{}",
config.hosts.voso_legacy, config.hosts.voso_legacy,
channel.id(), channel.id(),
+3
View File
@@ -9,6 +9,7 @@ mod channels;
mod customisation; mod customisation;
mod invites; mod invites;
mod onboard; mod onboard;
mod policy;
mod push; mod push;
mod root; mod root;
mod safety; mod safety;
@@ -36,6 +37,7 @@ pub fn mount(config: Settings, mut rocket: Rocket<Build>) -> Rocket<Build> {
"/auth/session" => rocket_authifier::routes::session::routes(), "/auth/session" => rocket_authifier::routes::session::routes(),
"/auth/mfa" => rocket_authifier::routes::mfa::routes(), "/auth/mfa" => rocket_authifier::routes::mfa::routes(),
"/onboard" => onboard::routes(), "/onboard" => onboard::routes(),
"/policy" => policy::routes(),
"/push" => push::routes(), "/push" => push::routes(),
"/sync" => sync::routes(), "/sync" => sync::routes(),
"/webhooks" => webhooks::routes() "/webhooks" => webhooks::routes()
@@ -56,6 +58,7 @@ pub fn mount(config: Settings, mut rocket: Rocket<Build>) -> Rocket<Build> {
"/auth/session" => rocket_authifier::routes::session::routes(), "/auth/session" => rocket_authifier::routes::session::routes(),
"/auth/mfa" => rocket_authifier::routes::mfa::routes(), "/auth/mfa" => rocket_authifier::routes::mfa::routes(),
"/onboard" => onboard::routes(), "/onboard" => onboard::routes(),
"/policy" => policy::routes(),
"/push" => push::routes(), "/push" => push::routes(),
"/sync" => sync::routes() "/sync" => sync::routes()
}; };
@@ -0,0 +1,13 @@
use revolt_database::{Database, User};
use revolt_result::Result;
use rocket::State;
/// # Acknowledge Policy Changes
///
/// Accept/acknowledge changes to platform policy.
#[openapi(tag = "Policy")]
#[post("/acknowledge")]
pub async fn acknowledge_policy_changes(db: &State<Database>, user: User) -> Result<()> {
db.acknowledge_policy_changes(&user.id).await
}
+11
View File
@@ -0,0 +1,11 @@
use revolt_rocket_okapi::revolt_okapi::openapi3::OpenApi;
use rocket::Route;
mod acknowledge_policy_changes;
pub fn routes() -> (Vec<Route>, OpenApi) {
openapi_get_routes_spec![
// Policy
acknowledge_policy_changes::acknowledge_policy_changes,
]
}
-1
View File
@@ -136,7 +136,6 @@ pub async fn root() -> Result<Json<RevoltConfig>> {
} }
#[cfg(test)] #[cfg(test)]
#[cfg(feature = "FIXME: THIS TEST CAUSES cargo test TO SEG FAULT, I HAVE NO CLUE HOW")]
mod test { mod test {
use crate::rocket; use crate::rocket;
use rocket::http::Status; use rocket::http::Status;
+3 -1
View File
@@ -18,6 +18,7 @@ mod roles_create;
mod roles_delete; mod roles_delete;
mod roles_edit; mod roles_edit;
mod roles_fetch; mod roles_fetch;
mod roles_edit_positions;
mod server_ack; mod server_ack;
mod server_create; mod server_create;
mod server_delete; mod server_delete;
@@ -47,6 +48,7 @@ pub fn routes() -> (Vec<Route>, OpenApi) {
roles_delete::delete, roles_delete::delete,
permissions_set::set_role_permission, permissions_set::set_role_permission,
permissions_set_default::set_default_permissions, permissions_set_default::set_default_permissions,
emoji_list::list_emoji emoji_list::list_emoji,
roles_edit_positions::edit_role_ranks
] ]
} }
+2 -10
View File
@@ -12,7 +12,7 @@ use validator::Validate;
/// ///
/// Edit a role by its id. /// Edit a role by its id.
#[openapi(tag = "Server Permissions")] #[openapi(tag = "Server Permissions")]
#[patch("/<target>/roles/<role_id>", data = "<data>")] #[patch("/<target>/roles/<role_id>", data = "<data>", rank = 1)]
pub async fn edit( pub async fn edit(
db: &State<Database>, db: &State<Database>,
user: User, user: User,
@@ -45,22 +45,14 @@ pub async fn edit(
name, name,
colour, colour,
hoist, hoist,
rank,
remove, remove,
..
} = data; } = data;
// Prevent us from moving a role above other roles
if let Some(rank) = &rank {
if rank <= &member_rank {
return Err(create_error!(NotElevated));
}
}
let partial = PartialRole { let partial = PartialRole {
name, name,
colour, colour,
hoist, hoist,
rank,
..Default::default() ..Default::default()
}; };
@@ -0,0 +1,177 @@
use revolt_database::{
util::{permissions::DatabasePermissionQuery, reference::Reference},
Database, User,
};
use revolt_models::v0;
use revolt_permissions::{calculate_server_permissions, ChannelPermission};
use revolt_result::{create_error, Result};
use rocket::{serde::json::Json, State};
/// # Edits server roles ranks
///
/// Edit's server role's ranks.
#[openapi(tag = "Server Permissions")]
#[patch("/<target>/roles/ranks", data = "<data>")]
pub async fn edit_role_ranks(
db: &State<Database>,
user: User,
target: Reference,
data: Json<v0::DataEditRoleRanks>,
) -> Result<Json<v0::Server>> {
let data = data.into_inner();
let mut server = target.as_server(db).await?;
let mut query = DatabasePermissionQuery::new(db, &user).server(&server);
calculate_server_permissions(&mut query)
.await
.throw_if_lacking_channel_permission(ChannelPermission::ManageRole)?;
let existing_order = server
.ordered_roles()
.into_iter()
.map(|(id, _)| id)
.collect::<Vec<_>>();
let new_order = data.ranks.clone().into_iter().collect::<Vec<_>>();
// Verify all roles are in the new ordering
if data.ranks.len() != server.roles.len()
|| !server.roles.iter().all(|(id, _)| data.ranks.contains(id))
{
return Err(create_error!(InvalidOperation));
}
// Don't have to check what the user can't modify if they are the server owner
if server.owner != user.id {
let member_top_rank = query.get_member_rank();
if server
.roles
.iter()
// Find all roles above the member which we should not be able to reorder
.filter(|(_, role)| {
if let Some(top_rank) = member_top_rank {
role.rank <= top_rank
} else {
true
}
})
// Check if user is trying to reorder roles they can't reorder (as found previously)
.any(|(id, _)| {
existing_order
.iter()
.position(|existing_id| id == existing_id)
!= new_order.iter().position(|new_id| id == new_id)
})
{
return Err(create_error!(NotElevated));
}
}
server.set_role_ordering(db, new_order).await?;
Ok(Json(server.into()))
}
#[cfg(test)]
mod test {
use revolt_database::fixture;
use revolt_models::v0;
use rocket::http::{ContentType, Header, Status};
use crate::util::test::TestHarness;
#[rocket::async_test]
async fn edit_role_rankings() {
let harness = TestHarness::new().await;
fixture!(harness.db, "server_with_many_roles",
owner user 0
moderator user 1
server server 4);
// Moderator can re-order the roles below them
let (_, moderator_session) = harness.account_from_user(moderator.id).await;
let mut target_order: Vec<String> = server
.ordered_roles()
.into_iter()
.map(|(id, _)| id)
.collect();
// Swap the two lower ranked roles
target_order.swap(2, 3);
let response = harness
.client
.patch(format!("/servers/{}/roles/ranks", server.id))
.header(ContentType::JSON)
.body(
json!(v0::DataEditRoleRanks {
ranks: target_order.clone()
})
.to_string(),
)
.header(Header::new(
"x-session-token",
moderator_session.token.to_string(),
))
.dispatch()
.await;
assert_eq!(response.status(), Status::Ok);
drop(response);
// ... but not above them
let mut target_order: Vec<String> = server
.ordered_roles()
.into_iter()
.map(|(id, _)| id)
.collect();
// Swap the two lower ranked roles
target_order.swap(0, 1);
let response = harness
.client
.patch(format!("/servers/{}/roles/ranks", server.id))
.header(ContentType::JSON)
.body(
json!(v0::DataEditRoleRanks {
ranks: target_order.clone()
})
.to_string(),
)
.header(Header::new(
"x-session-token",
moderator_session.token.to_string(),
))
.dispatch()
.await;
assert_eq!(response.status(), Status::Forbidden);
drop(response);
// The owner can set any order they want
let (_, owner_session) = harness.account_from_user(owner.id).await;
let response = harness
.client
.patch(format!("/servers/{}/roles/ranks", server.id))
.header(ContentType::JSON)
.body(
json!(v0::DataEditRoleRanks {
ranks: target_order.clone()
})
.to_string(),
)
.header(Header::new(
"x-session-token",
owner_session.token.to_string(),
))
.dispatch()
.await;
assert_eq!(response.status(), Status::Ok);
drop(response);
}
}
@@ -36,11 +36,11 @@ pub async fn webhook_execute(
let permissions: PermissionValue = webhook.permissions.into(); let permissions: PermissionValue = webhook.permissions.into();
permissions.throw_if_lacking_channel_permission(ChannelPermission::SendMessage)?; permissions.throw_if_lacking_channel_permission(ChannelPermission::SendMessage)?;
if data.attachments.as_ref().map_or(false, |v| !v.is_empty()) { if data.attachments.as_ref().is_some_and(|v| !v.is_empty()) {
permissions.throw_if_lacking_channel_permission(ChannelPermission::UploadFiles)?; permissions.throw_if_lacking_channel_permission(ChannelPermission::UploadFiles)?;
} }
if data.embeds.as_ref().map_or(false, |v| !v.is_empty()) { if data.embeds.as_ref().is_some_and(|v| !v.is_empty()) {
permissions.throw_if_lacking_channel_permission(ChannelPermission::SendEmbeds)?; permissions.throw_if_lacking_channel_permission(ChannelPermission::SendEmbeds)?;
} }
@@ -621,7 +621,7 @@ pub struct Event {
#[derive(Debug, JsonSchema)] #[derive(Debug, JsonSchema)]
pub struct EventHeader<'r>(pub &'r str); pub struct EventHeader<'r>(pub &'r str);
impl<'r> std::ops::Deref for EventHeader<'r> { impl std::ops::Deref for EventHeader<'_> {
type Target = str; type Target = str;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
+1 -3
View File
@@ -109,8 +109,6 @@ fn resolve_bucket<'r>(request: &'r rocket::Request<'_>) -> (&'r str, Option<&'r
}; };
if let Some(segment) = segment { if let Some(segment) = segment {
let resource = resource;
let method = request.method(); let method = request.method();
match (segment, resource, method) { match (segment, resource, method) {
("users", target, Method::Patch) => ("user_edit", target), ("users", target, Method::Patch) => ("user_edit", target),
@@ -254,7 +252,7 @@ impl<'r> FromRequest<'r> for Ratelimiter {
} }
} }
impl<'r> OpenApiFromRequest<'r> for Ratelimiter { impl OpenApiFromRequest<'_> for Ratelimiter {
fn from_request_input( fn from_request_input(
_gen: &mut OpenApiGenerator, _gen: &mut OpenApiGenerator,
_name: String, _name: String,
+31 -23
View File
@@ -1,5 +1,5 @@
use authifier::{ use authifier::{
models::{Account, Session}, models::{Account, EmailVerification, Session},
Authifier, Authifier,
}; };
use futures::StreamExt; use futures::StreamExt;
@@ -83,30 +83,41 @@ impl TestHarness {
} }
pub async fn new_user(&self) -> (Account, Session, User) { pub async fn new_user(&self) -> (Account, Session, User) {
let account = Account::new( let user = User::create(&self.db, TestHarness::rand_string(), None, None)
&self.authifier, .await
format!("{}@revolt.chat", TestHarness::rand_string()), .expect("`User`");
"password".to_string(),
false, let (account, session) = self.account_from_user(user.id.clone()).await;
)
.await (account, session, user)
.expect("`Account`"); }
pub async fn account_from_user(&self, id: String) -> (Account, Session) {
let account = Account {
id,
email: format!("{}@revolt.chat", TestHarness::rand_string()),
password: Default::default(),
email_normalised: Default::default(),
deletion: None,
disabled: false,
lockout: None,
mfa: Default::default(),
password_reset: None,
verification: EmailVerification::Verified,
};
self.authifier
.database
.save_account(&account)
.await
.expect("`Account`");
let session = account let session = account
.create_session(&self.authifier, String::new()) .create_session(&self.authifier, String::new())
.await .await
.expect("`Session`"); .expect("`Session`");
let user = User::create( (account, session)
&self.db,
TestHarness::rand_string(),
account.id.to_string(),
None,
)
.await
.expect("`User`");
(account, session, user)
} }
pub async fn new_server(&self, user: &User) -> (Server, Vec<Channel>) { pub async fn new_server(&self, user: &User) -> (Server, Vec<Channel>) {
@@ -198,10 +209,7 @@ impl TestHarness {
(channel.clone(), member, message) (channel.clone(), member, message)
} }
pub async fn with_session<'c>( pub async fn with_session(session: Session, request: LocalRequest<'_>) -> LocalResponse<'_> {
session: Session,
request: LocalRequest<'c>,
) -> LocalResponse<'c> {
request request
.header(Header::new("x-session-token", session.token.to_string())) .header(Header::new("x-session-token", session.token.to_string()))
.dispatch() .dispatch()
+5 -5
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "revolt-autumn" name = "revolt-autumn"
version = "0.8.6" version = "0.8.8"
edition = "2021" edition = "2021"
license = "AGPL-3.0-or-later" license = "AGPL-3.0-or-later"
@@ -43,12 +43,12 @@ tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] } tracing-subscriber = { version = "0.3", features = ["env-filter"] }
# Core crates # Core crates
revolt-files = { version = "0.8.6", path = "../../core/files" } revolt-files = { version = "0.8.8", path = "../../core/files" }
revolt-config = { version = "0.8.6", path = "../../core/config" } revolt-config = { version = "0.8.8", path = "../../core/config" }
revolt-database = { version = "0.8.6", path = "../../core/database", features = [ revolt-database = { version = "0.8.8", path = "../../core/database", features = [
"axum-impl", "axum-impl",
] } ] }
revolt-result = { version = "0.8.6", path = "../../core/result", features = [ revolt-result = { version = "0.8.8", path = "../../core/result", features = [
"utoipa", "utoipa",
"axum", "axum",
] } ] }
+5 -5
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "revolt-january" name = "revolt-january"
version = "0.8.6" version = "0.8.8"
edition = "2021" edition = "2021"
license = "AGPL-3.0-or-later" license = "AGPL-3.0-or-later"
@@ -32,13 +32,13 @@ tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] } tracing-subscriber = { version = "0.3", features = ["env-filter"] }
# Core crates # Core crates
revolt-config = { version = "0.8.6", path = "../../core/config" } revolt-config = { version = "0.8.8", path = "../../core/config" }
revolt-models = { version = "0.8.6", path = "../../core/models" } revolt-models = { version = "0.8.8", path = "../../core/models" }
revolt-result = { version = "0.8.6", path = "../../core/result", features = [ revolt-result = { version = "0.8.8", path = "../../core/result", features = [
"utoipa", "utoipa",
"axum", "axum",
] } ] }
revolt-files = { version = "0.8.6", path = "../../core/files" } revolt-files = { version = "0.8.8", path = "../../core/files" }
# Axum / web server # Axum / web server
axum = { version = "0.7.5" } axum = { version = "0.7.5" }
+1 -1
View File
@@ -327,7 +327,7 @@ pub async fn populate_special(original_url: String, metadata: &mut WebsiteMetada
Special::Twitch { .. } => metadata.colour = Some("#7B68EE".to_string()), Special::Twitch { .. } => metadata.colour = Some("#7B68EE".to_string()),
Special::Lightspeed { .. } => metadata.colour = Some("#7445D9".to_string()), Special::Lightspeed { .. } => metadata.colour = Some("#7445D9".to_string()),
Special::Spotify { .. } => metadata.colour = Some("#1ABC9C".to_string()), Special::Spotify { .. } => metadata.colour = Some("#1ABC9C".to_string()),
Special::Soundcloud { .. } => metadata.colour = Some("#FF7F50".to_string()), Special::Soundcloud => metadata.colour = Some("#FF7F50".to_string()),
Special::AppleMusic { .. } => metadata.colour = Some("#FA233B".to_string()), Special::AppleMusic { .. } => metadata.colour = Some("#FA233B".to_string()),
_ => {} _ => {}
} }
+1 -1
View File
@@ -1,7 +1,7 @@
publish: publish:
cargo publish --package revolt-parser cargo publish --package revolt-parser
cargo publish --package revolt-config
cargo publish --package revolt-result cargo publish --package revolt-result
cargo publish --package revolt-config
cargo publish --package revolt-files cargo publish --package revolt-files
cargo publish --package revolt-permissions cargo publish --package revolt-permissions
cargo publish --package revolt-models cargo publish --package revolt-models