Compare commits

..

70 Commits

Author SHA1 Message Date
Zomatree
6043ba6004 Merge branch 'main' into feat/oauth2 2025-11-03 03:28:19 +00:00
Aeledfyr
657a3f08e5 fix: preserve order of replies in message (#447)
Signed-off-by: Aeledfyr <aeledfyr@gmail.com>
2025-10-27 00:10:07 +00:00
Zomatree
af78ac0586 chore(ci): move to stoatchat 2025-10-11 23:22:41 +01:00
Zomatree
d65c1a1ab3 fix(ci): publish images under stoatchat and remove docker hub 2025-10-11 23:01:35 +01:00
izzy
4fb99e3bd0 ci: also include gifbox src 2025-09-23 12:12:33 -05:00
izzy
f0a83abcfa ci: add missing src copies for Docker build 2025-09-23 12:09:19 -05:00
izzy
6f1c715b8c chore: bump version to 0.8.9 2025-09-23 12:02:35 -05:00
Zomatree
38dd4d1079 fix: swap to using reqwest for query building 2025-09-19 02:50:00 +01:00
Zomatree
154204742d feat: add ratelimits to gifbox 2025-09-19 02:50:00 +01:00
Zomatree
db55998546 docs: document revolt-coalesced 2025-09-19 02:50:00 +01:00
Zomatree
5885e067a6 feat: trending and categories routes 2025-09-19 02:50:00 +01:00
Zomatree
a92152d86d fix: use our own result types instead of tenors types
add user auth
2025-09-19 02:50:00 +01:00
Zomatree
b5cd5e30ef feat: require auth for search 2025-09-19 02:50:00 +01:00
Zomatree
b0c977b324 feat: initial work on tenor gif searching 2025-09-19 02:50:00 +01:00
Zomatree
bfe4018e43 fix: apple music to use original url instead of metadata url
Apple Music returns the url without the query parameter in the opengraph meta tags, causing the regex to not find the track id, meaning any embed links generated would only link to the album.
2025-09-19 02:41:53 +01:00
Zomatree
cc7a7962a8 fix: use trust_cloudflare config value instead of env var 2025-09-18 21:22:31 +01:00
Zomatree
fb4011084d refactor: move ratelimits to a generic system for all web servers 2025-09-18 21:22:31 +01:00
Zomatree
3a3415915f fix: relax settings name regex 2025-09-17 15:41:54 +01:00
Zomatree
964884a5de chore: add policy changes 2025-09-17 15:41:54 +01:00
Zomatree
db57706794 feat: ready payload field customisation 2025-09-17 15:41:54 +01:00
Paul Makles
a186732ca5 merge: pull request #428 from ElfFlu/bugfix/16byte-attachment-gain 2025-09-12 12:48:28 +01:00
Tom
e635bc23ec fix: don't remove timeouts when a member leaves a server (#409) 2025-09-06 18:41:23 -07:00
Zomatree
3cb7da95e3 chore: add missing traits implementations to PermissionValue 2025-09-05 15:22:55 +01:00
Zomatree
dea0f675dd fix: implement Serialize to ClientMessage 2025-09-05 13:07:52 +01:00
Zomatree
480f210ce8 feat: include member payload in ServerMemberJoin event 2025-08-24 06:32:38 +01:00
Zomatree
caa8607468 feat: include groups and dms in fetch mutuals 2025-08-24 03:40:10 +01:00
ElfFlu
32e6600272 fix: remove authentication tag bytes from attachment download
Signed-off-by: ElfFlu <228066338+ElfFlu@users.noreply.github.com>
2025-08-23 19:05:32 +02:00
Zomatree
5335124306 fix: add license to revolt-parser 2025-08-20 18:55:52 +01:00
Zomatree
1561481eb4 feat: make message lexer use unowned string 2025-08-20 18:55:39 +01:00
IAmTomahawkx
8f9015a6ff fix: apply uname fix to january and autumn 2025-08-18 16:59:08 -07:00
Zomatree
67773d3e43 chore: sync branch with main 2025-08-18 02:14:36 +01:00
Zomatree
14ea180683 refactor: simplify scope struct macro 2025-08-18 01:58:15 +01:00
Zomatree
83c15404a5 fix: use correct key name for auth bots collection 2025-08-18 01:58:15 +01:00
Zomatree
9d4bcb5e3d chore: rework oauth2 route scoping 2025-08-18 01:58:15 +01:00
Zomatree
f895ca7b23 feat: allow connecting to ws via oauth2 2025-08-18 01:58:15 +01:00
Zomatree
ef65223c89 feat: initial work on refresh tokens 2025-08-18 01:58:14 +01:00
Zomatree
660e646b2b feat: initial oauth2 token revoking 2025-08-18 01:58:14 +01:00
Zomatree
5a5f84f207 fix: add more oauth2 checks 2025-08-18 01:58:14 +01:00
Zomatree
11eee02cfe feat: allowed scopes 2025-08-18 01:58:14 +01:00
Zomatree
1e5b27ff9e fix(oauth2): use public bot 2025-08-18 01:58:14 +01:00
Zomatree
3ae25fbcfe fix(oauth2): fix spec discrepancies 2025-08-18 01:58:14 +01:00
Zomatree
9e05e5be7e feat: initial oauth2 implementation 2025-08-18 01:58:14 +01:00
Zomatree
ed22b3a5ce chore: switch Reference to using an actual reference 2025-08-12 03:44:29 +01:00
Zomatree
65fbd36624 fix: allow for disabling default features 2025-08-12 02:35:09 +01:00
izzy
050ba16d4a fix: correct shebang for try-tag-and-release 2025-08-07 12:58:52 +02:00
izzy
65bc6c8fc6 chore: add just tool to nix shell 2025-08-07 12:58:15 +02:00
izzy
6ad3da5f35 fix: permit empty remove array in edit requests 2025-08-07 12:57:33 +02:00
izzy
947eb15771 fix: newly created roles should be ranked the lowest 2025-08-07 12:29:42 +02:00
IAmTomahawkx
f4ee35fb09 fix: don't update the same field while trying to remove it
fixes #392
2025-08-06 14:18:40 -07:00
IAmTomahawkx
6048587d34 fix: rename openapi operation ids
fixes #406
2025-08-06 12:28:58 -07:00
Builderb
80cf8fc4e8 Increase limit of embed icon url due to new cdn changes causing longer url (#426)
Signed-off-by: Builderb <builderbgamer@gmail.com>
2025-08-03 11:54:22 -07:00
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
243 changed files with 6749 additions and 2284 deletions

View File

@@ -49,13 +49,6 @@ jobs:
uses: docker/setup-buildx-action@v2
# Authenticate with Docker Hub and GHCR
- name: Login to DockerHub
uses: docker/login-action@v2
with:
registry: docker.io
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Login to Github Container Registry
uses: docker/login-action@v2
with:
@@ -72,14 +65,13 @@ jobs:
platforms: linux/amd64,linux/arm64
tags: ghcr.io/${{ github.repository_owner }}/base:latest
# revoltchat/server
# stoatchat/api
- name: Docker meta
id: meta-delta
uses: docker/metadata-action@v4
with:
images: |
docker.io/revoltchat/server
ghcr.io/revoltchat/server
ghcr.io/stoatchat/api
- name: Publish
uses: docker/build-push-action@v4
with:
@@ -92,14 +84,13 @@ jobs:
BASE_IMAGE=ghcr.io/${{ github.repository_owner }}/base:latest
labels: ${{ steps.meta-delta.outputs.labels }}
# revoltchat/bonfire
# stoatchat/events
- name: Docker meta
id: meta-bonfire
uses: docker/metadata-action@v4
with:
images: |
docker.io/revoltchat/bonfire
ghcr.io/revoltchat/bonfire
ghcr.io/stoatchat/events
- name: Publish
uses: docker/build-push-action@v4
with:
@@ -112,14 +103,13 @@ jobs:
BASE_IMAGE=ghcr.io/${{ github.repository_owner }}/base:latest
labels: ${{ steps.meta-bonfire.outputs.labels }}
# revoltchat/autumn
# stoatchat/file-server
- name: Docker meta
id: meta-autumn
uses: docker/metadata-action@v4
with:
images: |
docker.io/revoltchat/autumn
ghcr.io/revoltchat/autumn
ghcr.io/stoatchat/file-server
- name: Publish
uses: docker/build-push-action@v4
with:
@@ -132,14 +122,13 @@ jobs:
BASE_IMAGE=ghcr.io/${{ github.repository_owner }}/base:latest
labels: ${{ steps.meta-autumn.outputs.labels }}
# revoltchat/january
# stoatchat/proxy
- name: Docker meta
id: meta-january
uses: docker/metadata-action@v4
with:
images: |
docker.io/revoltchat/january
ghcr.io/revoltchat/january
ghcr.io/stoatchat/proxy
- name: Publish
uses: docker/build-push-action@v4
with:
@@ -152,14 +141,32 @@ jobs:
BASE_IMAGE=ghcr.io/${{ github.repository_owner }}/base:latest
labels: ${{ steps.meta-january.outputs.labels }}
# revoltchat/crond
# stoatchat/gifbox
- name: Docker meta
id: meta-gifbox
uses: docker/metadata-action@v4
with:
images: |
ghcr.io/stoatchat/gifbox
- name: Publish
uses: docker/build-push-action@v4
with:
context: .
push: true
platforms: linux/amd64,linux/arm64
file: crates/services/gifbox/Dockerfile
tags: ${{ steps.meta-gifbox.outputs.tags }}
build-args: |
BASE_IMAGE=ghcr.io/${{ github.repository_owner }}/base:latest
labels: ${{ steps.meta-gifbox.outputs.labels }}
# stoatchat/crond
- name: Docker meta
id: meta-crond
uses: docker/metadata-action@v4
with:
images: |
docker.io/revoltchat/crond
ghcr.io/revoltchat/crond
ghcr.io/stoatchat/crond
- name: Publish
uses: docker/build-push-action@v4
with:
@@ -172,14 +179,13 @@ jobs:
BASE_IMAGE=ghcr.io/${{ github.repository_owner }}/base:latest
labels: ${{ steps.meta-crond.outputs.labels }}
# revoltchat/pushd
# stoatchat/pushd
- name: Docker meta
id: meta-pushd
uses: docker/metadata-action@v4
with:
images: |
docker.io/revoltchat/pushd
ghcr.io/revoltchat/pushd
ghcr.io/stoatchat/pushd
- name: Publish
uses: docker/build-push-action@v4
with:

View File

@@ -73,7 +73,7 @@ jobs:
if: github.event_name != 'pull_request' && github.ref_name == 'main'
uses: actions/checkout@v3
with:
repository: revoltchat/api
repository: stoatchat/api
path: api
token: ${{ secrets.PAT }}

View File

@@ -14,7 +14,7 @@ jobs:
run: |
gh api graphql -f query='
query {
organization(login: "revoltchat"){
organization(login: "stoatchat"){
projectV2(number: 3) {
id
fields(first:20) {

View File

@@ -14,7 +14,7 @@ jobs:
run: |
gh api graphql -f query='
query {
organization(login: "revoltchat"){
organization(login: "stoatchat"){
projectV2(number: 5) {
id
fields(first:20) {

3309
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

@@ -27,8 +27,11 @@ COPY crates/core/parser/Cargo.toml ./crates/core/parser/
COPY crates/core/permissions/Cargo.toml ./crates/core/permissions/
COPY crates/core/presence/Cargo.toml ./crates/core/presence/
COPY crates/core/result/Cargo.toml ./crates/core/result/
COPY crates/core/coalesced/Cargo.toml ./crates/core/coalesced/
COPY crates/core/ratelimits/Cargo.toml ./crates/core/ratelimits/
COPY crates/services/autumn/Cargo.toml ./crates/services/autumn/
COPY crates/services/january/Cargo.toml ./crates/services/january/
COPY crates/services/gifbox/Cargo.toml ./crates/services/gifbox/
COPY crates/daemons/crond/Cargo.toml ./crates/daemons/crond/
COPY crates/daemons/pushd/Cargo.toml ./crates/daemons/pushd/
RUN sh /tmp/build-image-layer.sh deps

View File

@@ -23,8 +23,11 @@ COPY crates/core/parser/Cargo.toml ./crates/core/parser/
COPY crates/core/permissions/Cargo.toml ./crates/core/permissions/
COPY crates/core/presence/Cargo.toml ./crates/core/presence/
COPY crates/core/result/Cargo.toml ./crates/core/result/
COPY crates/core/coalesced/Cargo.toml ./crates/core/coalesced/
COPY crates/core/ratelimits/Cargo.toml ./crates/core/ratelimits/
COPY crates/services/autumn/Cargo.toml ./crates/services/autumn/
COPY crates/services/january/Cargo.toml ./crates/services/january/
COPY crates/services/gifbox/Cargo.toml ./crates/services/gifbox/
COPY crates/daemons/crond/Cargo.toml ./crates/daemons/crond/
COPY crates/daemons/pushd/Cargo.toml ./crates/daemons/pushd/
RUN sh /tmp/build-image-layer.sh deps

View File

@@ -21,9 +21,11 @@ The services and libraries that power the Revolt service.<br/>
| `core/permissions` | [crates/core/permissions](crates/core/permissions) | Core: Permission Logic | ![Crates.io Version](https://img.shields.io/crates/v/revolt-permissions) ![Crates.io Version](https://img.shields.io/crates/msrv/revolt-permissions) ![Crates.io Version](https://img.shields.io/crates/size/revolt-permissions) ![Crates.io License](https://img.shields.io/crates/l/revolt-permissions) |
| `core/presence` | [crates/core/presence](crates/core/presence) | Core: User Presence | ![Crates.io Version](https://img.shields.io/crates/v/revolt-presence) ![Crates.io Version](https://img.shields.io/crates/msrv/revolt-presence) ![Crates.io Version](https://img.shields.io/crates/size/revolt-presence) ![Crates.io License](https://img.shields.io/crates/l/revolt-presence) |
| `core/result` | [crates/core/result](crates/core/result) | Core: Result and Error types | ![Crates.io Version](https://img.shields.io/crates/v/revolt-result) ![Crates.io Version](https://img.shields.io/crates/msrv/revolt-result) ![Crates.io Version](https://img.shields.io/crates/size/revolt-result) ![Crates.io License](https://img.shields.io/crates/l/revolt-result) |
| `core/coalesced` | [crates/core/coalesced](crates/core/coalesced) | Core: Coalescion service | ![Crates.io Version](https://img.shields.io/crates/v/revolt-coalesced) ![Crates.io Version](https://img.shields.io/crates/msrv/revolt-coalesced) ![Crates.io Version](https://img.shields.io/crates/size/revolt-coalesced) ![Crates.io License](https://img.shields.io/crates/l/revolt-coalesced) |
| `delta` | [crates/delta](crates/delta) | REST API server | ![License](https://img.shields.io/badge/license-AGPL--3.0--or--later-blue) |
| `bonfire` | [crates/bonfire](crates/bonfire) | WebSocket events server | ![License](https://img.shields.io/badge/license-AGPL--3.0--or--later-blue) |
| `services/january` | [crates/services/january](crates/services/january) | Proxy server | ![License](https://img.shields.io/badge/license-AGPL--3.0--or--later-blue) |
| `services/gifbox` | [crates/services/gifbox](crates/services/gifbox) | Tenor proxy server | ![License](https://img.shields.io/badge/license-AGPL--3.0--or--later-blue) |
| `services/autumn` | [crates/services/autumn](crates/services/autumn) | File server | ![License](https://img.shields.io/badge/license-AGPL--3.0--or--later-blue) |
| `daemons/crond` | [crates/daemons/crond](crates/daemons/crond) | Timed data clean up daemon server | ![License](https://img.shields.io/badge/license-AGPL--3.0--or--later-blue) |
| `daemons/pushd` | [crates/daemons/pushd](crates/daemons/pushd) | Push notification daemon server | ![License](https://img.shields.io/badge/license-AGPL--3.0--or--later-blue) |
@@ -66,6 +68,7 @@ As a heads-up, the development environment uses the following ports:
| `crates/bonfire` | 14703 |
| `crates/services/autumn` | 14704 |
| `crates/services/january` | 14705 |
| `crates/services/gifbox` | 14706 |
Now you can clone and build the project:
@@ -114,7 +117,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/"
@@ -140,6 +144,8 @@ cargo run --bin revolt-bonfire
cargo run --bin revolt-autumn
# run the proxy server
cargo run --bin revolt-january
# run the tenor proxy
cargo run --bin revolt-gifbox
# run the push daemon (not usually needed in regular development)
cargo run --bin revolt-pushd

View File

@@ -40,6 +40,9 @@ port = 14025
use_tls = false
use_starttls = false
[api.security]
token_secret = "trolt"
[files.s3]
# S3 protocol endpoint
endpoint = "http://127.0.0.1:14009"

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.9"
license = "AGPL-3.0-or-later"
edition = "2021"
@@ -19,6 +19,7 @@ async-channel = "2.3.1"
# parsing
querystring = "1.1.0"
regex = "1.11.1"
# serde
bincode = "1.3.3"
@@ -41,7 +42,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.9", path = "../core/permissions" }
revolt-presence = { path = "../core/presence", features = ["redis-is-patched"] }
# redis

View File

@@ -1,5 +1,5 @@
# Build Stage
FROM ghcr.io/revoltchat/base:latest AS builder
FROM ghcr.io/stoatchat/base:latest AS builder
FROM debian:12 AS debian
# Bundle Stage

View File

@@ -1,9 +1,15 @@
use async_tungstenite::tungstenite::{handshake, Message};
use futures::channel::oneshot::Sender;
use once_cell::sync::Lazy;
use regex::Regex;
use revolt_database::events::client::ReadyPayloadFields;
use revolt_result::{create_error, Result};
use serde::{Deserialize, Serialize};
/// matches either a single word ie "users" or a key and value ie "settings[notifications]"
static READY_PAYLOAD_FIELD_REGEX: Lazy<Regex> =
Lazy::new(|| Regex::new(r#"^(\w+)(?:\[(\S+)\])?$"#).unwrap());
/// Enumeration of supported protocol formats
#[derive(Debug)]
pub enum ProtocolFormat {
@@ -17,6 +23,7 @@ pub struct ProtocolConfiguration {
protocol_version: i32,
format: ProtocolFormat,
session_token: Option<String>,
ready_payload_fields: ReadyPayloadFields,
}
impl ProtocolConfiguration {
@@ -25,11 +32,13 @@ impl ProtocolConfiguration {
protocol_version: i32,
format: ProtocolFormat,
session_token: Option<String>,
ready_payload_fields: ReadyPayloadFields,
) -> Self {
Self {
protocol_version,
format,
session_token,
ready_payload_fields,
}
}
@@ -86,14 +95,8 @@ impl ProtocolConfiguration {
}
/// Get ready payload fields
pub fn get_ready_payload_fields(&self) -> Vec<ReadyPayloadFields> {
vec![
ReadyPayloadFields::Users,
ReadyPayloadFields::Servers,
ReadyPayloadFields::Channels,
ReadyPayloadFields::Members,
ReadyPayloadFields::Emoji,
]
pub fn get_ready_payload_fields(&self) -> &ReadyPayloadFields {
&self.ready_payload_fields
}
}
@@ -124,6 +127,22 @@ impl handshake::server::Callback for WebsocketHandshakeCallback {
let mut protocol_version = 1;
let mut format = ProtocolFormat::Json;
let mut session_token = None;
let mut ready_payload_fields = if params.iter().any(|(k, _)| *k == "ready") {
// If they pass the ready field, set all fields to false
ReadyPayloadFields {
users: false,
servers: false,
channels: false,
members: false,
emojis: false,
user_settings: Vec::new(),
channel_unreads: false,
policy_changes: false,
}
} else {
ReadyPayloadFields::default()
};
// Parse and map parameters from key-value to known variables.
for (key, value) in params {
@@ -139,6 +158,30 @@ impl handshake::server::Callback for WebsocketHandshakeCallback {
_ => {}
},
"token" => session_token = Some(value.into()),
"ready" => {
// Re-enable all the fields the client specifies
if let Some(captures) = READY_PAYLOAD_FIELD_REGEX.captures(value) {
if let Some(field) = captures.get(0) {
match field.as_str() {
"users" => ready_payload_fields.users = true,
"servers" => ready_payload_fields.servers = true,
"channels" => ready_payload_fields.channels = true,
"members" => ready_payload_fields.members = true,
"emojis" => ready_payload_fields.emojis = true,
"channel_unreads" => ready_payload_fields.channel_unreads = true,
"user_settings" => {
if let Some(subkey) = captures.get(1) {
ready_payload_fields
.user_settings
.push(subkey.as_str().to_string());
}
}
"policy_changes" => ready_payload_fields.policy_changes = true,
_ => {}
}
}
}
}
_ => {}
}
}
@@ -151,6 +194,7 @@ impl handshake::server::Callback for WebsocketHandshakeCallback {
protocol_version,
format,
session_token,
ready_payload_fields,
})
.is_ok()
{

View File

@@ -95,21 +95,23 @@ impl State {
pub async fn generate_ready_payload(
&mut self,
db: &Database,
fields: Vec<ReadyPayloadFields>,
fields: &ReadyPayloadFields,
) -> Result<EventV1> {
let user = self.clone_user();
self.cache.is_bot = user.bot.is_some();
// Fetch pending policy changes.
let policy_changes = if user.bot.is_some() {
vec![]
let policy_changes = if user.bot.is_some() || !fields.policy_changes {
None
} else {
db.fetch_policy_changes()
.await?
.into_iter()
.filter(|policy| policy.created_time > user.last_acknowledged_policy_change)
.map(Into::into)
.collect()
Some(
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.
@@ -168,7 +170,7 @@ impl State {
.await?;
// Fetch customisations.
let emojis = if fields.contains(&ReadyPayloadFields::Emoji) {
let emojis = if fields.emojis {
Some(
db.fetch_emoji_by_parent_ids(
&servers
@@ -176,25 +178,34 @@ impl State {
.map(|x| x.id.to_string())
.collect::<Vec<String>>(),
)
.await?,
.await?
.into_iter()
.map(|emoji| emoji.into())
.collect(),
)
} else {
None
};
// Fetch user settings
let user_settings = if let Some(ReadyPayloadFields::UserSettings(keys)) = fields
.iter()
.find(|e| matches!(e, ReadyPayloadFields::UserSettings(_)))
{
Some(db.fetch_user_settings(&user.id, keys).await?)
let user_settings = if !fields.user_settings.is_empty() {
Some(
db.fetch_user_settings(&user.id, &fields.user_settings)
.await?,
)
} else {
None
};
// Fetch channel unreads
let channel_unreads = if fields.contains(&ReadyPayloadFields::ChannelUnreads) {
Some(db.fetch_unreads(&user.id).await?)
let channel_unreads = if fields.channel_unreads {
Some(
db.fetch_unreads(&user.id)
.await?
.into_iter()
.map(|unread| unread.into())
.collect(),
)
} else {
None
};
@@ -241,30 +252,25 @@ impl State {
}
Ok(EventV1::Ready {
users: if fields.contains(&ReadyPayloadFields::Users) {
Some(users)
} else {
None
},
servers: if fields.contains(&ReadyPayloadFields::Servers) {
users: if fields.users { Some(users) } else { None },
servers: if fields.servers {
Some(servers.into_iter().map(Into::into).collect())
} else {
None
},
channels: if fields.contains(&ReadyPayloadFields::Channels) {
channels: if fields.channels {
Some(channels.into_iter().map(Into::into).collect())
} else {
None
},
members: if fields.contains(&ReadyPayloadFields::Members) {
members: if fields.members {
Some(members.into_iter().map(Into::into).collect())
} else {
None
},
emojis: emojis.map(|vec| vec.into_iter().map(Into::into).collect()),
emojis,
user_settings,
channel_unreads: channel_unreads.map(|vec| vec.into_iter().map(Into::into).collect()),
channel_unreads,
policy_changes,
})

View File

@@ -17,8 +17,11 @@ use redis_kiss::{PayloadType, REDIS_PAYLOAD_TYPE, REDIS_URI};
use revolt_config::report_internal_error;
use revolt_database::{
events::{client::EventV1, server::ClientMessage},
util::oauth2,
iso8601_timestamp::Timestamp,
Database, User, UserHint,
};
use revolt_models::v0;
use revolt_presence::{create_session, delete_session};
use async_std::{
@@ -87,14 +90,46 @@ pub async fn client(db: &'static Database, stream: TcpStream, addr: SocketAddr)
return;
};
// Presume the token is a proper token first
let (user, session_id) = match User::from_token(db, token, UserHint::Any).await {
Ok(user) => user,
Err(err) => {
write
.send(config.encode(&EventV1::Error { data: err }))
Ok((user, session_id)) => {
db.update_session_last_seen(&session_id, Timestamp::now_utc())
.await
.ok();
return;
(user, session_id)
},
Err(err) => {
let revolt_config = revolt_config::config().await;
// If it fails to find the user from the token see if its an OAuth2 token
let res = match oauth2::decode_token(&revolt_config.api.security.token_secret, token) {
// Check if the OAuth2 token is allowed to establish an events websocket
Ok(claims) => if !claims.scopes.contains(&v0::OAuth2Scope::Events) {
// TODO: maybe a last_seen system for OAuth2 as well
db.fetch_user(&claims.sub).await.map(|user| (user, claims.jti))
} else {
Err(create_error!(MissingScope { scope: v0::OAuth2Scope::Events.to_string() }))
},
// If its expired return an error
Err(e) => if e.into_kind() == oauth2::JWTErrorKind::ExpiredSignature {
Err(create_error!(ExpiredToken))
} else {
// Finally re-return the error from User::from_token if everything else fails to avoid a confusing error
Err(err)
}
};
match res {
Ok(user) => user,
Err(err) => {
write
.send(config.encode(&EventV1::Error { data: err }))
.await
.ok();
return;
}
}
}
};

View File

@@ -0,0 +1,22 @@
[package]
name = "revolt-coalesced"
version = "0.8.9"
edition = "2021"
license = "MIT"
authors = ["Paul Makles <me@insrt.uk>", "Zomatree <me@zomatree.live>"]
description = "Revolt Backend: Coalescion service"
[features]
tokio = ["dep:tokio"]
queue = ["dep:indexmap"]
cache = ["dep:lru"]
default = ["tokio"]
[dependencies]
tokio = { version = "1.47.0", features = ["sync"], optional = true }
indexmap = { version = "*", optional = true }
lru = { version = "*", optional = true }
[dev-dependencies]
tokio = { version = "1.47.0", features = ["rt", "rt-multi-thread", "macros", "time"] }

View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) 2024 Pawel Makles
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,24 @@
#[derive(Clone, PartialEq, Eq, Debug)]
/// Config values for [`CoalescionService`].
pub struct CoalescionServiceConfig {
/// How many tasks are running at once
pub max_concurrent: Option<usize>,
/// Whether to queue tasks once `max_concurrent` is reached
#[cfg(feature = "queue")]
pub queue_requests: bool,
/// Max amount of tasks in the buffer queue
#[cfg(feature = "queue")]
pub max_queue: Option<usize>,
}
impl Default for CoalescionServiceConfig {
fn default() -> Self {
Self {
max_concurrent: Some(100),
#[cfg(feature = "queue")]
queue_requests: true,
#[cfg(feature = "queue")]
max_queue: Some(100)
}
}
}

View File

@@ -0,0 +1,27 @@
use std::fmt;
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
/// Coalescion service error.
pub enum Error {
/// Failed to receive the actions return from the channel for unknown reason
RecvError,
/// Reached the `max_concurrent` amount of actions running at once and could not queue the action
MaxConcurrent,
/// Reached the `max_queue` amount of actions in the queue
MaxQueue,
/// Failed to downcast the type to the current type being returned, this will be most likely an ID collision
DowncastError,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::RecvError => write!(f, "Unable to receive data from the channel"),
Error::MaxConcurrent => write!(f, "Max number of tasks running at once"),
Error::MaxQueue => write!(f, "Max number of tasks in queue"),
Error::DowncastError => write!(f, "Failed to downcast type, possible key collision with different types")
}
}
}
impl std::error::Error for Error {}

View File

@@ -0,0 +1,39 @@
//! # Coalesced
//!
//! Coalescion service to group, caching and queue duplicate actions.
//! useful for deduplicating web requests, database lookups and other similar resource
//! intensive or rate-limited actions.
//!
//! ## Features
//! - `tokio`: Uses tokio for the async backend, this is currently the only backend.
//! - `queue`: Whether to support queueing requests to only allow X amount of actions running at once.
//! - `cache`: Whether to cache the actions results for future actions with the same id, uses an LRU cache internally.
//!
//! [`CoalescionService`] uses both [`Arc`] and [`RwLock`] internally and can be cheaply cloned to
//! use in your codebase.
//!
//! It is common practice to wrap the service and in your own which delegates the executions to ensure all ids are tracked in one location across your codebase.
//!
//! All values are stored using [`Any`] and must be [`'static`] + [`Send`] + [`Sync`], if there is an id mismatch
//! and a type is wrong the library will return an error, values returned from the service are also
//! wrapped in an [`Arc`] as they are shared to each duplicate action.
//!
//! ## Example:
//! ```rs
//! use revolt_coalesced::CoalescionService;
//!
//! let service = CoalescionService::new();
//!
//! let user_id = "my_user_id";
//! let user = service.execute(user_id, || async move {
//! database.fetch_user(user_id).await.unwrap()
//! }).await;
//! ```
mod config;
mod error;
mod service;
pub use config::CoalescionServiceConfig;
pub use error::Error;
pub use service::CoalescionService;

View File

@@ -0,0 +1,208 @@
use std::{any::Any, collections::HashMap, fmt::Debug, future::Future, hash::Hash, sync::Arc};
use tokio::sync::{
watch::{channel as watch_channel, Receiver},
RwLock,
};
#[cfg(feature = "cache")]
use lru::LruCache;
#[cfg(feature = "queue")]
use indexmap::IndexMap;
use crate::{CoalescionServiceConfig, Error};
#[derive(Debug, Clone)]
#[allow(clippy::type_complexity)]
/// # Coalescion service
///
/// See module description for example usage.
pub struct CoalescionService<Id: Hash + Clone + Eq> {
config: Arc<CoalescionServiceConfig>,
watchers: Arc<RwLock<HashMap<Id, Receiver<Option<Result<Arc<dyn Any + Send + Sync>, Error>>>>>>,
#[cfg(feature = "queue")]
queue: Arc<RwLock<IndexMap<Id, Receiver<Option<Result<Arc<dyn Any + Send + Sync>, Error>>>>>>,
#[cfg(feature = "cache")]
cache: Option<Arc<tokio::sync::Mutex<LruCache<Id, Arc<dyn Any + Send + Sync>>>>>,
}
impl<Id: Hash + Clone + Eq> CoalescionService<Id> {
pub fn new() -> Self {
Default::default()
}
pub fn from_config(config: CoalescionServiceConfig) -> Self {
Self {
config: Arc::new(config),
watchers: Arc::new(RwLock::new(HashMap::new())),
#[cfg(feature = "queue")]
queue: Arc::new(RwLock::new(IndexMap::new())),
#[cfg(feature = "cache")]
cache: None,
}
}
#[cfg(feature = "cache")]
pub fn from_cache(
config: CoalescionServiceConfig,
cache: LruCache<Id, Arc<dyn Any + Send + Sync>>,
) -> Self {
Self {
cache: Some(Arc::new(Mutex::new(cache))),
..Self::from_config(config)
}
}
async fn wait_for<Value: Any + Send + Sync>(
&self,
mut receiver: Receiver<Option<Result<Arc<dyn Any + Send + Sync>, Error>>>,
) -> Result<Arc<Value>, Error> {
receiver
.wait_for(|v| v.is_some())
.await
.map_err(|_| Error::RecvError)
.and_then(|r| r.clone().unwrap())
.and_then(|arc| Arc::downcast(arc).map_err(|_| Error::DowncastError))
}
async fn insert_and_execute<
Value: Send + Sync + 'static,
F: FnOnce() -> Fut,
Fut: Future<Output = Value>,
>(
&self,
id: Id,
func: F,
) -> Result<Arc<Value>, Error> {
let (send, recv) = watch_channel(None);
self.watchers.write().await.insert(id.clone(), recv);
let value = Ok(Arc::new(func().await));
send.send_modify(|opt| {
opt.replace(value.clone().map(|v| v as Arc<dyn Any + Send + Sync>));
});
#[cfg(feature = "cache")]
if let Some(cache) = self.cache.as_ref() {
if let Ok(value) = &value {
cache.lock().await.push(id.clone(), value.clone());
}
};
self.watchers.write().await.remove(&id);
value
}
/// Coalesces an function, the actual function may not run if one with the same id is already running,
/// queued to be ran, or cached, the id should be globally unique for this specific action.
pub async fn execute<
Value: Send + Sync + 'static,
F: FnOnce() -> Fut,
Fut: Future<Output = Value>,
>(
&self,
id: Id,
func: F,
) -> Result<Arc<Value>, Error> {
#[cfg(feature = "cache")]
if let Some(cache) = self.cache.as_ref() {
if let Some(value) = cache.lock().await.get(&id) {
return Arc::downcast::<Value>(value.clone()).map_err(|_| Error::DowncastError);
}
};
let (receiver, length) = {
let watchers = self.watchers.read().await;
let length = watchers.len();
(watchers.get(&id).cloned(), length)
};
if let Some(receiver) = receiver {
self.wait_for(receiver).await
} else {
match self.config.max_concurrent {
Some(max_concurrent) if length >= max_concurrent => {
#[cfg(feature = "queue")]
if self.config.queue_requests {
let (receiver, length) = {
let queue = self.queue.read().await;
(queue.get(&id).cloned(), queue.len())
};
if let Some(receiver) = receiver {
return self.wait_for(receiver).await;
} else {
if self
.config
.max_queue
.is_some_and(|max_queue| max_queue >= length)
{
return Err(Error::MaxQueue);
};
let (send, recv) = watch_channel(None);
self.queue.write().await.insert(id.clone(), recv);
loop {
let length = self.watchers.read().await.len();
if length < max_concurrent {
let first_key = {
let queue = self.queue.read().await;
queue.first().map(|v| v.0).cloned()
};
if first_key == Some(id.clone()) {
self.queue.write().await.shift_remove(&id);
let response = self.insert_and_execute(id, func).await;
send.send_modify(|opt| {
opt.replace(
response
.clone()
.map(|v| v as Arc<dyn Any + Send + Sync>),
);
});
return response;
}
}
}
}
} else {
Err(Error::MaxConcurrent)
}
#[cfg(not(feature = "queue"))]
Err(Error::MaxConcurrent)
}
_ => self.insert_and_execute(id, func).await,
}
}
}
/// Fetches the amount of currently running tasks
pub async fn current_task_count(&self) -> usize {
self.watchers.read().await.len()
}
#[cfg(feature = "queue")]
/// Fetches the current length of the queue
pub async fn current_queue_len(&self) -> usize {
self.queue.read().await.len()
}
}
impl<Id: Hash + Clone + Eq> Default for CoalescionService<Id> {
fn default() -> Self {
Self::from_config(CoalescionServiceConfig::default())
}
}

View File

@@ -1,6 +1,6 @@
[package]
name = "revolt-config"
version = "0.8.7"
version = "0.8.9"
edition = "2021"
license = "MIT"
authors = ["Paul Makles <me@insrt.uk>"]
@@ -11,8 +11,9 @@ description = "Revolt Backend: Configuration"
[features]
anyhow = ["dep:sentry-anyhow"]
report-macros = ["revolt-result"]
sentry = ["dep:sentry"]
test = ["async-std"]
default = ["test", "anyhow"]
default = ["test", "sentry"]
[dependencies]
# Utility
@@ -32,8 +33,8 @@ log = "0.4.14"
pretty_env_logger = "0.4.0"
# Sentry
sentry = "0.31.5"
sentry = { version = "0.31.5", optional = true }
sentry-anyhow = { version = "0.38.1", optional = true }
# Core
revolt-result = { version = "0.8.7", path = "../result", optional = true }
revolt-result = { version = "0.8.9", path = "../result", optional = true }

View File

@@ -56,6 +56,10 @@ voso_legacy_token = ""
trust_cloudflare = false
# easypwned endpoint
easypwned = ""
# Secret used to encode and decode tokens
token_secret = ""
# Tenor API Key
tenor_key = ""
[api.security.captcha]
# hCaptcha configuration
@@ -277,3 +281,4 @@ files = ""
proxy = ""
pushd = ""
crond = ""
gifbox = ""

View File

@@ -6,10 +6,12 @@ use futures_locks::RwLock;
use once_cell::sync::Lazy;
use serde::Deserialize;
#[cfg(feature = "sentry")]
pub use sentry::{capture_error, capture_message, Level};
#[cfg(feature = "anyhow")]
pub use sentry_anyhow::capture_anyhow;
#[cfg(feature = "report-macros")]
#[cfg(all(feature = "report-macros", feature = "sentry"))]
#[macro_export]
macro_rules! report_error {
( $expr: expr, $error: ident $( $tt:tt )? ) => {
@@ -24,7 +26,7 @@ macro_rules! report_error {
};
}
#[cfg(feature = "report-macros")]
#[cfg(all(feature = "report-macros", feature = "sentry"))]
#[macro_export]
macro_rules! capture_internal_error {
( $expr: expr ) => {
@@ -35,7 +37,7 @@ macro_rules! capture_internal_error {
};
}
#[cfg(feature = "report-macros")]
#[cfg(all(feature = "report-macros", feature = "sentry"))]
#[macro_export]
macro_rules! report_internal_error {
( $expr: expr ) => {
@@ -60,6 +62,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 +78,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 {
@@ -171,6 +190,8 @@ pub struct ApiSecurity {
pub captcha: ApiSecurityCaptcha,
pub trust_cloudflare: bool,
pub easypwned: String,
pub token_secret: String,
pub tenor_key: String,
}
#[derive(Deserialize, Debug, Clone)]
@@ -346,6 +367,7 @@ pub struct Sentry {
pub proxy: String,
pub pushd: String,
pub crond: String,
pub gifbox: String,
}
#[derive(Deserialize, Debug, Clone)]
@@ -388,6 +410,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;
@@ -397,6 +424,7 @@ pub async fn config() -> Settings {
}
/// Configure logging and common Rust variables
#[cfg(feature = "sentry")]
pub async fn setup_logging(release: &'static str, dsn: String) -> Option<sentry::ClientInitGuard> {
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "info");
@@ -406,12 +434,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}");
@@ -428,6 +450,7 @@ pub async fn setup_logging(release: &'static str, dsn: String) -> Option<sentry:
}
}
#[cfg(feature = "sentry")]
#[macro_export]
macro_rules! configure {
($application: ident) => {

View File

@@ -1,6 +1,6 @@
[package]
name = "revolt-database"
version = "0.8.7"
version = "0.8.9"
edition = "2021"
license = "AGPL-3.0-or-later"
authors = ["Paul Makles <me@insrt.uk>"]
@@ -10,12 +10,12 @@ description = "Revolt Backend: Database Implementation"
[features]
# Databases
mongodb = ["dep:mongodb", "bson"]
mongodb = ["dep:mongodb", "bson", "authifier/database-mongodb"]
# ... Other
tasks = ["isahc", "linkify", "url-escape"]
async-std-runtime = ["async-std"]
rocket-impl = ["rocket", "schemars", "revolt_okapi", "revolt_rocket_okapi"]
async-std-runtime = ["async-std", "authifier/async-std-runtime"]
rocket-impl = ["rocket", "schemars", "revolt_okapi", "revolt_rocket_okapi", "authifier/rocket_impl"]
axum-impl = ["axum"]
redis-is-patched = ["revolt-presence/redis-is-patched"]
@@ -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.9", 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.9", path = "../result" }
revolt-models = { version = "0.8.9", 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.9", path = "../presence" }
revolt-permissions = { version = "0.8.9", path = "../permissions", features = [
"serde",
"bson",
] }
revolt-parser = { version = "0.8.7", path = "../parser" }
revolt-parser = { version = "0.8.9", path = "../parser" }
# Utility
log = "0.4"
@@ -53,6 +53,8 @@ linkify = { optional = true, version = "0.8.1" }
url-escape = { optional = true, version = "0.1.1" }
validator = { version = "0.16", features = ["derive"] }
isahc = { optional = true, version = "1.7", features = ["json"] }
jsonwebtoken = "9.3.1"
chrono = "0.4"
# Serialisation
serde_json = "1"
@@ -91,13 +93,8 @@ rocket = { version = "0.5.1", default-features = false, features = [
revolt_okapi = { version = "0.9.1", optional = true }
revolt_rocket_okapi = { version = "0.10.0", optional = true }
# Notifications
fcm_v1 = "0.3.0"
web-push = "0.10.0"
revolt_a2 = { version = "0.10", default-features = false, features = ["ring"] }
# Authifier
authifier = { version = "1.0.15", features = ["rocket_impl"] }
authifier = { version = "1.0.15" }
# RabbitMQ
amqprs = { version = "1.7.0" }

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

@@ -1,3 +1,4 @@
#[cfg(feature = "mongodb")]
mod mongodb;
mod reference;
@@ -13,6 +14,7 @@ use authifier::Authifier;
use rand::Rng;
use revolt_config::config;
#[cfg(feature = "mongodb")]
pub use self::mongodb::*;
pub use self::reference::*;
@@ -25,8 +27,10 @@ pub enum DatabaseInfo {
/// Use the mock database
Reference,
/// Connect to MongoDB
#[cfg(feature = "mongodb")]
MongoDb { uri: String, database_name: String },
/// Use existing MongoDB connection
#[cfg(feature = "mongodb")]
MongoDbFromClient(::mongodb::Client, String),
}
@@ -36,6 +40,7 @@ pub enum Database {
/// Mock database
Reference(ReferenceDb),
/// MongoDB database
#[cfg(feature = "mongodb")]
MongoDb(MongoDb),
}
@@ -45,7 +50,7 @@ impl DatabaseInfo {
pub async fn connect(self) -> Result<Database, String> {
let config = config().await;
Ok(match self {
match self {
DatabaseInfo::Auto => {
if std::env::var("TEST_DB").is_ok() {
DatabaseInfo::Test(format!(
@@ -53,16 +58,20 @@ impl DatabaseInfo {
rand::thread_rng().gen_range(1_000_000..10_000_000)
))
.connect()
.await?
.await
} else if !config.database.mongodb.is_empty() {
DatabaseInfo::MongoDb {
#[cfg(feature = "mongodb")]
return DatabaseInfo::MongoDb {
uri: config.database.mongodb,
database_name: "revolt".to_string(),
}
.connect()
.await?
.await;
#[cfg(not(feature = "mongodb"))]
return Err("MongoDB not enabled.".to_string())
} else {
DatabaseInfo::Reference.connect().await?
DatabaseInfo::Reference.connect().await
}
}
DatabaseInfo::Test(database_name) => {
@@ -70,30 +79,36 @@ impl DatabaseInfo {
.expect("`TEST_DB` environment variable should be set to REFERENCE or MONGODB")
.as_str()
{
"REFERENCE" => DatabaseInfo::Reference.connect().await?,
"REFERENCE" => DatabaseInfo::Reference.connect().await,
"MONGODB" => {
DatabaseInfo::MongoDb {
#[cfg(feature = "mongodb")]
return DatabaseInfo::MongoDb {
uri: config.database.mongodb,
database_name,
}
.connect()
.await?
.await;
#[cfg(not(feature = "mongodb"))]
return Err("MongoDB not enabled.".to_string())
}
_ => unreachable!("must specify REFERENCE or MONGODB"),
}
}
DatabaseInfo::Reference => Database::Reference(Default::default()),
DatabaseInfo::Reference => Ok(Database::Reference(Default::default())),
#[cfg(feature = "mongodb")]
DatabaseInfo::MongoDb { uri, database_name } => {
let client = ::mongodb::Client::with_uri_str(uri)
.await
.map_err(|_| "Failed to init db connection.".to_string())?;
Database::MongoDb(MongoDb(client, database_name))
Ok(Database::MongoDb(MongoDb(client, database_name)))
}
#[cfg(feature = "mongodb")]
DatabaseInfo::MongoDbFromClient(client, database_name) => {
Database::MongoDb(MongoDb(client, database_name))
Ok(Database::MongoDb(MongoDb(client, database_name)))
}
})
}
}
}
@@ -219,12 +234,16 @@ impl Database {
Authifier {
database: match self {
Database::Reference(_) => Default::default(),
#[cfg(feature = "mongodb")]
Database::MongoDb(MongoDb(client, _)) => authifier::Database::MongoDb(
authifier::database::MongoDb(client.database("revolt")),
),
},
config: auth_config,
#[cfg(feature = "tasks")]
event_channel: Some(crate::tasks::authifier_relay::sender()),
#[cfg(not(feature = "tasks"))]
event_channel: None,
}
}
}

View File

@@ -10,7 +10,6 @@ use serde::de::DeserializeOwned;
use serde::Serialize;
database_derived!(
#[cfg(feature = "mongodb")]
/// MongoDB implementation
pub struct MongoDb(pub ::mongodb::Client, pub String);
);

View File

@@ -5,13 +5,14 @@ use futures::lock::Mutex;
use crate::{
Bot, Channel, ChannelCompositeKey, ChannelUnread, Emoji, File, FileHash, Invite, Member,
MemberCompositeKey, Message, PolicyChange, RatelimitEvent, Report, Server, ServerBan, Snapshot,
User, UserSettings, Webhook,
User, UserSettings, Webhook, AuthorizedBotId, AuthorizedBot,
};
database_derived!(
/// Reference implementation
#[derive(Default)]
pub struct ReferenceDb {
pub authorized_bots: Arc<Mutex<HashMap<AuthorizedBotId, AuthorizedBot>>>,
pub bots: Arc<Mutex<HashMap<String, Bot>>>,
pub channels: Arc<Mutex<HashMap<String, Channel>>>,
pub channel_invites: Arc<Mutex<HashMap<String, Invite>>>,

View File

@@ -20,16 +20,31 @@ pub enum Ping {
}
/// Fields provided in Ready payload
#[derive(PartialEq)]
pub enum ReadyPayloadFields {
Users,
Servers,
Channels,
Members,
Emoji,
#[derive(PartialEq, Debug, Clone, Deserialize)]
pub struct ReadyPayloadFields {
pub users: bool,
pub servers: bool,
pub channels: bool,
pub members: bool,
pub emojis: bool,
pub user_settings: Vec<String>,
pub channel_unreads: bool,
pub policy_changes: bool,
}
UserSettings(Vec<String>),
ChannelUnreads,
impl Default for ReadyPayloadFields {
fn default() -> Self {
Self {
users: true,
servers: true,
channels: true,
members: true,
emojis: true,
user_settings: Vec::new(),
channel_unreads: false,
policy_changes: true,
}
}
}
/// Protocol Events
@@ -63,7 +78,8 @@ pub enum EventV1 {
#[serde(skip_serializing_if = "Option::is_none")]
channel_unreads: Option<Vec<ChannelUnread>>,
policy_changes: Vec<PolicyChange>,
#[serde(skip_serializing_if = "Option::is_none")]
policy_changes: Option<Vec<PolicyChange>>,
},
/// Ping response
@@ -144,7 +160,13 @@ pub enum EventV1 {
},
/// User joins server
ServerMemberJoin { id: String, user: String },
ServerMemberJoin {
id: String,
// Deprecated: use member.id.user
#[deprecated = "Use member.id.user instead"]
user: String,
member: Member,
},
/// User left server
ServerMemberLeave {
@@ -165,6 +187,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,8 +1,8 @@
use serde::Deserialize;
use serde::{Serialize, Deserialize};
use super::client::Ping;
#[derive(Deserialize, Debug)]
#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "type")]
pub enum ClientMessage {
Authenticate { token: String },

View File

@@ -25,6 +25,9 @@ pub use mongodb;
#[macro_use]
extern crate bson;
#[cfg(not(feature = "async-std-runtime"))]
compile_error!("async-std-runtime feature must be enabled.");
#[macro_export]
#[cfg(debug_assertions)]
macro_rules! query {
@@ -103,6 +106,7 @@ pub mod util;
pub use models::*;
pub mod events;
#[cfg(feature = "tasks")]
pub mod tasks;
mod amqp;

View File

@@ -1,3 +1,4 @@
#[cfg(feature = "mongodb")]
mod mongodb;
mod reference;

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

@@ -0,0 +1,5 @@
mod model;
mod ops;
pub use model::*;
pub use ops::*;

View File

@@ -0,0 +1,30 @@
use iso8601_timestamp::Timestamp;
use crate::OAuth2Scope;
auto_derived! (
/// Unique id of the user and bot
#[derive(Hash)]
pub struct AuthorizedBotId {
/// User id
pub user: String,
/// Bot Id
pub bot: String,
}
pub struct AuthorizedBot {
/// Unique Id
#[serde(rename = "_id")]
pub id: AuthorizedBotId,
/// When the authorized oauth2 bot connection was created at
pub created_at: Timestamp,
/// If and when the authorized oauth2 bot connection was revoked at
pub deauthorized_at: Option<Timestamp>,
/// Scopes the bot has access to
pub scope: Vec<OAuth2Scope>,
}
);

View File

@@ -0,0 +1,27 @@
use revolt_result::Result;
use crate::{AuthorizedBot, AuthorizedBotId};
mod mongodb;
mod reference;
#[async_trait]
pub trait AbstractAuthorizedBots: Sync + Send {
/// Insert emoji into database.
async fn insert_authorized_bot(&self, authorized_bot: &AuthorizedBot) -> Result<()>;
/// Fetch an authorized bot by its id
async fn fetch_authorized_bot(&self, id: &AuthorizedBotId) -> Result<AuthorizedBot>;
/// Fetch a users authorized bot by its id
async fn fetch_users_authorized_bots(&self, user_id: &str) -> Result<Vec<AuthorizedBot>>;
/// Deletes an authorized bot
async fn delete_authorized_bot(&self, id: &AuthorizedBotId) -> Result<()>;
/// Deauthorizes an authorized bot
async fn deauthorize_authorized_bot(&self, id: &AuthorizedBotId) -> Result<AuthorizedBot>;
// Fetches all authorized bots which have been deauthorized
async fn fetch_deauthorized_authorized_bots(&self) -> Result<Vec<AuthorizedBot>>;
}

View File

@@ -0,0 +1,71 @@
use bson::to_bson;
use revolt_result::Result;
use iso8601_timestamp::Timestamp;
use crate::{MongoDb, AuthorizedBot, AuthorizedBotId};
use super::AbstractAuthorizedBots;
static COL: &str = "authorized_bots";
#[async_trait]
impl AbstractAuthorizedBots for MongoDb {
/// Insert an authorized bot into database.
async fn insert_authorized_bot(&self, authorized_bot: &AuthorizedBot) -> Result<()> {
query!(self, insert_one, COL, &authorized_bot).map(|_| ())
}
/// Fetch an authorized bot by its id
async fn fetch_authorized_bot(&self, id: &AuthorizedBotId) -> Result<AuthorizedBot> {
query!(
self,
find_one,
COL,
doc! {
"_id.user": &id.user,
"_id.bot": &id.bot
}
)?.ok_or_else(|| create_error!(NotFound))
}
/// Fetch a users authorized bot by its id
async fn fetch_users_authorized_bots(&self, user_id: &str) -> Result<Vec<AuthorizedBot>> {
query!(self, find, COL, doc! { "_id.user": &user_id })
}
/// Deletes an authorized bot
async fn delete_authorized_bot(&self, id: &AuthorizedBotId) -> Result<()> {
query!(self, delete_one, COL, doc! { "_id.user": &id.user, "_id.bot": &id.bot }).map(|_| ())
}
/// Deauthorizes an authorized bot
async fn deauthorize_authorized_bot(&self, id: &AuthorizedBotId) -> Result<AuthorizedBot> {
self.col::<AuthorizedBot>(COL)
.find_one_and_update(
doc! {
"_id.user": &id.user,
"_id.bot": &id.bot
},
doc! {
"$set": {
"deauthorized_at": to_bson(&Timestamp::now_utc()).unwrap()
}
}
)
.await
.map_err(|_| create_database_error!("find_one_and_update", COL))
.and_then(|opt| opt.ok_or_else(|| create_database_error!("find_one_and_update", COL)))
}
// Fetches all authorized bots which have been deauthorized
async fn fetch_deauthorized_authorized_bots(&self) -> Result<Vec<AuthorizedBot>> {
query!(
self,
find,
COL,
doc! {
"deauthorized_at": { "$exists": true }
}
)
}
}

View File

@@ -0,0 +1,76 @@
use revolt_result::Result;
use iso8601_timestamp::Timestamp;
use crate::{ReferenceDb, AuthorizedBot, AuthorizedBotId};
use super::AbstractAuthorizedBots;
#[async_trait]
impl AbstractAuthorizedBots for ReferenceDb {
/// Insert an authorized bot into database.
async fn insert_authorized_bot(&self, authorized_bot: &AuthorizedBot) -> Result<()> {
let mut authorized_bots = self.authorized_bots.lock().await;
if authorized_bots.contains_key(&authorized_bot.id) {
Err(create_database_error!("insert", "authorized_bots"))
} else {
authorized_bots.insert(authorized_bot.id.clone(), authorized_bot.clone());
Ok(())
}
}
/// Fetch an authorized bot by its id
async fn fetch_authorized_bot(&self, id: &AuthorizedBotId) -> Result<AuthorizedBot> {
let authorized_bots = self.authorized_bots.lock().await;
authorized_bots.get(id).cloned().ok_or_else(|| create_error!(NotFound))
}
/// Fetch a users authorized bot by its id
async fn fetch_users_authorized_bots(&self, user_id: &str) -> Result<Vec<AuthorizedBot>> {
let authorized_bots = self.authorized_bots.lock().await;
Ok(authorized_bots
.values()
.filter(|authorized_bot| authorized_bot.id.user == user_id)
.cloned()
.collect()
)
}
/// Deletes an authorized bot
async fn delete_authorized_bot(&self, id: &AuthorizedBotId) -> Result<()> {
let mut authorized_bots = self.authorized_bots.lock().await;
if authorized_bots.remove(id).is_some() {
Ok(())
} else {
Err(create_error!(NotFound))
}
}
/// Deauthorizes an authorized bot
async fn deauthorize_authorized_bot(&self, id: &AuthorizedBotId) -> Result<AuthorizedBot> {
let mut authorized_bots = self.authorized_bots.lock().await;
if let Some(authorized_bot) = authorized_bots.get_mut(id) {
authorized_bot.deauthorized_at = Some(Timestamp::now_utc());
Ok(authorized_bot.clone())
} else {
Err(create_error!(NotFound))
}
}
// Fetches all authorized bots which have been deauthorized
async fn fetch_deauthorized_authorized_bots(&self) -> Result<Vec<AuthorizedBot>> {
let authorized_bots = self.authorized_bots.lock().await;
Ok(authorized_bots
.values()
.filter(|authorized_bot| authorized_bot.deauthorized_at.is_some())
.cloned()
.collect()
)
}
}

View File

@@ -1,5 +1,6 @@
use revolt_result::Result;
use ulid::Ulid;
use std::collections::HashMap;
use crate::{events::client::EventV1, BotInformation, Database, PartialUser, User};
@@ -35,6 +36,10 @@ auto_derived_partial!(
#[serde(skip_serializing_if = "String::is_empty", default)]
pub privacy_policy_url: String,
/// Oauth2 bot settings
#[serde(skip_serializing_if = "Option::is_none", default)]
pub oauth2: Option<BotOauth2>,
/// Enum of bot flags
#[serde(skip_serializing_if = "Option::is_none")]
pub flags: Option<i32>,
@@ -42,11 +47,52 @@ auto_derived_partial!(
"PartialBot"
);
auto_derived!(
#[derive(Copy, Hash)]
pub enum OAuth2Scope {
#[serde(rename = "read:identify")]
ReadIdentify,
#[serde(rename = "read:servers")]
ReadServers,
#[serde(rename = "write:files")]
WriteFiles,
#[serde(rename = "events")]
Events,
#[serde(rename = "full")]
Full,
}
pub struct OAuth2ScopeReasoning {
pub allow: String,
pub deny: String
}
);
auto_derived_partial!(
pub struct BotOauth2 {
/// Whether the oauth2 client is public and should not receive a secret key
#[serde(default)]
pub public: bool,
/// Secret key used for authorisation, not provided if the client is public
#[serde(default)]
pub secret: Option<String>,
/// Allowed redirects for the authorisation
#[serde(default)]
pub redirects: Vec<String>,
/// Mapping of allowed scopes and the reasonings
#[serde(default)]
pub allowed_scopes: HashMap<OAuth2Scope, OAuth2ScopeReasoning>,
},
"PartialBotOauth2"
);
auto_derived!(
/// Optional fields on bot object
pub enum FieldsBot {
Token,
InteractionsURL,
Oauth2,
Oauth2Secret,
}
);
@@ -63,11 +109,24 @@ impl Default for Bot {
interactions_url: Default::default(),
terms_of_service_url: Default::default(),
privacy_policy_url: Default::default(),
oauth2: Default::default(),
flags: Default::default(),
}
}
}
#[allow(clippy::derivable_impls)]
impl Default for BotOauth2 {
fn default() -> Self {
Self {
public: false,
secret: Some(nanoid::nanoid!(64)),
redirects: Vec::new(),
allowed_scopes: HashMap::new(),
}
}
}
#[allow(clippy::disallowed_methods)]
impl Bot {
/// Create a new bot
@@ -124,6 +183,14 @@ impl Bot {
FieldsBot::Token => self.token = nanoid::nanoid!(64),
FieldsBot::InteractionsURL => {
self.interactions_url = String::new();
},
FieldsBot::Oauth2 => self.oauth2 = None,
FieldsBot::Oauth2Secret => {
if let Some(oauth2) = &mut self.oauth2 {
if !oauth2.public {
oauth2.secret = Some(nanoid::nanoid!(64))
}
}
}
}
}

View File

@@ -2,6 +2,7 @@ use revolt_result::Result;
use crate::{Bot, FieldsBot, PartialBot};
#[cfg(feature = "mongodb")]
mod mongodb;
mod reference;

View File

@@ -87,6 +87,8 @@ impl IntoDocumentPath for FieldsBot {
match self {
FieldsBot::InteractionsURL => Some("interactions_url"),
FieldsBot::Token => None,
FieldsBot::Oauth2 => Some("oauth2"),
FieldsBot::Oauth2Secret => None,
}
}
}

View File

@@ -2,6 +2,7 @@ use revolt_result::Result;
use crate::Invite;
#[cfg(feature = "mongodb")]
mod mongodb;
mod reference;

View File

@@ -2,6 +2,7 @@ use revolt_result::Result;
use crate::ChannelUnread;
#[cfg(feature = "mongodb")]
mod mongodb;
mod reference;

View File

@@ -2,6 +2,7 @@ use revolt_result::Result;
use crate::{FieldsWebhook, PartialWebhook, Webhook};
#[cfg(feature = "mongodb")]
mod mongodb;
mod reference;

View File

@@ -8,10 +8,13 @@ use serde::{Deserialize, Serialize};
use ulid::Ulid;
use crate::{
events::client::EventV1, tasks::ack::AckEvent, Database, File, IntoDocumentPath, PartialServer,
events::client::EventV1, Database, File, PartialServer,
Server, SystemMessage, User, AMQP,
};
#[cfg(feature = "mongodb")]
use crate::IntoDocumentPath;
auto_derived!(
#[serde(tag = "channel_type")]
pub enum Channel {
@@ -646,10 +649,11 @@ impl Channel {
.private(user.to_string())
.await;
#[cfg(feature = "tasks")]
crate::tasks::ack::queue_ack(
self.id().to_string(),
user.to_string(),
AckEvent::AckMessage {
crate::tasks::ack::AckEvent::AckMessage {
id: message.to_string(),
},
)
@@ -766,6 +770,7 @@ impl Channel {
}
}
#[cfg(feature = "mongodb")]
impl IntoDocumentPath for FieldsChannel {
fn as_path(&self) -> Option<&'static str> {
Some(match self {

View File

@@ -1,5 +1,7 @@
use crate::{revolt_result::Result, Channel, FieldsChannel, PartialChannel};
use revolt_permissions::OverrideField;
#[cfg(feature = "mongodb")]
mod mongodb;
mod reference;

View File

@@ -2,6 +2,7 @@ use revolt_result::Result;
use crate::Emoji;
#[cfg(feature = "mongodb")]
mod mongodb;
mod reference;

View File

@@ -2,6 +2,7 @@ use revolt_result::Result;
use crate::FileHash;
#[cfg(feature = "mongodb")]
mod mongodb;
mod reference;

View File

@@ -4,6 +4,7 @@ use crate::File;
use super::FileUsedFor;
#[cfg(feature = "mongodb")]
mod mongodb;
mod reference;

View File

@@ -14,7 +14,6 @@ use validator::Validate;
use crate::{
events::client::EventV1,
tasks::{self, ack::AckEvent},
util::{
bulk_permissions::BulkDatabasePermissionQuery, idempotency::IdempotencyKey,
permissions::DatabasePermissionQuery,
@@ -22,6 +21,9 @@ use crate::{
Channel, Database, Emoji, File, User, AMQP,
};
#[cfg(feature = "tasks")]
use crate::tasks::{self, ack::AckEvent};
auto_derived_partial!(
/// Message
pub struct Message {
@@ -438,7 +440,8 @@ impl Message {
}
// Verify replies are valid.
let mut replies = HashSet::new();
let mut replies = Vec::new();
if let Some(entries) = data.replies {
if entries.len() > config.features.limits.global.message_replies {
return Err(create_error!(TooManyReplies {
@@ -446,6 +449,8 @@ impl Message {
}));
}
replies.reserve(entries.len());
for ReplyIntent {
id,
mention,
@@ -459,7 +464,12 @@ impl Message {
user_mentions.insert(message.author.to_owned());
}
replies.insert(message.id);
// This is O(n^2), but this is faster than a HashSet
// when n < 20; as long as the message_replies limit
// is reasonable, this will be fast.
if !replies.contains(&message.id) {
replies.push(message.id);
}
}
// If the referenced message doesn't exist and fail_if_not_exists
// is set to false, send the message without the reply.
@@ -532,9 +542,7 @@ impl Message {
}
if !replies.is_empty() {
message
.replies
.replace(replies.into_iter().collect::<Vec<String>>());
message.replies.replace(replies);
}
// Calculate final message flags
@@ -616,9 +624,11 @@ impl Message {
.await;
// Update last_message_id
#[cfg(feature = "tasks")]
tasks::last_message_id::queue(self.channel.to_string(), self.id.to_string(), is_dm).await;
// Add mentions for affected users
#[cfg(feature = "tasks")]
if !mentions_elsewhere {
if let Some(mentions) = &self.mentions {
tasks::ack::queue_message(
@@ -637,6 +647,7 @@ impl Message {
}
// Generate embeds
#[cfg(feature = "tasks")]
if generate_embeds {
if let Some(content) = &self.content {
tasks::process_embeds::queue(
@@ -673,10 +684,12 @@ impl Message {
)
.await?;
if !self.has_suppressed_notifications()
&& (self.mentions.is_some() || self.contains_mass_push_mention())
{
// send Push notifications
#[cfg(feature = "tasks")]
tasks::ack::queue_message(
self.channel.to_string(),
AckEvent::ProcessMessage {

View File

@@ -2,6 +2,7 @@ use revolt_result::Result;
use crate::{AppendMessage, FieldsMessage, Message, MessageQuery, PartialMessage};
#[cfg(feature = "mongodb")]
mod mongodb;
mod reference;

View File

@@ -1,4 +1,5 @@
mod admin_migrations;
mod authorized_bots;
mod bots;
mod channel_invites;
mod channel_unreads;
@@ -19,6 +20,7 @@ mod user_settings;
mod users;
pub use admin_migrations::*;
pub use authorized_bots::*;
pub use bots::*;
pub use channel_invites::*;
pub use channel_unreads::*;
@@ -38,11 +40,15 @@ pub use servers::*;
pub use user_settings::*;
pub use users::*;
use crate::{Database, MongoDb, ReferenceDb};
use crate::{Database, ReferenceDb};
#[cfg(feature = "mongodb")]
use crate::MongoDb;
pub trait AbstractDatabase:
Sync
+ Send
+ authorized_bots::AbstractAuthorizedBots
+ admin_migrations::AbstractMigrations
+ bots::AbstractBots
+ channels::AbstractChannels
@@ -66,6 +72,8 @@ pub trait AbstractDatabase:
}
impl AbstractDatabase for ReferenceDb {}
#[cfg(feature = "mongodb")]
impl AbstractDatabase for MongoDb {}
impl std::ops::Deref for Database {
@@ -74,6 +82,7 @@ impl std::ops::Deref for Database {
fn deref(&self) -> &Self::Target {
match &self {
Database::Reference(dummy) => dummy,
#[cfg(feature = "mongodb")]
Database::MongoDb(mongo) => mongo,
}
}

View File

@@ -2,6 +2,7 @@ use revolt_result::Result;
use crate::PolicyChange;
#[cfg(feature = "mongodb")]
mod mongodb;
mod reference;

View File

@@ -1,6 +1,8 @@
use std::time::Duration;
use crate::{revolt_result::Result, RatelimitEvent, RatelimitEventType};
#[cfg(feature = "mongodb")]
mod mongodb;
mod reference;

View File

@@ -2,6 +2,7 @@ use revolt_result::Result;
use crate::Report;
#[cfg(feature = "mongodb")]
mod mongodb;
mod reference;

View File

@@ -2,6 +2,7 @@ use revolt_result::Result;
use crate::Snapshot;
#[cfg(feature = "mongodb")]
mod mongodb;
mod reference;

View File

@@ -2,6 +2,7 @@ use revolt_result::Result;
use crate::{MemberCompositeKey, ServerBan};
#[cfg(feature = "mongodb")]
mod mongodb;
mod reference;

View File

@@ -30,6 +30,9 @@ auto_derived_partial!(
/// Timestamp this member is timed out until
#[serde(skip_serializing_if = "Option::is_none")]
pub timeout: Option<Timestamp>,
// This value only exists in the database, not the models.
// If it is not-None, the database layer should return None to member fetching queries.
// pub pending_deletion_at: Option<Timestamp>
},
"PartialMember"
);
@@ -50,6 +53,7 @@ auto_derived!(
Avatar,
Roles,
Timeout,
JoinedAt,
}
/// Member removal intention
@@ -90,7 +94,7 @@ impl Member {
return Err(create_error!(AlreadyInServer));
}
let member = Member {
let mut member = Member {
id: MemberCompositeKey {
server: server.id.to_string(),
user: user.id.to_string(),
@@ -98,7 +102,9 @@ impl Member {
..Default::default()
};
db.insert_member(&member).await?;
if let Some(updated) = db.insert_or_merge_member(&member).await? {
member = updated;
}
let should_fetch = channels.is_none();
let mut channels = channels.unwrap_or_default();
@@ -124,6 +130,7 @@ impl Member {
EventV1::ServerMemberJoin {
id: server.id.clone(),
user: user.id.clone(),
member: member.clone().into(),
}
.p(server.id.clone())
.await;
@@ -186,6 +193,7 @@ impl Member {
pub fn remove_field(&mut self, field: &FieldsMember) {
match field {
FieldsMember::JoinedAt => (),
FieldsMember::Avatar => self.avatar = None,
FieldsMember::Nickname => self.nickname = None,
FieldsMember::Roles => self.roles.clear(),
@@ -224,7 +232,7 @@ impl Member {
intention: RemovalIntention,
silent: bool,
) -> Result<()> {
db.delete_member(&self.id).await?;
db.soft_delete_member(&self.id).await?;
EventV1::ServerMemberLeave {
id: self.id.server.to_string(),
@@ -260,3 +268,74 @@ impl Member {
Ok(())
}
}
#[cfg(test)]
mod tests {
use iso8601_timestamp::{Duration, Timestamp};
use revolt_models::v0::DataCreateServer;
use crate::{Member, PartialMember, RemovalIntention, Server, User};
#[async_std::test]
async fn muted_member_rejoin() {
database_test!(|db| async move {
match db {
crate::Database::Reference(_) => return,
crate::Database::MongoDb(_) => (),
}
let owner = User::create(&db, "Server Owner".to_string(), None, None)
.await
.unwrap();
let kickable_user = User::create(&db, "Member".to_string(), None, None)
.await
.unwrap();
let server = Server::create(
&db,
DataCreateServer {
name: "Server".to_string(),
description: None,
nsfw: None,
},
&owner,
false,
)
.await
.unwrap()
.0;
Member::create(&db, &server, &owner, None).await.unwrap();
let mut kickable_member = Member::create(&db, &server, &kickable_user, None)
.await
.unwrap()
.0;
kickable_member
.update(
&db,
PartialMember {
timeout: Some(Timestamp::now_utc() + Duration::minutes(5)),
..Default::default()
},
vec![],
)
.await
.unwrap();
assert!(kickable_member.in_timeout());
kickable_member
.remove(&db, &server, RemovalIntention::Kick, false)
.await
.unwrap();
let kickable_member = Member::create(&db, &server, &kickable_user, None)
.await
.unwrap()
.0;
assert!(kickable_member.in_timeout())
});
}
}

View File

@@ -1,16 +1,20 @@
use ::mongodb::SessionCursor;
#[cfg(feature = "mongodb")]
use ::mongodb::{ClientSession, SessionCursor};
use revolt_result::Result;
use crate::{FieldsMember, Member, MemberCompositeKey, PartialMember};
#[cfg(feature = "mongodb")]
mod mongodb;
mod reference;
#[derive(Debug)]
#[allow(clippy::large_enum_variant)]
pub enum ChunkedServerMembersGenerator {
#[cfg(feature = "mongodb")]
MongoDb {
session: ::mongodb::ClientSession,
session: ClientSession,
cursor: Option<SessionCursor<Member>>,
},
@@ -22,7 +26,7 @@ pub enum ChunkedServerMembersGenerator {
impl ChunkedServerMembersGenerator {
#[cfg(feature = "mongodb")]
pub fn new_mongo(session: ::mongodb::ClientSession, cursor: SessionCursor<Member>) -> Self {
pub fn new_mongo(session: ClientSession, cursor: SessionCursor<Member>) -> Self {
ChunkedServerMembersGenerator::MongoDb {
session,
cursor: Some(cursor),
@@ -69,13 +73,13 @@ impl ChunkedServerMembersGenerator {
#[async_trait]
pub trait AbstractServerMembers: Sync + Send {
/// Insert a new server member into the database
async fn insert_member(&self, member: &Member) -> Result<()>;
async fn insert_or_merge_member(&self, member: &Member) -> Result<Option<Member>>;
/// Fetch a server member by their id
async fn fetch_member(&self, server_id: &str, user_id: &str) -> Result<Member>;
/// Fetch all members in a server
async fn fetch_all_members<'a>(&self, server_id: &str) -> Result<Vec<Member>>;
async fn fetch_all_members(&self, server_id: &str) -> Result<Vec<Member>>;
/// Fetch all members in a server as an iterator
async fn fetch_all_members_chunked(
@@ -96,10 +100,10 @@ pub trait AbstractServerMembers: Sync + Send {
) -> Result<ChunkedServerMembersGenerator>;
/// Fetch all memberships for a user
async fn fetch_all_memberships<'a>(&self, user_id: &str) -> Result<Vec<Member>>;
async fn fetch_all_memberships(&self, user_id: &str) -> Result<Vec<Member>>;
/// Fetch multiple members by their ids
async fn fetch_members<'a>(&self, server_id: &str, ids: &'a [String]) -> Result<Vec<Member>>;
async fn fetch_members(&self, server_id: &str, ids: &[String]) -> Result<Vec<Member>>;
/// Fetch member count of a server
async fn fetch_member_count(&self, server_id: &str) -> Result<usize>;
@@ -115,6 +119,14 @@ pub trait AbstractServerMembers: Sync + Send {
remove: Vec<FieldsMember>,
) -> Result<()>;
/// Delete a server member by their id
async fn delete_member(&self, id: &MemberCompositeKey) -> Result<()>;
/// Marks a user as no longer a member of a server, while retaining the database value.
/// This is used to keep information such as timeouts in place, but will remove information such as join date and applied roles.
async fn soft_delete_member(&self, id: &MemberCompositeKey) -> Result<()>;
/// Forcibly delete a server member by their id.
/// This will cancel any pending timeouts or other longer term actions, and they will not be reapplied on rejoin.
async fn force_delete_member(&self, id: &MemberCompositeKey) -> Result<()>;
/// Fetch all members who have been marked for deletion.
async fn remove_dangling_members(&self) -> Result<()>;
}

View File

@@ -1,4 +1,6 @@
use bson::Document;
use futures::StreamExt;
use iso8601_timestamp::Timestamp;
use mongodb::options::ReadConcern;
use revolt_result::Result;
@@ -11,9 +13,42 @@ static COL: &str = "server_members";
#[async_trait]
impl AbstractServerMembers for MongoDb {
/// Insert a new server member into the database
async fn insert_member(&self, member: &Member) -> Result<()> {
query!(self, insert_one, COL, &member).map(|_| ())
/// Insert a new server member (or use the existing member if one is found)
async fn insert_or_merge_member(&self, member: &Member) -> Result<Option<Member>> {
let existing: Result<Option<Document>> = query!(
self,
find_one,
COL,
doc! {
"_id.server": &member.id.server,
"_id.user": &member.id.user,
"pending_deletion_at": {"$exists": true}
}
);
// Update the existing record if it exist, otherwise make a new record
if existing.is_ok_and(|x| x.is_some()) {
self.col::<Member>(COL)
.find_one_and_update(
doc! {
"_id.server": &member.id.server,
"_id.user": &member.id.user,
},
doc! {
"$set": {
"joined_at": member.joined_at.duration_since(Timestamp::UNIX_EPOCH).whole_seconds(),
},
"$unset": {
"pending_deletion_at": ""
}
},
)
.return_document(mongodb::options::ReturnDocument::After)
.await
.map_err(|_| create_database_error!("update_one", COL))
} else {
query!(self, insert_one, COL, &member).map(|_| ())?;
Ok(None)
}
}
/// Fetch a server member by their id
@@ -24,18 +59,20 @@ impl AbstractServerMembers for MongoDb {
COL,
doc! {
"_id.server": server_id,
"_id.user": user_id
"_id.user": user_id,
"pending_deletion_at": {"$exists": false}
}
)?
.ok_or_else(|| create_error!(NotFound))
}
/// Fetch all members in a server
async fn fetch_all_members<'a>(&self, server_id: &str) -> Result<Vec<Member>> {
async fn fetch_all_members(&self, server_id: &str) -> Result<Vec<Member>> {
Ok(self
.col::<Member>(COL)
.find(doc! {
"_id.server": server_id
"_id.server": server_id,
"pending_deletion_at": {"$exists": false}
})
.await
.map_err(|_| create_database_error!("find", COL))?
@@ -139,11 +176,12 @@ impl AbstractServerMembers for MongoDb {
}
/// Fetch all memberships for a user
async fn fetch_all_memberships<'a>(&self, user_id: &str) -> Result<Vec<Member>> {
async fn fetch_all_memberships(&self, user_id: &str) -> Result<Vec<Member>> {
Ok(self
.col::<Member>(COL)
.find(doc! {
"_id.user": user_id
"_id.user": user_id,
"pending_deletion_at": {"$exists": false}
})
.await
.map_err(|_| create_database_error!("find", COL))?
@@ -159,11 +197,12 @@ impl AbstractServerMembers for MongoDb {
}
/// Fetch multiple members by their ids
async fn fetch_members<'a>(&self, server_id: &str, ids: &'a [String]) -> Result<Vec<Member>> {
async fn fetch_members(&self, server_id: &str, ids: &[String]) -> Result<Vec<Member>> {
Ok(self
.col::<Member>(COL)
.find(doc! {
"_id.server": server_id,
"pending_deletion_at": {"$exists": false},
"_id.user": {
"$in": ids
}
@@ -185,7 +224,8 @@ impl AbstractServerMembers for MongoDb {
async fn fetch_member_count(&self, server_id: &str) -> Result<usize> {
self.col::<Member>(COL)
.count_documents(doc! {
"_id.server": server_id
"_id.server": server_id,
"pending_deletion_at": {"$exists": false}
})
.await
.map(|c| c as usize)
@@ -196,7 +236,8 @@ impl AbstractServerMembers for MongoDb {
async fn fetch_server_count(&self, user_id: &str) -> Result<usize> {
self.col::<Member>(COL)
.count_documents(doc! {
"_id.user": user_id
"_id.user": user_id,
"pending_deletion_at": {"$exists": false}
})
.await
.map(|c| c as usize)
@@ -225,8 +266,42 @@ impl AbstractServerMembers for MongoDb {
.map(|_| ())
}
/// Marks a member for deletion.
/// This will remove the record if the user has no pending actions (eg. timeout),
/// otherwise will slate the record for deletion by revolt_crond once the actions expire.
async fn soft_delete_member(&self, id: &MemberCompositeKey) -> Result<()> {
let member = self.fetch_member(&id.server, &id.user).await;
if let Ok(member) = member {
if member.in_timeout() {
self.col::<Document>(COL)
.update_many(
doc! {
"_id.server": &id.server,
"_id.user": &id.user,
},
doc! {
"$set": {"pending_deletion_at": format!("{}", member.timeout.unwrap().format())},
"$unset": {
"joined_at": "",
"avatar": "",
"nickname": "",
"roles": ""
}
},
)
.await
.map(|_| ())
.map_err(|_| create_database_error!("update_many", COL))
} else {
self.force_delete_member(id).await
}
} else {
Err(create_database_error!("fetch_member", COL))
}
}
/// Delete a server member by their id
async fn delete_member(&self, id: &MemberCompositeKey) -> Result<()> {
async fn force_delete_member(&self, id: &MemberCompositeKey) -> Result<()> {
query!(
self,
delete_one,
@@ -238,11 +313,25 @@ impl AbstractServerMembers for MongoDb {
)
.map(|_| ())
}
async fn remove_dangling_members(&self) -> Result<()> {
let now = Timestamp::now_utc();
let date = bson::to_bson(&now).expect("Failed to serialize timestamp");
self.col::<Document>(COL)
.delete_many(doc! {
"pending_deletion_at": {"$lt": date}
})
.await
.map(|_| ())
.map_err(|_| create_database_error!("count_documents", COL))
}
}
impl IntoDocumentPath for FieldsMember {
fn as_path(&self) -> Option<&'static str> {
Some(match self {
FieldsMember::JoinedAt => "joined_at",
FieldsMember::Avatar => "avatar",
FieldsMember::Nickname => "nickname",
FieldsMember::Roles => "roles",

View File

@@ -8,13 +8,13 @@ use super::{AbstractServerMembers, ChunkedServerMembersGenerator};
#[async_trait]
impl AbstractServerMembers for ReferenceDb {
/// Insert a new server member into the database
async fn insert_member(&self, member: &Member) -> Result<()> {
async fn insert_or_merge_member(&self, member: &Member) -> Result<Option<Member>> {
let mut server_members = self.server_members.lock().await;
if server_members.contains_key(&member.id) {
Err(create_database_error!("insert", "member"))
} else {
server_members.insert(member.id.clone(), member.clone());
Ok(())
Ok(None)
}
}
@@ -31,7 +31,7 @@ impl AbstractServerMembers for ReferenceDb {
}
/// Fetch all members in a server
async fn fetch_all_members<'a>(&self, server_id: &str) -> Result<Vec<Member>> {
async fn fetch_all_members(&self, server_id: &str) -> Result<Vec<Member>> {
let server_members = self.server_members.lock().await;
Ok(server_members
.values()
@@ -105,7 +105,7 @@ impl AbstractServerMembers for ReferenceDb {
}
/// Fetch all memberships for a user
async fn fetch_all_memberships<'a>(&self, user_id: &str) -> Result<Vec<Member>> {
async fn fetch_all_memberships(&self, user_id: &str) -> Result<Vec<Member>> {
let server_members = self.server_members.lock().await;
Ok(server_members
.values()
@@ -115,7 +115,7 @@ impl AbstractServerMembers for ReferenceDb {
}
/// Fetch multiple members by their ids
async fn fetch_members<'a>(&self, server_id: &str, ids: &'a [String]) -> Result<Vec<Member>> {
async fn fetch_members(&self, server_id: &str, ids: &[String]) -> Result<Vec<Member>> {
let server_members = self.server_members.lock().await;
Ok(ids
.iter()
@@ -169,8 +169,26 @@ impl AbstractServerMembers for ReferenceDb {
}
}
/// Soft delete a member
async fn soft_delete_member(&self, id: &MemberCompositeKey) -> Result<()> {
let mut server_members = self.server_members.lock().await;
let member = server_members.get_mut(id);
if let Some(member) = member {
if member.in_timeout() {
panic!("Soft deletion is not implemented.")
} else if server_members.remove(id).is_some() {
Ok(())
} else {
Err(create_error!(NotFound))
}
} else {
Err(create_error!(NotFound))
}
}
/// Delete a server member by their id
async fn delete_member(&self, id: &MemberCompositeKey) -> Result<()> {
async fn force_delete_member(&self, id: &MemberCompositeKey) -> Result<()> {
let mut server_members = self.server_members.lock().await;
if server_members.remove(id).is_some() {
Ok(())
@@ -178,4 +196,8 @@ impl AbstractServerMembers for ReferenceDb {
Err(create_error!(NotFound))
}
}
async fn remove_dangling_members(&self) -> Result<()> {
todo!()
}
}

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

@@ -2,6 +2,7 @@ use revolt_result::Result;
use crate::{FieldsRole, FieldsServer, PartialRole, PartialServer, Role, Server};
#[cfg(feature = "mongodb")]
mod mongodb;
mod reference;

View File

@@ -2,6 +2,7 @@ use revolt_result::Result;
use crate::UserSettings;
#[cfg(feature = "mongodb")]
mod mongodb;
mod reference;

View File

@@ -1,14 +1,22 @@
use axum::{extract::FromRequestParts, http::request::Parts};
use axum::{extract::{FromRef, FromRequestParts}, http::request::Parts};
use revolt_config::config;
use revolt_models::v0;
use revolt_result::{create_error, Error, Result};
use crate::{Database, User};
use crate::{util::oauth2, Database, OAuth2Scope, User};
#[async_trait::async_trait]
impl FromRequestParts<Database> for User {
impl<S> FromRequestParts<S> for User
where
Database: FromRef<S>,
S: Send + Sync
{
type Rejection = Error;
async fn from_request_parts(parts: &mut Parts, db: &Database) -> Result<User> {
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<User> {
let db = Database::from_ref(state);
if let Some(Ok(bot_token)) = parts.headers.get("x-bot-token").map(|v| v.to_str()) {
let bot = db.fetch_bot_by_token(bot_token).await?;
db.fetch_user(&bot.id).await
@@ -17,6 +25,24 @@ impl FromRequestParts<Database> for User {
{
let session = db.fetch_session_by_token(session_token).await?;
db.fetch_user(&session.user_id).await
} else if let Some(Ok(header_oauth_token)) = parts.headers.get("x-oauth2-token").map(|v| v.to_str()) {
let config = config().await;
let claims = oauth2::decode_token(
&config.api.security.token_secret,
header_oauth_token,
).map_err(|_| create_error!(NotAuthenticated))?;
let required_scope: v0::OAuth2Scope = parts.extensions.get::<OAuth2Scope>()
.copied()
.ok_or_else(|| create_error!(NotAuthenticated))?
.into();
if claims.scopes.contains(&v0::OAuth2Scope::Full) || claims.scopes.contains(&required_scope) {
db.fetch_user(&claims.sub).await
} else {
Err(create_error!(MissingScope { scope: required_scope.to_string() }))
}
} else {
Err(create_error!(NotAuthenticated))
}

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,8 +1,10 @@
use authifier::models::Session;
use iso8601_timestamp::Timestamp;
use revolt_result::Result;
use crate::{FieldsUser, PartialUser, RelationshipStatus, User};
#[cfg(feature = "mongodb")]
mod mongodb;
mod reference;
@@ -61,4 +63,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;
@@ -211,16 +212,34 @@ impl AbstractUsers for MongoDb {
partial: &PartialUser,
remove: Vec<FieldsUser>,
) -> Result<()> {
query!(
self,
update_one_by_id,
COL,
id,
partial,
remove.iter().map(|x| x as &dyn IntoDocumentPath).collect(),
None
)
.map(|_| ())
if remove.contains(&FieldsUser::StatusText) && partial.status.is_some() {
// stupid-ass workaround to fix mongo conflicting the same item
let _: Result<()> = query!(
self,
update_one_by_id,
COL,
id,
PartialUser {
..Default::default()
},
remove.iter().map(|x| x as &dyn IntoDocumentPath).collect(),
None
)
.map(|_| ());
query!(self, update_one_by_id, COL, id, partial, vec![], None).map(|_| ())
} else {
query!(
self,
update_one_by_id,
COL,
id,
partial,
remove.iter().map(|x| x as &dyn IntoDocumentPath).collect(),
None
)
.map(|_| ())
}
}
/// Set relationship with another user
@@ -317,7 +336,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

@@ -1,7 +1,10 @@
use authifier::models::Session;
use revolt_config::config;
use revolt_models::v0;
use rocket::http::Status;
use rocket::request::{self, FromRequest, Outcome, Request};
use crate::util::oauth2;
use crate::{Database, User};
#[rocket::async_trait]
@@ -19,12 +22,38 @@ impl<'r> FromRequest<'r> for User {
.next()
.map(|x| x.to_string());
let header_oauth_token = request
.headers()
.get("x-oauth2-token")
.next()
.map(|x| x.to_string());
if let Some(bot_token) = header_bot_token {
if let Ok(bot) = db.fetch_bot_by_token(&bot_token).await {
if let Ok(user) = db.fetch_user(&bot.id).await {
return Some(user);
}
}
} else if let Some(header_oauth_token) = header_oauth_token {
let config = config().await;
let claims = oauth2::decode_token(
&config.api.security.token_secret,
&header_oauth_token,
)
.ok()?;
// access the scope required for the route stored in the request local cache set via `OAuth2Scoped`
let required_scope: v0::OAuth2Scope = request.local_cache(|| None::<crate::OAuth2Scope>)
.as_ref()
.copied()?
.into();
if claims.scopes.contains(&v0::OAuth2Scope::Full) || claims.scopes.contains(&required_scope) {
if let Ok(user) = db.fetch_user(&claims.sub).await {
return Some(user);
}
}
} else if let Outcome::Success(session) = request.guard::<Session>().await {
if let Ok(user) = db.fetch_user(&session.user_id).await {
return Some(user);

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(),
}
}
@@ -34,6 +33,7 @@ impl From<crate::Bot> for Bot {
interactions_url: value.interactions_url,
terms_of_service_url: value.terms_of_service_url,
privacy_policy_url: value.privacy_policy_url,
oauth2: value.oauth2.map(|oauth2| oauth2.into()),
flags: value.flags.unwrap_or_default() as u32,
}
}
@@ -44,6 +44,8 @@ impl From<FieldsBot> for crate::FieldsBot {
match value {
FieldsBot::InteractionsURL => crate::FieldsBot::InteractionsURL,
FieldsBot::Token => crate::FieldsBot::Token,
FieldsBot::Oauth2 => crate::FieldsBot::Oauth2,
FieldsBot::Oauth2Secret => crate::FieldsBot::Oauth2Secret,
}
}
}
@@ -53,6 +55,78 @@ impl From<crate::FieldsBot> for FieldsBot {
match value {
crate::FieldsBot::InteractionsURL => FieldsBot::InteractionsURL,
crate::FieldsBot::Token => FieldsBot::Token,
crate::FieldsBot::Oauth2 => FieldsBot::Oauth2,
crate::FieldsBot::Oauth2Secret => FieldsBot::Oauth2Secret,
}
}
}
impl From<BotOauth2> for crate::BotOauth2 {
fn from(value: BotOauth2) -> Self {
crate::BotOauth2 {
public: value.public,
secret: value.secret,
redirects: value.redirects,
allowed_scopes: value.allowed_scopes
.into_iter()
.map(|(scope, value)| (scope.into(), value.into()))
.collect(),
}
}
}
impl From<crate::BotOauth2> for BotOauth2 {
fn from(value: crate::BotOauth2) -> Self {
BotOauth2 {
public: value.public,
secret: value.secret,
redirects: value.redirects,
allowed_scopes: value.allowed_scopes
.into_iter()
.map(|(scope, value)| (scope.into(), value.into()))
.collect(),
}
}
}
impl From<crate::OAuth2Scope> for OAuth2Scope {
fn from(value: crate::OAuth2Scope) -> Self {
match value {
crate::OAuth2Scope::ReadIdentify => OAuth2Scope::ReadIdentify,
crate::OAuth2Scope::ReadServers => OAuth2Scope::ReadServers,
crate::OAuth2Scope::WriteFiles => OAuth2Scope::WriteFiles,
crate::OAuth2Scope::Events => OAuth2Scope::Events,
crate::OAuth2Scope::Full => OAuth2Scope::Full,
}
}
}
impl From<OAuth2Scope> for crate::OAuth2Scope {
fn from(value: OAuth2Scope) -> Self {
match value {
OAuth2Scope::ReadIdentify => crate::OAuth2Scope::ReadIdentify,
OAuth2Scope::ReadServers => crate::OAuth2Scope::ReadServers,
OAuth2Scope::WriteFiles => crate::OAuth2Scope::WriteFiles,
OAuth2Scope::Events => crate::OAuth2Scope::Events,
OAuth2Scope::Full => crate::OAuth2Scope::Full,
}
}
}
impl From<crate::OAuth2ScopeReasoning> for OAuth2ScopeReasoning {
fn from(value: crate::OAuth2ScopeReasoning) -> Self {
OAuth2ScopeReasoning {
allow: value.allow,
deny: value.deny,
}
}
}
impl From<OAuth2ScopeReasoning> for crate::OAuth2ScopeReasoning {
fn from(value: OAuth2ScopeReasoning) -> Self {
crate::OAuth2ScopeReasoning {
allow: value.allow,
deny: value.deny,
}
}
}
@@ -708,6 +782,7 @@ impl From<crate::FieldsMember> for FieldsMember {
crate::FieldsMember::Nickname => FieldsMember::Nickname,
crate::FieldsMember::Roles => FieldsMember::Roles,
crate::FieldsMember::Timeout => FieldsMember::Timeout,
crate::FieldsMember::JoinedAt => FieldsMember::JoinedAt,
}
}
}
@@ -719,6 +794,7 @@ impl From<FieldsMember> for crate::FieldsMember {
FieldsMember::Nickname => crate::FieldsMember::Nickname,
FieldsMember::Roles => crate::FieldsMember::Roles,
FieldsMember::Timeout => crate::FieldsMember::Timeout,
FieldsMember::JoinedAt => crate::FieldsMember::JoinedAt,
}
}
}
@@ -1114,7 +1190,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 {
@@ -1386,3 +1462,43 @@ impl From<FieldsMessage> for crate::FieldsMessage {
}
}
}
impl From<AuthorizedBotId> for crate::AuthorizedBotId {
fn from(value: AuthorizedBotId) -> Self {
crate::AuthorizedBotId {
user: value.user,
bot: value.bot
}
}
}
impl From<crate::AuthorizedBotId> for AuthorizedBotId {
fn from(value: crate::AuthorizedBotId) -> Self {
AuthorizedBotId {
user: value.user,
bot: value.bot
}
}
}
impl From<AuthorizedBot> for crate::AuthorizedBot {
fn from(value: AuthorizedBot) -> Self {
crate::AuthorizedBot {
id: value.id.into(),
created_at: value.created_at,
deauthorized_at: value.deauthorized_at,
scope: value.scope.into_iter().map(|scope| scope.into()).collect(),
}
}
}
impl From<crate::AuthorizedBot> for AuthorizedBot {
fn from(value: crate::AuthorizedBot) -> Self {
AuthorizedBot {
id: value.id.into(),
created_at: value.created_at,
deauthorized_at: value.deauthorized_at,
scope: value.scope.into_iter().map(|scope| scope.into()).collect(),
}
}
}

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

@@ -4,3 +4,4 @@ pub mod idempotency;
pub mod permissions;
pub mod reference;
pub mod test_fixtures;
pub mod oauth2;

View File

@@ -0,0 +1,17 @@
use std::marker::PhantomData;
use axum::{extract::FromRequestParts, http::request::Parts};
use revolt_result::{Error, Result};
use super::{OAuth2Scoped, scopes::OAuth2Scope};
#[rocket::async_trait]
impl<S: Send + Sync, Scope: OAuth2Scope> FromRequestParts<S> for OAuth2Scoped<Scope> {
type Rejection = Error;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self> {
parts.extensions.insert(Scope::SCOPE);
Ok(OAuth2Scoped { _scope: PhantomData })
}
}

View File

@@ -0,0 +1,120 @@
use chrono::{TimeDelta, Utc};
use jsonwebtoken::{decode, encode, errors::Error, DecodingKey, EncodingKey, Header, Validation};
use redis_kiss::AsyncCommands;
use revolt_models::v0;
use revolt_result::Result;
use serde::{Deserialize, Serialize};
pub mod scopes;
pub use scopes::OAuth2Scoped;
#[cfg(feature = "rocket")]
pub mod rocket;
#[cfg(feature = "axum")]
pub mod axum;
pub use jsonwebtoken::errors::{Error as JWTError, ErrorKind as JWTErrorKind};
use ulid::Ulid;
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum TokenType {
Auth,
Access,
Refresh,
}
impl TokenType {
pub fn lifetime(self) -> TimeDelta {
match self {
TokenType::Access => TimeDelta::weeks(1),
TokenType::Auth => TimeDelta::minutes(5),
TokenType::Refresh => TimeDelta::weeks(4),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
pub jti: String,
pub sub: String,
pub exp: i64,
pub r#type: TokenType,
pub client_id: String,
pub scopes: Vec<v0::OAuth2Scope>,
pub redirect_uri: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub code_challange_method: Option<v0::OAuth2CodeChallangeMethod>,
}
#[allow(clippy::too_many_arguments)]
pub fn encode_token(
token_secret: &str,
token_type: TokenType,
user_id: String,
client_id: String,
redirect_uri: String,
scopes: Vec<v0::OAuth2Scope>,
code_challange_method: Option<v0::OAuth2CodeChallangeMethod>,
) -> Result<String, Error> {
let now = Utc::now();
let exp = now.checked_add_signed(token_type.lifetime()).unwrap();
println!("{now:?} {exp:}");
let claims = Claims {
jti: Ulid::new().to_string(),
sub: user_id,
exp: exp.timestamp(),
r#type: token_type,
client_id,
scopes,
redirect_uri,
code_challange_method,
};
let encoding_key = EncodingKey::from_secret(token_secret.as_bytes());
encode(&Header::default(), &claims, &encoding_key)
}
pub fn decode_token(token_secret: &str, code: &str) -> Result<Claims, Error> {
let decoding_key = DecodingKey::from_secret(token_secret.as_bytes());
let data = decode(
code,
&decoding_key,
&Validation::new(jsonwebtoken::Algorithm::HS256),
)?;
Ok(data.claims)
}
pub async fn add_code_challange(token: &str, code_challenge: &str) -> Result<()> {
let mut conn = redis_kiss::get_connection()
.await
.map_err(|_| create_error!(InternalError))?;
conn.pset_ex::<_, _, ()>(
format!("oauth2:{token}:code_challenge"),
code_challenge,
TokenType::Access.lifetime().num_milliseconds() as usize,
)
.await
.map_err(|_| create_error!(InternalError))?;
Ok(())
}
pub async fn get_code_challange(token: &str) -> Result<Option<String>> {
let mut conn = redis_kiss::get_connection()
.await
.map_err(|_| create_error!(InternalError))?;
conn.get(format!("oauth2:{token}:code_challenge"))
.await
.map_err(|_| create_error!(InternalError))
}

View File

@@ -0,0 +1,53 @@
use std::{convert::Infallible, marker::PhantomData};
use revolt_okapi::openapi3::{OAuthFlows, SecurityScheme, SecuritySchemeData};
use revolt_rocket_okapi::request::{OpenApiFromRequest, RequestHeaderInput};
use rocket::{request::{self, FromRequest}, Request};
use super::{OAuth2Scoped, scopes::OAuth2Scope};
#[rocket::async_trait]
impl<'r, Scope: OAuth2Scope> FromRequest<'r> for OAuth2Scoped<Scope> {
type Error = Infallible;
async fn from_request(request: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
request.local_cache(|| Some(Scope::SCOPE));
request::Outcome::Success(OAuth2Scoped { _scope: PhantomData })
}
}
impl<'r, Scope: OAuth2Scope> OpenApiFromRequest<'r> for OAuth2Scoped<Scope> {
fn from_request_input(
_gen: &mut revolt_rocket_okapi::r#gen::OpenApiGenerator,
_name: String,
_required: bool,
) -> revolt_rocket_okapi::Result<revolt_rocket_okapi::request::RequestHeaderInput> {
Ok(RequestHeaderInput::Security(
"OAuth2".to_owned(),
SecurityScheme {
description: None,
extensions: Default::default(),
data: SecuritySchemeData::OAuth2 {
flows: OAuthFlows::AuthorizationCode {
authorization_url: "todo".to_string(),
token_url: "todo".to_string(),
refresh_url: Some("todo".to_string()),
scopes: revolt_okapi::map! {
"read:identify".to_string() => "".to_string(),
"read:servers".to_string() => "".to_string(),
"write:files".to_string() => "".to_string(),
"events".to_string() => "".to_string(),
"full".to_string() => "".to_string(),
},
extensions: Default::default()
}
}
},
revolt_okapi::map! {
"OAuth2".to_owned() => vec![Scope::MODEL.to_string()]
},
))
}
}

View File

@@ -0,0 +1,29 @@
use std::marker::PhantomData;
pub struct OAuth2Scoped<Scope> {
pub(crate) _scope: PhantomData<Scope>
}
pub trait OAuth2Scope {
const SCOPE: crate::OAuth2Scope;
const MODEL: revolt_models::v0::OAuth2Scope;
}
macro_rules! define_oauth2_scope {
($struct_name:ident) => {
pub struct $struct_name;
impl OAuth2Scope for $struct_name {
const SCOPE: crate::OAuth2Scope = crate::OAuth2Scope::$struct_name;
const MODEL: revolt_models::v0::OAuth2Scope = revolt_models::v0::OAuth2Scope::$struct_name;
}
};
}
// This must match the OAuth2Scope enum
// TODO: automatically sync this
define_oauth2_scope!(ReadIdentify);
define_oauth2_scope!(ReadServers);
define_oauth2_scope!(WriteFiles);
define_oauth2_scope!(Events);
define_oauth2_scope!(Full);

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

@@ -14,41 +14,40 @@ use crate::{
};
/// Reference to some object in the database
#[derive(Serialize, Deserialize)]
pub struct Reference {
pub struct Reference<'a> {
/// Id of object
pub id: String,
pub id: &'a str,
}
impl Reference {
impl<'a> Reference<'a> {
/// Create a Ref from an unchecked string
pub fn from_unchecked(id: String) -> Reference {
pub fn from_unchecked(id: &'a str) -> Reference<'a> {
Reference { id }
}
/// Fetch ban from Ref
pub async fn as_ban(&self, db: &Database, server: &str) -> Result<ServerBan> {
db.fetch_ban(server, &self.id).await
db.fetch_ban(server, self.id).await
}
/// Fetch bot from Ref
pub async fn as_bot(&self, db: &Database) -> Result<Bot> {
db.fetch_bot(&self.id).await
db.fetch_bot(self.id).await
}
/// Fetch emoji from Ref
pub async fn as_emoji(&self, db: &Database) -> Result<Emoji> {
db.fetch_emoji(&self.id).await
db.fetch_emoji(self.id).await
}
/// Fetch channel from Ref
pub async fn as_channel(&self, db: &Database) -> Result<Channel> {
db.fetch_channel(&self.id).await
db.fetch_channel(self.id).await
}
/// Fetch invite from Ref or create invite to server if discoverable
pub async fn as_invite(&self, db: &Database) -> Result<Invite> {
if ulid::Ulid::from_str(&self.id).is_ok() {
if ulid::Ulid::from_str(self.id).is_ok() {
let server = self.as_server(db).await?;
if !server.discoverable {
return Err(create_error!(NotFound));
@@ -65,18 +64,18 @@ impl Reference {
.ok_or(create_error!(NotFound))?,
})
} else {
db.fetch_invite(&self.id).await
db.fetch_invite(self.id).await
}
}
/// Fetch message from Ref
pub async fn as_message(&self, db: &Database) -> Result<Message> {
db.fetch_message(&self.id).await
db.fetch_message(self.id).await
}
/// Fetch message from Ref and validate channel
pub async fn as_message_in_channel(&self, db: &Database, channel: &str) -> Result<Message> {
let msg = db.fetch_message(&self.id).await?;
let msg = db.fetch_message(self.id).await?;
if msg.channel != channel {
return Err(create_error!(NotFound));
}
@@ -86,36 +85,36 @@ impl Reference {
/// Fetch member from Ref
pub async fn as_member(&self, db: &Database, server: &str) -> Result<Member> {
db.fetch_member(server, &self.id).await
db.fetch_member(server, self.id).await
}
/// Fetch server from Ref
pub async fn as_server(&self, db: &Database) -> Result<Server> {
db.fetch_server(&self.id).await
db.fetch_server(self.id).await
}
/// Fetch user from Ref
pub async fn as_user(&self, db: &Database) -> Result<User> {
db.fetch_user(&self.id).await
db.fetch_user(self.id).await
}
/// Fetch webhook from Ref
pub async fn as_webhook(&self, db: &Database) -> Result<Webhook> {
db.fetch_webhook(&self.id).await
db.fetch_webhook(self.id).await
}
}
#[cfg(feature = "rocket-impl")]
impl<'r> FromParam<'r> for Reference {
impl<'r> FromParam<'r> for Reference<'r> {
type Error = &'r str;
fn from_param(param: &'r str) -> Result<Self, Self::Error> {
Ok(Reference::from_unchecked(param.into()))
Ok(Reference::from_unchecked(param))
}
}
#[cfg(feature = "rocket-impl")]
impl JsonSchema for Reference {
impl<'a> JsonSchema for Reference<'a> {
fn schema_name() -> String {
"Id".to_string()
}

View File

@@ -39,7 +39,9 @@ pub async fn load_fixture(db: &Database, input: &str) -> HashMap<String, String>
LoadedFixture::User(user) => db.insert_user(&user).await.unwrap(),
LoadedFixture::Channel(channel) => db.insert_channel(&channel).await.unwrap(),
LoadedFixture::Server(server) => db.insert_server(&server).await.unwrap(),
LoadedFixture::ServerMember(member) => db.insert_member(&member).await.unwrap(),
LoadedFixture::ServerMember(member) => {
db.insert_or_merge_member(&member).await.unwrap();
}
}
}

View File

@@ -1,6 +1,6 @@
[package]
name = "revolt-files"
version = "0.8.7"
version = "0.8.9"
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.9", path = "../config", features = [
"report-macros",
] }
revolt-result = { version = "0.8.7", path = "../result" }
revolt-result = { version = "0.8.9", path = "../result" }
# image processing
jxl-oxide = "0.8.1"

View File

@@ -80,6 +80,9 @@ pub async fn fetch_from_s3(bucket_id: &str, path: &str, nonce: &str) -> Result<V
.decrypt_in_place(nonce, b"", &mut buf)
.map_err(|_| create_error!(InternalError))?;
// Remove the authentication tag bytes that were added during encryption
buf.truncate(buf.len() - AUTHENTICATION_TAG_SIZE_BYTES);
Ok(buf)
}

View File

@@ -1,6 +1,6 @@
[package]
name = "revolt-models"
version = "0.8.7"
version = "0.8.9"
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.9", path = "../config" }
revolt-permissions = { version = "0.8.9", path = "../permissions" }
# Utility
regex = "1.11"

View File

@@ -0,0 +1,34 @@
use iso8601_timestamp::Timestamp;
use crate::v0::{PublicBot, OAuth2Scope};
auto_derived!(
/// Unique id of the user and bot
pub struct AuthorizedBotId {
/// User id
pub user: String,
/// Bot Id
pub bot: String,
}
pub struct AuthorizedBot {
/// Unique Id
#[serde(rename = "_id")]
pub id: AuthorizedBotId,
/// When the authorized oauth2 bot connection was created at
pub created_at: Timestamp,
/// If and when the authorized oauth2 bot connection was revoked at
pub deauthorized_at: Option<Timestamp>,
/// Scopes the bot has access to
pub scope: Vec<OAuth2Scope>,
}
pub struct AuthorizedBotsResponse {
pub public_bot: PublicBot,
pub authorized_bot: AuthorizedBot,
}
);

View File

@@ -1,4 +1,8 @@
use super::User;
use super::{User, OAuth2Scope, OAuth2ScopeReasoning};
use std::collections::HashMap;
#[cfg(feature = "validator")]
use validator::Validate;
auto_derived!(
/// Bot
@@ -48,6 +52,13 @@ auto_derived!(
)]
pub privacy_policy_url: String,
/// Oauth2 bot settings
#[cfg_attr(
feature = "serde",
serde(skip_serializing_if = "Option::is_none", default)
)]
pub oauth2: Option<BotOauth2>,
/// Enum of bot flags
#[cfg_attr(
feature = "serde",
@@ -60,6 +71,8 @@ auto_derived!(
pub enum FieldsBot {
Token,
InteractionsURL,
Oauth2,
Oauth2Secret,
}
/// Flags that may be attributed to a bot
@@ -101,7 +114,7 @@ auto_derived!(
/// Bot Details
#[derive(Default)]
#[cfg_attr(feature = "validator", derive(validator::Validate))]
#[cfg_attr(feature = "validator", derive(Validate))]
pub struct DataCreateBot {
/// Bot username
#[cfg_attr(
@@ -113,7 +126,7 @@ auto_derived!(
/// New Bot Details
#[derive(Default)]
#[cfg_attr(feature = "validator", derive(validator::Validate))]
#[cfg_attr(feature = "validator", derive(Validate))]
pub struct DataEditBot {
/// Bot username
#[cfg_attr(
@@ -131,9 +144,22 @@ auto_derived!(
/// Interactions URL
#[cfg_attr(feature = "validator", validate(length(min = 1, max = 2048)))]
pub interactions_url: Option<String>,
#[cfg_attr(feature = "validator", validate)]
pub oauth2: Option<DataEditBotOauth2>,
/// Fields to remove from bot object
#[cfg_attr(feature = "validator", validate(length(min = 1)))]
pub remove: Option<Vec<FieldsBot>>,
#[cfg_attr(feature = "serde", serde(default))]
pub remove: Vec<FieldsBot>,
}
#[derive(Default)]
#[cfg_attr(feature = "validator", derive(Validate))]
pub struct DataEditBotOauth2 {
pub public: Option<bool>,
#[cfg_attr(feature = "validator", validate(length(min = 1, max = 10)))]
pub redirects: Option<Vec<String>>,
pub allowed_scopes: Option<HashMap<OAuth2Scope, OAuth2ScopeReasoning>>
}
/// Where we are inviting a bot to
@@ -170,3 +196,22 @@ auto_derived!(
pub user: User,
}
);
auto_derived_partial!(
/// Bot Oauth2 information
pub struct BotOauth2 {
/// Whether the oauth client is public and should not receive a secret key
#[serde(default)]
pub public: bool,
/// Secret key used for authorisation, not provided if the client is public
#[serde(default)]
pub secret: Option<String>,
/// Allowed redirects for the authorisation
#[serde(default)]
pub redirects: Vec<String>,
/// Mapping of allowed scopes and the reasonings
#[serde(default)]
pub allowed_scopes: HashMap<OAuth2Scope, OAuth2ScopeReasoning>,
},
"PartialBotOauth2"
);

View File

@@ -207,7 +207,7 @@ auto_derived!(
/// Fields to remove from channel
#[cfg_attr(feature = "serde", serde(default))]
pub remove: Option<Vec<FieldsChannel>>,
pub remove: Vec<FieldsChannel>,
}
/// Create new group
@@ -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

@@ -215,7 +215,7 @@ auto_derived!(
#[derive(Default)]
#[cfg_attr(feature = "validator", derive(Validate))]
pub struct SendableEmbed {
#[cfg_attr(feature = "validator", validate(length(min = 1, max = 128)))]
#[cfg_attr(feature = "validator", validate(length(min = 1, max = 256)))]
pub icon_url: Option<String>,
#[cfg_attr(feature = "validator", validate(length(min = 1, max = 256)))]
pub url: Option<String>,

View File

@@ -1,3 +1,4 @@
mod authorized_bots;
mod bots;
mod channel_invites;
mod channel_unreads;
@@ -7,6 +8,7 @@ mod embeds;
mod emojis;
mod files;
mod messages;
mod oauth2;
mod policy_changes;
mod safety_reports;
mod server_bans;
@@ -15,6 +17,7 @@ mod servers;
mod user_settings;
mod users;
pub use authorized_bots::*;
pub use bots::*;
pub use channel_invites::*;
pub use channel_unreads::*;
@@ -24,6 +27,7 @@ pub use embeds::*;
pub use emojis::*;
pub use files::*;
pub use messages::*;
pub use oauth2::*;
pub use policy_changes::*;
pub use safety_reports::*;
pub use server_bans::*;

View File

@@ -0,0 +1,140 @@
use crate::v0::{PublicBot, User};
use std::{collections::HashMap, fmt::Display};
auto_derived!(
pub struct OAuth2AuthorizeAuthResponse {
/// Redirect URI which will contain the access token
pub redirect_uri: String,
}
pub struct OAuth2ScopeReasoning {
pub allow: String,
pub deny: String
}
pub struct OAuth2AuthorizeInfoResponse {
pub bot: PublicBot,
pub user: User,
pub allowed_scopes: HashMap<OAuth2Scope, OAuth2ScopeReasoning>
}
#[derive(Copy)]
#[cfg_attr(feature = "serde", serde(rename = "lowercase"))]
#[cfg_attr(feature = "rocket", derive(rocket::FromFormField))]
pub enum OAuth2ResponseType {
#[cfg_attr(feature = "rocket", field(value = "code"))]
Code,
#[cfg_attr(feature = "rocket", field(value = "token"))]
Token,
}
#[derive(Copy)]
#[cfg_attr(feature = "rocket", derive(rocket::FromFormField))]
pub enum OAuth2GrantType {
#[cfg_attr(feature = "rocket", field(value = "authorization_code"))]
#[cfg_attr(feature = "serde", serde(rename = "authorization_code"))]
AuthorizationCode,
#[cfg_attr(feature = "rocket", field(value = "implicit"))]
#[cfg_attr(feature = "serde", serde(rename = "implicit"))]
Implicit,
#[cfg_attr(feature = "rocket", field(value = "refresh_token"))]
#[cfg_attr(feature = "serde", serde(rename = "refresh_token"))]
RefreshToken
}
#[derive(Copy)]
#[cfg_attr(feature = "rocket", derive(rocket::FromFormField))]
pub enum OAuth2CodeChallangeMethod {
#[cfg_attr(feature = "rocket", field(value = "plain"))]
#[cfg_attr(feature = "serde", serde(rename = "plain"))]
Plain,
S256
}
#[cfg_attr(feature = "rocket", derive(rocket::FromForm))]
pub struct OAuth2AuthorizationForm {
pub client_id: String,
pub scope: String,
pub redirect_uri: String,
pub response_type: OAuth2ResponseType,
pub state: Option<String>,
pub code_challenge: Option<String>,
pub code_challenge_method: Option<OAuth2CodeChallangeMethod>,
}
#[cfg_attr(feature = "rocket", derive(rocket::FromForm))]
pub struct OAuth2TokenExchangeForm {
pub grant_type: OAuth2GrantType,
pub client_id: String,
pub client_secret: Option<String>,
/// Authorization code
pub code: Option<String>,
// Refresh token to generate new access token
pub refresh_token: Option<String>,
pub code_verifier: Option<String>,
}
pub struct OAuth2TokenExchangeResponse {
pub access_token: String,
pub refresh_token: Option<String>,
pub token_type: String,
pub scope: String,
}
#[derive(Copy, Hash)]
#[cfg_attr(feature = "serde", serde(rename = "snake_case"))]
pub enum OAuth2Scope {
#[cfg_attr(feature = "serde", serde(rename = "read:identify"))]
ReadIdentify,
#[cfg_attr(feature = "serde", serde(rename = "read:servers"))]
ReadServers,
#[cfg_attr(feature = "serde", serde(rename = "write:files"))]
WriteFiles,
#[cfg_attr(feature = "serde", serde(rename = "events"))]
Events,
#[cfg_attr(feature = "serde", serde(rename = "full"))]
Full,
}
);
impl Display for OAuth2Scope {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
OAuth2Scope::ReadIdentify => "read:identify",
OAuth2Scope::ReadServers => "read:servers",
OAuth2Scope::WriteFiles => "write:files",
OAuth2Scope::Events => "events",
OAuth2Scope::Full => "full",
})
}
}
impl OAuth2Scope {
#[allow(clippy::should_implement_trait)]
pub fn from_str(str: &str) -> Option<OAuth2Scope> {
match str {
"read:identify" => Some(OAuth2Scope::ReadIdentify),
"read:servers" => Some(OAuth2Scope::ReadServers),
"events" => Some(OAuth2Scope::Events),
"full" => Some(OAuth2Scope::Full),
_ => None,
}
}
pub fn scopes_from_str(string: &str) -> Option<Vec<OAuth2Scope>> {
let mut scopes = Vec::new();
for scope in string.split(' ') {
if let Some(scope) = OAuth2Scope::from_str(scope) {
scopes.push(scope);
} else {
return None;
}
}
Some(scopes)
}
}

View File

@@ -77,6 +77,7 @@ auto_derived!(
Avatar,
Roles,
Timeout,
JoinedAt,
}
/// Member removal intention
@@ -124,7 +125,7 @@ auto_derived!(
/// Timestamp this member is timed out until
pub timeout: Option<Timestamp>,
/// Fields to remove from channel object
#[cfg_attr(feature = "validator", validate(length(min = 1)))]
pub remove: Option<Vec<FieldsMember>>,
#[cfg_attr(feature = "serde", serde(default))]
pub remove: Vec<FieldsMember>,
}
);

View File

@@ -175,6 +175,8 @@ auto_derived!(
/// Ranking position
///
/// Smaller values take priority.
///
/// **Removed** - no effect, use the edit server role positions route
pub rank: Option<i64>,
}
@@ -247,8 +249,8 @@ auto_derived!(
pub analytics: Option<bool>,
/// Fields to remove from server object
#[cfg_attr(feature = "validator", validate(length(min = 1)))]
pub remove: Option<Vec<FieldsServer>>,
#[cfg_attr(feature = "serde", serde(default))]
pub remove: Vec<FieldsServer>,
}
/// New role information
@@ -267,11 +269,11 @@ 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)))]
pub remove: Option<Vec<FieldsRole>>,
#[cfg_attr(feature = "serde", serde(default))]
pub remove: Vec<FieldsRole>,
}
/// New role permissions
@@ -286,4 +288,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

@@ -245,8 +245,8 @@ auto_derived!(
pub flags: Option<i32>,
/// Fields to remove from user object
#[cfg_attr(feature = "validator", validate(length(min = 1)))]
pub remove: Option<Vec<FieldsUser>>,
#[cfg_attr(feature = "serde", serde(default))]
pub remove: Vec<FieldsUser>,
}
/// User flag reponse
@@ -255,12 +255,14 @@ auto_derived!(
pub flags: i32,
}
/// Mutual friends and servers response
/// Mutual friends, servers, groups and DMs response
pub struct MutualResponse {
/// Array of mutual user IDs that both users are friends with
pub users: Vec<String>,
/// Array of mutual server IDs that both users are in
pub servers: Vec<String>,
/// Array of mutual group and dm IDs that both users are in
pub channels: Vec<String>,
}
/// Bot information for if the user is a bot

View File

@@ -1,8 +1,9 @@
[package]
name = "revolt-parser"
version = "0.8.7"
version = "0.8.9"
edition = "2021"
license = "AGPL-3.0-or-later"
license = "MIT"
authors = ["Zomatree <me@zomatree.live>", "Paul Makles <me@insrt.uk>"]
description = "Revolt Backend: Message Parser"
[dependencies]

View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) 2024 Pawel Makles
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -4,15 +4,18 @@ use logos::Logos;
#[derive(Debug, Clone, Logos, PartialEq)]
#[logos(skip "\n")]
pub enum MessageToken {
#[logos(subpattern id="[0123456789ABCDEFGHJKMNPQRSTVWXYZ]{26}")]
pub enum MessageToken<'a> {
#[token("\\")]
Escape,
#[regex("(```[^`\n]*)|(``)|`", |lex| lex.slice().to_owned().chars().filter(|&c| c == '`').count())]
#[regex("```[^`\n]*", |_| 3)]
#[regex("``", |_| 2)]
#[regex("`", |_| 1)]
CodeblockMarker(usize),
#[regex("<@[0123456789ABCDEFGHJKMNPQRSTVWXYZ]{26}>", |lex| lex.slice()[2..lex.slice().len() - 1].to_owned())]
UserMention(String),
#[regex("<%[0123456789ABCDEFGHJKMNPQRSTVWXYZ]{26}>", |lex| lex.slice()[2..lex.slice().len() - 1].to_owned())]
RoleMention(String),
#[regex("<@(?&id)>", |lex| &lex.slice()[2..lex.slice().len() - 1])]
UserMention(&'a str),
#[regex("<%(?&id)>", |lex| &lex.slice()[2..lex.slice().len() - 1],)]
RoleMention(&'a str),
#[token("@everyone")]
MentionEveryone,
#[token("@online")]
@@ -27,13 +30,13 @@ pub struct MessageResults {
pub mentions_online: bool
}
struct MessageParserIterator<I> {
struct MessageParserIterator<'a, I> {
inner: I,
temp: VecDeque<MessageToken>
temp: VecDeque<MessageToken<'a>>
}
impl<I: Iterator<Item = MessageToken>> Iterator for MessageParserIterator<I> {
type Item = MessageToken;
impl<'a, I: Iterator<Item = MessageToken<'a>>> Iterator for MessageParserIterator<'a, I> {
type Item = MessageToken<'a>;
fn next(&mut self) -> Option<Self::Item> {
if !self.temp.is_empty() {
@@ -80,8 +83,8 @@ pub fn parse_message(text: &str) -> MessageResults {
match token {
MessageToken::Escape => {}
MessageToken::CodeblockMarker(_) => {},
MessageToken::UserMention(id) => { results.user_mentions.insert(id); },
MessageToken::RoleMention(id) => { results.role_mentions.insert(id); },
MessageToken::UserMention(id) => { results.user_mentions.insert(id.to_string()); },
MessageToken::RoleMention(id) => { results.role_mentions.insert(id.to_string()); },
MessageToken::MentionEveryone => results.mentions_everyone = true,
MessageToken::MentionOnline => results.mentions_online = true,
};
@@ -106,7 +109,7 @@ mod tests {
let output = parse_message_iter("Hello <@01FD58YK5W7QRV5H3D64KTQYX3>.").collect::<Vec<_>>();
assert_eq!(output.len(), 1);
assert_eq!(output[0], MessageToken::UserMention("01FD58YK5W7QRV5H3D64KTQYX3".to_string()));
assert_eq!(output[0], MessageToken::UserMention("01FD58YK5W7QRV5H3D64KTQYX3"));
}
#[test]
@@ -114,7 +117,7 @@ mod tests {
let output = parse_message_iter("Hello <%01FD58YK5W7QRV5H3D64KTQYX3>.").collect::<Vec<_>>();
assert_eq!(output.len(), 1);
assert_eq!(output[0], MessageToken::RoleMention("01FD58YK5W7QRV5H3D64KTQYX3".to_string()));
assert_eq!(output[0], MessageToken::RoleMention("01FD58YK5W7QRV5H3D64KTQYX3"));
}
#[test]
@@ -138,8 +141,8 @@ mod tests {
let output = parse_message_iter("Hello <@01FD58YK5W7QRV5H3D64KTQYX3>, <%01FD58YK5W7QRV5H3D64KTQYX3>, @everyone and @online.").collect::<Vec<_>>();
assert_eq!(output.len(), 4);
assert_eq!(output[0], MessageToken::UserMention("01FD58YK5W7QRV5H3D64KTQYX3".to_string()));
assert_eq!(output[1], MessageToken::RoleMention("01FD58YK5W7QRV5H3D64KTQYX3".to_string()));
assert_eq!(output[0], MessageToken::UserMention("01FD58YK5W7QRV5H3D64KTQYX3"));
assert_eq!(output[1], MessageToken::RoleMention("01FD58YK5W7QRV5H3D64KTQYX3"));
assert_eq!(output[2], MessageToken::MentionEveryone);
assert_eq!(output[3], MessageToken::MentionOnline);
}
@@ -149,8 +152,8 @@ mod tests {
let output = parse_message_iter("<@01FD58YK5W7QRV5H3D64KTQYX3><%01FD58YK5W7QRV5H3D64KTQYX3>@everyone@online").collect::<Vec<_>>();
assert_eq!(output.len(), 4);
assert_eq!(output[0], MessageToken::UserMention("01FD58YK5W7QRV5H3D64KTQYX3".to_string()));
assert_eq!(output[1], MessageToken::RoleMention("01FD58YK5W7QRV5H3D64KTQYX3".to_string()));
assert_eq!(output[0], MessageToken::UserMention("01FD58YK5W7QRV5H3D64KTQYX3"));
assert_eq!(output[1], MessageToken::RoleMention("01FD58YK5W7QRV5H3D64KTQYX3"));
assert_eq!(output[2], MessageToken::MentionEveryone);
assert_eq!(output[3], MessageToken::MentionOnline);
}
@@ -170,15 +173,14 @@ mod tests {
assert_eq!(output.len(), 5);
assert_eq!(output[0], MessageToken::CodeblockMarker(3));
assert_eq!(output[1], MessageToken::UserMention("01FD58YK5W7QRV5H3D64KTQYX3".to_string()));
assert_eq!(output[2], MessageToken::RoleMention("01FD58YK5W7QRV5H3D64KTQYX3".to_string()));
assert_eq!(output[1], MessageToken::UserMention("01FD58YK5W7QRV5H3D64KTQYX3"));
assert_eq!(output[2], MessageToken::RoleMention("01FD58YK5W7QRV5H3D64KTQYX3"));
assert_eq!(output[3], MessageToken::MentionEveryone);
assert_eq!(output[4], MessageToken::MentionOnline);
}
#[test]
fn test_inline_codeblock_no_mentions() {
let output = parse_message_iter("`<@01FD58YK5W7QRV5H3D64KTQYX3><%01FD58YK5W7QRV5H3D64KTQYX3>@everyone@online`").collect::<Vec<_>>();
assert_eq!(output.len(), 2);
@@ -192,12 +194,21 @@ mod tests {
assert_eq!(output.len(), 5);
assert_eq!(output[0], MessageToken::CodeblockMarker(1));
assert_eq!(output[1], MessageToken::UserMention("01FD58YK5W7QRV5H3D64KTQYX3".to_string()));
assert_eq!(output[2], MessageToken::RoleMention("01FD58YK5W7QRV5H3D64KTQYX3".to_string()));
assert_eq!(output[1], MessageToken::UserMention("01FD58YK5W7QRV5H3D64KTQYX3"));
assert_eq!(output[2], MessageToken::RoleMention("01FD58YK5W7QRV5H3D64KTQYX3"));
assert_eq!(output[3], MessageToken::MentionEveryone);
assert_eq!(output[4], MessageToken::MentionOnline);
}
#[test]
fn test_codeblock_with_language_no_mentions() {
let output = parse_message_iter("```rust\n<@01FD58YK5W7QRV5H3D64KTQYX3><%01FD58YK5W7QRV5H3D64KTQYX3>@everyone@online```").collect::<Vec<_>>();
assert_eq!(output.len(), 2);
assert_eq!(output[0], MessageToken::CodeblockMarker(3));
assert_eq!(output[1], MessageToken::CodeblockMarker(3));
}
#[test]
fn test_double_inline_codeblock() {
let output = parse_message_iter("``this should not ping @everyone``").collect::<Vec<_>>();

View File

@@ -1,6 +1,6 @@
[package]
name = "revolt-permissions"
version = "0.8.7"
version = "0.8.9"
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.9", path = "../result" }
# Utility
auto_ops = "0.3.0"

Some files were not shown because too many files have changed in this diff Show More