forked from jmug/stoatchat
merge: branch 'master' into insert/feat/user-safety-api
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "revolt-quark"
|
||||
version = "0.1.0"
|
||||
version = "0.5.7"
|
||||
license = "AGPL-3.0-or-later"
|
||||
edition = "2021"
|
||||
|
||||
@@ -16,9 +16,9 @@ rocket_impl = [
|
||||
"lru",
|
||||
"dashmap",
|
||||
|
||||
"rauth/database-mongodb",
|
||||
"rauth/rocket_impl",
|
||||
"rauth/okapi_impl"
|
||||
"authifier/database-mongodb",
|
||||
"authifier/rocket_impl",
|
||||
"authifier/okapi_impl"
|
||||
]
|
||||
|
||||
test = [ "async-std", "mongo", "mongodb/async-std-runtime", "rocket_impl" ]
|
||||
@@ -38,10 +38,8 @@ bson = { version = "2.1.0", features = ["chrono-0_4"] }
|
||||
|
||||
# Spec Generation
|
||||
schemars = "0.8.8"
|
||||
okapi = { git = "https://github.com/insertish/okapi", rev = "a1048d0c8cd771e424ec97d33d825c32e06aa120" }
|
||||
rocket_okapi = { git = "https://github.com/insertish/okapi", rev = "a1048d0c8cd771e424ec97d33d825c32e06aa120" }
|
||||
# okapi = "0.7.0-rc.1"
|
||||
# rocket_okapi = "0.8.0-rc.1"
|
||||
revolt_okapi = "0.9.1"
|
||||
revolt_rocket_okapi = { version = "0.9.1", features = [ "swagger" ] }
|
||||
|
||||
# Databases
|
||||
redis-kiss = { version = "0.1.3" }
|
||||
@@ -71,6 +69,7 @@ reqwest = "0.11.10"
|
||||
bitfield = "0.13.2"
|
||||
once_cell = "1.13.0"
|
||||
lazy_static = "1.4.0"
|
||||
async-lock = "2.6.0"
|
||||
|
||||
lru = { version = "0.7.6", optional = true }
|
||||
dashmap = { version = "5.2.0", optional = true }
|
||||
@@ -82,11 +81,11 @@ web-push = "0.7.2"
|
||||
# Implementations
|
||||
rocket_http = { optional = true, version = "0.5.0-rc.2" }
|
||||
rocket = { optional = true, version = "0.5.0-rc.2", default-features = false, features = ["json"] }
|
||||
rocket_empty = { optional = true, git = "https://github.com/insertish/rocket_empty", branch = "master" }
|
||||
rocket_cors = { optional = true, git = "https://github.com/lawliet89/rocket_cors", rev = "5843861a88958c16bfaa0b40f0d8910772bcd2f6" }
|
||||
rocket_empty = { version = "0.1.1", optional = true, features = [ "schema" ] }
|
||||
rocket_cors = { optional = true, git = "https://github.com/lawliet89/rocket_cors", rev = "c17e8145baa4790319fdb6a473e465b960f55e7c" }
|
||||
|
||||
# rAuth
|
||||
rauth = { git = "https://github.com/insertish/rauth", rev = "cbdec69c684a4854fbedba9ed1f0e7ee466bf3f7", features = [ "async-std-runtime" ] }
|
||||
# Authifier
|
||||
authifier = { version = "1.0.7", features = [ "async-std-runtime" ] }
|
||||
|
||||
# Sentry
|
||||
sentry = "0.25.0"
|
||||
|
||||
@@ -61,13 +61,13 @@ impl Deref for Database {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Database> for rauth::Database {
|
||||
impl From<Database> for authifier::Database {
|
||||
fn from(val: Database) -> Self {
|
||||
match val {
|
||||
Database::Dummy(_) => rauth::Database::default(),
|
||||
Database::MongoDb(MongoDb(client)) => {
|
||||
rauth::Database::MongoDb(rauth::database::MongoDb(client.database("revolt")))
|
||||
}
|
||||
Database::Dummy(_) => authifier::Database::default(),
|
||||
Database::MongoDb(MongoDb(client)) => authifier::Database::MongoDb(
|
||||
authifier::database::MongoDb(client.database("revolt")),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use authifier::AuthifierEvent;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::models::channel::{FieldsChannel, PartialChannel};
|
||||
@@ -195,9 +196,23 @@ pub enum EventV1 {
|
||||
/// Settings updated remotely
|
||||
UserSettingsUpdate { id: String, update: UserSettings },
|
||||
|
||||
/// User has been platform banned or deleted their account
|
||||
///
|
||||
/// Clients should remove the following associated data:
|
||||
/// - Messages
|
||||
/// - DM Channels
|
||||
/// - Relationships
|
||||
/// - Server Memberships
|
||||
///
|
||||
/// User flags are specified to explain why a wipe is occurring though not all reasons will necessarily ever appear.
|
||||
UserPlatformWipe { user_id: String, flags: i32 },
|
||||
|
||||
/// New emoji
|
||||
EmojiCreate(Emoji),
|
||||
|
||||
/// Delete emoji
|
||||
EmojiDelete { id: String },
|
||||
|
||||
/// Auth events
|
||||
Auth(AuthifierEvent),
|
||||
}
|
||||
|
||||
@@ -23,11 +23,7 @@ impl Cache {
|
||||
pub async fn can_view_channel(&self, db: &Database, channel: &Channel) -> bool {
|
||||
match &channel {
|
||||
Channel::TextChannel { server, .. } | Channel::VoiceChannel { server, .. } => {
|
||||
let member = self
|
||||
.members
|
||||
.iter()
|
||||
.map(|(_, x)| x)
|
||||
.find(|x| &x.id.server == server);
|
||||
let member = self.members.values().find(|x| &x.id.server == server);
|
||||
|
||||
let server = self.servers.get(server);
|
||||
let mut perms = perms(self.users.get(&self.user_id).unwrap()).channel(channel);
|
||||
@@ -563,4 +559,9 @@ impl EventV1 {
|
||||
pub async fn private(self, id: String) {
|
||||
self.p(format!("{}!", id)).await;
|
||||
}
|
||||
|
||||
/// Publish internal global event
|
||||
pub async fn global(self) {
|
||||
self.p("global".to_string()).await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -215,7 +215,7 @@ pub async fn run_migrations(db: &MongoDb, revision: i32) -> i32 {
|
||||
}
|
||||
|
||||
if revision <= 8 {
|
||||
info!("Running migration [revision 8 / 2021-09-10]: Update to rAuth version 1.");
|
||||
info!("Running migration [revision 8 / 2021-09-10]: Update to Authifier version 1.");
|
||||
|
||||
db.db()
|
||||
.run_command(
|
||||
@@ -603,20 +603,20 @@ pub async fn run_migrations(db: &MongoDb, revision: i32) -> i32 {
|
||||
}
|
||||
|
||||
if revision <= 15 {
|
||||
info!("Running migration [revision 15 / 04-06-2022]: Migrate rAuth to latest version.");
|
||||
info!("Running migration [revision 15 / 04-06-2022]: Migrate Authifier to latest version.");
|
||||
|
||||
let db = rauth::Database::MongoDb(rauth::database::MongoDb(db.db()));
|
||||
db.run_migration(rauth::Migration::M2022_06_03EnsureUpToSpec)
|
||||
let db = authifier::Database::MongoDb(authifier::database::MongoDb(db.db()));
|
||||
db.run_migration(authifier::Migration::M2022_06_03EnsureUpToSpec)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
if revision <= 16 {
|
||||
info!("Running migration [revision 16 / 07-07-2022]: Add `emojis` collection and rAuth migration.");
|
||||
info!("Running migration [revision 16 / 07-07-2022]: Add `emojis` collection and Authifier migration.");
|
||||
|
||||
let rauth_db = rauth::Database::MongoDb(rauth::database::MongoDb(db.db()));
|
||||
rauth_db
|
||||
.run_migration(rauth::Migration::M2022_06_09AddIndexForDeletion)
|
||||
let authifier_db = authifier::Database::MongoDb(authifier::database::MongoDb(db.db()));
|
||||
authifier_db
|
||||
.run_migration(authifier::Migration::M2022_06_09AddIndexForDeletion)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use okapi::openapi3::{SecurityScheme, SecuritySchemeData};
|
||||
use rauth::models::Session;
|
||||
use rocket_okapi::gen::OpenApiGenerator;
|
||||
use rocket_okapi::request::{OpenApiFromRequest, RequestHeaderInput};
|
||||
use authifier::models::Session;
|
||||
use revolt_okapi::openapi3::{SecurityScheme, SecuritySchemeData};
|
||||
use revolt_rocket_okapi::gen::OpenApiGenerator;
|
||||
use revolt_rocket_okapi::request::{OpenApiFromRequest, RequestHeaderInput};
|
||||
|
||||
use rocket::http::Status;
|
||||
use rocket::request::{self, FromRequest, Outcome, Request};
|
||||
@@ -12,7 +12,7 @@ use crate::Database;
|
||||
|
||||
#[rocket::async_trait]
|
||||
impl<'r> FromRequest<'r> for User {
|
||||
type Error = rauth::Error;
|
||||
type Error = authifier::Error;
|
||||
|
||||
async fn from_request(request: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
|
||||
let user: &Option<User> = request
|
||||
@@ -43,7 +43,7 @@ impl<'r> FromRequest<'r> for User {
|
||||
if let Some(user) = user {
|
||||
Outcome::Success(user.clone())
|
||||
} else {
|
||||
Outcome::Failure((Status::Unauthorized, rauth::Error::InvalidSession))
|
||||
Outcome::Failure((Status::Unauthorized, authifier::Error::InvalidSession))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,7 +53,7 @@ impl<'r> OpenApiFromRequest<'r> for User {
|
||||
_gen: &mut OpenApiGenerator,
|
||||
_name: String,
|
||||
_required: bool,
|
||||
) -> rocket_okapi::Result<RequestHeaderInput> {
|
||||
) -> revolt_rocket_okapi::Result<RequestHeaderInput> {
|
||||
let mut requirements = schemars::Map::new();
|
||||
requirements.insert("Session Token".to_owned(), vec![]);
|
||||
|
||||
|
||||
@@ -17,8 +17,8 @@ extern crate bitfield;
|
||||
#[macro_use]
|
||||
extern crate bson;
|
||||
|
||||
pub use authifier;
|
||||
pub use iso8601_timestamp::Timestamp;
|
||||
pub use rauth;
|
||||
pub use redis_kiss;
|
||||
|
||||
pub mod events;
|
||||
|
||||
@@ -81,7 +81,7 @@ pub struct Masquerade {
|
||||
pub name: Option<String>,
|
||||
/// Replace the avatar shown on this message (URL to image file)
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[validate(length(min = 1, max = 128))]
|
||||
#[validate(length(min = 1, max = 256))]
|
||||
pub avatar: Option<String>,
|
||||
/// Replace the display role colour shown on this message
|
||||
///
|
||||
@@ -98,6 +98,8 @@ pub struct Interactions {
|
||||
#[serde(skip_serializing_if = "Option::is_none", default)]
|
||||
pub reactions: Option<IndexSet<String>>,
|
||||
/// Whether reactions should be restricted to the given list
|
||||
///
|
||||
/// Can only be set to true if reactions list is of at least length 1
|
||||
#[serde(skip_serializing_if = "if_false", default)]
|
||||
pub restrict_reactions: bool,
|
||||
}
|
||||
|
||||
@@ -105,6 +105,8 @@ pub enum Flags {
|
||||
Deleted = 2,
|
||||
/// User was banned off the platform
|
||||
Banned = 4,
|
||||
/// User was marked as spam and removed from platform
|
||||
Spam = 8,
|
||||
}
|
||||
|
||||
/// Bot information for if the user is a bot
|
||||
|
||||
@@ -97,7 +97,7 @@ impl From<i64> for PermissionValue {
|
||||
|
||||
impl From<u64> for PermissionValue {
|
||||
fn from(v: u64) -> Self {
|
||||
Self(v as u64)
|
||||
Self(v)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ pub enum Permission {
|
||||
/// Manage server customisation (includes emoji)
|
||||
ManageCustomisation = 1 << 4,
|
||||
|
||||
// % 1 bits reserved
|
||||
// % 1 bit reserved
|
||||
|
||||
// * Member permissions
|
||||
/// Kick other members below their ranking
|
||||
@@ -109,10 +109,11 @@ lazy_static! {
|
||||
+ Permission::Connect
|
||||
+ Permission::Speak;
|
||||
pub static ref DEFAULT_PERMISSION_SAVED_MESSAGES: u64 = Permission::GrantAllSafe as u64;
|
||||
pub static ref DEFAULT_PERMISSION_DIRECT_MESSAGE: u64 =
|
||||
*DEFAULT_PERMISSION + Permission::ManageChannel;
|
||||
pub static ref DEFAULT_PERMISSION_DIRECT_MESSAGE: u64 = *DEFAULT_PERMISSION
|
||||
+ Permission::ManageChannel
|
||||
+ Permission::React;
|
||||
pub static ref DEFAULT_PERMISSION_SERVER: u64 =
|
||||
*DEFAULT_PERMISSION + Permission::ChangeNickname + Permission::ChangeAvatar;
|
||||
*DEFAULT_PERMISSION + Permission::React + Permission::ChangeNickname + Permission::ChangeAvatar;
|
||||
}
|
||||
|
||||
bitfield! {
|
||||
|
||||
@@ -35,7 +35,7 @@ pub async fn presence_create_session(user_id: &str, flags: u8) -> (bool, u8) {
|
||||
__set_key_presence_entry(&mut conn, user_id, entry).await;
|
||||
|
||||
// Add to region set in case of failure.
|
||||
__add_to_set_sessions(&mut conn, &*REGION_KEY, user_id, session_id).await;
|
||||
__add_to_set_sessions(&mut conn, ®ION_KEY, user_id, session_id).await;
|
||||
(was_empty, session_id)
|
||||
}
|
||||
|
||||
@@ -74,7 +74,7 @@ async fn presence_delete_session_internal(
|
||||
|
||||
// Remove from region set.
|
||||
if !skip_region {
|
||||
__remove_from_set_sessions(&mut conn, &*REGION_KEY, user_id, session_id).await;
|
||||
__remove_from_set_sessions(&mut conn, ®ION_KEY, user_id, session_id).await;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
use crate::util::variables::delta::{JANUARY_URL, MAX_EMBED_COUNT};
|
||||
use crate::util::variables::delta::{JANUARY_URL, MAX_EMBED_COUNT, JANUARY_CONCURRENT_CONNECTIONS};
|
||||
use crate::{
|
||||
models::{message::AppendMessage, Message},
|
||||
types::january::Embed,
|
||||
Database,
|
||||
};
|
||||
|
||||
use async_lock::Semaphore;
|
||||
use async_std::task::spawn;
|
||||
use deadqueue::limited::Queue;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Task information
|
||||
#[derive(Debug)]
|
||||
@@ -36,21 +39,30 @@ pub async fn queue(channel: String, id: String, content: String) {
|
||||
|
||||
/// Start a new worker
|
||||
pub async fn worker(db: Database) {
|
||||
let semaphore = Arc::new(Semaphore::new(*JANUARY_CONCURRENT_CONNECTIONS));
|
||||
|
||||
loop {
|
||||
let task = Q.pop().await;
|
||||
if let Ok(embeds) = Embed::generate(task.content, &*JANUARY_URL, *MAX_EMBED_COUNT).await {
|
||||
if let Err(err) = Message::append(
|
||||
&db,
|
||||
task.id,
|
||||
task.channel,
|
||||
AppendMessage {
|
||||
embeds: Some(embeds),
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
error!("Encountered an error appending to message: {:?}", err);
|
||||
let db = db.clone();
|
||||
let semaphore = semaphore.clone();
|
||||
|
||||
spawn(async move {
|
||||
let embeds = Embed::generate(task.content, &JANUARY_URL, *MAX_EMBED_COUNT, semaphore).await;
|
||||
|
||||
if let Ok(embeds) = embeds {
|
||||
if let Err(err) = Message::append(
|
||||
&db,
|
||||
task.id,
|
||||
task.channel,
|
||||
AppendMessage {
|
||||
embeds: Some(embeds),
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
error!("Encountered an error appending to message: {:?}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use crate::bson::doc;
|
||||
use crate::util::variables::delta::VAPID_PRIVATE_KEY;
|
||||
|
||||
use authifier::Database;
|
||||
use deadqueue::limited::Queue;
|
||||
use rauth::Database;
|
||||
use web_push::{
|
||||
ContentEncoding, SubscriptionInfo, SubscriptionKeys, VapidSignatureBuilder, WebPushClient,
|
||||
WebPushMessageBuilder,
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
use async_lock::Semaphore;
|
||||
use async_std::task::spawn;
|
||||
use futures::future::join_all;
|
||||
use linkify::{LinkFinder, LinkKind};
|
||||
use regex::Regex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashSet;
|
||||
use std::{collections::HashSet, sync::Arc};
|
||||
|
||||
use crate::{models::attachment::File, Error, Result};
|
||||
|
||||
@@ -95,6 +98,8 @@ pub enum Special {
|
||||
content_type: BandcampType,
|
||||
id: String,
|
||||
},
|
||||
/// Streamable Video
|
||||
Streamable { id: String },
|
||||
}
|
||||
|
||||
/// Website metadata
|
||||
@@ -172,7 +177,12 @@ pub enum Embed {
|
||||
|
||||
impl Embed {
|
||||
/// Generate embeds from given content
|
||||
pub async fn generate(content: String, host: &str, max_embeds: usize) -> Result<Vec<Embed>> {
|
||||
pub async fn generate(
|
||||
content: String,
|
||||
host: &str,
|
||||
max_embeds: usize,
|
||||
semaphore: Arc<Semaphore>,
|
||||
) -> Result<Vec<Embed>> {
|
||||
lazy_static! {
|
||||
static ref RE_CODE: Regex = Regex::new("```(?:.|\n)+?```|`(?:.|\n)+?`").unwrap();
|
||||
static ref RE_IGNORED: Regex = Regex::new("(<http.+>)").unwrap();
|
||||
@@ -223,26 +233,37 @@ impl Embed {
|
||||
}
|
||||
|
||||
// ! FIXME: batch request to january?
|
||||
let mut embeds: Vec<Embed> = Vec::new();
|
||||
let client = reqwest::Client::new();
|
||||
|
||||
let mut tasks = Vec::new();
|
||||
let url = format!("{host}/embed");
|
||||
|
||||
for link in links {
|
||||
let result = client
|
||||
.get(&format!("{}/embed", host))
|
||||
.query(&[("url", link)])
|
||||
.send()
|
||||
.await;
|
||||
let client = client.clone();
|
||||
let url = url.clone();
|
||||
let semaphore = semaphore.clone();
|
||||
|
||||
if result.is_err() {
|
||||
continue;
|
||||
}
|
||||
tasks.push(spawn(async move {
|
||||
let guard = semaphore.acquire().await;
|
||||
|
||||
let response = result.unwrap();
|
||||
if response.status().is_success() {
|
||||
let res: Embed = response.json().await.map_err(|_| Error::InvalidOperation)?;
|
||||
embeds.push(res);
|
||||
}
|
||||
let response = client.get(url).query(&[("url", link)]).send().await.ok()?;
|
||||
|
||||
drop(guard);
|
||||
|
||||
if response.status().is_success() {
|
||||
response.json::<Embed>().await.ok()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
let embeds = join_all(tasks)
|
||||
.await
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.collect::<Vec<Embed>>();
|
||||
|
||||
// Prevent database update when no embeds are found.
|
||||
if !embeds.is_empty() {
|
||||
Ok(embeds)
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
use authifier::config::{ResolveIp, Shield};
|
||||
|
||||
use super::variables::delta::{
|
||||
APP_URL, HCAPTCHA_KEY, INVITE_ONLY, SMTP_FROM, SMTP_HOST, SMTP_PASSWORD, SMTP_USERNAME,
|
||||
USE_EMAIL, USE_HCAPTCHA,
|
||||
APP_URL, AUTHIFIER_SHIELD_KEY, HCAPTCHA_KEY, INVITE_ONLY, SMTP_FROM, SMTP_HOST, SMTP_PASSWORD,
|
||||
SMTP_USERNAME, USE_EMAIL, USE_HCAPTCHA,
|
||||
};
|
||||
|
||||
use crate::rauth::config::{
|
||||
use crate::authifier::config::{
|
||||
Captcha, Config, EmailVerificationConfig, SMTPSettings, Template, Templates,
|
||||
};
|
||||
|
||||
@@ -59,5 +61,19 @@ pub fn config() -> Config {
|
||||
};
|
||||
}
|
||||
|
||||
if let Some(api_key) = &*AUTHIFIER_SHIELD_KEY {
|
||||
config.shield = Shield::Enabled {
|
||||
api_key: api_key.to_string(),
|
||||
strict: false,
|
||||
};
|
||||
}
|
||||
|
||||
if std::env::var("TRUST_CLOUDFLARE")
|
||||
.map(|x| x == "1")
|
||||
.unwrap_or_default()
|
||||
{
|
||||
config.resolve_ip = ResolveIp::Cloudflare;
|
||||
}
|
||||
|
||||
config
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
pub mod authifier;
|
||||
pub mod log;
|
||||
pub mod manipulation;
|
||||
pub mod pfp;
|
||||
pub mod rauth;
|
||||
pub mod r#ref;
|
||||
pub mod regex;
|
||||
pub mod result;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use okapi::openapi3::{self, SchemaObject};
|
||||
use revolt_okapi::openapi3::SchemaObject;
|
||||
use revolt_rocket_okapi::revolt_okapi::openapi3;
|
||||
use rocket::{
|
||||
http::{ContentType, Status},
|
||||
response::{self, Responder},
|
||||
@@ -19,10 +20,10 @@ pub enum Error {
|
||||
/// This error was not labeled :(
|
||||
LabelMe,
|
||||
|
||||
// ? Onboarding related errors.
|
||||
// ? Onboarding related errors
|
||||
AlreadyOnboarded,
|
||||
|
||||
// ? User related errors.
|
||||
// ? User related errors
|
||||
UsernameTaken,
|
||||
InvalidUsername,
|
||||
UnknownUser,
|
||||
@@ -32,7 +33,7 @@ pub enum Error {
|
||||
BlockedByOther,
|
||||
NotFriends,
|
||||
|
||||
// ? Channel related errors.
|
||||
// ? Channel related errors
|
||||
UnknownChannel,
|
||||
UnknownAttachment,
|
||||
UnknownMessage,
|
||||
@@ -49,7 +50,7 @@ pub enum Error {
|
||||
AlreadyInGroup,
|
||||
NotInGroup,
|
||||
|
||||
// ? Server related errors.
|
||||
// ? Server related errors
|
||||
UnknownServer,
|
||||
InvalidRole,
|
||||
Banned,
|
||||
@@ -58,12 +59,12 @@ pub enum Error {
|
||||
},
|
||||
TooManyEmoji,
|
||||
|
||||
// ? Bot related errors.
|
||||
// ? Bot related errors
|
||||
ReachedMaximumBots,
|
||||
IsBot,
|
||||
BotIsPrivate,
|
||||
|
||||
// ? Permission errors.
|
||||
// ? Permission errors
|
||||
MissingPermission {
|
||||
permission: Permission,
|
||||
},
|
||||
@@ -74,7 +75,7 @@ pub enum Error {
|
||||
CannotGiveMissingPermissions,
|
||||
NotOwner,
|
||||
|
||||
// ? General errors.
|
||||
// ? General errors
|
||||
DatabaseError {
|
||||
operation: &'static str,
|
||||
with: &'static str,
|
||||
@@ -82,6 +83,7 @@ pub enum Error {
|
||||
InternalError,
|
||||
InvalidOperation,
|
||||
InvalidCredentials,
|
||||
InvalidProperty,
|
||||
InvalidSession,
|
||||
DuplicateNonce,
|
||||
VosoUnavailable,
|
||||
@@ -174,6 +176,7 @@ impl<'r> Responder<'r, 'static> for Error {
|
||||
Error::InternalError => Status::InternalServerError,
|
||||
Error::InvalidOperation => Status::BadRequest,
|
||||
Error::InvalidCredentials => Status::Unauthorized,
|
||||
Error::InvalidProperty => Status::BadRequest,
|
||||
Error::InvalidSession => Status::Unauthorized,
|
||||
Error::DuplicateNonce => Status::Conflict,
|
||||
Error::VosoUnavailable => Status::BadRequest,
|
||||
@@ -194,11 +197,11 @@ impl<'r> Responder<'r, 'static> for Error {
|
||||
}
|
||||
}
|
||||
|
||||
impl rocket_okapi::response::OpenApiResponderInner for Error {
|
||||
impl revolt_rocket_okapi::response::OpenApiResponderInner for Error {
|
||||
fn responses(
|
||||
gen: &mut rocket_okapi::gen::OpenApiGenerator,
|
||||
) -> std::result::Result<openapi3::Responses, rocket_okapi::OpenApiError> {
|
||||
let mut content = okapi::Map::new();
|
||||
gen: &mut revolt_rocket_okapi::gen::OpenApiGenerator,
|
||||
) -> std::result::Result<openapi3::Responses, revolt_rocket_okapi::OpenApiError> {
|
||||
let mut content = revolt_okapi::Map::new();
|
||||
|
||||
let settings = schemars::gen::SchemaSettings::default().with(|s| {
|
||||
s.option_nullable = true;
|
||||
|
||||
@@ -13,6 +13,8 @@ lazy_static! {
|
||||
env::var("AUTUMN_PUBLIC_URL").unwrap_or_else(|_| "https://example.com".to_string());
|
||||
pub static ref JANUARY_URL: String =
|
||||
env::var("JANUARY_PUBLIC_URL").unwrap_or_else(|_| "https://example.com".to_string());
|
||||
pub static ref JANUARY_CONCURRENT_CONNECTIONS: usize =
|
||||
env::var("JANUARY_CONCURRENT_CONNECTIONS").map_or(50, |v| v.parse().unwrap());
|
||||
pub static ref VOSO_URL: String =
|
||||
env::var("VOSO_PUBLIC_URL").unwrap_or_else(|_| "https://example.com".to_string());
|
||||
pub static ref VOSO_WS_HOST: String =
|
||||
@@ -28,6 +30,8 @@ lazy_static! {
|
||||
env::var("REVOLT_VAPID_PRIVATE_KEY").expect("Missing REVOLT_VAPID_PRIVATE_KEY environment variable.");
|
||||
pub static ref VAPID_PUBLIC_KEY: String =
|
||||
env::var("REVOLT_VAPID_PUBLIC_KEY").expect("Missing REVOLT_VAPID_PUBLIC_KEY environment variable.");
|
||||
pub static ref AUTHIFIER_SHIELD_KEY: Option<String> =
|
||||
env::var("REVOLT_AUTHIFIER_SHIELD_KEY").ok();
|
||||
|
||||
// Application Flags
|
||||
pub static ref INVITE_ONLY: bool = env::var("REVOLT_INVITE_ONLY").map_or(false, |v| v == "1");
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use crate::{Error, Result};
|
||||
|
||||
use async_std::sync::Mutex;
|
||||
use revolt_rocket_okapi::gen::OpenApiGenerator;
|
||||
use revolt_rocket_okapi::request::{OpenApiFromRequest, RequestHeaderInput};
|
||||
use revolt_rocket_okapi::revolt_okapi::openapi3::{Parameter, ParameterValue};
|
||||
use rocket::http::Status;
|
||||
use rocket::request::{FromRequest, Outcome};
|
||||
use rocket_okapi::gen::OpenApiGenerator;
|
||||
use rocket_okapi::okapi::openapi3::{Parameter, ParameterValue};
|
||||
use rocket_okapi::request::{OpenApiFromRequest, RequestHeaderInput};
|
||||
use schemars::schema::{InstanceType, SchemaObject, SingleOrVec};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use validator::Validate;
|
||||
@@ -47,7 +47,7 @@ impl<'r> OpenApiFromRequest<'r> for IdempotencyKey {
|
||||
_gen: &mut OpenApiGenerator,
|
||||
_name: String,
|
||||
_required: bool,
|
||||
) -> rocket_okapi::Result<RequestHeaderInput> {
|
||||
) -> revolt_rocket_okapi::Result<RequestHeaderInput> {
|
||||
Ok(RequestHeaderInput::Parameter(Parameter {
|
||||
name: "Idempotency-Key".to_string(),
|
||||
description: Some("Unique key to prevent duplicate requests".to_string()),
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::hash::Hasher;
|
||||
use std::ops::Add;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use crate::rauth::models::Session;
|
||||
use crate::authifier::models::Session;
|
||||
use rocket::fairing::{Fairing, Info, Kind};
|
||||
use rocket::http::uri::Origin;
|
||||
use rocket::http::{Method, Status};
|
||||
@@ -16,8 +16,8 @@ use rocket::request::{FromRequest, Outcome};
|
||||
use rocket::serde::json::Json;
|
||||
use rocket::{Data, Request, Response};
|
||||
|
||||
use rocket_okapi::gen::OpenApiGenerator;
|
||||
use rocket_okapi::request::{OpenApiFromRequest, RequestHeaderInput};
|
||||
use revolt_rocket_okapi::gen::OpenApiGenerator;
|
||||
use revolt_rocket_okapi::request::{OpenApiFromRequest, RequestHeaderInput};
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
@@ -51,7 +51,7 @@ impl Entry {
|
||||
}
|
||||
|
||||
/// Deduct one unit from the bucket and save
|
||||
pub fn deduct(mut self, key: u64) {
|
||||
pub fn deduct(mut self) {
|
||||
let current_time = now().as_millis();
|
||||
if current_time > self.reset {
|
||||
self.used = 1;
|
||||
@@ -59,7 +59,10 @@ impl Entry {
|
||||
} else {
|
||||
self.used += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Save information
|
||||
pub fn save(self, key: u64) {
|
||||
MAP.insert(key, self);
|
||||
}
|
||||
|
||||
@@ -193,10 +196,12 @@ impl Ratelimiter {
|
||||
let entry = Entry::from(key);
|
||||
|
||||
let remaining = entry.get_remaining(limit);
|
||||
let reset = entry.left_until_reset();
|
||||
|
||||
if remaining > 0 {
|
||||
entry.deduct(key);
|
||||
entry.deduct();
|
||||
|
||||
let reset = entry.left_until_reset();
|
||||
entry.save(key);
|
||||
|
||||
Ok(Ratelimiter {
|
||||
key,
|
||||
limit,
|
||||
@@ -204,7 +209,7 @@ impl Ratelimiter {
|
||||
reset,
|
||||
})
|
||||
} else {
|
||||
Err(reset)
|
||||
Err(entry.left_until_reset())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -240,7 +245,7 @@ impl<'r> OpenApiFromRequest<'r> for Ratelimiter {
|
||||
_gen: &mut OpenApiGenerator,
|
||||
_name: String,
|
||||
_required: bool,
|
||||
) -> rocket_okapi::Result<RequestHeaderInput> {
|
||||
) -> revolt_rocket_okapi::Result<RequestHeaderInput> {
|
||||
Ok(RequestHeaderInput::None)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use rocket::Route;
|
||||
|
||||
pub fn routes() -> Vec<Route> {
|
||||
rocket_okapi::swagger_ui::make_swagger_ui(&rocket_okapi::swagger_ui::SwaggerUIConfig {
|
||||
revolt_rocket_okapi::swagger_ui::make_swagger_ui(&revolt_rocket_okapi::swagger_ui::SwaggerUIConfig {
|
||||
url: "../openapi.json".to_owned(),
|
||||
..Default::default()
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user