Compare commits

...

19 Commits

Author SHA1 Message Date
higgs01
4f54227495 chore: use mc alias set instead of removed mc config (#423) 2025-07-18 09:28:31 +01:00
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
51 changed files with 2094 additions and 1189 deletions

2550
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -11,6 +11,8 @@ members = [
[patch.crates-io]
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
# hence builds have been failing since, let's just

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:
>
> ```toml
> # Revolt.overrides.toml
> # Revolt.overrides.toml
> # and Revolt.test-overrides.toml
> [database]
> mongodb = "mongodb://127.0.0.1:14017"
> redis = "redis://127.0.0.1:14079/"

View File

@@ -34,7 +34,7 @@ services:
- minio
entrypoint: >
/bin/sh -c "while ! /usr/bin/mc ready minio; do
/usr/bin/mc config host add minio http://minio:9000 minioautumn minioautumn;
/usr/bin/mc alias set minio http://minio:9000 minioautumn minioautumn;
echo 'Waiting minio...' && sleep 1;
done; /usr/bin/mc mb minio/revolt-uploads; exit 0;"

View File

@@ -1,6 +1,6 @@
[package]
name = "revolt-bonfire"
version = "0.8.7"
version = "0.8.8"
license = "AGPL-3.0-or-later"
edition = "2021"
@@ -41,7 +41,7 @@ revolt-result = { path = "../core/result" }
revolt-models = { path = "../core/models" }
revolt-config = { path = "../core/config" }
revolt-database = { path = "../core/database" }
revolt-permissions = { version = "0.8.7", path = "../core/permissions" }
revolt-permissions = { version = "0.8.8", path = "../core/permissions" }
revolt-presence = { path = "../core/presence", features = ["redis-is-patched"] }
# redis

View File

@@ -17,6 +17,7 @@ use redis_kiss::{PayloadType, REDIS_PAYLOAD_TYPE, REDIS_URI};
use revolt_config::report_internal_error;
use revolt_database::{
events::{client::EventV1, server::ClientMessage},
iso8601_timestamp::Timestamp,
Database, User, UserHint,
};
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);
db.update_session_last_seen(&session_id, Timestamp::now_utc())
.await
.ok();
// Create local state.
let mut state = State::from(user, session_id);
let user_id = state.cache.user_id.clone();

View File

@@ -1,6 +1,6 @@
[package]
name = "revolt-config"
version = "0.8.7"
version = "0.8.8"
edition = "2021"
license = "MIT"
authors = ["Paul Makles <me@insrt.uk>"]
@@ -36,4 +36,4 @@ sentry = "0.31.5"
sentry-anyhow = { version = "0.38.1", optional = true }
# Core
revolt-result = { version = "0.8.7", path = "../result", optional = true }
revolt-result = { version = "0.8.8", path = "../result", optional = true }

View File

@@ -60,6 +60,9 @@ static CONFIG_SEARCH_PATHS: [&str; 3] = [
"/Revolt.toml",
];
/// Path to search for test overrides
static TEST_OVERRIDE_PATH: &str = "Revolt.test-overrides.toml";
/// Configuration builder
static CONFIG_BUILDER: Lazy<RwLock<Config>> = Lazy::new(|| {
RwLock::new({
@@ -73,6 +76,20 @@ static CONFIG_BUILDER: Lazy<RwLock<Config>> = Lazy::new(|| {
include_str!("../Revolt.test.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 {
@@ -388,6 +405,11 @@ pub async fn read() -> Config {
pub async fn config() -> Settings {
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
if config.hosts.api.contains("https") && config.hosts.api.contains("revolt.chat") {
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");
}
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();
log::info!("Starting {release}");

View File

@@ -1,6 +1,6 @@
[package]
name = "revolt-database"
version = "0.8.7"
version = "0.8.8"
edition = "2021"
license = "AGPL-3.0-or-later"
authors = ["Paul Makles <me@insrt.uk>"]
@@ -24,19 +24,19 @@ default = ["mongodb", "async-std-runtime", "tasks"]
[dependencies]
# Core
revolt-config = { version = "0.8.7", path = "../config", features = [
revolt-config = { version = "0.8.8", path = "../config", features = [
"report-macros",
] }
revolt-result = { version = "0.8.7", path = "../result" }
revolt-models = { version = "0.8.7", path = "../models", features = [
revolt-result = { version = "0.8.8", path = "../result" }
revolt-models = { version = "0.8.8", path = "../models", features = [
"validator",
] }
revolt-presence = { version = "0.8.7", path = "../presence" }
revolt-permissions = { version = "0.8.7", path = "../permissions", features = [
revolt-presence = { version = "0.8.8", path = "../presence" }
revolt-permissions = { version = "0.8.8", path = "../permissions", features = [
"serde",
"bson",
] }
revolt-parser = { version = "0.8.7", path = "../parser" }
revolt-parser = { version = "0.8.8", path = "../parser" }
# Utility
log = "0.4"

View File

@@ -3,18 +3,21 @@
"_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": "Member",
"last_acknowledged_policy_change": "2025-06-07T04:04:48+0000",
"discriminator": "0001"
},
{
"_object_type": "User",
"_id": "__ID:2__",
"username": "Member",
"last_acknowledged_policy_change": "2025-06-07T04:04:48+0000",
"discriminator": "0002"
},
{
@@ -23,6 +26,9 @@
"channel_type": "Group",
"name": "My Group",
"owner": "__ID:0__",
"recipients": ["__ID:0__", "__ID:1__"]
"recipients": [
"__ID:0__",
"__ID:1__"
]
}
]
]

View File

@@ -3,18 +3,21 @@
"_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"
},
{
@@ -39,7 +42,9 @@
"_id": "__ID:4__",
"owner": "__ID:0__",
"name": "Server",
"channels": ["__ID:3__"],
"channels": [
"__ID:3__"
],
"roles": {
"__ID:5__": {
"name": "Moderator",
@@ -47,7 +52,7 @@
"a": 545270208,
"d": 0
},
"rank": 3
"rank": 1
},
"__ID:6__": {
"name": "Owner",
@@ -66,7 +71,9 @@
"user": "__ID:0__",
"server": "__ID:4__"
},
"roles": ["__ID:6__"],
"roles": [
"__ID:6__"
],
"joined_at": 1698318340195
},
{
@@ -75,7 +82,9 @@
"user": "__ID:1__",
"server": "__ID:4__"
},
"roles": ["__ID:5__"],
"roles": [
"__ID:5__"
],
"joined_at": 1698318340195
},
{
@@ -86,4 +95,4 @@
},
"joined_at": 1698318340195
}
]
]

View File

@@ -165,6 +165,9 @@ pub enum EventV1 {
/// Server role deleted
ServerRoleDelete { id: String, role_id: String },
/// Server roles ranks updated
ServerRoleRanksUpdate { id: String, ranks: Vec<String> },
/// Update existing user
UserUpdate {
id: String,

View File

@@ -1,4 +1,8 @@
use std::{collections::HashSet, ops::BitXor, time::Duration};
use std::{
collections::{HashMap, HashSet},
ops::BitXor,
time::Duration,
};
use crate::{
mongodb::{
@@ -22,7 +26,7 @@ struct MigrationInfo {
revision: i32,
}
pub const LATEST_REVISION: i32 = 41; // 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) {
let migrations = db.col::<Document>("migrations");
@@ -1165,6 +1169,63 @@ pub async fn run_migrations(db: &MongoDb, revision: i32) -> i32 {
.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.
LATEST_REVISION.max(revision)
}

View File

@@ -181,7 +181,7 @@ impl Server {
}
/// Update server data
pub async fn update<'a>(
pub async fn update(
&mut self,
db: &Database,
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
pub async fn set_role_permission(
&mut self,
@@ -253,6 +260,37 @@ impl Server {
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 {

View File

@@ -7,11 +7,5 @@ mod rocket;
#[cfg(feature = "rocket-impl")]
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 ops::*;

View File

@@ -1,4 +1,5 @@
use authifier::models::Session;
use iso8601_timestamp::Timestamp;
use revolt_result::Result;
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)
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<()>;
}

View File

@@ -1,6 +1,7 @@
use ::mongodb::options::{Collation, CollationStrength, FindOneOptions, FindOptions};
use authifier::models::Session;
use futures::StreamExt;
use iso8601_timestamp::Timestamp;
use revolt_result::Result;
use crate::DocumentId;
@@ -317,7 +318,26 @@ impl AbstractUsers for MongoDb {
)
.await
.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"))
}
}

View File

@@ -1,4 +1,5 @@
use authifier::models::Session;
use iso8601_timestamp::Timestamp;
use revolt_result::Result;
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<()> {
todo!()
}
async fn update_session_last_seen(&self, _session_id: &str, _when: Timestamp) -> Result<()> {
todo!()
}
}

View File

@@ -4,7 +4,7 @@ use once_cell::sync::Lazy;
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
pub fn sender() -> Sender<AuthifierEvent> {

View File

@@ -15,8 +15,7 @@ impl crate::Bot {
avatar: user.avatar.map(|x| x.id).unwrap_or_default(),
description: user
.profile
.map(|profile| profile.content)
.flatten()
.and_then(|profile| profile.content)
.unwrap_or_default(),
}
}
@@ -1114,7 +1113,7 @@ impl crate::User {
}
/// 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;
User {

View File

@@ -54,7 +54,7 @@ use revolt_rocket_okapi::{
use schemars::schema::{InstanceType, SchemaObject, SingleOrVec};
#[cfg(feature = "rocket-impl")]
impl<'r> OpenApiFromRequest<'r> for IdempotencyKey {
impl OpenApiFromRequest<'_> for IdempotencyKey {
fn from_request_input(
_gen: &mut OpenApiGenerator,
_name: String,

View File

@@ -104,7 +104,7 @@ impl PermissionQuery for DatabasePermissionQuery<'_> {
.unwrap_or_default();
self.cached_mutual_connection = Some(value);
matches!(value, true)
value
} else {
false
}

View File

@@ -1,6 +1,6 @@
[package]
name = "revolt-files"
version = "0.8.7"
version = "0.8.8"
edition = "2021"
license = "AGPL-3.0-or-later"
authors = ["Paul Makles <me@insrt.uk>"]
@@ -20,10 +20,10 @@ typenum = "1.17.0"
aws-config = "1.5.5"
aws-sdk-s3 = { version = "1.46.0", features = ["behavior-version-latest"] }
revolt-config = { version = "0.8.7", path = "../config", features = [
revolt-config = { version = "0.8.8", path = "../config", features = [
"report-macros",
] }
revolt-result = { version = "0.8.7", path = "../result" }
revolt-result = { version = "0.8.8", path = "../result" }
# image processing
jxl-oxide = "0.8.1"

View File

@@ -1,6 +1,6 @@
[package]
name = "revolt-models"
version = "0.8.7"
version = "0.8.8"
edition = "2021"
license = "MIT"
authors = ["Paul Makles <me@insrt.uk>"]
@@ -20,8 +20,8 @@ default = ["serde", "partials", "rocket"]
[dependencies]
# Core
revolt-config = { version = "0.8.7", path = "../config" }
revolt-permissions = { version = "0.8.7", path = "../permissions" }
revolt-config = { version = "0.8.8", path = "../config" }
revolt-permissions = { version = "0.8.8", path = "../permissions" }
# Utility
regex = "1.11"

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,
/// 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.
pub fn name(&self) -> Result<&str, ()> {
/// If it returns None, you need to fetch the name from the db.
pub fn name(&self) -> Option<&str> {
match self {
Channel::DirectMessage { .. } => Err(()),
Channel::SavedMessages { .. } => Ok("Saved Messages"),
Channel::DirectMessage { .. } => None,
Channel::SavedMessages { .. } => Some("Saved Messages"),
Channel::TextChannel { name, .. }
| Channel::Group { name, .. }
| Channel::VoiceChannel { name, .. } => Ok(name),
| Channel::VoiceChannel { name, .. } => Some(name),
}
}
}

View File

@@ -267,7 +267,7 @@ auto_derived!(
pub hoist: Option<bool>,
/// Ranking position
///
/// Smaller values take priority.
/// **Removed** - no effect, use the edit server role positions route
pub rank: Option<i64>,
/// Fields to remove from role object
#[cfg_attr(feature = "validator", validate(length(min = 1)))]
@@ -286,4 +286,9 @@ auto_derived!(
/// Whether to not send a leave message
pub leave_silently: Option<bool>,
}
/// New role positions
pub struct DataEditRoleRanks {
pub ranks: Vec<String>,
}
);

View File

@@ -1,6 +1,6 @@
[package]
name = "revolt-parser"
version = "0.8.7"
version = "0.8.8"
edition = "2021"
license = "AGPL-3.0-or-later"
description = "Revolt Backend: Message Parser"

View File

@@ -1,6 +1,6 @@
[package]
name = "revolt-permissions"
version = "0.8.7"
version = "0.8.8"
edition = "2021"
license = "MIT"
authors = ["Paul Makles <me@insrt.uk>"]
@@ -21,7 +21,7 @@ async-std = { version = "1.8.0", features = ["attributes"] }
[dependencies]
# Core
revolt-result = { version = "0.8.7", path = "../result" }
revolt-result = { version = "0.8.8", path = "../result" }
# Utility
auto_ops = "0.3.0"

View File

@@ -1,6 +1,6 @@
[package]
name = "revolt-presence"
version = "0.8.7"
version = "0.8.8"
edition = "2021"
license = "AGPL-3.0-or-later"
authors = ["Paul Makles <me@insrt.uk>"]
@@ -15,6 +15,9 @@ redis-is-patched = []
# Async
async-std = { version = "1.8.0", features = ["attributes"] }
# Config for loading Redis URI
revolt-config = { version = "0.8.8", path = "../config" }
[dependencies]
# Utility
log = "0.4.17"

View File

@@ -197,6 +197,8 @@ mod tests {
#[async_std::test]
async fn it_works() {
revolt_config::config().await;
// Clear the region before we start the tests:
clear_region(None).await;

View File

@@ -1,6 +1,6 @@
[package]
name = "revolt-result"
version = "0.8.7"
version = "0.8.8"
edition = "2021"
license = "MIT"
authors = ["Paul Makles <me@insrt.uk>"]

View File

@@ -1,6 +1,6 @@
[package]
name = "revolt-crond"
version = "0.8.7"
version = "0.8.8"
license = "AGPL-3.0-or-later"
authors = ["Paul Makles <me@insrt.uk>"]
edition = "2021"
@@ -16,7 +16,7 @@ log = "0.4"
tokio = { version = "1" }
# Core
revolt-database = { version = "0.8.7", path = "../../core/database" }
revolt-result = { version = "0.8.7", path = "../../core/result" }
revolt-config = { version = "0.8.7", path = "../../core/config" }
revolt-files = { version = "0.8.7", path = "../../core/files" }
revolt-database = { version = "0.8.8", path = "../../core/database" }
revolt-result = { version = "0.8.8", path = "../../core/result" }
revolt-config = { version = "0.8.8", path = "../../core/config" }
revolt-files = { version = "0.8.8", path = "../../core/files" }

View File

@@ -1,19 +1,19 @@
[package]
name = "revolt-pushd"
version = "0.8.7"
version = "0.8.8"
edition = "2021"
license = "AGPL-3.0-or-later"
[dependencies]
revolt-result = { version = "0.8.7", path = "../../core/result" }
revolt-config = { version = "0.8.7", path = "../../core/config", features = [
revolt-result = { version = "0.8.8", path = "../../core/result" }
revolt-config = { version = "0.8.8", path = "../../core/config", features = [
"report-macros",
] }
revolt-database = { version = "0.8.7", path = "../../core/database" }
revolt-models = { version = "0.8.7", path = "../../core/models", features = [
revolt-database = { version = "0.8.8", path = "../../core/database" }
revolt-models = { version = "0.8.8", path = "../../core/models", features = [
"validator",
] }
revolt-presence = { version = "0.8.7", path = "../../core/presence", features = [
revolt-presence = { version = "0.8.8", path = "../../core/presence", features = [
"redis-is-patched",
] }

View File

@@ -1,6 +1,6 @@
[package]
name = "revolt-delta"
version = "0.8.7"
version = "0.8.8"
license = "AGPL-3.0-or-later"
authors = ["Paul Makles <paulmakles@gmail.com>"]
edition = "2018"

View File

@@ -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
}
]

View File

@@ -16,7 +16,7 @@ pub async fn fetch_public_bot(
target: Reference,
) -> Result<Json<PublicBot>> {
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));
}

View File

@@ -84,7 +84,8 @@ pub async fn message_send(
// Create model user / members
let model_user = user
.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
.member_ref()
@@ -491,7 +492,7 @@ mod test {
let (_, _, other_user) = harness.new_user().await;
let (server, _) = harness.new_server(&user).await;
let channel = harness.new_channel(&server).await;
let (role_id, mut role) = harness
let (role_id, _role) = harness
.new_role(
&server,
1,

View File

@@ -41,7 +41,7 @@ pub async fn call(
// - If not, create it.
let client = reqwest::Client::new();
let result = client
.get(&format!(
.get(format!(
"{}/room/{}",
config.hosts.voso_legacy,
channel.id()
@@ -59,7 +59,7 @@ pub async fn call(
reqwest::StatusCode::OK => (),
reqwest::StatusCode::NOT_FOUND => {
if (client
.post(&format!(
.post(format!(
"{}/room/{}",
config.hosts.voso_legacy,
channel.id()
@@ -81,7 +81,7 @@ pub async fn call(
// Then create a user for the room.
if let Ok(response) = client
.post(&format!(
.post(format!(
"{}/room/{}/user/{}",
config.hosts.voso_legacy,
channel.id(),

View File

@@ -1,11 +1,7 @@
use revolt_database::{events::client::EventV1, Database, Report, Snapshot, SnapshotContent, User};
use revolt_models::v0::{ReportStatus, ReportedContent};
use revolt_result::{create_error, Result};
use serde::Deserialize;
use ulid::Ulid;
use validator::Validate;
use revolt_database::{Database, User};
use revolt_result::Result;
use rocket::{serde::json::Json, State};
use rocket::State;
/// # Acknowledge Policy Changes
///

View File

@@ -136,7 +136,6 @@ pub async fn root() -> Result<Json<RevoltConfig>> {
}
#[cfg(test)]
#[cfg(feature = "FIXME: THIS TEST CAUSES cargo test TO SEG FAULT, I HAVE NO CLUE HOW")]
mod test {
use crate::rocket;
use rocket::http::Status;

View File

@@ -18,6 +18,7 @@ mod roles_create;
mod roles_delete;
mod roles_edit;
mod roles_fetch;
mod roles_edit_positions;
mod server_ack;
mod server_create;
mod server_delete;
@@ -47,6 +48,7 @@ pub fn routes() -> (Vec<Route>, OpenApi) {
roles_delete::delete,
permissions_set::set_role_permission,
permissions_set_default::set_default_permissions,
emoji_list::list_emoji
emoji_list::list_emoji,
roles_edit_positions::edit_role_ranks
]
}

View File

@@ -12,7 +12,7 @@ use validator::Validate;
///
/// Edit a role by its id.
#[openapi(tag = "Server Permissions")]
#[patch("/<target>/roles/<role_id>", data = "<data>")]
#[patch("/<target>/roles/<role_id>", data = "<data>", rank = 1)]
pub async fn edit(
db: &State<Database>,
user: User,
@@ -45,22 +45,14 @@ pub async fn edit(
name,
colour,
hoist,
rank,
remove,
..
} = 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 {
name,
colour,
hoist,
rank,
..Default::default()
};

View File

@@ -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);
}
}

View File

@@ -36,11 +36,11 @@ pub async fn webhook_execute(
let permissions: PermissionValue = webhook.permissions.into();
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)?;
}
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)?;
}

View File

@@ -621,7 +621,7 @@ pub struct Event {
#[derive(Debug, JsonSchema)]
pub struct EventHeader<'r>(pub &'r str);
impl<'r> std::ops::Deref for EventHeader<'r> {
impl std::ops::Deref for EventHeader<'_> {
type Target = str;
fn deref(&self) -> &Self::Target {

View File

@@ -109,8 +109,6 @@ fn resolve_bucket<'r>(request: &'r rocket::Request<'_>) -> (&'r str, Option<&'r
};
if let Some(segment) = segment {
let resource = resource;
let method = request.method();
match (segment, resource, method) {
("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(
_gen: &mut OpenApiGenerator,
_name: String,

View File

@@ -1,5 +1,5 @@
use authifier::{
models::{Account, Session},
models::{Account, EmailVerification, Session},
Authifier,
};
use futures::StreamExt;
@@ -83,30 +83,41 @@ impl TestHarness {
}
pub async fn new_user(&self) -> (Account, Session, User) {
let account = Account::new(
&self.authifier,
format!("{}@revolt.chat", TestHarness::rand_string()),
"password".to_string(),
false,
)
.await
.expect("`Account`");
let user = User::create(&self.db, TestHarness::rand_string(), None, None)
.await
.expect("`User`");
let (account, session) = self.account_from_user(user.id.clone()).await;
(account, session, user)
}
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
.create_session(&self.authifier, String::new())
.await
.expect("`Session`");
let user = User::create(
&self.db,
TestHarness::rand_string(),
account.id.to_string(),
None,
)
.await
.expect("`User`");
(account, session, user)
(account, session)
}
pub async fn new_server(&self, user: &User) -> (Server, Vec<Channel>) {
@@ -198,10 +209,7 @@ impl TestHarness {
(channel.clone(), member, message)
}
pub async fn with_session<'c>(
session: Session,
request: LocalRequest<'c>,
) -> LocalResponse<'c> {
pub async fn with_session(session: Session, request: LocalRequest<'_>) -> LocalResponse<'_> {
request
.header(Header::new("x-session-token", session.token.to_string()))
.dispatch()

View File

@@ -1,6 +1,6 @@
[package]
name = "revolt-autumn"
version = "0.8.7"
version = "0.8.8"
edition = "2021"
license = "AGPL-3.0-or-later"
@@ -43,12 +43,12 @@ tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
# Core crates
revolt-files = { version = "0.8.7", path = "../../core/files" }
revolt-config = { version = "0.8.7", path = "../../core/config" }
revolt-database = { version = "0.8.7", path = "../../core/database", features = [
revolt-files = { version = "0.8.8", path = "../../core/files" }
revolt-config = { version = "0.8.8", path = "../../core/config" }
revolt-database = { version = "0.8.8", path = "../../core/database", features = [
"axum-impl",
] }
revolt-result = { version = "0.8.7", path = "../../core/result", features = [
revolt-result = { version = "0.8.8", path = "../../core/result", features = [
"utoipa",
"axum",
] }

View File

@@ -1,6 +1,6 @@
[package]
name = "revolt-january"
version = "0.8.7"
version = "0.8.8"
edition = "2021"
license = "AGPL-3.0-or-later"
@@ -32,13 +32,13 @@ tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
# Core crates
revolt-config = { version = "0.8.7", path = "../../core/config" }
revolt-models = { version = "0.8.7", path = "../../core/models" }
revolt-result = { version = "0.8.7", path = "../../core/result", features = [
revolt-config = { version = "0.8.8", path = "../../core/config" }
revolt-models = { version = "0.8.8", path = "../../core/models" }
revolt-result = { version = "0.8.8", path = "../../core/result", features = [
"utoipa",
"axum",
] }
revolt-files = { version = "0.8.7", path = "../../core/files" }
revolt-files = { version = "0.8.8", path = "../../core/files" }
# Axum / web server
axum = { version = "0.7.5" }

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::Lightspeed { .. } => metadata.colour = Some("#7445D9".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()),
_ => {}
}

View File

@@ -1,7 +1,7 @@
publish:
cargo publish --package revolt-parser
cargo publish --package revolt-config
cargo publish --package revolt-result
cargo publish --package revolt-config
cargo publish --package revolt-files
cargo publish --package revolt-permissions
cargo publish --package revolt-models