repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/filter/lazy_load.rs
crates/core/src/client/filter/lazy_load.rs
use salvo::prelude::*; use serde::{Deserialize, Serialize, Serializer, ser::SerializeStruct as _}; /// Specifies options for [lazy-loading membership events][lazy-loading] on /// supported endpoints /// /// [lazy-loading]: https://spec.matrix.org/latest/client-server-api/#lazy-loading-room-members #[derive(ToSchema, Clone, Copy, Debug, Default, Eq, PartialEq, Deserialize)] #[serde(from = "LazyLoadJsonRepr")] #[allow(clippy::exhaustive_enums)] pub enum LazyLoadOptions { /// Disables lazy-loading of membership events. #[default] Disabled, /// Enables lazy-loading of events. Enabled { /// If `true`, sends all membership events for all events, even if they /// have already been sent to the client. /// /// Defaults to `false`. include_redundant_members: bool, }, } impl LazyLoadOptions { /// Returns `true` is `self` is `Disabled`. pub fn is_disabled(&self) -> bool { matches!(self, Self::Disabled) } pub fn is_enabled(&self) -> bool { !self.is_disabled() } } impl Serialize for LazyLoadOptions { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut state; match *self { Self::Enabled { include_redundant_members: true, } => { state = serializer.serialize_struct("LazyLoad", 2)?; state.serialize_field("lazy_load_members", &true)?; state.serialize_field("include_redundant_members", &true)?; } Self::Enabled { .. } => { state = serializer.serialize_struct("LazyLoad", 1)?; state.serialize_field("lazy_load_members", &true)?; } Self::Disabled => { state = serializer.serialize_struct("LazyLoad", 0)?; } } state.end() } } #[derive(Deserialize)] struct LazyLoadJsonRepr { lazy_load_members: Option<bool>, include_redundant_members: Option<bool>, } impl From<LazyLoadJsonRepr> for LazyLoadOptions { fn from(opts: LazyLoadJsonRepr) -> Self { if opts.lazy_load_members.unwrap_or(false) { Self::Enabled { include_redundant_members: opts.include_redundant_members.unwrap_or(false), } } else { Self::Disabled } } } #[cfg(test)] mod tests { use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; use super::LazyLoadOptions; #[test] fn serialize_disabled() { let lazy_load_options = LazyLoadOptions::Disabled; assert_eq!(to_json_value(lazy_load_options).unwrap(), json!({})); } #[test] fn serialize_no_redundant() { let lazy_load_options = LazyLoadOptions::Enabled { include_redundant_members: false, }; assert_eq!( to_json_value(lazy_load_options).unwrap(), json!({ "lazy_load_members": true }) ); } #[test] fn serialize_with_redundant() { let lazy_load_options = LazyLoadOptions::Enabled { include_redundant_members: true, }; assert_eq!( to_json_value(lazy_load_options).unwrap(), json!({ "lazy_load_members": true, "include_redundant_members": true }) ); } #[test] fn deserialize_no_lazy_load() { let json = json!({}); assert_eq!( from_json_value::<LazyLoadOptions>(json).unwrap(), LazyLoadOptions::Disabled ); let json = json!({ "include_redundant_members": true }); assert_eq!( from_json_value::<LazyLoadOptions>(json).unwrap(), LazyLoadOptions::Disabled ); } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/filter/url.rs
crates/core/src/client/filter/url.rs
use salvo::prelude::*; use serde::{ de::{Deserialize, Deserializer}, ser::{Serialize, Serializer}, }; /// Options for filtering based on the presence of a URL. #[derive(ToSchema, Clone, Copy, Debug, Eq, PartialEq)] #[allow(clippy::exhaustive_enums)] pub enum UrlFilter { /// Includes only events with a url key in their content. EventsWithUrl, /// Excludes events with a url key in their content. EventsWithoutUrl, } impl Serialize for UrlFilter { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match *self { Self::EventsWithUrl => serializer.serialize_bool(true), Self::EventsWithoutUrl => serializer.serialize_bool(false), } } } impl<'de> Deserialize<'de> for UrlFilter { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { Ok(match bool::deserialize(deserializer)? { true => Self::EventsWithUrl, false => Self::EventsWithoutUrl, }) } } #[cfg(test)] mod tests { use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; use super::UrlFilter; #[test] fn serialize_filter_events_with_url() { let events_with_url = UrlFilter::EventsWithUrl; assert_eq!(to_json_value(events_with_url).unwrap(), json!(true)); } #[test] fn serialize_filter_events_without_url() { let events_without_url = UrlFilter::EventsWithoutUrl; assert_eq!(to_json_value(events_without_url).unwrap(), json!(false)); } #[test] fn deserialize_filter_events_with_url() { let json = json!(true); assert_eq!( from_json_value::<UrlFilter>(json).unwrap(), UrlFilter::EventsWithUrl ); } #[test] fn deserialize_filter_events_without_url() { let json = json!(false); assert_eq!( from_json_value::<UrlFilter>(json).unwrap(), UrlFilter::EventsWithoutUrl ); } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/room/thread_msc4306.rs
crates/core/src/client/room/thread_msc4306.rs
use salvo::oapi::ToSchema; use serde::{Deserialize, Serialize}; use crate::OwnedEventId; // `GET /_matrix/client/*/rooms/{roomId}/thread/{eventId}/subscription` // // Gets the subscription state of the current user to a thread in a room. // `/unstable/` ([spec]) // // [spec]: https://github.com/matrix-org/matrix-spec-proposals/pull/4306 // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: true, // authentication: AccessToken, // history: { // unstable("org.matrix.msc4306") => "/_matrix/client/unstable/io.element.msc4306/rooms/{room_id}/thread/{thread_root}/subscription", // } // }; // /// Request type for the `get_thread_subscription` endpoint. // #[request(error = crate::Error)] // pub struct Request { // /// The room ID where the thread is located. // #[palpo_api(path)] // pub room_id: OwnedRoomId, // /// The event ID of the thread root to get the status for. // #[palpo_api(path)] // pub thread_root: OwnedEventId, // } /// Response type for the `get_thread_subscription` endpoint. #[derive(ToSchema, Serialize, Debug)] pub struct ThreadSubscriptionResBody { /// Whether the subscription was made automatically by a client, not by manual user choice. pub automatic: bool, } impl ThreadSubscriptionResBody { /// Creates a new `Response`. pub fn new(automatic: bool) -> Self { Self { automatic } } } // `PUT /_matrix/client/*/rooms/{roomId}/thread/{eventId}/subscription` // // Updates the subscription state of the current user to a thread in a room. // `/unstable/` ([spec]) // // [spec]: https://github.com/matrix-org/matrix-spec-proposals/pull/4306 // const METADATA: Metadata = metadata! { // method: PUT, // rate_limited: true, // authentication: AccessToken, // history: { // unstable("org.matrix.msc4306") => "/_matrix/client/unstable/io.element.msc4306/rooms/{room_id}/thread/{thread_root}/subscription", // } // }; /// Request type for the `subscribe_thread` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct SetThreadSubscriptionReqBody { // /// The room ID where the thread is located. // #[palpo_api(path)] // pub room_id: OwnedRoomId, // /// The event ID of the thread root to subscribe to. // #[palpo_api(path)] // pub thread_root: OwnedEventId, /// Whether the subscription was made automatically by a client, not by manual user choice, /// and up to which event. #[serde(skip_serializing_if = "Option::is_none")] pub automatic: Option<OwnedEventId>, } // /// Response type for the `subscribe_thread` endpoint. // #[response(error = crate::Error)] // pub struct Response {} impl SetThreadSubscriptionReqBody { /// Creates a new `SetThreadSubscriptionReqBody` for the given room and thread IDs. /// /// If `automatic` is set, it must be the ID of the last thread event causing an automatic /// update, which is not necessarily the latest thread event. See the MSC for more details. pub fn new(automatic: Option<OwnedEventId>) -> Self { Self { automatic } } } // impl Response { // /// Creates a new `Response`. // pub fn new() -> Self { // Self {} // } // } // `DELETE /_matrix/client/*/rooms/{roomId}/thread/{eventId}/subscription` // // Removes the subscription state of the current user to a thread in a room. // `/unstable/` ([spec]) // // [spec]: https://github.com/matrix-org/matrix-spec-proposals/pull/4306 // const METADATA: Metadata = metadata! { // method: DELETE, // rate_limited: true, // authentication: AccessToken, // history: { // unstable("org.matrix.msc4306") => "/_matrix/client/unstable/io.element.msc4306/rooms/{room_id}/thread/{thread_root}/subscription", // } // }; // /// Request type for the `unsubscribe_thread` endpoint. // #[request(error = crate::Error)] // pub struct Request { // /// The room ID where the thread is located. // #[palpo_api(path)] // pub room_id: OwnedRoomId, // /// The event ID of the thread root to unsubscribe to. // #[palpo_api(path)] // pub thread_root: OwnedEventId, // } // /// Response type for the `unsubscribe_thread` endpoint. // #[response(error = crate::Error)] // pub struct Response {} // impl Request { // /// Creates a new `Request` for the given room and thread IDs. // pub fn new(room_id: OwnedRoomId, thread_root: OwnedEventId) -> Self { // Self { // room_id, // thread_root, // } // } // } // impl Response { // /// Creates a new `Response`. // pub fn new() -> Self { // Self {} // } // }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/room/summary.rs
crates/core/src/client/room/summary.rs
use salvo::prelude::*; use serde::{Deserialize, Serialize}; use crate::{ EventEncryptionAlgorithm, events::room::member::MembershipState, identifiers::*, room::RoomType, space::SpaceRoomJoinRule, }; // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: AccessTokenOptional, // history: { // unstable => // "/_matrix/client/unstable/im.nheko.summary/summary/:room_id_or_alias", // //1.15 => "/_matrix/client/v1/summary/:room_id_or_alias", // } // }; /// Request type for the `get_summary` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct SummaryMsc3266ReqArgs { /// Alias or ID of the room to be summarized. #[salvo(parameter(parameter_in = Path))] pub room_id_or_alias: OwnedRoomOrAliasId, /// Limit messages chunks size #[salvo(parameter(parameter_in = Query))] #[serde(default, skip_serializing_if = "Vec::is_empty")] pub via: Vec<OwnedServerName>, } /// Response type for the `get_room_event` endpoint. #[derive(ToSchema, Deserialize, Serialize, Debug)] pub struct SummaryMsc3266ResBody { /// ID of the room (useful if it's an alias). pub room_id: OwnedRoomId, /// The canonical alias for this room, if set. #[serde(skip_serializing_if = "Option::is_none")] pub canonical_alias: Option<OwnedRoomAliasId>, /// Avatar of the room. #[serde(skip_serializing_if = "Option::is_none")] pub avatar_url: Option<OwnedMxcUri>, /// Whether guests can join the room. pub guest_can_join: bool, /// Name of the room. #[serde(skip_serializing_if = "Option::is_none")] pub name: Option<String>, /// Member count of the room. pub num_joined_members: u64, /// Topic of the room. #[serde(skip_serializing_if = "Option::is_none")] pub topic: Option<String>, /// Whether the room history can be read without joining. pub world_readable: bool, /// Join rule of the room. pub join_rule: SpaceRoomJoinRule, /// Type of the room, if any. #[serde(skip_serializing_if = "Option::is_none")] pub room_type: Option<RoomType>, /// Version of the room. #[serde( skip_serializing_if = "Option::is_none", rename = "im.nheko.summary.room_version", alias = "im.nheko.summary.version", alias = "room_version" )] pub room_version: Option<RoomVersionId>, /// The current membership of this user in the room. /// /// This field will not be present when called unauthenticated, but is /// required when called authenticated. It should be `leave` if the /// server doesn't know about the room, since for all other membership /// states the server would know about the room already. #[serde(skip_serializing_if = "Option::is_none")] pub membership: Option<MembershipState>, /// If the room is encrypted, the algorithm used for this room. #[serde( skip_serializing_if = "Option::is_none", rename = "im.nheko.summary.encryption", alias = "encryption" )] pub encryption: Option<EventEncryptionAlgorithm>, /// If the room is a restricted room, these are the room IDs which are /// specified by the join rules. #[serde(default, skip_serializing_if = "crate::serde::is_default")] pub allowed_room_ids: Vec<OwnedRoomId>, } impl SummaryMsc3266ResBody { /// Creates a new [`Response`] with all the mandatory fields set. pub fn new( room_id: OwnedRoomId, join_rule: SpaceRoomJoinRule, guest_can_join: bool, num_joined_members: u64, world_readable: bool, ) -> Self { Self { room_id, canonical_alias: None, avatar_url: None, guest_can_join, name: None, num_joined_members, topic: None, world_readable, join_rule, room_type: None, room_version: None, membership: None, encryption: None, allowed_room_ids: Vec::new(), } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/room/alias.rs
crates/core/src/client/room/alias.rs
/// `GET /_matrix/client/*/rooms/{room_id}/aliases` /// /// Get a list of aliases maintained by the local server for the given room. /// `/v3/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3roomsroomidaliases use salvo::prelude::*; use serde::{Deserialize, Serialize}; use crate::{OwnedRoomAliasId, OwnedRoomId, OwnedServerName}; // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: true, // authentication: AccessToken, // history: { // unstable => // "/_matrix/client/unstable/org.matrix.msc2432/rooms/:room_id/aliases", // 1.0 => "/_matrix/client/r0/rooms/:room_id/aliases", // 1.1 => "/_matrix/client/v3/rooms/:room_id/aliases", // } // }; // /// Request type for the `aliases` endpoint. // pub struct Requesxt { // /// The room ID to get aliases of. // #[salvo(parameter(parameter_in = Path))] // pub room_id: OwnedRoomId, // } /// Response type for the `aliases` endpoint. #[derive(ToSchema, Serialize, Debug)] pub struct AliasesResBody { /// The server's local aliases on the room. pub aliases: Vec<OwnedRoomAliasId>, } impl AliasesResBody { /// Creates a new `Response` with the given aliases. pub fn new(aliases: Vec<OwnedRoomAliasId>) -> Self { Self { aliases } } } // /// Endpoints for room aliases. // /// `GET /_matrix/client/*/directory/room/{roomAlias}` // /// // /// Resolve a room alias to a room ID. // /// `/v3/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3directoryroomroomalias // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: None, // history: { // 1.0 => "/_matrix/client/r0/directory/room/:room_alias", // 1.1 => "/_matrix/client/v3/directory/room/:room_alias", // } // }; // /// Request type for the `get_alias` endpoint. // pub struct Request { // /// The room alias. // #[salvo(parameter(parameter_in = Path))] // pub room_alias: OwnedRoomAliasId, // } /// Response type for the `get_alias` endpoint. #[derive(ToSchema, Serialize, Deserialize, Debug)] pub struct AliasResBody { /// The room ID for this room alias. pub room_id: OwnedRoomId, /// A list of servers that are aware of this room ID. pub servers: Vec<OwnedServerName>, } impl AliasResBody { /// Creates a new `Response` with the given room id and servers pub fn new(room_id: OwnedRoomId, servers: Vec<OwnedServerName>) -> Self { Self { room_id, servers } } } // /// `PUT /_matrix/client/*/directory/room/{roomAlias}` // /// // /// Add an alias to a room. // /// `/v3/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/client-server-api/#put_matrixclientv3directoryroomroomalias // const METADATA: Metadata = metadata! { // method: PUT, // rate_limited: false, // authentication: AccessToken, // history: { // 1.0 => "/_matrix/client/r0/directory/room/:room_alias", // 1.1 => "/_matrix/client/v3/directory/room/:room_alias", // } // }; /// Request type for the `create_alias` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct SetAliasReqBody { // /// The room alias to set. // #[salvo(parameter(parameter_in = Path))] // pub room_alias: OwnedRoomAliasId, /// The room ID to set. pub room_id: OwnedRoomId, } // `DELETE /_matrix/client/*/directory/room/{roomAlias}` // // Remove an alias from a room. // `/v3/` ([spec]) // // [spec]: https://spec.matrix.org/latest/client-server-api/#delete_matrixclientv3directoryroomroomalias // const METADATA: Metadata = metadata! { // method: DELETE, // rate_limited: false, // authentication: AccessToken, // history: { // 1.0 => "/_matrix/client/r0/directory/room/:room_alias", // 1.1 => "/_matrix/client/v3/directory/room/:room_alias", // } // }; // /// Request type for the `delete_alias` endpoint. // pub struct DeleteAliasReqArgs { // /// The room alias to remove. // #[salvo(parameter(parameter_in = Path))] // pub room_alias: OwnedRoomAliasId, // }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/room/thread_msc4308.rs
crates/core/src/client/room/thread_msc4308.rs
//! `GET /_matrix/client/*/thread_subscriptions` //! //! Retrieve a paginated range of thread subscriptions across all rooms. //! `/unstable/` ([spec]) //! //! [spec]: https://github.com/matrix-org/matrix-spec-proposals/pull/4308 use std::collections::BTreeMap; use salvo::oapi::ToSchema; use serde::{Deserialize, Serialize}; use crate::{Direction, OwnedEventId, OwnedRoomId}; // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: true, // authentication: AccessToken, // history: { // unstable("org.matrix.msc4308") => "/_matrix/client/unstable/io.element.msc4308/thread_subscriptions", // } // }; /// Request type for the `get_thread_subscriptions_changes` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct ThreadSubscriptionsChangesReqArgs { /// The direction to use for pagination. /// /// Only `Direction::Backward` is meant to be supported, which is why this field is private /// for now (as of 2025-08-21). #[allow(dead_code)] dir: Direction, /// A token to continue pagination from. /// /// This token can be acquired from a previous `/thread_subscriptions` response, or the /// `prev_batch` in a sliding sync response's `thread_subscriptions` field. /// /// The token is opaque and has no client-discernible meaning. /// /// If not provided, then the pagination starts from the "end". #[serde(skip_serializing_if = "Option::is_none")] pub from: Option<String>, /// A token used to limit the pagination. /// /// The token can be set to the value of a sliding sync `pos` field used in a request that /// returned new thread subscriptions with a `prev_batch` token. #[serde(skip_serializing_if = "Option::is_none")] pub to: Option<String>, /// A maximum number of thread subscriptions to fetch in one response. /// /// Defaults to 100, if not provided. Servers may impose a smaller limit than requested. #[serde(skip_serializing_if = "Option::is_none")] pub limit: Option<i64>, } impl Default for ThreadSubscriptionsChangesReqArgs { fn default() -> Self { Self::new() } } impl ThreadSubscriptionsChangesReqArgs { /// Creates a new empty `ThreadSubscriptionsChangesReqArgs`. pub fn new() -> Self { Self { dir: Direction::Backward, from: None, to: None, limit: None, } } } /// A thread has been subscribed to at some point. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ThreadSubscription { /// Whether the subscription was made automatically by a client, not by manual user choice. pub automatic: bool, /// The bump stamp of the thread subscription, to be used to compare with other changes /// related to the same thread. pub bump_stamp: i64, } impl ThreadSubscription { /// Create a new [`ThreadSubscription`] with the given values. pub fn new(automatic: bool, bump_stamp: i64) -> Self { Self { automatic, bump_stamp, } } } /// A thread has been unsubscribed to at some point. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ThreadUnsubscription { /// The bump stamp of the thread subscription, to be used to compare with other changes /// related to the same thread. pub bump_stamp: i64, } impl ThreadUnsubscription { /// Create a new [`ThreadUnsubscription`] with the given bump stamp. pub fn new(bump_stamp: i64) -> Self { Self { bump_stamp } } } /// Response type for the `get_thread_subscriptions_changes` endpoint. #[derive(ToSchema, Serialize, Debug)] pub struct ThreadSubscriptionsChangesResBody { /// New thread subscriptions. #[serde(skip_serializing_if = "BTreeMap::is_empty")] pub subscribed: BTreeMap<OwnedRoomId, BTreeMap<OwnedEventId, ThreadSubscription>>, /// New thread unsubscriptions. #[serde(skip_serializing_if = "BTreeMap::is_empty")] pub unsubscribed: BTreeMap<OwnedRoomId, BTreeMap<OwnedEventId, ThreadUnsubscription>>, /// If there are still more results to fetch, this is the token to use as the next `from` /// value. #[serde(skip_serializing_if = "Option::is_none")] pub end: Option<String>, } impl Default for ThreadSubscriptionsChangesResBody { fn default() -> Self { Self::new() } } impl ThreadSubscriptionsChangesResBody { /// Creates a new empty `ThreadSubscriptionsChangesResBody`. pub fn new() -> Self { Self { subscribed: BTreeMap::new(), unsubscribed: BTreeMap::new(), end: None, } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/room/thread.rs
crates/core/src/client/room/thread.rs
//! `GET /_matrix/client/*/rooms/{room_id}/threads` //! //! Retrieve a list of threads in a room, with optional filters. //! `/v1/` ([spec]) //! //! [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv1roomsroomidthreads use salvo::prelude::*; use serde::{Deserialize, Serialize}; use crate::{ OwnedRoomId, PrivOwnedStr, events::AnyTimelineEvent, serde::{RawJson, StringEnum}, }; // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: true, // authentication: AccessToken, // history: { // unstable => // "/_matrix/client/unstable/org.matrix.msc3856/rooms/:room_id/threads", // 1.4 => "/_matrix/client/v1/rooms/:room_id/threads", // } // }; // /// Request type for the `get_thread_roots` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct ThreadsReqArgs { /// The room ID where the thread roots are located. #[salvo(parameter(parameter_in = Path))] pub room_id: OwnedRoomId, /// The pagination token to start returning results from. /// /// If `None`, results start at the most recent topological event visible to /// the user. #[serde(default, skip_serializing_if = "Option::is_none")] #[salvo(parameter(parameter_in = Query))] pub from: Option<String>, /// Which thread roots are of interest to the caller. #[serde(default, skip_serializing_if = "crate::serde::is_default")] #[salvo(parameter(parameter_in = Query))] pub include: IncludeThreads, /// The maximum number of results to return in a single `chunk`. /// /// Servers should apply a default value, and impose a maximum value to /// avoid resource exhaustion. #[serde(default, skip_serializing_if = "Option::is_none")] #[salvo(parameter(parameter_in = Query))] pub limit: Option<usize>, } /// Response type for the `get_thread_roots` endpoint. #[derive(ToSchema, Serialize, Debug)] pub struct ThreadsResBody { /// The thread roots, ordered by the `latest_event` in each event's /// aggregation bundle. /// /// All events returned include bundled aggregations. pub chunk: Vec<RawJson<AnyTimelineEvent>>, /// An opaque string to provide to `from` to keep paginating the responses. /// /// If this is `None`, there are no more results to fetch and the client /// should stop paginating. #[serde(default, skip_serializing_if = "Option::is_none")] pub next_batch: Option<String>, } impl ThreadsResBody { /// Creates a new `Response` with the given chunk. pub fn new(chunk: Vec<RawJson<AnyTimelineEvent>>) -> Self { Self { chunk, next_batch: None, } } } /// Which threads to include in the response. #[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))] #[derive(ToSchema, Clone, Default, StringEnum)] #[palpo_enum(rename_all = "lowercase")] #[non_exhaustive] pub enum IncludeThreads { /// `all` /// /// Include all thread roots found in the room. /// /// This is the default. #[default] All, /// `participated` /// /// Only include thread roots for threads where /// [`current_user_participated`] is `true`. /// /// [`current_user_participated`]: https://spec.matrix.org/latest/client-server-api/#server-side-aggregation-of-mthread-relationships Participated, #[doc(hidden)] #[salvo(schema(skip))] _Custom(PrivOwnedStr), }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/key/claim_key.rs
crates/core/src/client/key/claim_key.rs
//! `POST /_matrix/client/*/keys/claim` //! //! Claims one-time keys for use in pre-key messages. use std::{collections::BTreeMap, time::Duration}; use salvo::oapi::ToSchema; use serde::{Deserialize, Serialize}; use crate::{ DeviceKeyAlgorithm, client::key::{SignedKeys, SignedKeysIter}, encryption::OneTimeKey, identifiers::*, serde::{JsonValue, RawJsonValue}, }; impl<'a> IntoIterator for &'a SignedKeys { type Item = (&'a str, &'a RawJsonValue); type IntoIter = SignedKeysIter<'a>; fn into_iter(self) -> Self::IntoIter { self.iter() } } // const METADATA: Metadata = metadata! { // method: POST, // rate_limited: false, // authentication: AccessToken, // history: { // 1.0 => "/_matrix/client/r0/keys/claim", // 1.1 => "/_matrix/client/v3/keys/claim", // } // }; /// Request type for the `claim_keys` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct ClaimKeysReqBody { /// The time (in milliseconds) to wait when downloading keys from remote /// servers. 10 seconds is the recommended default. #[serde( with = "crate::serde::duration::opt_ms", default, skip_serializing_if = "Option::is_none" )] pub timeout: Option<Duration>, /// The keys to be claimed. pub one_time_keys: BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceId, DeviceKeyAlgorithm>>, } impl ClaimKeysReqBody { /// Creates a new `Request` with the given key claims and the recommended 10 /// second timeout. pub fn new( one_time_keys: BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceId, DeviceKeyAlgorithm>>, ) -> Self { Self { timeout: Some(Duration::from_secs(10)), one_time_keys, } } } /// Response type for the `claim_keys` endpoint. #[derive(ToSchema, Serialize, Debug)] pub struct ClaimKeysResBody { /// If any remote homeservers could not be reached, they are recorded here. /// /// The names of the properties are the names of the unreachable servers. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] #[salvo(schema(value_type = Object, additional_properties = true))] pub failures: BTreeMap<String, JsonValue>, /// One-time keys for the queried devices. pub one_time_keys: BTreeMap<OwnedUserId, OneTimeKeys>, } impl ClaimKeysResBody { /// Creates a new `Response` with the given keys and no failures. pub fn new(one_time_keys: BTreeMap<OwnedUserId, OneTimeKeys>) -> Self { Self { failures: BTreeMap::new(), one_time_keys, } } } /// The one-time keys for a given device. pub type OneTimeKeys = BTreeMap<OwnedDeviceId, BTreeMap<OwnedDeviceKeyId, OneTimeKey>>;
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/uiaa/auth_data.rs
crates/core/src/client/uiaa/auth_data.rs
//! Authentication data types for the different [`AuthType`]s. use std::{borrow::Cow, fmt}; use serde::{Deserialize, Serialize, de::DeserializeOwned}; use serde_json::Value as JsonValue; use salvo::oapi::ToSchema; mod data_serde; use super::AuthType; use crate::{PrivOwnedStr, OwnedClientSecret, OwnedSessionId, OwnedUserId, serde::JsonObject, third_party::Medium, }; /// Information for one authentication stage. #[derive(ToSchema, Clone, Serialize)] #[non_exhaustive] #[serde(untagged)] pub enum AuthData { /// Password-based authentication (`m.login.password`). Password(Password), /// Google ReCaptcha 2.0 authentication (`m.login.recaptcha`). ReCaptcha(ReCaptcha), /// Email-based authentication (`m.login.email.identity`). EmailIdentity(EmailIdentity), /// Phone number-based authentication (`m.login.msisdn`). Msisdn(Msisdn), /// Dummy authentication (`m.login.dummy`). Dummy(Dummy), /// Registration token-based authentication (`m.login.registration_token`). RegistrationToken(RegistrationToken), /// Fallback acknowledgement. FallbackAcknowledgement(FallbackAcknowledgement), /// Terms of service (`m.login.terms`). /// /// This type is only valid during account registration. Terms(Terms), /// OAuth 2.0 (`m.oauth`). /// /// This type is only valid with the cross-signing keys upload endpoint, after logging in with /// the OAuth 2.0 API. OAuth(OAuth), /// Unsupported authentication type. #[doc(hidden)] #[salvo(schema(value_type = Object))] _Custom(CustomAuthData), } impl AuthData { /// Creates a new `AuthData` with the given `auth_type` string, session and data. /// /// Prefer to use the public variants of `AuthData` where possible; this constructor is meant to /// be used for unsupported authentication types only and does not allow setting arbitrary /// data for supported ones. /// /// # Errors /// /// Returns an error if the `auth_type` is known and serialization of `data` to the /// corresponding `AuthData` variant fails. pub fn new( auth_type: &str, session: Option<String>, data: JsonObject, ) -> serde_json::Result<Self> { fn deserialize_variant<T: DeserializeOwned>( session: Option<String>, mut obj: JsonObject, ) -> serde_json::Result<T> { if let Some(session) = session { obj.insert("session".into(), session.into()); } serde_json::from_value(JsonValue::Object(obj)) } Ok(match auth_type { "m.login.password" => Self::Password(deserialize_variant(session, data)?), "m.login.recaptcha" => Self::ReCaptcha(deserialize_variant(session, data)?), "m.login.email.identity" => Self::EmailIdentity(deserialize_variant(session, data)?), "m.login.msisdn" => Self::Msisdn(deserialize_variant(session, data)?), "m.login.dummy" => Self::Dummy(deserialize_variant(session, data)?), "m.registration_token" => Self::RegistrationToken(deserialize_variant(session, data)?), "m.login.terms" => Self::Terms(deserialize_variant(session, data)?), "m.oauth" | "org.matrix.cross_signing_reset" => { Self::OAuth(deserialize_variant(session, data)?) } _ => Self::_Custom(CustomAuthData { auth_type: auth_type.into(), session, extra: data, }), }) } /// Creates a new `AuthData::FallbackAcknowledgement` with the given session key. pub fn fallback_acknowledgement(session: String) -> Self { Self::FallbackAcknowledgement(FallbackAcknowledgement::new(session)) } /// Returns the value of the `type` field, if it exists. pub fn auth_type(&self) -> Option<AuthType> { match self { Self::Password(_) => Some(AuthType::Password), Self::ReCaptcha(_) => Some(AuthType::ReCaptcha), Self::EmailIdentity(_) => Some(AuthType::EmailIdentity), Self::Msisdn(_) => Some(AuthType::Msisdn), Self::Dummy(_) => Some(AuthType::Dummy), Self::RegistrationToken(_) => Some(AuthType::RegistrationToken), Self::FallbackAcknowledgement(_) => None, Self::Terms(_) => Some(AuthType::Terms), Self::OAuth(_) => Some(AuthType::OAuth), Self::_Custom(c) => Some(AuthType::_Custom(PrivOwnedStr(c.auth_type.as_str().into()))), } } /// Returns the value of the `session` field, if it exists. pub fn session(&self) -> Option<&str> { match self { Self::Password(x) => x.session.as_deref(), Self::ReCaptcha(x) => x.session.as_deref(), Self::EmailIdentity(x) => x.session.as_deref(), Self::Msisdn(x) => x.session.as_deref(), Self::Dummy(x) => x.session.as_deref(), Self::RegistrationToken(x) => x.session.as_deref(), Self::FallbackAcknowledgement(x) => Some(&x.session), Self::Terms(x) => x.session.as_deref(), Self::OAuth(x) => x.session.as_deref(), Self::_Custom(x) => x.session.as_deref(), } } /// Returns the associated data. /// /// The returned JSON object won't contain the `type` and `session` fields, use /// [`.auth_type()`][Self::auth_type] / [`.session()`](Self::session) to access those. /// /// Prefer to use the public variants of `AuthData` where possible; this method is meant to be /// used for custom auth types only. pub fn data(&self) -> Cow<'_, JsonObject> { fn serialize<T: Serialize>(obj: T) -> JsonObject { match serde_json::to_value(obj).expect("auth data serialization to succeed") { JsonValue::Object(obj) => obj, _ => panic!("all auth data variants must serialize to objects"), } } match self { Self::Password(x) => Cow::Owned(serialize(Password { identifier: x.identifier.clone(), password: x.password.clone(), session: None, })), Self::ReCaptcha(x) => Cow::Owned(serialize(ReCaptcha { response: x.response.clone(), session: None, })), Self::EmailIdentity(x) => Cow::Owned(serialize(EmailIdentity { thirdparty_id_creds: x.thirdparty_id_creds.clone(), session: None, })), Self::Msisdn(x) => Cow::Owned(serialize(Msisdn { thirdparty_id_creds: x.thirdparty_id_creds.clone(), session: None, })), Self::RegistrationToken(x) => Cow::Owned(serialize(RegistrationToken { token: x.token.clone(), session: None, })), // These types have no associated data. Self::Dummy(_) | Self::FallbackAcknowledgement(_) | Self::Terms(_) | Self::OAuth(_) => { Cow::Owned(JsonObject::default()) } Self::_Custom(c) => Cow::Borrowed(&c.extra), } } } impl fmt::Debug for AuthData { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // Print `Password { .. }` instead of `Password(Password { .. })` match self { Self::Password(inner) => inner.fmt(f), Self::ReCaptcha(inner) => inner.fmt(f), Self::EmailIdentity(inner) => inner.fmt(f), Self::Msisdn(inner) => inner.fmt(f), Self::Dummy(inner) => inner.fmt(f), Self::RegistrationToken(inner) => inner.fmt(f), Self::FallbackAcknowledgement(inner) => inner.fmt(f), Self::Terms(inner) => inner.fmt(f), Self::OAuth(inner) => inner.fmt(f), Self::_Custom(inner) => inner.fmt(f), } } } /// Data for password-based UIAA flow. /// /// See [the spec] for how to use this. /// /// [the spec]: https://spec.matrix.org/latest/client-server-api/#password-based #[derive(ToSchema, Clone, Deserialize, Serialize)] #[serde(tag = "type", rename = "m.login.password")] pub struct Password { /// One of the user's identifiers. pub identifier: UserIdentifier, /// The plaintext password. pub password: String, /// The value of the session key given by the homeserver, if any. pub session: Option<String>, } impl Password { /// Creates a new `Password` with the given identifier and password. pub fn new(identifier: UserIdentifier, password: String) -> Self { Self { identifier, password, session: None, } } } impl fmt::Debug for Password { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let Self { identifier, password: _, session, } = self; f.debug_struct("Password") .field("identifier", identifier) .field("session", session) .finish_non_exhaustive() } } /// Data for ReCaptcha UIAA flow. /// /// See [the spec] for how to use this. /// /// [the spec]: https://spec.matrix.org/latest/client-server-api/#google-recaptcha #[derive(ToSchema, Clone, Deserialize, Serialize)] #[serde(tag = "type", rename = "m.login.recaptcha")] pub struct ReCaptcha { /// The captcha response. pub response: String, /// The value of the session key given by the homeserver, if any. pub session: Option<String>, } impl ReCaptcha { /// Creates a new `ReCaptcha` with the given response string. pub fn new(response: String) -> Self { Self { response, session: None, } } } impl fmt::Debug for ReCaptcha { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let Self { response: _, session, } = self; f.debug_struct("ReCaptcha") .field("session", session) .finish_non_exhaustive() } } /// Data for Email-based UIAA flow. /// /// See [the spec] for how to use this. /// /// [the spec]: https://spec.matrix.org/latest/client-server-api/#email-based-identity--homeserver #[derive(ToSchema, Clone, Debug, Deserialize, Serialize)] #[serde(tag = "type", rename = "m.login.email.identity")] pub struct EmailIdentity { /// Thirdparty identifier credentials. #[serde(rename = "threepid_creds")] pub thirdparty_id_creds: ThirdpartyIdCredentials, /// The value of the session key given by the homeserver, if any. pub session: Option<String>, } /// Data for phone number-based UIAA flow. /// /// See [the spec] for how to use this. /// /// [the spec]: https://spec.matrix.org/latest/client-server-api/#phone-numbermsisdn-based-identity--homeserver #[derive(ToSchema, Clone, Debug, Deserialize, Serialize)] #[serde(tag = "type", rename = "m.login.msisdn")] pub struct Msisdn { /// Thirdparty identifier credentials. #[serde(rename = "threepid_creds")] pub thirdparty_id_creds: ThirdpartyIdCredentials, /// The value of the session key given by the homeserver, if any. pub session: Option<String>, } /// Data for dummy UIAA flow. /// /// See [the spec] for how to use this. /// /// [the spec]: https://spec.matrix.org/latest/client-server-api/#dummy-auth #[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)] #[serde(tag = "type", rename = "m.login.dummy")] pub struct Dummy { /// The value of the session key given by the homeserver, if any. pub session: Option<String>, } impl Dummy { /// Creates an empty `Dummy`. pub fn new() -> Self { Self::default() } } /// Data for registration token-based UIAA flow. /// /// See [the spec] for how to use this. /// /// [the spec]: https://spec.matrix.org/latest/client-server-api/#token-authenticated-registration #[derive(ToSchema,Clone, Deserialize, Serialize)] #[serde(tag = "type", rename = "m.login.registration_token")] pub struct RegistrationToken { /// The registration token. pub token: String, /// The value of the session key given by the homeserver, if any. pub session: Option<String>, } impl RegistrationToken { /// Creates a new `RegistrationToken` with the given token. pub fn new(token: String) -> Self { Self { token, session: None, } } } impl fmt::Debug for RegistrationToken { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let Self { token: _, session } = self; f.debug_struct("RegistrationToken") .field("session", session) .finish_non_exhaustive() } } /// Data for UIAA fallback acknowledgement. /// /// See [the spec] for how to use this. /// /// [the spec]: https://spec.matrix.org/latest/client-server-api/#fallback #[derive(ToSchema, Clone, Debug, Deserialize, Serialize)] pub struct FallbackAcknowledgement { /// The value of the session key given by the homeserver. pub session: String, } impl FallbackAcknowledgement { /// Creates a new `FallbackAcknowledgement` with the given session key. pub fn new(session: String) -> Self { Self { session } } } /// Data for terms of service flow. /// /// This type is only valid during account registration. /// /// See [the spec] for how to use this. /// /// [the spec]: https://spec.matrix.org/latest/client-server-api/#terms-of-service-at-registration #[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)] #[serde(tag = "type", rename = "m.login.terms")] pub struct Terms { /// The value of the session key given by the homeserver, if any. pub session: Option<String>, } impl Terms { /// Creates an empty `Terms`. pub fn new() -> Self { Self::default() } } /// Data for an [OAuth 2.0-based] UIAA flow. /// /// [OAuth 2.0-based]: https://spec.matrix.org/latest/client-server-api/#oauth-authentication #[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)] #[serde(tag = "type", rename = "m.oauth")] pub struct OAuth { /// The value of the session key given by the homeserver, if any. pub session: Option<String>, } impl OAuth { /// Construct an empty `OAuth`. pub fn new() -> Self { Self::default() } } /// Data for an unsupported authentication type. #[doc(hidden)] #[derive(Clone, Deserialize, Serialize)] #[non_exhaustive] pub struct CustomAuthData { /// The type of authentication. #[serde(rename = "type")] auth_type: String, /// The value of the session key given by the homeserver, if any. session: Option<String>, /// Extra data. #[serde(flatten)] extra: JsonObject, } impl fmt::Debug for CustomAuthData { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let Self { auth_type, session, extra: _, } = self; f.debug_struct("CustomAuthData") .field("auth_type", auth_type) .field("session", session) .finish_non_exhaustive() } } /// Identification information for the user. #[derive(ToSchema, Clone, Debug, PartialEq, Eq)] #[allow(clippy::exhaustive_enums)] pub enum UserIdentifier { /// Either a fully qualified Matrix user ID, or just the localpart (as part of the 'identifier' /// field). UserIdOrLocalpart(String), /// An email address. Email { /// The email address. address: String, }, /// A phone number in the MSISDN format. Msisdn { /// The phone number according to the [E.164] numbering plan. /// /// [E.164]: https://www.itu.int/rec/T-REC-E.164-201011-I/en number: String, }, /// A phone number as a separate country code and phone number. /// /// The homeserver will be responsible for canonicalizing this to the MSISDN format. PhoneNumber { /// The country that the phone number is from. /// /// This is a two-letter uppercase [ISO-3166-1 alpha-2] country code. /// /// [ISO-3166-1 alpha-2]: https://www.iso.org/iso-3166-country-codes.html country: String, /// The phone number. phone: String, }, /// Unsupported `m.id.thirdpartyid`. #[doc(hidden)] _CustomThirdParty(CustomThirdPartyId), } impl UserIdentifier { /// Creates a new `UserIdentifier` from the given third party identifier. pub fn third_party_id(medium: Medium, address: String) -> Self { match medium { Medium::Email => Self::Email { address }, Medium::Msisdn => Self::Msisdn { number: address }, _ => Self::_CustomThirdParty(CustomThirdPartyId { medium, address }), } } /// Get this `UserIdentifier` as a third party identifier if it is one. pub fn as_third_party_id(&self) -> Option<(&Medium, &str)> { match self { Self::Email { address } => Some((&Medium::Email, address)), Self::Msisdn { number } => Some((&Medium::Msisdn, number)), Self::_CustomThirdParty(CustomThirdPartyId { medium, address }) => { Some((medium, address)) } _ => None, } } } impl From<OwnedUserId> for UserIdentifier { fn from(id: OwnedUserId) -> Self { Self::UserIdOrLocalpart(id.into()) } } impl From<&OwnedUserId> for UserIdentifier { fn from(id: &OwnedUserId) -> Self { Self::UserIdOrLocalpart(id.as_str().to_owned()) } } /// Data for an unsupported third-party ID. #[doc(hidden)] #[derive(ToSchema, Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct CustomThirdPartyId { /// The kind of the third-party ID. medium: Medium, /// The third-party ID. address: String, } /// Credentials for third-party authentication (e.g. email / phone number). #[derive(ToSchema, Clone, Deserialize, Serialize)] pub struct ThirdpartyIdCredentials { /// Identity server (or homeserver) session ID. pub sid: OwnedSessionId, /// Identity server (or homeserver) client secret. pub client_secret: OwnedClientSecret, /// Identity server URL. #[serde(skip_serializing_if = "Option::is_none")] pub id_server: Option<String>, /// Identity server access token. #[serde(skip_serializing_if = "Option::is_none")] pub id_access_token: Option<String>, } impl ThirdpartyIdCredentials { /// Creates a new `ThirdpartyIdCredentials` with the given session ID and client secret. pub fn new(sid: OwnedSessionId, client_secret: OwnedClientSecret) -> Self { Self { sid, client_secret, id_server: None, id_access_token: None, } } } impl fmt::Debug for ThirdpartyIdCredentials { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let Self { sid, client_secret: _, id_server, id_access_token, } = self; f.debug_struct("ThirdpartyIdCredentials") .field("sid", sid) .field("id_server", id_server) .field("id_access_token", id_access_token) .finish_non_exhaustive() } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/uiaa/get_uiaa_fallback_page.rs
crates/core/src/client/uiaa/get_uiaa_fallback_page.rs
//! `GET /_matrix/client/*/auth/{auth_type}/fallback/web?session={session_id}` //! //! Get UIAA fallback web page. //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/latest/client-server-api/#fallback use serde::Deserialize; use crate::client::uiaa::AuthType; // metadata! { // method: GET, // rate_limited: false, // authentication: NoAuthentication, // history: { // 1.0 => "/_matrix/client/r0/auth/{auth_type}/fallback/web", // 1.1 => "/_matrix/client/v3/auth/{auth_type}/fallback/web", // } // } /// Request type for the `authorize_fallback` endpoint. #[derive(Deserialize, Debug)] pub struct FallbackWebArgs { /// The type name (`m.login.dummy`, etc.) of the UIAA stage to get a fallback page for. // #[salvo(parameter(parameter_in = Path))] pub auth_type: AuthType, /// The ID of the session given by the homeserver. // #[salvo(parameter(parameter_in = Query))] pub session: String, } impl FallbackWebArgs { /// Creates a new `FallbackWebArgs` with the given auth type and session ID. pub fn new(auth_type: AuthType, session: String) -> Self { Self { auth_type, session } } } // /// Response type for the `authorize_fallback` endpoint. // #[derive(Debug, Clone)] // #[allow(clippy::exhaustive_enums)] // pub enum Response { // /// The response is a redirect. // Redirect(Redirect), // /// The response is an HTML page. // Html(HtmlPage), // } // /// The data of a redirect. // #[derive(Debug, Clone)] // pub struct Redirect { // /// The URL to redirect the user to. // pub url: String, // } // /// The data of a HTML page. // #[derive(Debug, Clone)] // pub struct HtmlPage { // /// The body of the HTML page. // pub body: Vec<u8>, // } // impl Response { // /// Creates a new HTML `Response` with the given HTML body. // pub fn html(body: Vec<u8>) -> Self { // Self::Html(HtmlPage { body }) // } // /// Creates a new HTML `Response` with the given redirect URL. // pub fn redirect(url: String) -> Self { // Self::Redirect(Redirect { url }) // } // } // #[cfg(feature = "server")] // impl crate::api::OutgoingResponse for Response { // fn try_into_http_response<T: Default + bytes::BufMut>( // self, // ) -> Result<http::Response<T>, crate::api::error::IntoHttpError> { // match self { // Response::Redirect(Redirect { url }) => Ok(http::Response::builder() // .status(http::StatusCode::FOUND) // .header(http::header::LOCATION, url) // .body(T::default())?), // Response::Html(HtmlPage { body }) => Ok(http::Response::builder() // .status(http::StatusCode::OK) // .header(http::header::CONTENT_TYPE, "text/html; charset=utf-8") // .body(crate::serde::slice_to_buf(&body))?), // } // } // } // #[cfg(feature = "client")] // impl crate::api::IncomingResponse for Response { // type EndpointError = crate::Error; // fn try_from_http_response<T: AsRef<[u8]>>( // response: http::Response<T>, // ) -> Result<Self, crate::api::error::FromHttpResponseError<Self::EndpointError>> { // use crate::api::{ // EndpointError, // error::{DeserializationError, FromHttpResponseError, HeaderDeserializationError}, // }; // if response.status().as_u16() >= 400 { // return Err(FromHttpResponseError::Server( // Self::EndpointError::from_http_response(response), // )); // } // if response.status() == http::StatusCode::FOUND { // let Some(location) = response.headers().get(http::header::LOCATION) else { // return Err(DeserializationError::Header( // HeaderDeserializationError::MissingHeader(http::header::LOCATION.to_string()), // ) // .into()); // }; // let url = location.to_str()?; // return Ok(Self::Redirect(Redirect { // url: url.to_owned(), // })); // } // let body = response.into_body().as_ref().to_owned(); // Ok(Self::Html(HtmlPage { body })) // } // } // #[cfg(all(test, feature = "client"))] // mod tests_client { // use crate::api::IncomingResponse; // use assert_matches2::assert_matches; // use http::header::{CONTENT_TYPE, LOCATION}; // use super::Response; // #[test] // fn incoming_redirect() { // use super::Redirect; // let http_response = http::Response::builder() // .status(http::StatusCode::FOUND) // .header(LOCATION, "http://localhost/redirect") // .body(Vec::<u8>::new()) // .unwrap(); // let response = Response::try_from_http_response(http_response).unwrap(); // assert_matches!(response, Response::Redirect(Redirect { url })); // assert_eq!(url, "http://localhost/redirect"); // } // #[test] // fn incoming_html() { // use super::HtmlPage; // let http_response = http::Response::builder() // .status(http::StatusCode::OK) // .header(CONTENT_TYPE, "text/html; charset=utf-8") // .body(b"<h1>My Page</h1>") // .unwrap(); // let response = Response::try_from_http_response(http_response).unwrap(); // assert_matches!(response, Response::Html(HtmlPage { body })); // assert_eq!(body, b"<h1>My Page</h1>"); // } // } // #[cfg(all(test, feature = "server"))] // mod tests_server { // use crate::api::OutgoingResponse; // use http::header::{CONTENT_TYPE, LOCATION}; // use super::Response; // #[test] // fn outgoing_redirect() { // let response = Response::redirect("http://localhost/redirect".to_owned()); // let http_response = response.try_into_http_response::<Vec<u8>>().unwrap(); // assert_eq!(http_response.status(), http::StatusCode::FOUND); // assert_eq!( // http_response // .headers() // .get(LOCATION) // .unwrap() // .to_str() // .unwrap(), // "http://localhost/redirect" // ); // assert!(http_response.into_body().is_empty()); // } // #[test] // fn outgoing_html() { // let response = Response::html(b"<h1>My Page</h1>".to_vec()); // let http_response = response.try_into_http_response::<Vec<u8>>().unwrap(); // assert_eq!(http_response.status(), http::StatusCode::OK); // assert_eq!( // http_response // .headers() // .get(CONTENT_TYPE) // .unwrap() // .to_str() // .unwrap(), // "text/html; charset=utf-8" // ); // assert_eq!(http_response.into_body(), b"<h1>My Page</h1>"); // } // }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/uiaa/auth_params.rs
crates/core/src/client/uiaa/auth_params.rs
//! Authentication parameters types for the different [`AuthType`]s. use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; mod params_serde; /// Parameters for the terms of service flow. /// /// This type is only valid during account registration. /// /// See [the spec] for how to use this. /// /// [the spec]: https://spec.matrix.org/latest/client-server-api/#terms-of-service-at-registration #[derive(Clone, Debug, Default, Deserialize, Serialize)] pub struct LoginTermsParams { /// A map from policy ID to the current definition of this policy document. pub policies: BTreeMap<String, PolicyDefinition>, } impl LoginTermsParams { /// Construct a new `LoginTermsParams` with the given policy documents. pub fn new(policies: BTreeMap<String, PolicyDefinition>) -> Self { Self { policies } } } /// The definition of a policy document. #[derive(Clone, Debug, Serialize)] pub struct PolicyDefinition { /// The version of this policy document. pub version: String, /// Map from language codes to details of the document in that language. /// /// Language codes SHOULD be formatted as per Section 2.2 of RFC 5646, though some /// implementations may use an underscore instead of dash (for example, en_US instead of /// en-US). #[serde(flatten)] pub translations: BTreeMap<String, PolicyTranslation>, } impl PolicyDefinition { /// Construct a new `PolicyDefinition` with the given version and translations. pub fn new(version: String, translations: BTreeMap<String, PolicyTranslation>) -> Self { Self { version, translations } } } /// Details about a translation of a policy document. #[derive(Clone, Debug, Deserialize, Serialize)] pub struct PolicyTranslation { /// The name of this document, in the appropriate language. pub name: String, /// A link to the text of this document, in the appropriate language. /// /// MUST be a valid URI with scheme `https://` or `http://`. Insecure HTTP is discouraged.. pub url: String, } impl PolicyTranslation { /// Construct a new `PolicyTranslation` with the given name and URL. pub fn new(name: String, url: String) -> Self { Self { name, url } } } /// Parameters for an [OAuth 2.0-based] UIAA flow. /// /// [OAuth 2.0-based]: https://spec.matrix.org/latest/client-server-api/#oauth-authentication #[derive(Clone, Debug, Deserialize, Serialize)] pub struct OAuthParams { /// A URL pointing to the homeserver’s OAuth 2.0 account management web UI where the user can /// approve the action. /// /// Must be a valid URI with scheme `http://` or `https://`, the latter being recommended. pub url: String, } impl OAuthParams { /// Construct an `OAuthParams` with the given URL. pub fn new(url: String) -> Self { Self { url } } } #[cfg(test)] mod tests { use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; use super::{LoginTermsParams, PolicyDefinition, PolicyTranslation}; #[test] fn serialize_login_terms_params() { let privacy_definition = PolicyDefinition::new( "1".to_owned(), [ ( "en-US".to_owned(), PolicyTranslation::new( "Privacy Policy".to_owned(), "http://matrix.local/en-US/privacy".to_owned(), ), ), ( "fr-FR".to_owned(), PolicyTranslation::new( "Politique de confidentialité".to_owned(), "http://matrix.local/fr-FR/privacy".to_owned(), ), ), ] .into(), ); let params = LoginTermsParams::new([("privacy".to_owned(), privacy_definition)].into()); assert_eq!( to_json_value(&params).unwrap(), json!({ "policies": { "privacy": { "en-US": { "name": "Privacy Policy", "url": "http://matrix.local/en-US/privacy", }, "fr-FR": { "name": "Politique de confidentialité", "url": "http://matrix.local/fr-FR/privacy", }, "version": "1", }, }, }) ); } #[test] fn deserialize_login_terms_params() { // Missing version field in policy. let json = json!({ "policies": { "privacy": { "en-US": { "name": "Privacy Policy", "url": "http://matrix.local/en-US/privacy", }, "fr-FR": { "name": "Politique de confidentialité", "url": "http://matrix.local/fr-FR/privacy", }, }, }, }); from_json_value::<LoginTermsParams>(json).unwrap_err(); // Valid params. let json = json!({ "policies": { "privacy_policy": { "en": { "name": "Privacy Policy", "url": "https://example.org/somewhere/privacy-1.2-en.html" }, "fr": { "name": "Politique de confidentialité", "url": "https://example.org/somewhere/privacy-1.2-fr.html" }, // Unsupported field will be ignored. "foo": "bar", "version": "1.2", }, // No translations is fine. "terms_of_service": { "version": "1.2", } } }); let params = from_json_value::<LoginTermsParams>(json).unwrap(); assert_eq!(params.policies.len(), 2); let policy = params.policies.get("privacy_policy").unwrap(); assert_eq!(policy.version, "1.2"); assert_eq!(policy.translations.len(), 2); let translation = policy.translations.get("en").unwrap(); assert_eq!(translation.name, "Privacy Policy"); assert_eq!(translation.url, "https://example.org/somewhere/privacy-1.2-en.html"); let translation = policy.translations.get("fr").unwrap(); assert_eq!(translation.name, "Politique de confidentialité"); assert_eq!(translation.url, "https://example.org/somewhere/privacy-1.2-fr.html"); let policy = params.policies.get("terms_of_service").unwrap(); assert_eq!(policy.version, "1.2"); assert_eq!(policy.translations.len(), 0); } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/uiaa/auth_params/params_serde.rs
crates/core/src/client/uiaa/auth_params/params_serde.rs
//! Custom Serialize / Deserialize implementations for the authentication parameters types. use std::{collections::BTreeMap, fmt}; use serde::{ Deserialize, Deserializer, de::{self, Error}, }; use super::{PolicyDefinition, PolicyTranslation}; // Custom implementation because the translations are at the root of the object, but we want to // ignore fields whose value fails to deserialize because they might be custom fields. impl<'de> Deserialize<'de> for PolicyDefinition { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct PolicyDefinitionVisitor; impl<'de> de::Visitor<'de> for PolicyDefinitionVisitor { type Value = PolicyDefinition; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("PolicyDefinition") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: de::MapAccess<'de>, { let mut version = None; let mut translations = BTreeMap::new(); while let Some(key) = map.next_key::<String>()? { if key == "version" { if version.is_some() { return Err(A::Error::duplicate_field("version")); } version = Some(map.next_value()?); continue; } if let Ok(translation) = map.next_value::<PolicyTranslation>() { if translations.contains_key(&key) { return Err(A::Error::custom(format!("duplicate field `{key}`"))); } translations.insert(key, translation); } } Ok(PolicyDefinition { version: version.ok_or_else(|| A::Error::missing_field("version"))?, translations, }) } } deserializer.deserialize_map(PolicyDefinitionVisitor) } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/uiaa/auth_data/data_serde.rs
crates/core/src/client/uiaa/auth_data/data_serde.rs
//! Custom Serialize / Deserialize implementations for the authentication data types. use std::borrow::Cow; use crate::{serde::from_raw_json_value, third_party::Medium}; use serde::{Deserialize, Deserializer, Serialize, de, ser::SerializeStruct}; use serde_json::value::RawValue as RawJsonValue; use super::{AuthData, CustomThirdPartyId, UserIdentifier}; impl<'de> Deserialize<'de> for AuthData { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let json = Box::<RawJsonValue>::deserialize(deserializer)?; #[derive(Deserialize)] struct ExtractType<'a> { #[serde(borrow, rename = "type")] auth_type: Option<Cow<'a, str>>, } let auth_type = serde_json::from_str::<ExtractType<'_>>(json.get()) .map_err(de::Error::custom)? .auth_type; match auth_type.as_deref() { Some("m.login.password") => from_raw_json_value(&json).map(Self::Password), Some("m.login.recaptcha") => from_raw_json_value(&json).map(Self::ReCaptcha), Some("m.login.email.identity") => from_raw_json_value(&json).map(Self::EmailIdentity), Some("m.login.msisdn") => from_raw_json_value(&json).map(Self::Msisdn), Some("m.login.dummy") => from_raw_json_value(&json).map(Self::Dummy), Some("m.login.registration_token") => { from_raw_json_value(&json).map(Self::RegistrationToken) } Some("m.login.terms") => from_raw_json_value(&json).map(Self::Terms), Some("m.oauth" | "org.matrix.cross_signing_reset") => { from_raw_json_value(&json).map(Self::OAuth) } None => from_raw_json_value(&json).map(Self::FallbackAcknowledgement), Some(_) => from_raw_json_value(&json).map(Self::_Custom), } } } impl Serialize for UserIdentifier { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { let mut id; match self { Self::UserIdOrLocalpart(user) => { id = serializer.serialize_struct("UserIdentifier", 2)?; id.serialize_field("type", "m.id.user")?; id.serialize_field("user", user)?; } Self::PhoneNumber { country, phone } => { id = serializer.serialize_struct("UserIdentifier", 3)?; id.serialize_field("type", "m.id.phone")?; id.serialize_field("country", country)?; id.serialize_field("phone", phone)?; } Self::Email { address } => { id = serializer.serialize_struct("UserIdentifier", 3)?; id.serialize_field("type", "m.id.thirdparty")?; id.serialize_field("medium", &Medium::Email)?; id.serialize_field("address", address)?; } Self::Msisdn { number } => { id = serializer.serialize_struct("UserIdentifier", 3)?; id.serialize_field("type", "m.id.thirdparty")?; id.serialize_field("medium", &Medium::Msisdn)?; id.serialize_field("address", number)?; } Self::_CustomThirdParty(CustomThirdPartyId { medium, address }) => { id = serializer.serialize_struct("UserIdentifier", 3)?; id.serialize_field("type", "m.id.thirdparty")?; id.serialize_field("medium", &medium)?; id.serialize_field("address", address)?; } } id.end() } } impl<'de> Deserialize<'de> for UserIdentifier { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let json = Box::<RawJsonValue>::deserialize(deserializer)?; #[derive(Deserialize)] #[serde(tag = "type")] enum ExtractType { #[serde(rename = "m.id.user")] User, #[serde(rename = "m.id.phone")] Phone, #[serde(rename = "m.id.thirdparty")] ThirdParty, } #[derive(Deserialize)] struct UserIdOrLocalpart { user: String, } #[derive(Deserialize)] struct ThirdPartyId { medium: Medium, address: String, } #[derive(Deserialize)] struct PhoneNumber { country: String, phone: String, } let id_type = serde_json::from_str::<ExtractType>(json.get()).map_err(de::Error::custom)?; match id_type { ExtractType::User => from_raw_json_value(&json) .map(|user_id: UserIdOrLocalpart| Self::UserIdOrLocalpart(user_id.user)), ExtractType::Phone => from_raw_json_value(&json) .map(|nb: PhoneNumber| Self::PhoneNumber { country: nb.country, phone: nb.phone }), ExtractType::ThirdParty => { let ThirdPartyId { medium, address } = from_raw_json_value(&json)?; match medium { Medium::Email => Ok(Self::Email { address }), Medium::Msisdn => Ok(Self::Msisdn { number: address }), _ => Ok(Self::_CustomThirdParty(CustomThirdPartyId { medium, address })), } } } } } // #[cfg(test)] // mod tests { // use assert_matches2::assert_matches; // use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; // use crate::uiaa::UserIdentifier; // #[test] // fn serialize() { // assert_eq!( // to_json_value(UserIdentifier::UserIdOrLocalpart("@user:notareal.hs".to_owned())) // .unwrap(), // json!({ // "type": "m.id.user", // "user": "@user:notareal.hs", // }) // ); // assert_eq!( // to_json_value(UserIdentifier::PhoneNumber { // country: "33".to_owned(), // phone: "0102030405".to_owned() // }) // .unwrap(), // json!({ // "type": "m.id.phone", // "country": "33", // "phone": "0102030405", // }) // ); // assert_eq!( // to_json_value(UserIdentifier::Email { address: "me@myprovider.net".to_owned() }) // .unwrap(), // json!({ // "type": "m.id.thirdparty", // "medium": "email", // "address": "me@myprovider.net", // }) // ); // assert_eq!( // to_json_value(UserIdentifier::Msisdn { number: "330102030405".to_owned() }).unwrap(), // json!({ // "type": "m.id.thirdparty", // "medium": "msisdn", // "address": "330102030405", // }) // ); // assert_eq!( // to_json_value(UserIdentifier::third_party_id("robot".into(), "01001110".to_owned())) // .unwrap(), // json!({ // "type": "m.id.thirdparty", // "medium": "robot", // "address": "01001110", // }) // ); // } // #[test] // fn deserialize() { // let json = json!({ // "type": "m.id.user", // "user": "@user:notareal.hs", // }); // assert_matches!(from_json_value(json), Ok(UserIdentifier::UserIdOrLocalpart(user))); // assert_eq!(user, "@user:notareal.hs"); // let json = json!({ // "type": "m.id.phone", // "country": "33", // "phone": "0102030405", // }); // assert_matches!(from_json_value(json), Ok(UserIdentifier::PhoneNumber { country, phone })); // assert_eq!(country, "33"); // assert_eq!(phone, "0102030405"); // let json = json!({ // "type": "m.id.thirdparty", // "medium": "email", // "address": "me@myprovider.net", // }); // assert_matches!(from_json_value(json), Ok(UserIdentifier::Email { address })); // assert_eq!(address, "me@myprovider.net"); // let json = json!({ // "type": "m.id.thirdparty", // "medium": "msisdn", // "address": "330102030405", // }); // assert_matches!(from_json_value(json), Ok(UserIdentifier::Msisdn { number })); // assert_eq!(number, "330102030405"); // let json = json!({ // "type": "m.id.thirdparty", // "medium": "robot", // "address": "01110010", // }); // let id = from_json_value::<UserIdentifier>(json).unwrap(); // let (medium, address) = id.as_third_party_id().unwrap(); // assert_eq!(medium.as_str(), "robot"); // assert_eq!(address, "01110010"); // } // }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/tests/headers.rs
crates/core/src/client/tests/headers.rs
#![cfg(feature = "client")] use http::HeaderMap; use palpo_core::client::discovery::homeserver; use crate::api::{MatrixVersion, OutgoingRequest as _, SendAccessToken}; #[test] fn get_request_headers() { let req: http::Request<Vec<u8>> = discover_homeserver::Request::new() .try_into_http_request( "https://homeserver.tld", SendAccessToken::None, &[MatrixVersion::V1_1], ) .unwrap(); assert_eq!(*req.headers(), HeaderMap::default()); }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/tests/uiaa.rs
crates/core/src/client/tests/uiaa.rs
use assert_matches2::assert_matches; use assign::assign; use palpo_core::client::{ error::ErrorKind, uiaa::{self, AuthData, AuthFlow, AuthType, UiaaInfo, , UserIdentifier}, }; crateapi::{EndpointError, OutgoingResponse}; use serde_json::{ from_slice as from_json_slice, from_str as from_json_str, from_value as from_json_value, json, to_value as to_json_value, value::to_raw_value as to_raw_json_value, Value as JsonValue, }; #[test] fn deserialize_user_identifier() { assert_matches!( from_json_value(json!({ "type": "m.id.user", "user": "cheeky_monkey" })) .unwrap(), UserIdentifier::UserIdOrLocalpart(id) ); assert_eq!(id, "cheeky_monkey"); } #[test] fn serialize_auth_data_registration_token() { let auth_data = AuthData::RegistrationToken(assign!(uiaa::RegistrationToken::new("mytoken".to_owned()), { session: Some("session".to_owned()), })); assert_eq!( to_json_value(auth_data).unwrap(), json!({ "type": "m.login.registration_token", "token": "mytoken", "session": "session", }) ); } #[test] fn deserialize_auth_data_registration_token() { let json = json!({ "type": "m.login.registration_token", "token": "mytoken", "session": "session", }); assert_matches!(from_json_value(json), Ok(AuthData::RegistrationToken(data))); assert_eq!(data.token, "mytoken"); assert_eq!(data.session.as_deref(), Some("session")); } #[test] fn serialize_auth_data_fallback() { let auth_data = AuthData::FallbackAcknowledgement(uiaa::FallbackAcknowledgement::new("ZXY000".to_owned())); assert_eq!(json!({ "session": "ZXY000" }), to_json_value(auth_data).unwrap()); } #[test] fn deserialize_auth_data_fallback() { let json = json!({ "session": "opaque_session_id" }); assert_matches!(from_json_value(json).unwrap(), AuthData::FallbackAcknowledgement(data)); assert_eq!(data.session, "opaque_session_id"); } #[test] fn serialize_uiaa_info() { let flows = vec![AuthFlow::new(vec!["m.login.password".into(), "m.login.dummy".into()])]; let params = to_raw_json_value(&json!({ "example.type.baz": { "example_key": "foobar" } })) .unwrap(); let uiaa_info = assign!(UiaaInfo::new(flows, params), { completed: vec!["m.login.password".into()], }); let json = json!({ "flows": [{ "stages": ["m.login.password", "m.login.dummy"] }], "completed": ["m.login.password"], "params": { "example.type.baz": { "example_key": "foobar" } } }); assert_eq!(to_json_value(uiaa_info).unwrap(), json); } #[test] fn deserialize_uiaa_info() { let json = json!({ "errcode": "M_FORBIDDEN", "error": "Invalid password", "completed": ["m.login.recaptcha"], "flows": [ { "stages": ["m.login.password"] }, { "stages": ["m.login.email.identity", "m.login.msisdn"] } ], "params": { "example.type.baz": { "example_key": "foobar" } }, "session": "xxxxxx" }); let info = from_json_value::<UiaaInfo>(json).unwrap(); assert_eq!(info.completed, vec![AuthType::ReCaptcha]); assert_eq!(info.flows.len(), 2); assert_eq!(info.flows[0].stages, vec![AuthType::Password]); assert_eq!(info.flows[1].stages, vec![AuthType::EmailIdentity, AuthType::Msisdn]); assert_eq!(info.session.as_deref(), Some("xxxxxx")); let auth_error = info.auth_error.unwrap(); assert_eq!(auth_error.kind, ErrorKind::Forbidden); assert_eq!(auth_error.message, "Invalid password"); assert_eq!( from_json_str::<JsonValue>(info.params.get()).unwrap(), json!({ "example.type.baz": { "example_key": "foobar" } }) ); } #[test] fn try_uiaa_response_into_http_response() { let flows = vec![AuthFlow::new(vec![AuthType::Password, AuthType::Dummy])]; let params = to_raw_json_value(&json!({ "example.type.baz": { "example_key": "foobar" } })) .unwrap(); let uiaa_info = assign!(UiaaInfo::new(flows, params), { completed: vec![AuthType::ReCaptcha], }); let uiaa_response = ::AuthResponse(uiaa_info).try_into_http_response::<Vec<u8>>().unwrap(); let info = from_json_slice::<UiaaInfo>(uiaa_response.body()).unwrap(); assert_eq!(info.flows.len(), 1); assert_eq!(info.flows[0].stages, vec![AuthType::Password, AuthType::Dummy]); assert_eq!(info.completed, vec![AuthType::ReCaptcha]); assert_eq!(info.session, None); assert_matches!(info.auth_error, None); assert_eq!( from_json_str::<JsonValue>(info.params.get()).unwrap(), json!({ "example.type.baz": { "example_key": "foobar" } }) ); assert_eq!(uiaa_response.status(), http::status::StatusCode::UNAUTHORIZED); } #[test] fn try_uiaa_response_from_http_response() { let json = serde_json::to_string(&json!({ "errcode": "M_FORBIDDEN", "error": "Invalid password", "completed": ["m.login.recaptcha"], "flows": [ { "stages": ["m.login.password"] }, { "stages": ["m.login.email.identity", "m.login.msisdn"] } ], "params": { "example.type.baz": { "example_key": "foobar" } }, "session": "xxxxxx" })) .unwrap(); let http_response = http::Response::builder() .status(http::StatusCode::UNAUTHORIZED) .body(json.as_bytes()) .unwrap(); assert_matches!( ::from_http_response(http_response), ::AuthResponse(info) ); assert_eq!(info.completed, vec![AuthType::ReCaptcha]); assert_eq!(info.flows.len(), 2); assert_eq!(info.flows[0].stages, vec![AuthType::Password]); assert_eq!(info.flows[1].stages, vec![AuthType::EmailIdentity, AuthType::Msisdn]); assert_eq!(info.session.as_deref(), Some("xxxxxx")); let auth_error = info.auth_error.unwrap(); assert_eq!(auth_error.kind, ErrorKind::Forbidden); assert_eq!(auth_error.message, "Invalid password"); assert_eq!( from_json_str::<JsonValue>(info.params.get()).unwrap(), json!({ "example.type.baz": { "example_key": "foobar" } }) ); }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/voip/get_turn_server_info.rs
crates/core/src/client/voip/get_turn_server_info.rs
//! `GET /_matrix/client/*/voip/turnServer` //! //! Get credentials for the client to use when initiating VoIP calls. pub mod v3 { //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3voipturnserver use std::time::Duration; use crate::{ api::{auth_scheme::AccessToken, request, response}, metadata, }; metadata! { method: GET, rate_limited: true, authentication: AccessToken, history: { 1.0 => "/_matrix/client/r0/voip/turnServer", 1.1 => "/_matrix/client/v3/voip/turnServer", } } /// Request type for the `turn_server_info` endpoint. #[request(error = crate::Error)] #[derive(Default)] pub struct Request {} /// Response type for the `turn_server_info` endpoint. #[response(error = crate::Error)] pub struct Response { /// The username to use. pub username: String, /// The password to use. pub password: String, /// A list of TURN URIs. pub uris: Vec<String>, /// The time-to-live in seconds. #[serde(with = "crate::serde::duration::secs")] pub ttl: Duration, } impl Request { /// Creates an empty `Request`. pub fn new() -> Self { Self {} } } impl Response { /// Creates a new `Response` with the given username, password, TURN URIs and time-to-live. pub fn new(username: String, password: String, uris: Vec<String>, ttl: Duration) -> Self { Self { username, password, uris, ttl } } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/account/threepid.rs
crates/core/src/client/account/threepid.rs
//! `POST /_matrix/client/*/account/3pid/add` //! //! Add contact information to a user's account //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3account3pidadd use salvo::prelude::*; use serde::{Deserialize, Serialize}; // 1.0 => "/_matrix/client/r0/account/3pid/add", // 1.1 => "/_matrix/client/v3/account/3pid/add", // 1.0 => "/_matrix/client/r0/account/3pid/bind", // 1.1 => "/_matrix/client/v3/account/3pid/bind", use crate::client::account::IdentityServerInfo; use crate::{ OwnedClientSecret, OwnedSessionId, client::{account::ThirdPartyIdRemovalStatus, uiaa::AuthData}, third_party::{Medium, ThirdPartyIdentifier}, }; #[derive(ToSchema, Serialize, Debug)] pub struct ThreepidsResBody { /// A list of third party identifiers the homeserver has associated with the /// user's account. /// /// If the `compat-get-3pids` feature is enabled, this field will always be /// serialized, even if its value is an empty list. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub three_pids: Vec<ThirdPartyIdentifier>, } impl ThreepidsResBody { pub fn new(three_pids: Vec<ThirdPartyIdentifier>) -> Self { Self { three_pids } } } /// Request type for the `add_3pid` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct AddThreepidReqBody { /// Additional information for the User-Interactive Authentication API. #[serde(default, skip_serializing_if = "Option::is_none")] pub auth: Option<AuthData>, /// Client-generated secret string used to protect this session. pub client_secret: OwnedClientSecret, /// The session identifier given by the identity server. pub sid: OwnedSessionId, } /// Request type for the `bind_3pid` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct BindThreepidReqBody { /// Client-generated secret string used to protect this session. pub client_secret: OwnedClientSecret, /// The ID server to send the onward request to as a hostname with an /// appended colon and port number if the port is not the default. #[serde(flatten)] pub identity_server_info: IdentityServerInfo, /// The session identifier given by the identity server. pub sid: OwnedSessionId, } /// Request type for the `bind_3pid` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct UnbindThreepidReqBody { /// Identity server to unbind from. #[serde(default, skip_serializing_if = "Option::is_none")] pub id_server: Option<String>, /// Medium of the 3PID to be removed. pub medium: Medium, /// Third-party address being removed. pub address: String, } #[derive(ToSchema, Serialize, Debug)] pub struct UnbindThreepidResBody { /// Result of unbind operation. pub id_server_unbind_result: ThirdPartyIdRemovalStatus, } /// Request type for the `bind_3pid` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct DeleteThreepidReqBody { /// Identity server to delete from. #[serde(default, skip_serializing_if = "Option::is_none")] pub id_server: Option<String>, /// Medium of the 3PID to be removed. pub medium: Medium, /// Third-party address being removed. pub address: String, } #[derive(ToSchema, Serialize, Debug)] pub struct DeleteThreepidResBody { /// Result of unbind operation. pub id_server_unbind_result: ThirdPartyIdRemovalStatus, } // /// `POST /_matrix/client/*/account/3pid/email/requestToken` // /// // /// Request a 3PID management token with a 3rd party email. // /// `/v3/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3account3pidemailrequesttoken // const METADATA: Metadata = metadata! { // method: POST, // rate_limited: false, // authentication: None, // history: { // 1.0 => "/_matrix/client/r0/account/3pid/email/requestToken", // 1.1 => "/_matrix/client/v3/account/3pid/email/requestToken", // } // }; /// Request type for the `request_3pid_management_token_via_email` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct TokenViaEmailReqBody { /// Client-generated secret string used to protect this session. pub client_secret: OwnedClientSecret, /// The email address. pub email: String, /// Used to distinguish protocol level retries from requests to re-send the /// email. pub send_attempt: u64, /// Return URL for identity server to redirect the client back to. #[serde(default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } /// Response type for the `request_3pid_management_token_via_email` endpoint. #[derive(ToSchema, Serialize, Debug)] pub struct TokenViaEmailResBody { /// The session identifier given by the identity server. pub sid: OwnedSessionId, /// URL to submit validation token to. /// /// If omitted, verification happens without client. #[serde( skip_serializing_if = "Option::is_none", default, deserialize_with = "crate::serde::empty_string_as_none" )] pub submit_url: Option<String>, } // /// `POST /_matrix/client/*/account/3pid/msisdn/requestToken` // /// // /// Request a 3PID management token with a phone number. // /// `/v3/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3account3pidmsisdnrequesttoken // const METADATA: Metadata = metadata! { // method: POST, // rate_limited: false, // authentication: None, // history: { // 1.0 => "/_matrix/client/r0/account/3pid/msisdn/requestToken", // 1.1 => "/_matrix/client/v3/account/3pid/msisdn/requestToken", // } // }; /// Request type for the `request_3pid_management_token_via_msisdn` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct TokenViaMsisdnReqBody { /// Client-generated secret string used to protect this session. pub client_secret: OwnedClientSecret, /// Two-letter ISO 3166 country code for the phone number. pub country: String, /// Phone number to validate. pub phone_number: String, /// Used to distinguish protocol level retries from requests to re-send the /// SMS. pub send_attempt: u64, /// Return URL for identity server to redirect the client back to. #[serde(default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } /// Response type for the `request_3pid_management_token_via_msisdn` endpoint. #[derive(ToSchema, Serialize, Debug)] pub struct TokenViaMsisdnResBody { /// The session identifier given by the identity server. pub sid: OwnedSessionId, /// URL to submit validation token to. /// /// If omitted, verification happens without client. #[serde( skip_serializing_if = "Option::is_none", default, deserialize_with = "crate::serde::empty_string_as_none" )] pub submit_url: Option<String>, }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/account/data.rs
crates/core/src/client/account/data.rs
use salvo::oapi::ToSchema; use serde::{Deserialize, Serialize}; use crate::{ events::{AnyGlobalAccountDataEventContent, AnyRoomAccountDataEventContent}, serde::RawJson, }; /// Response type for the `get_global_account_data` endpoint. #[derive(ToSchema, Serialize, Debug)] pub struct GlobalAccountDataResBody( /// Account data content for the given type. /// /// Since the inner type of the `RawJson` does not implement `Deserialize`, /// you need to use `.deserialize_as::<T>()` or /// `.cast_ref::<T>().deserialize_with_type()` for event types with a /// variable suffix (like [`SecretStorageKeyEventContent`]) to /// deserialize it. /// /// [`SecretStorageKeyEventContent`]: palpo_core::events::secret_storage::key::SecretStorageKeyEventContent // #[salvo(schema(value_type = Object, additional_properties = true))] // #[serde(flatten)] pub RawJson<AnyGlobalAccountDataEventContent>, ); /// Response type for the `get_room_account_data` endpoint. #[derive(ToSchema, Serialize, Debug)] pub struct RoomAccountDataResBody( /// Account data content for the given type. /// /// Since the inner type of the `RawJson` does not implement `Deserialize`, /// you need to use `.deserialize_as::<T>()` or /// `.cast_ref::<T>().deserialize_with_type()` for event types with a /// variable suffix (like [`SecretStorageKeyEventContent`]) to /// deserialize it. /// /// [`SecretStorageKeyEventContent`]: palpo_core::events::secret_storage::key::SecretStorageKeyEventContent // #[salvo(schema(value_type = Object, additional_properties = true))] // #[serde(flatten)] pub RawJson<AnyRoomAccountDataEventContent>, ); /// `PUT /_matrix/client/*/user/{user_id}/account_data/{type}` /// /// Sets global account data. /// `/v3/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/client-server-api/#put_matrixclientv3useruser_idaccount_datatype // const METADATA: Metadata = metadata! { // method: PUT, // rate_limited: false, // authentication: AccessToken, // history: { // 1.0 => "/_matrix/client/r0/user/:user_id/account_data/:event_type", // 1.1 => "/_matrix/client/v3/user/:user_id/account_data/:event_type", // } // }; #[derive(ToSchema, Deserialize, Debug)] #[salvo(schema(value_type = Object))] pub struct SetGlobalAccountDataReqBody( /// Arbitrary JSON to store as config data. /// /// To create a `RawJsonValue`, use `serde_json::value::to_raw_value`. pub RawJson<AnyGlobalAccountDataEventContent>, ); /// Request type for the `set_room_account_data` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct SetRoomAccountDataReqBody { /// Arbitrary JSON to store as config data. /// /// To create a `RawJsonValue`, use `serde_json::value::to_raw_value`. #[salvo(schema(value_type = Object, additional_properties = true))] pub data: RawJson<AnyRoomAccountDataEventContent>, }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/profile/profile_field_serde.rs
crates/core/src/client/profile/profile_field_serde.rs
use std::{borrow::Cow, fmt, marker::PhantomData}; use serde::{Deserialize, Serialize, Serializer, de, ser::SerializeMap}; use super::{CustomProfileFieldValue, ProfileFieldName, ProfileFieldValue, StaticProfileField}; /// Helper type to deserialize any type that implements [`StaticProfileField`]. pub(super) struct StaticProfileFieldVisitor<F: StaticProfileField>(pub(super) PhantomData<F>); impl<'de, F: StaticProfileField> de::Visitor<'de> for StaticProfileFieldVisitor<F> { type Value = Option<F::Value>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { write!(formatter, "a map with optional key `{}` and value", F::NAME) } fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error> where V: de::MapAccess<'de>, { let mut found = false; while let Some(key) = map.next_key::<Cow<'_, str>>()? { if key == F::NAME { found = true; break; } } if !found { return Ok(None); } Ok(Some(map.next_value()?)) } } impl Serialize for CustomProfileFieldValue { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut map = serializer.serialize_map(Some(1))?; map.serialize_entry(&self.field, &self.value)?; map.end() } } /// Helper type to deserialize [`ProfileFieldValue`]. /// /// If the inner value is set, this will try to deserialize a map entry using this key, otherwise /// this will deserialize the first key-value pair encountered. pub(super) struct ProfileFieldValueVisitor(pub(super) Option<ProfileFieldName>); impl<'de> de::Visitor<'de> for ProfileFieldValueVisitor { type Value = Option<ProfileFieldValue>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("enum ProfileFieldValue") } fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error> where V: de::MapAccess<'de>, { let field = if let Some(field) = self.0 { let mut found = false; while let Some(key) = map.next_key::<ProfileFieldName>()? { if key == field { found = true; break; } } if !found { return Ok(None); } field } else { let Some(field) = map.next_key()? else { return Ok(None); }; field }; Ok(Some(match field { ProfileFieldName::AvatarUrl => ProfileFieldValue::AvatarUrl(map.next_value()?), ProfileFieldName::DisplayName => ProfileFieldValue::DisplayName(map.next_value()?), ProfileFieldName::TimeZone => ProfileFieldValue::TimeZone(map.next_value()?), ProfileFieldName::_Custom(field) => { ProfileFieldValue::_Custom(CustomProfileFieldValue { field: field.0.into(), value: map.next_value()?, }) } })) } } pub(super) fn deserialize_profile_field_value_option<'de, D>( deserializer: D, ) -> Result<Option<ProfileFieldValue>, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_map(ProfileFieldValueVisitor(None)) } impl<'de> Deserialize<'de> for ProfileFieldValue { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: de::Deserializer<'de>, { deserialize_profile_field_value_option(deserializer)? .ok_or_else(|| de::Error::invalid_length(0, &"at least one key-value pair")) } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/rtc/transports.rs
crates/core/src/client/rtc/transports.rs
//! `GET /_matrix/client/*/rtc/transports` //! //! Discover the RTC transports advertised by the homeserver. //! `/v1/` ([MSC]) //! //! [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/4143 use std::borrow::Cow; use salvo::oapi::ToSchema; use serde::{Deserialize, Serialize, de::DeserializeOwned}; use serde_json::Value as JsonValue; use crate::serde::JsonObject; // metadata! { // method: GET, // rate_limited: false, // authentication: AccessToken, // history: { // unstable => "/_matrix/client/unstable/org.matrix.msc4143/rtc/transports", // } // } // /// Request type for the `transports` endpoint. // #[request(error = crate::Error)] // #[derive(Default)] // pub struct Request {} // impl Request { // /// Creates a new empty `Request`. // pub fn new() -> Self { // Self {} // } // } /// Response type for the `transports` endpoint. #[derive(ToSchema, Serialize, Default)] pub struct RtcTransportsResBody { /// The RTC transports advertised by the homeserver. #[salvo(schema(value_type = Object, additional_properties = true))] pub rtc_transports: Vec<RtcTransport>, } impl RtcTransportsResBody { /// Creates a `Response` with the given RTC transports. pub fn new(rtc_transports: Vec<RtcTransport>) -> Self { Self { rtc_transports } } } /// A MatrixRTC transport. /// /// This type can hold arbitrary RTC transports. Their data can be accessed with /// [`transport_type()`](Self::transport_type) and [`data()`](Self::data()). #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] #[serde(tag = "type")] pub enum RtcTransport { /// A LiveKit multi-SFU transport. #[cfg(feature = "unstable-msc4195")] #[serde(rename = "livekit_multi_sfu")] LivekitMultiSfu(LivekitMultiSfuTransport), /// An unsupported transport. #[doc(hidden)] #[serde(untagged)] _Custom(CustomRtcTransport), } impl RtcTransport { /// A constructor to create a custom RTC transport. /// /// Prefer to use the public variants of `RtcTransport` where possible; this constructor is /// meant to be used for unsupported focus types only and does not allow setting arbitrary /// data for supported ones. /// /// # Errors /// /// Returns an error if the `transport_type` is known and deserialization of `data` to the /// corresponding `RtcTransport` variant fails. pub fn new(transport_type: String, data: JsonObject) -> serde_json::Result<Self> { fn deserialize_variant<T: DeserializeOwned>(obj: JsonObject) -> serde_json::Result<T> { serde_json::from_value(obj.into()) } Ok(match transport_type.as_str() { #[cfg(feature = "unstable-msc4195")] "livekit_multi_sfu" => Self::LivekitMultiSfu(deserialize_variant(data)?), _ => Self::_Custom(CustomRtcTransport { transport_type, data, }), }) } /// Returns a reference to the type of this RTC transport. pub fn transport_type(&self) -> &str { match self { #[cfg(feature = "unstable-msc4195")] Self::LivekitMultiSfu(_) => "livekit_multi_sfu", Self::_Custom(custom) => &custom.transport_type, } } /// Returns the associated data. /// /// The returned JSON object won't contain the `type` field, please use /// [`transport_type()`][Self::transport_type] to access that. /// /// Prefer to use the public variants of `RtcTransport` where possible; this method is meant /// to be used for custom focus types only. pub fn data(&self) -> Cow<'_, JsonObject> { fn serialize<T: Serialize>(object: &T) -> JsonObject { match serde_json::to_value(object).expect("rtc focus type serialization to succeed") { JsonValue::Object(object) => object, _ => panic!("rtc transports must serialize to JSON objects"), } } match self { #[cfg(feature = "unstable-msc4195")] Self::LivekitMultiSfu(info) => Cow::Owned(serialize(info)), Self::_Custom(info) => Cow::Borrowed(&info.data), } } } /// A LiveKit multi-SFU transport. #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] #[cfg(feature = "unstable-msc4195")] pub struct LivekitMultiSfuTransport { /// The URL for the LiveKit service. pub livekit_service_url: String, } #[cfg(feature = "unstable-msc4195")] impl LivekitMultiSfuTransport { /// Construct a new `LivekitMultiSfuTransport` with the given LiveKit service URL. pub fn new(livekit_service_url: String) -> Self { Self { livekit_service_url, } } } #[cfg(feature = "unstable-msc4195")] impl From<LivekitMultiSfuTransport> for RtcTransport { fn from(value: LivekitMultiSfuTransport) -> Self { Self::LivekitMultiSfu(value) } } #[cfg(feature = "unstable-msc4195")] impl From<LivekitMultiSfuTransport> for crate::client::discovery::homeserver::LiveKitRtcFocusInfo { fn from(value: LivekitMultiSfuTransport) -> Self { let LivekitMultiSfuTransport { livekit_service_url, } = value; Self { service_url: livekit_service_url, } } } #[cfg(feature = "unstable-msc4195")] impl From<crate::client::discovery::homeserver::LiveKitRtcFocusInfo> for LivekitMultiSfuTransport { fn from(value: crate::client::discovery::homeserver::LiveKitRtcFocusInfo) -> Self { let crate::client::discovery::homeserver::LiveKitRtcFocusInfo { service_url } = value; Self { livekit_service_url: service_url, } } } /// Information about an unsupported RTC transport. #[doc(hidden)] #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] pub struct CustomRtcTransport { /// The type of RTC transport. #[serde(rename = "type")] transport_type: String, /// Remaining data. #[serde(flatten)] data: JsonObject, } // #[cfg(test)] // mod tests { // use assert_matches2::assert_matches; // use serde_json::{ // Value as JsonValue, from_value as from_json_value, json, to_value as to_json_value, // }; // use super::v1::{LivekitMultiSfuTransport, RtcTransport}; // #[test] // fn serialize_roundtrip_custom_rtc_transport() { // let transport_type = "local.custom.transport"; // assert_matches!( // json!({ // "foo": "bar", // "baz": true, // }), // JsonValue::Object(transport_data) // ); // let transport = // RtcTransport::new(transport_type.to_owned(), transport_data.clone()).unwrap(); // let json = json!({ // "type": transport_type, // "foo": "bar", // "baz": true, // }); // assert_eq!(transport.transport_type(), transport_type); // assert_eq!(*transport.data().as_ref(), transport_data); // assert_eq!(to_json_value(&transport).unwrap(), json); // assert_eq!(from_json_value::<RtcTransport>(json).unwrap(), transport); // } // #[cfg(feature = "unstable-msc4195")] // #[test] // fn serialize_roundtrip_livekit_multi_sfu_transport() { // let transport_type = "livekit_multi_sfu"; // let livekit_service_url = "http://livekit.local/"; // let transport = RtcTransport::from(LivekitMultiSfuTransport::new( // livekit_service_url.to_owned(), // )); // let json = json!({ // "type": transport_type, // "livekit_service_url": livekit_service_url, // }); // assert_eq!(transport.transport_type(), transport_type); // assert_eq!(to_json_value(&transport).unwrap(), json); // assert_eq!(from_json_value::<RtcTransport>(json).unwrap(), transport); // } // }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/authenticated_media/get_content_as_filename.rs
crates/core/src/client/authenticated_media/get_content_as_filename.rs
//! `GET /_matrix/client/*/media/download/{serverName}/{mediaId}/{fileName}` //! //! Retrieve content from the media store, specifying a filename to return. pub mod v1 { //! `/v1/` ([spec]) //! //! [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv1mediadownloadservernamemediaidfilename use std::time::Duration; use http::header::{CONTENT_DISPOSITION, CONTENT_TYPE}; use crate::{ IdParseError, MxcUri, OwnedServerName, api::{auth_scheme::AccessToken, request, response}, http_headers::ContentDisposition, metadata, }; metadata! { method: GET, rate_limited: true, authentication: AccessToken, history: { unstable("org.matrix.msc3916") => "/_matrix/client/unstable/org.matrix.msc3916/media/download/{server_name}/{media_id}/{filename}", 1.11 | stable("org.matrix.msc3916.stable") => "/_matrix/client/v1/media/download/{server_name}/{media_id}/{filename}", } } /// Request type for the `get_media_content_as_filename` endpoint. #[request(error = crate::Error)] pub struct Request { /// The server name from the mxc:// URI (the authoritory component). #[palpo_api(path)] pub server_name: OwnedServerName, /// The media ID from the mxc:// URI (the path component). #[palpo_api(path)] pub media_id: String, /// The filename to return in the `Content-Disposition` header. #[palpo_api(path)] pub filename: String, /// The maximum duration that the client is willing to wait to start receiving data, in the /// case that the content has not yet been uploaded. /// /// The default value is 20 seconds. #[palpo_api(query)] #[serde( with = "crate::serde::duration::ms", default = "crate::media::default_download_timeout", skip_serializing_if = "crate::media::is_default_download_timeout" )] pub timeout_ms: Duration, } /// Response type for the `get_media_content_as_filename` endpoint. #[response(error = crate::Error)] pub struct Response { /// The content that was previously uploaded. #[palpo_api(raw_body)] pub file: Vec<u8>, /// The content type of the file that was previously uploaded. #[palpo_api(header = CONTENT_TYPE)] pub content_type: Option<String>, /// The value of the `Content-Disposition` HTTP header, possibly containing the name of the /// file that was previously uploaded. #[palpo_api(header = CONTENT_DISPOSITION)] pub content_disposition: Option<ContentDisposition>, } impl Request { /// Creates a new `Request` with the given media ID, server name and filename. pub fn new(media_id: String, server_name: OwnedServerName, filename: String) -> Self { Self { media_id, server_name, filename, timeout_ms: crate::media::default_download_timeout(), } } /// Creates a new `Request` with the given URI and filename. pub fn from_uri(uri: &MxcUri, filename: String) -> Result<Self, IdParseError> { let (server_name, media_id) = uri.parts()?; Ok(Self::new(media_id.to_owned(), server_name.to_owned(), filename)) } } impl Response { /// Creates a new `Response` with the given file. pub fn new( file: Vec<u8>, content_type: String, content_disposition: ContentDisposition, ) -> Self { Self { file, content_type: Some(content_type), content_disposition: Some(content_disposition), } } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/authenticated_media/get_content.rs
crates/core/src/client/authenticated_media/get_content.rs
//! `GET /_matrix/client/*/media/download/{serverName}/{mediaId}` //! //! Retrieve content from the media store. pub mod v1 { //! `/v1/` ([spec]) //! //! [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv1mediadownloadservernamemediaid use std::time::Duration; use http::header::{CONTENT_DISPOSITION, CONTENT_TYPE}; use crate::{ IdParseError, MxcUri, OwnedServerName, api::{auth_scheme::AccessToken, request, response}, http_headers::ContentDisposition, metadata, }; metadata! { method: GET, rate_limited: true, authentication: AccessToken, history: { unstable("org.matrix.msc3916") => "/_matrix/client/unstable/org.matrix.msc3916/media/download/{server_name}/{media_id}", 1.11 | stable("org.matrix.msc3916.stable") => "/_matrix/client/v1/media/download/{server_name}/{media_id}", } } /// Request type for the `get_media_content` endpoint. #[request(error = crate::Error)] pub struct Request { /// The server name from the mxc:// URI (the authoritory component). #[palpo_api(path)] pub server_name: OwnedServerName, /// The media ID from the mxc:// URI (the path component). #[palpo_api(path)] pub media_id: String, /// The maximum duration that the client is willing to wait to start receiving data, in the /// case that the content has not yet been uploaded. /// /// The default value is 20 seconds. #[palpo_api(query)] #[serde( with = "crate::serde::duration::ms", default = "crate::media::default_download_timeout", skip_serializing_if = "crate::media::is_default_download_timeout" )] pub timeout_ms: Duration, } /// Response type for the `get_media_content` endpoint. #[response(error = crate::Error)] pub struct Response { /// The content that was previously uploaded. #[palpo_api(raw_body)] pub file: Vec<u8>, /// The content type of the file that was previously uploaded. #[palpo_api(header = CONTENT_TYPE)] pub content_type: Option<String>, /// The value of the `Content-Disposition` HTTP header, possibly containing the name of the /// file that was previously uploaded. #[palpo_api(header = CONTENT_DISPOSITION)] pub content_disposition: Option<ContentDisposition>, } impl Request { /// Creates a new `Request` with the given media ID and server name. pub fn new(media_id: String, server_name: OwnedServerName) -> Self { Self { media_id, server_name, timeout_ms: crate::media::default_download_timeout(), } } /// Creates a new `Request` with the given URI. pub fn from_uri(uri: &MxcUri) -> Result<Self, IdParseError> { let (server_name, media_id) = uri.parts()?; Ok(Self::new(media_id.to_owned(), server_name.to_owned())) } } impl Response { /// Creates a new `Response` with the given file contents. pub fn new( file: Vec<u8>, content_type: String, content_disposition: ContentDisposition, ) -> Self { Self { file, content_type: Some(content_type), content_disposition: Some(content_disposition), } } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/authenticated_media/get_content_thumbnail.rs
crates/core/src/client/authenticated_media/get_content_thumbnail.rs
//! `GET /_matrix/client/*/media/thumbnail/{serverName}/{mediaId}` //! //! Get a thumbnail of content from the media store. //! `/v1/` ([spec]) //! //! [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv1mediathumbnailservernamemediaid use std::time::Duration; use http::header::{CONTENT_DISPOSITION, CONTENT_TYPE}; use crate::{ IdParseError, MxcUri, OwnedServerName, api::{auth_scheme::AccessToken, request, response}, http_headers::ContentDisposition, media::Method, metadata, }; // metadata! { // method: GET, // rate_limited: true, // authentication: AccessToken, // history: { // unstable("org.matrix.msc3916") => "/_matrix/client/unstable/org.matrix.msc3916/media/thumbnail/{server_name}/{media_id}", // 1.11 | stable("org.matrix.msc3916.stable") => "/_matrix/client/v1/media/thumbnail/{server_name}/{media_id}", // } // } /// Request type for the `get_content_thumbnail` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct GetMediaThumbnailArgs { /// The server name from the mxc:// URI (the authoritory component). #[salvo(parameter(parameter_in = Path))] pub server_name: OwnedServerName, /// The media ID from the mxc:// URI (the path component). #[salvo(parameter(parameter_in = Path))] pub media_id: String, /// The desired resizing method. #[salvo(parameter(parameter_in = Query))] #[serde(skip_serializing_if = "Option::is_none")] pub method: Option<Method>, /// The *desired* width of the thumbnail. /// /// The actual thumbnail may not match the size specified. #[palpo_api(query)] pub width: u32, /// The *desired* height of the thumbnail. /// /// The actual thumbnail may not match the size specified. #[salvo(parameter(parameter_in = Query))] pub height: u32, /// The maximum duration that the client is willing to wait to start receiving data, in the /// case that the content has not yet been uploaded. /// /// The default value is 20 seconds. #[salvo(parameter(parameter_in = Query))] #[serde( with = "crate::serde::duration::ms", default = "crate::media::default_download_timeout", skip_serializing_if = "crate::media::is_default_download_timeout" )] pub timeout_ms: Duration, /// Whether the server should return an animated thumbnail. /// /// When `Some(true)`, the server should return an animated thumbnail if possible and /// supported. When `Some(false)`, the server must not return an animated /// thumbnail. When `None`, the server should not return an animated thumbnail. #[salvo(parameter(parameter_in = Query))] #[serde(skip_serializing_if = "Option::is_none")] pub animated: Option<bool>, } // /// Response type for the `get_content_thumbnail` endpoint. // #[response(error = crate::Error)] // pub struct GetMediaThumbnailResBody { // /// A thumbnail of the requested content. // #[palpo_api(raw_body)] // pub file: Vec<u8>, // /// The content type of the thumbnail. // #[palpo_api(header = CONTENT_TYPE)] // pub content_type: Option<String>, // /// The value of the `Content-Disposition` HTTP header, possibly containing the name of the // /// file that was previously uploaded. // /// // /// See [MDN] for the syntax. // /// // /// [MDN]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#Syntax // #[palpo_api(header = CONTENT_DISPOSITION)] // pub content_disposition: Option<ContentDisposition>, // } impl GetMediaThumbnailArgs { /// Creates a new `GetMediaThumbnailArgs` with the given media ID, server name, desired thumbnail width /// and desired thumbnail height. pub fn new(media_id: String, server_name: OwnedServerName, width: u32, height: u32) -> Self { Self { media_id, server_name, method: None, width, height, timeout_ms: crate::media::default_download_timeout(), animated: None, } } /// Creates a new `Request` with the given URI, desired thumbnail width and /// desired thumbnail height. pub fn from_uri(uri: &MxcUri, width: UInt, height: UInt) -> Result<Self, IdParseError> { let (server_name, media_id) = uri.parts()?; Ok(Self::new( media_id.to_owned(), server_name.to_owned(), width, height, )) } } // impl Response { // /// Creates a new `Response` with the given thumbnail. // pub fn new( // file: Vec<u8>, // content_type: String, // content_disposition: ContentDisposition, // ) -> Self { // Self { // file, // content_type: Some(content_type), // content_disposition: Some(content_disposition), // } // } // }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/authenticated_media/get_media_config.rs
crates/core/src/client/authenticated_media/get_media_config.rs
//! `GET /_matrix/client/*/media/config` //! //! Gets the config for the media repository. //! `/v1/` ([spec]) //! //! [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv1mediaconfig use salvo::oapi::{ToParameters, ToSchema}; use serde::{Deserialize, Serialize}; use crate::auth_scheme::AccessToken; // metadata! { // method: GET, // rate_limited: true, // authentication: AccessToken, // history: { // unstable("org.matrix.msc3916") => "/_matrix/client/unstable/org.matrix.msc3916/media/config", // 1.11 | stable("org.matrix.msc3916.stable") => "/_matrix/client/v1/media/config", // } // } // /// Request type for the `get_media_config` endpoint. // #[request(error = crate::Error)] // #[derive(Default)] // pub struct Request {} /// Response type for the `get_media_config` endpoint. #[derive(ToSchema, Serialize, Debug)] pub struct MediaConfigResBody { /// Maximum size of upload in bytes. #[serde(rename = "m.upload.size")] pub upload_size: usize, } impl MediaConfigResBody { /// Creates a new `Response` with the given maximum upload size. pub fn new(upload_size: usize) -> Self { Self { upload_size } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/authenticated_media/get_media_preview.rs
crates/core/src/client/authenticated_media/get_media_preview.rs
//! `GET /_matrix/client/*/media/preview_url` //! //! Get a preview for a URL. pub mod v1 { //! `/v1/` ([spec]) //! //! [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv1mediapreview_url use crate::{ UnixMillis, api::{auth_scheme::AccessToken, request, response}, metadata, }; use serde::Serialize; use serde_json::value::{RawValue as RawJsonValue, to_raw_value as to_raw_json_value}; metadata! { method: GET, rate_limited: true, authentication: AccessToken, history: { unstable("org.matrix.msc3916") => "/_matrix/client/unstable/org.matrix.msc3916/media/preview_url", 1.11 | stable("org.matrix.msc3916.stable") => "/_matrix/client/v1/media/preview_url", } } /// Request type for the `get_media_preview` endpoint. #[request(error = crate::Error)] pub struct Request { /// URL to get a preview of. #[palpo_api(query)] pub url: String, /// Preferred point in time (in milliseconds) to return a preview for. #[palpo_api(query)] #[serde(skip_serializing_if = "Option::is_none")] pub ts: Option<UnixMillis>, } /// Response type for the `get_media_preview` endpoint. #[response(error = crate::Error)] #[derive(Default)] pub struct Response { /// OpenGraph-like data for the URL. /// /// Differences from OpenGraph: the image size in bytes is added to the `matrix:image:size` /// field, and `og:image` returns the MXC URI to the image, if any. #[palpo_api(body)] pub data: Option<Box<RawJsonValue>>, } impl Request { /// Creates a new `Request` with the given URL. pub fn new(url: String) -> Self { Self { url, ts: None } } } impl Response { /// Creates an empty `Response`. pub fn new() -> Self { Self { data: None } } /// Creates a new `Response` with the given OpenGraph data (in a /// `serde_json::value::RawValue`). pub fn from_raw_value(data: Box<RawJsonValue>) -> Self { Self { data: Some(data) } } /// Creates a new `Response` with the given OpenGraph data (in any kind of serializable /// object). pub fn from_serialize<T: Serialize>(data: &T) -> serde_json::Result<Self> { Ok(Self { data: Some(to_raw_json_value(data)?) }) } } #[cfg(test)] mod tests { use assert_matches2::assert_matches; use serde_json::{ from_value as from_json_value, json, value::{RawValue as RawJsonValue, to_raw_value as to_raw_json_value}, }; // Since BTreeMap<String, Box<RawJsonValue>> deserialization doesn't seem to // work, test that Option<RawJsonValue> works #[test] fn raw_json_deserialize() { type OptRawJson = Option<Box<RawJsonValue>>; assert_matches!(from_json_value::<OptRawJson>(json!(null)).unwrap(), None); from_json_value::<OptRawJson>(json!("test")).unwrap().unwrap(); from_json_value::<OptRawJson>(json!({ "a": "b" })).unwrap().unwrap(); } // For completeness sake, make sure serialization works too #[test] fn raw_json_serialize() { to_raw_json_value(&json!(null)).unwrap(); to_raw_json_value(&json!("string")).unwrap(); to_raw_json_value(&json!({})).unwrap(); to_raw_json_value(&json!({ "a": "b" })).unwrap(); } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/media/content.rs
crates/core/src/client/media/content.rs
/// `GET /_matrix/media/*/download/{serverName}/{mediaId}` /// /// Retrieve content from the media store. use std::time::Duration; use reqwest::Url; use salvo::prelude::*; use serde::{Deserialize, Serialize}; // use crate::http_headers::CROSS_ORIGIN_RESOURCE_POLICY; use crate::sending::{SendRequest, SendResult}; use crate::{OwnedMxcUri, OwnedServerName}; // /// `/v3/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixmediav3downloadservernamemediaid // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: None, // history: { // 1.0 => "/_matrix/media/r0/download/:server_name/:media_id", // 1.1 => "/_matrix/media/v3/download/:server_name/:media_id", // } // }; pub fn content_request(origin: &str, args: ContentReqArgs) -> SendResult<SendRequest> { let url = Url::parse(&format!( "{origin}/_matrix/client/v1/media/download/{}/{}?allow_remote={}&allow_redirect={}", args.server_name, args.media_id, args.allow_remote, args.allow_redirect ))?; Ok(crate::sending::get(url)) } /// Request type for the `get_media_content` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct ContentReqArgs { /// The server name from the mxc:// URI (the authoritory component). #[salvo(parameter(parameter_in = Path))] pub server_name: OwnedServerName, /// The media ID from the mxc:// URI (the path component). #[salvo(parameter(parameter_in = Path))] pub media_id: String, /// Whether to fetch media deemed remote. /// /// Used to prevent routing loops. Defaults to `true`. #[salvo(parameter(parameter_in = Query))] #[serde( default = "crate::serde::default_true", skip_serializing_if = "crate::serde::is_true" )] pub allow_remote: bool, /// The maximum duration that the client is willing to wait to start /// receiving data, in the case that the content has not yet been /// uploaded. /// /// The default value is 20 seconds. #[salvo(parameter(parameter_in = Query))] #[serde( with = "crate::serde::duration::ms", default = "crate::client::media::default_download_timeout", skip_serializing_if = "crate::client::media::is_default_download_timeout" )] pub timeout_ms: Duration, /// Whether the server may return a 307 or 308 redirect response that points /// at the relevant media content. /// /// Unless explicitly set to `true`, the server must return the media /// content itself. #[salvo(parameter(parameter_in = Query))] #[serde(default, skip_serializing_if = "crate::serde::is_default")] pub allow_redirect: bool, } #[derive(ToParameters, Deserialize, Debug)] pub struct ContentWithFileNameReqArgs { /// The server name from the mxc:// URI (the authoritory component). #[salvo(parameter(parameter_in = Path))] pub server_name: OwnedServerName, /// The media ID from the mxc:// URI (the path component). #[salvo(parameter(parameter_in = Path))] pub media_id: String, #[salvo(parameter(parameter_in = Path))] pub filename: String, /// Whether to fetch media deemed remote. /// /// Used to prevent routing loops. Defaults to `true`. #[salvo(parameter(parameter_in = Query))] #[serde( default = "crate::serde::default_true", skip_serializing_if = "crate::serde::is_true" )] pub allow_remote: bool, /// The maximum duration that the client is willing to wait to start /// receiving data, in the case that the content has not yet been /// uploaded. /// /// The default value is 20 seconds. #[salvo(parameter(parameter_in = Query))] #[serde( with = "crate::serde::duration::ms", default = "crate::client::media::default_download_timeout", skip_serializing_if = "crate::client::media::is_default_download_timeout" )] pub timeout_ms: Duration, /// Whether the server may return a 307 or 308 redirect response that points /// at the relevant media content. /// /// Unless explicitly set to `true`, the server must return the media /// content itself. #[salvo(parameter(parameter_in = Query))] #[serde(default, skip_serializing_if = "crate::serde::is_default")] pub allow_redirect: bool, } // /// Response type for the `get_media_content` endpoint. // #[derive(ToSchema, Serialize, Debug)] // pub struct Content { // /// The content that was previously uploaded. // pub data: Vec<u8>, // /// The content type of the file that was previously uploaded. // pub content_type: Option<String>, // /// The value of the `Content-Disposition` HTTP header, possibly // containing the name of the /// file that was previously uploaded. // /// // /// See [MDN] for the syntax. // /// // /// [MDN]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#Syntax // pub content_disposition: Option<String>, // /// The value of the `Cross-Origin-Resource-Policy` HTTP header. // /// // /// See [MDN] for the syntax. // /// // /// [MDN]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy#syntax // pub cross_origin_resource_policy: Option<String>, // } // impl Content { // /// Creates a new `Response` with the given file contents. // /// // /// The Cross-Origin Resource Policy defaults to `cross-origin`. // pub fn new(data: Vec<u8>) -> Self { // Self { // data, // content_type: None, // content_disposition: None, // cross_origin_resource_policy: Some("cross-origin".to_owned()), // } // } // } // impl Scribe for Content { // fn render(self, res: &mut Response) { // let Self { // data, // content_type, // content_disposition, // cross_origin_resource_policy, // } = self; // if let Some(content_type) = content_type { // res.add_header(CONTENT_TYPE, content_type, true); // } // if let Some(content_disposition) = content_disposition { // res.add_header(CONTENT_DISPOSITION, content_disposition, true); // } // if let Some(cross_origin_resource_policy) = // cross_origin_resource_policy { // res.add_header("cross-origin-resource-policy", cross_origin_resource_policy, // true); } // res.write_body(data); // } // } /// `POST /_matrix/media/*/upload` /// /// Upload content to the media store. /// `/v3/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/client-server-api/#post_matrixmediav3upload // const METADATA: Metadata = metadata! { // method: POST, // rate_limited: true, // authentication: AccessToken, // history: { // 1.0 => "/_matrix/media/r0/upload", // 1.1 => "/_matrix/media/v3/upload", // } // }; #[derive(ToParameters, Deserialize, Debug)] pub struct CreateContentReqArgs { /// The name of the file being uploaded. #[salvo(parameter(parameter_in = Query))] #[serde(default, skip_serializing_if = "Option::is_none")] pub filename: Option<String>, /// The content type of the file being uploaded. #[serde(rename = "content-type")] #[salvo(parameter(parameter_in = Header))] pub content_type: Option<String>, /// Should the server return a blurhash or not. /// /// This uses the unstable prefix in /// [MSC2448](https://github.com/matrix-org/matrix-spec-proposals/pull/2448). #[salvo(parameter(parameter_in = Query))] #[serde( default, skip_serializing_if = "crate::serde::is_default", rename = "xyz.amorgan.generate_blurhash" )] pub generate_blurhash: bool, } /// Response type for the `create_media_content` endpoint. #[derive(ToSchema, Serialize, Debug)] pub struct CreateContentResBody { /// The MXC URI for the uploaded content. pub content_uri: OwnedMxcUri, /// The [BlurHash](https://blurha.sh) for the uploaded content. /// /// This uses the unstable prefix in /// [MSC2448](https://github.com/matrix-org/matrix-spec-proposals/pull/2448). pub blurhash: Option<String>, } impl CreateContentResBody { /// Creates a new `Response` with the given MXC URI. pub fn new(content_uri: OwnedMxcUri) -> Self { Self { content_uri, blurhash: None, } } } // /// `PUT /_matrix/media/*/upload/{serverName}/{mediaId}` // /// // /// Upload media to an MXC URI that was created with create_mxc_uri. // /// `/v3/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/client-server-api/#put_matrixmediav3uploadservernamemediaid // const METADATA: Metadata = metadata! { // method: PUT, // rate_limited: true, // authentication: AccessToken, // history: { // unstable => "/_matrix/media/unstable/fi.mau.msc2246/upload/:server_name/:media_id", // 1.7 => "/_matrix/media/v3/upload/:server_name/:media_id", // } // }; /// Request type for the `create_content_async` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct UploadContentReqArgs { /// The server name from the mxc:// URI (the authoritory component). #[salvo(parameter(parameter_in = Path))] pub server_name: OwnedServerName, /// The media ID from the mxc:// URI (the path component). #[salvo(parameter(parameter_in = Path))] pub media_id: String, /// The file contents to upload. // #[palpo_api(raw_body)] // pub file: Vec<u8>, /// The content type of the file being uploaded. #[salvo(rename="content-type", parameter(parameter_in = Header))] pub content_type: Option<String>, /// The name of the file being uploaded. #[salvo(parameter(parameter_in = Query))] #[serde(skip_serializing_if = "Option::is_none")] pub filename: Option<String>, // TODO: How does this and msc2448 (blurhash) interact? } // /// `GET /_matrix/media/*/download/{serverName}/{mediaId}/{fileName}` // /// // /// Retrieve content from the media store, specifying a filename to return. // /// `/v3/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixmediav3downloadservernamemediaidfilename // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: None, // history: { // 1.0 => "/_matrix/media/r0/download/:server_name/:media_id/:filename", // 1.1 => "/_matrix/media/v3/download/:server_name/:media_id/:filename", // } // }; /// Request type for the `get_media_content_as_filename` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct ContentAsFileNameReqArgs { /// The server name from the mxc:// URI (the authoritory component). #[salvo(parameter(parameter_in = Path))] pub server_name: OwnedServerName, /// The media ID from the mxc:// URI (the path component). #[salvo(parameter(parameter_in = Path))] pub media_id: String, /// The filename to return in the `Content-Disposition` header. #[salvo(parameter(parameter_in = Path))] pub filename: String, /// Whether to fetch media deemed remote. /// /// Used to prevent routing loops. Defaults to `true`. #[salvo(parameter(parameter_in = Query))] #[serde( default = "crate::serde::default_true", skip_serializing_if = "crate::serde::is_true" )] pub allow_remote: bool, /// The maximum duration that the client is willing to wait to start /// receiving data, in the case that the content has not yet been /// uploaded. /// /// The default value is 20 seconds. #[salvo(parameter(parameter_in = Query))] #[serde( with = "crate::serde::duration::ms", default = "crate::client::media::default_download_timeout", skip_serializing_if = "crate::client::media::is_default_download_timeout" )] pub timeout_ms: Duration, /// Whether the server may return a 307 or 308 redirect response that points /// at the relevant media content. /// /// Unless explicitly set to `true`, the server must return the media /// content itself. #[salvo(parameter(parameter_in = Query))] #[serde(default, skip_serializing_if = "crate::serde::is_default")] pub allow_redirect: bool, } // /// Response type for the `get_media_content_as_filename` endpoint. // #[derive(ToSchema, Serialize, Debug)] // pub struct ContentAsFileNameResBody { // /// The content that was previously uploaded. // #[palpo_api(raw_body)] // pub file: Vec<u8>, // /// The content type of the file that was previously uploaded. // #[palpo_api(header = CONTENT_TYPE)] // pub content_type: Option<String>, // /// The value of the `Content-Disposition` HTTP header, possibly // containing the name of the /// file that was previously uploaded. // /// // /// See [MDN] for the syntax. // /// // /// [MDN]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#Syntax // #[palpo_api(header = CONTENT_DISPOSITION)] // pub content_disposition: Option<String>, // /// The value of the `Cross-Origin-Resource-Policy` HTTP header. // /// // /// See [MDN] for the syntax. // /// // /// [MDN]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy#syntax // #[palpo_api(header = CROSS_ORIGIN_RESOURCE_POLICY)] // pub cross_origin_resource_policy: Option<String>, // } // impl ContentAsFileNameResBody { // /// Creates a new `Response` with the given file. // /// // /// The Cross-Origin Resource Policy defaults to `cross-origin`. // pub fn new(file: Vec<u8>) -> Self { // Self { // file, // content_type: None, // content_disposition: None, // cross_origin_resource_policy: Some("cross-origin".to_owned()), // } // } // } // `GET /_matrix/media/*/thumbnail/{serverName}/{mediaId}` // // Get a thumbnail of content from the media store. // `/v3/` ([spec]) // // [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixmediav3thumbnailservernamemediaid // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: true, // authentication: None, // history: { // 1.0 => "/_matrix/media/r0/thumbnail/:server_name/:media_id", // 1.1 => "/_matrix/media/v3/thumbnail/:server_name/:media_id", // } // };
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/sync_events/v5.rs
crates/core/src/client/sync_events/v5.rs
//! `POST /_matrix/client/unstable/org.matrix.msc3575/sync` ([MSC]) //! //! Get all new events in a sliding window of rooms since the last sync or a //! given point in time. //! //! [MSC]: https://github.com/matrix-org/matrix-doc/blob/kegan/sync-v3/proposals/3575-sync.md use std::{ collections::{BTreeMap, BTreeSet}, time::Duration, }; use salvo::prelude::*; use serde::{Deserialize, Serialize, de::Error as _}; use super::UnreadNotificationsCount; use crate::device::DeviceLists; use crate::events::receipt::SyncReceiptEvent; use crate::events::typing::SyncTypingEvent; use crate::events::{AnyGlobalAccountDataEvent, AnyRoomAccountDataEvent, AnyToDeviceEvent}; use crate::{ OwnedMxcUri, Seqnum, directory::RoomTypeFilter, events::{AnyStrippedStateEvent, AnySyncStateEvent, AnySyncTimelineEvent, StateEventType}, identifiers::*, serde::{RawJson, deserialize_cow_str, duration::opt_ms}, state::TypeStateKey, }; #[derive(Copy, Clone, Debug)] pub struct SyncInfo<'a> { pub sender_id: &'a UserId, pub device_id: &'a DeviceId, pub since_sn: Seqnum, pub req_body: &'a SyncEventsReqBody, } pub type KnownRooms = BTreeMap<String, BTreeMap<OwnedRoomId, Seqnum>>; #[derive(Clone, Debug)] pub struct TodoRoom { pub required_state: BTreeSet<TypeStateKey>, pub timeline_limit: usize, pub room_since_sn: Seqnum, } impl TodoRoom { pub fn new( required_state: BTreeSet<TypeStateKey>, timeline_limit: usize, room_since_sn: Seqnum, ) -> Self { Self { required_state, timeline_limit, room_since_sn, } } } pub type TodoRooms = BTreeMap<OwnedRoomId, TodoRoom>; // const METADATA: Metadata = metadata! { // method: POST, // rate_limited: false, // authentication: AccessToken, // history: { // unstable => // "/_matrix/client/unstable/org.matrix.simplified_msc3575/sync", // 1.4 // => "/_matrix/client/v5/sync", } // }; #[derive(ToParameters, Deserialize, Debug)] pub struct SyncEventsReqArgs { /// A point in time to continue a sync from. /// /// Should be a token from the `pos` field of a previous `/sync` /// response. #[salvo(parameter(parameter_in = Query))] #[serde(default, skip_serializing_if = "Option::is_none")] pub pos: Option<String>, /// The maximum time to poll before responding to this request. #[salvo(parameter(parameter_in = Query))] #[serde(with = "opt_ms", default, skip_serializing_if = "Option::is_none")] pub timeout: Option<Duration>, } /// Request type for the `sync` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct SyncEventsReqBody { /// A unique string identifier for this connection to the server. /// /// Optional. If this is missing, only one sliding sync connection can be /// made to the server at any one time. Clients need to set this to /// allow more than one connection concurrently, so the server can /// distinguish between connections. This is NOT STICKY and must be /// provided with every request, if your client needs more than one /// concurrent connection. /// /// Limitation: it must not contain more than 16 chars, due to it being /// required with every request. #[serde(default, skip_serializing_if = "Option::is_none")] pub conn_id: Option<String>, /// Allows clients to know what request params reached the server, /// functionally similar to txn IDs on /send for events. #[serde(default, skip_serializing_if = "Option::is_none")] pub txn_id: Option<String>, /// The list configurations of rooms we are interested in mapped by /// name. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub lists: BTreeMap<String, ReqList>, /// Specific rooms and event types that we want to receive events from. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub room_subscriptions: BTreeMap<OwnedRoomId, RoomSubscription>, /// Specific rooms we no longer want to receive events from. #[serde(default, skip_serializing_if = "<[_]>::is_empty")] pub unsubscribe_rooms: Vec<OwnedRoomId>, /// Extensions API. #[serde(default, skip_serializing_if = "ExtensionsConfig::is_empty")] pub extensions: ExtensionsConfig, } /// Response type for the `sync` endpoint. #[derive(ToSchema, Serialize, Default, Debug)] pub struct SyncEventsResBody { /// Matches the `txn_id` sent by the request. Please see /// [`Request::txn_id`]. #[serde(default, skip_serializing_if = "Option::is_none")] pub txn_id: Option<String>, /// The token to supply in the `pos` param of the next `/sync` request. pub pos: String, /// Updates on the order of rooms, mapped by the names we asked for. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub lists: BTreeMap<String, SyncList>, /// The updates on rooms. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub rooms: BTreeMap<OwnedRoomId, SyncRoom>, /// Extensions API. #[serde(default, skip_serializing_if = "Extensions::is_empty")] pub extensions: Extensions, } impl SyncEventsResBody { /// Creates a new `Response` with the given pos. pub fn new(pos: String) -> Self { Self { pos, ..Default::default() } } pub fn is_empty(&self) -> bool { self.lists.is_empty() && (self.rooms.is_empty() || self.rooms.iter().all(|(_id, r)| { r.timeline.is_empty() && r.required_state.is_empty() && r.invite_state.is_none() })) && self.extensions.is_empty() && self.txn_id.is_none() } } /// A sliding sync response updates to joiend rooms (see /// [`super::Response::lists`]). #[derive(Clone, Debug, Default, Deserialize, Serialize)] pub struct SyncList { /// The total number of rooms found for this list. pub count: usize, } /// A sliding sync response updated room (see [`super::Response::rooms`]). #[derive(Clone, Debug, Default, Deserialize, Serialize)] pub struct SyncRoom { /// The name as calculated by the server. #[serde(skip_serializing_if = "Option::is_none")] pub name: Option<String>, /// The avatar. #[serde(default, skip_serializing_if = "Option::is_none")] pub avatar: Option<OwnedMxcUri>, /// Whether it is an initial response. #[serde(skip_serializing_if = "Option::is_none")] pub initial: Option<bool>, /// Whether it is a direct room. #[serde(skip_serializing_if = "Option::is_none")] pub is_dm: Option<bool>, /// If this is `Some(_)`, this is a not-yet-accepted invite containing /// the given stripped state events. #[serde(skip_serializing_if = "Option::is_none")] pub invite_state: Option<Vec<RawJson<AnyStrippedStateEvent>>>, /// Number of unread notifications. #[serde( flatten, default, skip_serializing_if = "UnreadNotificationsCount::is_empty" )] pub unread_notifications: UnreadNotificationsCount, /// Message-like events and live state events. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub timeline: Vec<RawJson<AnySyncTimelineEvent>>, /// State events as configured by the request. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub required_state: Vec<RawJson<AnySyncStateEvent>>, /// The `prev_batch` allowing you to paginate through the messages /// before the given ones. #[serde(skip_serializing_if = "Option::is_none")] pub prev_batch: Option<String>, /// True if the number of events returned was limited by the limit on /// the filter. #[serde(default, skip_serializing_if = "crate::serde::is_default")] pub limited: bool, /// The number of users with membership of `join`, including the /// client’s own user ID. #[serde(skip_serializing_if = "Option::is_none")] pub joined_count: Option<i64>, /// The number of users with membership of `invite`. #[serde(skip_serializing_if = "Option::is_none")] pub invited_count: Option<i64>, /// The number of timeline events which have just occurred and are not /// historical. #[serde(skip_serializing_if = "Option::is_none")] pub num_live: Option<i64>, /// The bump stamp of the room. /// /// It can be interpreted as a “recency stamp” or “streaming order /// index”. For example, consider `roomA` with `bump_stamp = 2`, `roomB` /// with `bump_stamp = 1` and `roomC` with `bump_stamp = 0`. If `roomC` /// receives an update, its `bump_stamp` will be 3. #[serde(skip_serializing_if = "Option::is_none")] pub bump_stamp: Option<i64>, /// Heroes of the room, if requested. #[serde(skip_serializing_if = "Option::is_none")] pub heroes: Option<Vec<SyncRoomHero>>, } /// Filter for a sliding sync list, set at request. /// /// All fields are applied with AND operators, hence if `is_dm` is `true` and /// `is_encrypted` is `true` then only encrypted DM rooms will be returned. The /// absence of fields implies no filter on that criteria: it does NOT imply /// `false`. /// /// Filters are considered _sticky_, meaning that the filter only has to be /// provided once and their parameters 'sticks' for future requests until a new /// filter overwrites them. #[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize)] pub struct ReqListFilters { /// Whether to return invited Rooms, only joined rooms or both. /// /// Flag which only returns rooms the user is currently invited to. If /// unset, both invited and joined rooms are returned. If false, no /// invited rooms are returned. If true, only invited rooms are /// returned. #[serde(default, skip_serializing_if = "Option::is_none")] pub is_invite: Option<bool>, /// Only list rooms that are not of these create-types, or all. /// /// Same as "room_types" but inverted. This can be used to filter out spaces /// from the room list. #[serde(default, skip_serializing_if = "<[_]>::is_empty")] pub not_room_types: Vec<RoomTypeFilter>, } /// Sliding Sync Request for each list. #[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize)] pub struct ReqList { /// The ranges of rooms we're interested in. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub ranges: Vec<(usize, usize)>, /// The details to be included per room #[serde(flatten)] pub room_details: RoomDetailsConfig, /// Request a stripped variant of membership events for the users used /// to calculate the room name. #[serde(skip_serializing_if = "Option::is_none")] pub include_heroes: Option<bool>, /// Filters to apply to the list before sorting. #[serde(skip_serializing_if = "Option::is_none")] pub filters: Option<ReqListFilters>, } /// Configuration for requesting room details. #[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize)] pub struct RoomDetailsConfig { /// Required state for each room returned. An array of event type and state /// key tuples. /// /// Note that elements of this array are NOT sticky so they must be /// specified in full when they are changed. Sticky. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub required_state: Vec<(StateEventType, String)>, /// The maximum number of timeline events to return per room. Sticky. pub timeline_limit: usize, } /// Configuration for old rooms to include #[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize)] pub struct IncludeOldRooms { /// Required state for each room returned. An array of event type and state /// key tuples. /// /// Note that elements of this array are NOT sticky so they must be /// specified in full when they are changed. Sticky. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub required_state: Vec<(StateEventType, String)>, /// The maximum number of timeline events to return per room. Sticky. #[serde(default, skip_serializing_if = "Option::is_none")] pub timeline_limit: Option<usize>, } /// Sliding sync request room subscription (see /// [`super::Request::room_subscriptions`]). #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct RoomSubscription { /// Required state for each returned room. An array of event type and /// state key tuples. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub required_state: Vec<(StateEventType, String)>, /// The maximum number of timeline events to return per room. pub timeline_limit: i64, /// Include the room heroes. #[serde(skip_serializing_if = "Option::is_none")] pub include_heroes: Option<bool>, } /// Single entry for a room-related read receipt configuration in /// [`Receipts`]. #[derive(Clone, Debug, PartialEq)] pub enum ReceiptsRoom { /// Get read receipts for all the subscribed rooms. AllSubscribed, /// Get read receipts for this particular room. Room(OwnedRoomId), } impl Serialize for ReceiptsRoom { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { match self { Self::AllSubscribed => serializer.serialize_str("*"), Self::Room(r) => r.serialize(serializer), } } } impl<'de> Deserialize<'de> for ReceiptsRoom { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::de::Deserializer<'de>, { match deserialize_cow_str(deserializer)?.as_ref() { "*" => Ok(Self::AllSubscribed), other => Ok(Self::Room( RoomId::parse(other).map_err(D::Error::custom)?.to_owned(), )), } } } /// A sliding sync room hero. #[derive(ToSchema, Clone, Debug, Deserialize, Serialize)] pub struct SyncRoomHero { /// The user ID of the hero. pub user_id: OwnedUserId, /// The name of the hero. #[serde(rename = "displayname", skip_serializing_if = "Option::is_none")] pub name: Option<String>, /// The avatar of the hero. #[serde(rename = "avatar_url", skip_serializing_if = "Option::is_none")] pub avatar: Option<OwnedMxcUri>, } impl SyncRoomHero { /// Creates a new `SyncRoomHero` with the given user id. pub fn new(user_id: OwnedUserId) -> Self { Self { user_id, name: None, avatar: None, } } } /// Sliding-Sync extension configuration. #[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize, PartialEq)] pub struct ExtensionsConfig { /// Request to devices messages with the given config. #[serde(default, skip_serializing_if = "ToDeviceConfig::is_empty")] pub to_device: ToDeviceConfig, /// Configure the end-to-end-encryption extension. #[serde(default, skip_serializing_if = "E2eeConfig::is_empty")] pub e2ee: E2eeConfig, /// Configure the account data extension. #[serde(default, skip_serializing_if = "AccountDataConfig::is_empty")] pub account_data: AccountDataConfig, /// Request to receipt information with the given config. #[serde(default, skip_serializing_if = "ReceiptsConfig::is_empty")] pub receipts: ReceiptsConfig, /// Request to typing information with the given config. #[serde(default)] pub typing: TypingConfig, /// Extensions may add further fields to the list. #[serde(flatten)] #[salvo(schema(value_type = Object, additional_properties = true))] other: BTreeMap<String, serde_json::Value>, } impl ExtensionsConfig { /// Whether all fields are empty or `None`. pub fn is_empty(&self) -> bool { self.to_device.is_empty() && self.e2ee.is_empty() && self.account_data.is_empty() && self.receipts.is_empty() && self.typing.is_empty() && self.other.is_empty() } } /// Extensions specific response data. #[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize)] pub struct Extensions { /// To-device extension in response. #[serde(default, skip_serializing_if = "Option::is_none")] pub to_device: Option<ToDevice>, /// E2ee extension in response. #[serde(default, skip_serializing_if = "E2ee::is_empty")] pub e2ee: E2ee, /// Account data extension in response. #[serde(default, skip_serializing_if = "AccountData::is_empty")] pub account_data: AccountData, /// Receipt data extension in response. #[serde(default, skip_serializing_if = "Receipts::is_empty")] pub receipts: Receipts, /// Typing data extension in response. #[serde(default, skip_serializing_if = "Typing::is_empty")] pub typing: Typing, } impl Extensions { /// Whether the extension data is empty. /// /// True if neither to-device, e2ee nor account data are to be found. pub fn is_empty(&self) -> bool { self.to_device .as_ref() .is_none_or(|to| to.events.is_empty()) && self.e2ee.is_empty() && self.account_data.is_empty() && self.receipts.is_empty() && self.typing.is_empty() } } /// To-device messages extension configuration. /// /// According to [MSC3885](https://github.com/matrix-org/matrix-spec-proposals/pull/3885). #[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize, PartialEq)] pub struct ToDeviceConfig { /// Activate or deactivate this extension. Sticky. #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, /// Max number of to-device messages per response. #[serde(default, skip_serializing_if = "Option::is_none")] pub limit: Option<usize>, /// Give messages since this token only. #[serde(default, skip_serializing_if = "Option::is_none")] pub since: Option<String>, /// List of list names for which to-device events should be enabled. /// /// If not defined, will be enabled for *all* the lists appearing in the /// request. If defined and empty, will be disabled for all the lists. /// /// Sticky. #[serde(default, skip_serializing_if = "Option::is_none")] pub lists: Option<Vec<String>>, /// List of room names for which to-device events should be enabled. /// /// If not defined, will be enabled for *all* the rooms appearing in the /// `room_subscriptions`. If defined and empty, will be disabled for all /// the rooms. /// /// Sticky. #[serde(default, skip_serializing_if = "Option::is_none")] pub rooms: Option<Vec<OwnedRoomId>>, } impl ToDeviceConfig { /// Whether all fields are empty or `None`. pub fn is_empty(&self) -> bool { self.enabled.is_none() && self.limit.is_none() && self.since.is_none() } } /// To-device messages extension response. /// /// According to [MSC3885](https://github.com/matrix-org/matrix-spec-proposals/pull/3885). #[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize)] pub struct ToDevice { /// Fetch the next batch from this entry. pub next_batch: String, /// The to-device Events. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub events: Vec<RawJson<AnyToDeviceEvent>>, } /// E2ee extension configuration. /// /// According to [MSC3884](https://github.com/matrix-org/matrix-spec-proposals/pull/3884). #[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize, PartialEq)] pub struct E2eeConfig { /// Activate or deactivate this extension. Sticky. #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, } impl E2eeConfig { /// Whether all fields are empty or `None`. pub fn is_empty(&self) -> bool { self.enabled.is_none() } } /// E2ee extension response data. /// /// According to [MSC3884](https://github.com/matrix-org/matrix-spec-proposals/pull/3884). #[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize)] pub struct E2ee { /// Information on E2ee device updates. /// /// Only present on an incremental sync. #[serde(default, skip_serializing_if = "DeviceLists::is_empty")] pub device_lists: DeviceLists, /// For each key algorithm, the number of unclaimed one-time keys /// currently held on the server for a device. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub device_one_time_keys_count: BTreeMap<DeviceKeyAlgorithm, u64>, /// For each key algorithm, the number of unclaimed one-time keys /// currently held on the server for a device. /// /// The presence of this field indicates that the server supports /// fallback keys. #[serde(default, skip_serializing_if = "Option::is_none")] pub device_unused_fallback_key_types: Option<Vec<DeviceKeyAlgorithm>>, } impl E2ee { /// Whether all fields are empty or `None`. pub fn is_empty(&self) -> bool { self.device_lists.is_empty() && self.device_one_time_keys_count.is_empty() && self.device_unused_fallback_key_types.is_none() } } /// Account-data extension configuration. /// /// Not yet part of the spec proposal. Taken from the reference implementation /// <https://github.com/matrix-org/sliding-sync/blob/main/sync3/extensions/account_data.go> #[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize, PartialEq)] pub struct AccountDataConfig { /// Activate or deactivate this extension. Sticky. #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, /// List of list names for which account data should be enabled. /// /// This is specific to room account data (e.g. user-defined room tags). /// /// If not defined, will be enabled for *all* the lists appearing in the /// request. If defined and empty, will be disabled for all the lists. /// /// Sticky. #[serde(default, skip_serializing_if = "Option::is_none")] pub lists: Option<Vec<String>>, /// List of room names for which account data should be enabled. /// /// This is specific to room account data (e.g. user-defined room tags). /// /// If not defined, will be enabled for *all* the rooms appearing in the /// `room_subscriptions`. If defined and empty, will be disabled for all /// the rooms. /// /// Sticky. #[serde(default, skip_serializing_if = "Option::is_none")] pub rooms: Option<Vec<OwnedRoomId>>, } impl AccountDataConfig { /// Whether all fields are empty or `None`. pub fn is_empty(&self) -> bool { self.enabled.is_none() } } /// Account-data extension response data. /// /// Not yet part of the spec proposal. Taken from the reference implementation /// <https://github.com/matrix-org/sliding-sync/blob/main/sync3/extensions/account_data.go> #[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize)] pub struct AccountData { /// The global private data created by this user. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub global: Vec<RawJson<AnyGlobalAccountDataEvent>>, /// The private data that this user has attached to each room. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub rooms: BTreeMap<OwnedRoomId, Vec<RawJson<AnyRoomAccountDataEvent>>>, } impl AccountData { /// Whether all fields are empty or `None`. pub fn is_empty(&self) -> bool { self.global.is_empty() && self.rooms.is_empty() } } /// Receipt extension configuration. /// /// According to [MSC3960](https://github.com/matrix-org/matrix-spec-proposals/pull/3960) #[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize, PartialEq)] pub struct ReceiptsConfig { /// Activate or deactivate this extension. Sticky. #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, /// List of list names for which receipts should be enabled. /// /// If not defined, will be enabled for *all* the lists appearing in the /// request. If defined and empty, will be disabled for all the lists. /// /// Sticky. #[serde(default, skip_serializing_if = "Option::is_none")] pub lists: Option<Vec<String>>, /// List of room names for which receipts should be enabled. /// /// If not defined, will be enabled for *all* the rooms appearing in the /// `room_subscriptions`. If defined and empty, will be disabled for all /// the rooms. /// /// Sticky. #[serde(default, skip_serializing_if = "Option::is_none")] pub rooms: Option<Vec<RoomReceiptConfig>>, } impl ReceiptsConfig { /// Whether all fields are empty or `None`. pub fn is_empty(&self) -> bool { self.enabled.is_none() } } /// Single entry for a room-related read receipt configuration in /// `ReceiptsConfig`. #[derive(ToSchema, Clone, Debug, PartialEq)] pub enum RoomReceiptConfig { /// Get read receipts for all the subscribed rooms. AllSubscribed, /// Get read receipts for this particular room. Room(OwnedRoomId), } impl Serialize for RoomReceiptConfig { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { match self { RoomReceiptConfig::AllSubscribed => serializer.serialize_str("*"), RoomReceiptConfig::Room(r) => r.serialize(serializer), } } } impl<'de> Deserialize<'de> for RoomReceiptConfig { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::de::Deserializer<'de>, { match deserialize_cow_str(deserializer)?.as_ref() { "*" => Ok(RoomReceiptConfig::AllSubscribed), other => Ok(RoomReceiptConfig::Room( RoomId::parse(other).map_err(D::Error::custom)?.to_owned(), )), } } } /// Receipt extension response data. /// /// According to [MSC3960](https://github.com/matrix-org/matrix-spec-proposals/pull/3960) #[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize)] pub struct Receipts { /// The ephemeral receipt room event for each room #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] #[salvo(schema(value_type = Object, additional_properties = true))] pub rooms: BTreeMap<OwnedRoomId, SyncReceiptEvent>, } impl Receipts { /// Whether all fields are empty or `None`. pub fn is_empty(&self) -> bool { self.rooms.is_empty() } } /// Typing extension configuration. /// /// Not yet part of the spec proposal. Taken from the reference implementation /// <https://github.com/matrix-org/sliding-sync/blob/main/sync3/extensions/typing.go> #[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize, PartialEq)] pub struct TypingConfig { /// Activate or deactivate this extension. Sticky. #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, /// List of list names for which typing notifications should be enabled. /// /// If not defined, will be enabled for *all* the lists appearing in the /// request. If defined and empty, will be disabled for all the lists. /// /// Sticky. #[serde(default, skip_serializing_if = "Option::is_none")] pub lists: Option<Vec<String>>, /// List of room names for which typing notifications should be enabled. /// /// If not defined, will be enabled for *all* the rooms appearing in the /// `room_subscriptions`. If defined and empty, will be disabled for all /// the rooms. /// /// Sticky. #[serde(default, skip_serializing_if = "Option::is_none")] pub rooms: Option<Vec<OwnedRoomId>>, } impl TypingConfig { /// Whether all fields are empty or `None`. pub fn is_empty(&self) -> bool { self.enabled.is_none() } } /// Typing extension response data. /// /// Not yet part of the spec proposal. Taken from the reference implementation /// <https://github.com/matrix-org/sliding-sync/blob/main/sync3/extensions/typing.go> #[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize)] pub struct Typing { /// The ephemeral typing event for each room #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] #[salvo(schema(value_type = Object, additional_properties = true))] pub rooms: BTreeMap<OwnedRoomId, SyncTypingEvent>, } impl Typing { pub fn new() -> Self { Self::default() } /// Whether all fields are empty or `None`. pub fn is_empty(&self) -> bool { self.rooms.is_empty() } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/sync_events/v3.rs
crates/core/src/client/sync_events/v3.rs
//! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3sync use std::{collections::BTreeMap, time::Duration}; use as_variant::as_variant; use salvo::oapi::{ToParameters, ToSchema}; use serde::{Deserialize, Serialize}; use super::UnreadNotificationsCount; use crate::{ DeviceKeyAlgorithm, OwnedEventId, OwnedRoomId, client::filter::FilterDefinition, device::DeviceLists, events::{ AnyGlobalAccountDataEvent, AnyRoomAccountDataEvent, AnyStrippedStateEvent, AnySyncEphemeralRoomEvent, AnySyncStateEvent, AnySyncTimelineEvent, AnyToDeviceEvent, presence::PresenceEvent, }, presence::PresenceState, serde::RawJson, }; // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: AccessToken, // history: { // 1.0 => "/_matrix/client/r0/sync", // 1.1 => "/_matrix/client/v3/sync", // } // }; /// Request type for the `sync` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct SyncEventsReqArgs { /// A filter represented either as its full JSON definition or the ID of a /// saved filter. #[salvo(parameter(parameter_in = Query))] #[serde(default, skip_serializing_if = "Option::is_none")] pub filter: Option<Filter>, /// A point in time to continue a sync from. /// /// Should be a token from the `next_batch` field of a previous `/sync` /// request. #[salvo(parameter(parameter_in = Query))] #[serde(default, skip_serializing_if = "Option::is_none")] pub since: Option<String>, /// Controls whether to include the full state for all rooms the user is a /// member of. #[serde(default, skip_serializing_if = "crate::serde::is_default")] pub full_state: bool, /// Controls whether the client is automatically marked as online by polling /// this API. /// /// Defaults to `PresenceState::Online`. #[salvo(parameter(parameter_in = Query))] #[serde(default, skip_serializing_if = "crate::serde::is_default")] pub set_presence: PresenceState, /// The maximum time to poll in milliseconds before returning this request. #[salvo(parameter(parameter_in = Query))] #[serde( with = "crate::serde::duration::opt_ms", default, skip_serializing_if = "Option::is_none" )] pub timeout: Option<Duration>, #[serde(default, skip_serializing_if = "crate::serde::is_default")] #[salvo(parameter(parameter_in = Query))] pub use_state_after: bool, } /// Response type for the `sync` endpoint. #[derive(ToSchema, Serialize, Clone, Debug)] pub struct SyncEventsResBody { /// The batch token to supply in the `since` param of the next `/sync` /// request. pub next_batch: String, /// Updates to rooms. #[serde(default, skip_serializing_if = "Rooms::is_empty")] pub rooms: Rooms, /// Updates to the presence status of other users. #[serde(default, skip_serializing_if = "Presence::is_empty")] pub presence: Presence, /// The global private data created by this user. #[serde(default, skip_serializing_if = "GlobalAccountData::is_empty")] pub account_data: GlobalAccountData, /// Messages sent directly between devices. #[serde(default, skip_serializing_if = "ToDevice::is_empty")] pub to_device: ToDevice, /// Information on E2E device updates. /// /// Only present on an incremental sync. #[serde(default, skip_serializing_if = "DeviceLists::is_empty")] pub device_lists: DeviceLists, /// For each key algorithm, the number of unclaimed one-time keys /// currently held on the server for a device. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub device_one_time_keys_count: BTreeMap<DeviceKeyAlgorithm, u64>, /// For each key algorithm, the number of unclaimed one-time keys /// currently held on the server for a device. /// /// The presence of this field indicates that the server supports /// fallback keys. #[serde(default, skip_serializing_if = "Option::is_none")] pub device_unused_fallback_key_types: Option<Vec<DeviceKeyAlgorithm>>, } impl SyncEventsResBody { /// Creates a new `Response` with the given batch token. pub fn new(next_batch: String) -> Self { Self { next_batch, rooms: Default::default(), presence: Default::default(), account_data: Default::default(), to_device: Default::default(), device_lists: Default::default(), device_one_time_keys_count: BTreeMap::new(), device_unused_fallback_key_types: None, } } } /// A filter represented either as its full JSON definition or the ID of a saved /// filter. #[derive(ToSchema, Deserialize, Serialize, Clone, Debug)] #[allow(clippy::large_enum_variant)] #[serde(untagged)] pub enum Filter { // The filter definition needs to be (de)serialized twice because it is a URL-encoded JSON // string. Since only does the latter and this is a very uncommon // setup, we implement it through custom serde logic for this specific enum variant rather // than adding another palpo_api attribute. // // On the deserialization side, because this is an enum with #[serde(untagged)], serde // will try the variants in order (https://serde.rs/enum-representations.html). That means because // FilterDefinition is the first variant, JSON decoding is attempted first which is almost // functionally equivalent to looking at whether the first symbol is a '{' as the spec // says. (there are probably some corner cases like leading whitespace) /// A complete filter definition serialized to JSON. #[serde(with = "crate::serde::json_string")] FilterDefinition(FilterDefinition), /// The ID of a filter saved on the server. FilterId(String), } impl From<FilterDefinition> for Filter { fn from(def: FilterDefinition) -> Self { Self::FilterDefinition(def) } } impl From<String> for Filter { fn from(id: String) -> Self { Self::FilterId(id) } } /// Updates to rooms. #[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)] pub struct Rooms { /// The rooms that the user has left or been banned from. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub leave: BTreeMap<OwnedRoomId, LeftRoom>, /// The rooms that the user has joined. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub join: BTreeMap<OwnedRoomId, JoinedRoom>, /// The rooms that the user has been invited to. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub invite: BTreeMap<OwnedRoomId, InvitedRoom>, /// The rooms that the user has knocked on. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub knock: BTreeMap<OwnedRoomId, KnockedRoom>, } impl Rooms { /// Creates an empty `Rooms`. pub fn new() -> Self { Default::default() } /// Returns true if there is no update in any room. pub fn is_empty(&self) -> bool { self.leave.is_empty() && self.join.is_empty() && self.invite.is_empty() && self.knock.is_empty() } } /// Historical updates to left rooms. #[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)] pub struct LeftRoom { /// The timeline of messages and state changes in the room up to the point /// when the user left. #[serde(default)] pub timeline: Timeline, /// The state updates for the room up to the start of the timeline. #[serde(flatten, skip_serializing_if = "State::is_empty")] pub state: State, /// The private data that this user has attached to this room. #[serde(default, skip_serializing_if = "RoomAccountData::is_empty")] pub account_data: RoomAccountData, } impl LeftRoom { /// Creates an empty `LeftRoom`. pub fn new() -> Self { Default::default() } /// Returns true if there are updates in the room. pub fn is_empty(&self) -> bool { self.timeline.is_empty() && self.state.is_empty() && self.account_data.is_empty() } } /// Updates to joined rooms. #[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)] pub struct JoinedRoom { /// Information about the room which clients may need to correctly render it /// to users. #[serde(default, skip_serializing_if = "RoomSummary::is_empty")] pub summary: RoomSummary, /// Counts of [unread notifications] for this room. /// /// If `unread_thread_notifications` was set to `true` in the /// [`RoomEventFilter`], these include only the unread notifications for /// the main timeline. /// /// [unread notifications]: https://spec.matrix.org/latest/client-server-api/#receiving-notifications /// [`RoomEventFilter`]: crate::filter::RoomEventFilter #[serde(default, skip_serializing_if = "UnreadNotificationsCount::is_empty")] pub unread_notifications: UnreadNotificationsCount, /// Counts of [unread notifications] for threads in this room. /// /// This is a map from thread root ID to unread notifications in the thread. /// /// Only set if `unread_thread_notifications` was set to `true` in the /// [`RoomEventFilter`]. /// /// [unread notifications]: https://spec.matrix.org/latest/client-server-api/#receiving-notifications /// [`RoomEventFilter`]: crate::filter::RoomEventFilter #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub unread_thread_notifications: BTreeMap<OwnedEventId, UnreadNotificationsCount>, /// The timeline of messages and state changes in the room. #[serde(default, skip_serializing_if = "Timeline::is_empty")] pub timeline: Timeline, /// Updates to the state, between the time indicated by the `since` /// parameter, and the start of the `timeline` (or all state up to the /// start of the `timeline`, if `since` is not given, or `full_state` is /// true). #[serde(flatten, skip_serializing_if = "State::is_before_and_empty")] pub state: State, /// The private data that this user has attached to this room. #[serde(default, skip_serializing_if = "RoomAccountData::is_empty")] pub account_data: RoomAccountData, /// The ephemeral events in the room that aren't recorded in the timeline or /// state of the room. #[serde(default, skip_serializing_if = "Ephemeral::is_empty")] pub ephemeral: Ephemeral, /// The number of unread events since the latest read receipt. /// /// This uses the unstable prefix in [MSC2654]. /// /// [MSC2654]: https://github.com/matrix-org/matrix-spec-proposals/pull/2654 #[serde( rename = "org.matrix.msc2654.unread_count", skip_serializing_if = "Option::is_none" )] pub unread_count: Option<u64>, } impl JoinedRoom { /// Creates an empty `JoinedRoom`. pub fn new() -> Self { Default::default() } /// Returns true if there are no updates in the room. pub fn is_empty(&self) -> bool { let is_empty = self.summary.is_empty() && self.unread_notifications.is_empty() && self.unread_thread_notifications.is_empty() && self.timeline.is_empty() && self.state.is_empty() && self.account_data.is_empty() && self.ephemeral.is_empty(); #[cfg(not(feature = "unstable-msc2654"))] return is_empty; #[cfg(feature = "unstable-msc2654")] return is_empty && self.unread_count.is_none(); } } /// Updates to knocked rooms. #[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)] pub struct KnockedRoom { /// The knock state. pub knock_state: KnockState, } /// A mapping from a key `events` to a list of `StrippedStateEvent`. #[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)] pub struct KnockState { /// The list of events. pub events: Vec<RawJson<AnyStrippedStateEvent>>, } /// Events in the room. #[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)] pub struct Timeline { /// True if the number of events returned was limited by the `limit` on the /// filter. /// /// Default to `false`. #[serde(default)] pub limited: bool, /// A token that can be supplied to to the `from` parameter of the /// `/rooms/{room_id}/messages` endpoint. #[serde(default, skip_serializing_if = "Option::is_none")] pub prev_batch: Option<String>, /// A list of events. #[serde(default)] pub events: Vec<RawJson<AnySyncTimelineEvent>>, } impl Timeline { /// Creates an empty `Timeline`. pub fn new() -> Self { Default::default() } /// Returns true if there are no timeline updates. pub fn is_empty(&self) -> bool { self.events.is_empty() } } /// State events in the room. #[derive(ToSchema, Clone, Debug, Deserialize, Serialize)] pub enum State { /// The state changes between the previous sync and the **start** of the timeline. /// /// To get the full list of state changes since the previous sync, the state events in /// [`Timeline`] must be added to these events to update the local state. /// /// To get this variant, `use_state_after` must be set to `false` in the [`Request`], which is /// the default. #[serde(rename = "state")] Before(StateEvents), /// The state changes between the previous sync and the **end** of the timeline. /// /// This contains the full list of state changes since the previous sync. State events in /// [`Timeline`] must be ignored to update the local state. /// /// To get this variant, `use_state_after` must be set to `true` in the [`Request`]. #[serde(rename = "state_after")] After(StateEvents), } impl State { /// Returns true if this is the `Before` variant and there are no state updates. fn is_before_and_empty(&self) -> bool { as_variant!(self, Self::Before).is_some_and(|state| state.is_empty()) } /// Returns true if there are no state updates. pub fn is_empty(&self) -> bool { match self { Self::Before(state) => state.is_empty(), Self::After(state) => state.is_empty(), } } } impl Default for State { fn default() -> Self { Self::Before(Default::default()) } } /// State events in the room. #[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)] pub struct StateEvents { /// A list of state events. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub events: Vec<RawJson<AnySyncStateEvent>>, } impl StateEvents { /// Creates an empty `State`. pub fn new(events: Vec<RawJson<AnySyncStateEvent>>) -> Self { Self { events } } /// Returns true if there are no state updates. pub fn is_empty(&self) -> bool { self.events.is_empty() } } impl From<Vec<RawJson<AnySyncStateEvent>>> for StateEvents { fn from(events: Vec<RawJson<AnySyncStateEvent>>) -> Self { Self::new(events) } } /// The global private data created by this user. #[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)] pub struct GlobalAccountData { /// A list of events. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub events: Vec<RawJson<AnyGlobalAccountDataEvent>>, } impl GlobalAccountData { /// Creates an empty `GlobalAccountData`. pub fn new() -> Self { Default::default() } /// Returns true if there are no global account data updates. pub fn is_empty(&self) -> bool { self.events.is_empty() } } /// The private data that this user has attached to this room. #[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)] pub struct RoomAccountData { /// A list of events. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub events: Vec<RawJson<AnyRoomAccountDataEvent>>, } impl RoomAccountData { /// Creates an empty `RoomAccountData`. pub fn new() -> Self { Default::default() } /// Returns true if there are no room account data updates. pub fn is_empty(&self) -> bool { self.events.is_empty() } } /// Ephemeral events not recorded in the timeline or state of the room. #[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)] pub struct Ephemeral { /// A list of events. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub events: Vec<RawJson<AnySyncEphemeralRoomEvent>>, } impl Ephemeral { /// Creates an empty `Ephemeral`. pub fn new() -> Self { Default::default() } /// Returns true if there are no ephemeral event updates. pub fn is_empty(&self) -> bool { self.events.is_empty() } } /// Information about room for rendering to clients. #[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)] pub struct RoomSummary { /// Users which can be used to generate a room name if the room does not /// have one. /// /// Required if room name or canonical aliases are not set or empty. #[serde(rename = "m.heroes", default, skip_serializing_if = "Vec::is_empty")] pub heroes: Vec<String>, /// Number of users whose membership status is `join`. /// Required if field has changed since last sync; otherwise, it may be /// omitted. #[serde( default, rename = "m.joined_member_count", skip_serializing_if = "Option::is_none" )] pub joined_member_count: Option<u64>, /// Number of users whose membership status is `invite`. /// Required if field has changed since last sync; otherwise, it may be /// omitted. #[serde( default, rename = "m.invited_member_count", skip_serializing_if = "Option::is_none" )] pub invited_member_count: Option<u64>, } impl RoomSummary { /// Creates an empty `RoomSummary`. pub fn new() -> Self { Default::default() } /// Returns true if there are no room summary updates. pub fn is_empty(&self) -> bool { self.heroes.is_empty() && self.joined_member_count.is_none() && self.invited_member_count.is_none() } } /// Updates to the rooms that the user has been invited to. #[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)] pub struct InvitedRoom { /// The state of a room that the user has been invited to. #[serde(default, skip_serializing_if = "InviteState::is_empty")] pub invite_state: InviteState, } impl InvitedRoom { /// Creates an empty `InvitedRoom`. pub fn new(invite_state: InviteState) -> Self { Self { invite_state } } /// Returns true if there are no updates to this room. pub fn is_empty(&self) -> bool { self.invite_state.is_empty() } } impl From<InviteState> for InvitedRoom { fn from(invite_state: InviteState) -> Self { InvitedRoom { invite_state } } } /// The state of a room that the user has been invited to. #[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)] pub struct InviteState { /// A list of state events. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub events: Vec<RawJson<AnyStrippedStateEvent>>, } impl InviteState { /// Creates an empty `InviteState`. pub fn new(events: Vec<RawJson<AnyStrippedStateEvent>>) -> Self { Self { events } } /// Returns true if there are no state updates. pub fn is_empty(&self) -> bool { self.events.is_empty() } } impl From<Vec<RawJson<AnyStrippedStateEvent>>> for InviteState { fn from(events: Vec<RawJson<AnyStrippedStateEvent>>) -> Self { Self { events } } } /// Updates to the presence status of other users. #[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)] pub struct Presence { /// A list of events. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub events: Vec<RawJson<PresenceEvent>>, } impl Presence { /// Creates an empty `Presence`. pub fn new() -> Self { Default::default() } /// Returns true if there are no presence updates. pub fn is_empty(&self) -> bool { self.events.is_empty() } } /// Messages sent directly between devices. #[derive(ToSchema, Clone, Debug, Default, Deserialize, Serialize)] pub struct ToDevice { /// A list of to-device events. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub events: Vec<RawJson<AnyToDeviceEvent>>, } impl ToDevice { /// Creates an empty `ToDevice`. pub fn new() -> Self { Default::default() } /// Returns true if there are no to-device events. pub fn is_empty(&self) -> bool { self.events.is_empty() } } // #[cfg(test)] // mod tests { // use assign::assign; // use serde_json::{from_value as from_json_value, json, to_value as // to_json_value}; // use super::Timeline; // #[test] // fn timeline_serde() { // let timeline = assign!(Timeline::new(), { limited: true }); // let timeline_serialized = json!({ "limited": true }); // assert_eq!(to_json_value(timeline).unwrap(), timeline_serialized); // let timeline_deserialized = // from_json_value::<Timeline>(timeline_serialized).unwrap(); assert! // (timeline_deserialized.limited); // let timeline_default = Timeline::default(); // assert_eq!(to_json_value(timeline_default).unwrap(), json!({})); // let timeline_default_deserialized = // from_json_value::<Timeline>(json!({})).unwrap(); assert!(! // timeline_default_deserialized.limited); } // } // #[cfg(all(test))] // mod server_tests { // use std::time::Duration; // use crate::{api::IncomingRequest as _, presence::PresenceState}; // use assert_matches2::assert_matches; // use super::{Filter, Request}; // #[test] // fn deserialize_all_query_params() { // let uri = http::Uri::builder() // .scheme("https") // .authority("matrix.org") // .path_and_query( // "/_matrix/client/r0/sync\ // ?filter=myfilter\ // &since=myts\ // &full_state=false\ // &set_presence=offline\ // &timeout=5000", // ) // .build() // .unwrap(); // let req = Request::try_from_http_request( // http::Request::builder().uri(uri).body(&[] as &[u8]).unwrap(), // &[] as &[String], // ) // .unwrap(); // assert_matches!(req.filter, Some(Filter::FilterId(id))); // assert_eq!(id, "myfilter"); // assert_eq!(req.since.as_deref(), Some("myts")); // assert!(!req.full_state); // assert_eq!(req.set_presence, PresenceState::Offline); // assert_eq!(req.timeout, Some(Duration::from_millis(5000))); // } // #[test] // fn deserialize_no_query_params() { // let uri = http::Uri::builder() // .scheme("https") // .authority("matrix.org") // .path_and_query("/_matrix/client/r0/sync") // .build() // .unwrap(); // let req = Request::try_from_http_request( // http::Request::builder().uri(uri).body(&[] as &[u8]).unwrap(), // &[] as &[String], // ) // .unwrap(); // assert_matches!(req.filter, None); // assert_eq!(req.since, None); // assert!(!req.full_state); // assert_eq!(req.set_presence, PresenceState::Online); // assert_eq!(req.timeout, None); // } // #[test] // fn deserialize_some_query_params() { // let uri = http::Uri::builder() // .scheme("https") // .authority("matrix.org") // .path_and_query( // "/_matrix/client/r0/sync\ // ?filter=EOKFFmdZYF\ // &timeout=0", // ) // .build() // .unwrap(); // let req = Request::try_from_http_request( // http::Request::builder().uri(uri).body(&[] as &[u8]).unwrap(), // &[] as &[String], // ) // .unwrap(); // assert_matches!(req.filter, Some(Filter::FilterId(id))); // assert_eq!(id, "EOKFFmdZYF"); // assert_eq!(req.since, None); // assert!(!req.full_state); // assert_eq!(req.set_presence, PresenceState::Online); // assert_eq!(req.timeout, Some(Duration::from_millis(0))); // } // }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/client/rendezvous/create_rendezvous_session.rs
crates/core/src/client/rendezvous/create_rendezvous_session.rs
//! `POST /_matrix/client/*/rendezvous/` //! //! Create a rendezvous session. pub mod unstable { //! `msc4108` ([MSC]) //! //! [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/4108 use http::header::{CONTENT_TYPE, ETAG, EXPIRES, LAST_MODIFIED}; #[cfg(feature = "client")] use crate::api::error::FromHttpResponseError; use crate::{ api::{auth_scheme::NoAuthentication, error::HeaderDeserializationError}, metadata, }; use serde::{Deserialize, Serialize}; use url::Url; use web_time::SystemTime; metadata! { method: POST, rate_limited: true, authentication: NoAuthentication, history: { unstable("org.matrix.msc4108") => "/_matrix/client/unstable/org.matrix.msc4108/rendezvous", } } /// Request type for the `POST` `rendezvous` endpoint. #[derive(Debug, Default, Clone)] pub struct Request { /// Any data up to maximum size allowed by the server. pub content: String, } #[cfg(feature = "client")] impl crate::api::OutgoingRequest for Request { type EndpointError = crate::Error; type IncomingResponse = Response; fn try_into_http_request<T: Default + bytes::BufMut>( self, base_url: &str, _: crate::api::auth_scheme::SendAccessToken<'_>, considering: std::borrow::Cow<'_, crate::api::SupportedVersions>, ) -> Result<http::Request<T>, crate::api::error::IntoHttpError> { use http::header::CONTENT_LENGTH; use crate::api::Metadata; let url = Self::make_endpoint_url(considering, base_url, &[], "")?; let body = self.content.as_bytes(); let content_length = body.len(); Ok(http::Request::builder() .method(Self::METHOD) .uri(url) .header(CONTENT_TYPE, "text/plain") .header(CONTENT_LENGTH, content_length) .body(crate::serde::slice_to_buf(body))?) } } #[cfg(feature = "server")] impl crate::api::IncomingRequest for Request { type EndpointError = crate::Error; type OutgoingResponse = Response; fn try_from_http_request<B, S>( request: http::Request<B>, _path_args: &[S], ) -> Result<Self, crate::api::error::FromHttpRequestError> where B: AsRef<[u8]>, S: AsRef<str>, { const EXPECTED_CONTENT_TYPE: &str = "text/plain"; use crate::api::error::DeserializationError; Self::check_request_method(request.method())?; let content_type = request .headers() .get(CONTENT_TYPE) .ok_or(HeaderDeserializationError::MissingHeader(CONTENT_TYPE.to_string()))?; let content_type = content_type.to_str()?; if content_type != EXPECTED_CONTENT_TYPE { Err(HeaderDeserializationError::InvalidHeaderValue { header: CONTENT_TYPE.to_string(), expected: EXPECTED_CONTENT_TYPE.to_owned(), unexpected: content_type.to_owned(), } .into()) } else { let body = request.into_body().as_ref().to_vec(); let content = String::from_utf8(body) .map_err(|e| DeserializationError::Utf8(e.utf8_error()))?; Ok(Self { content }) } } } impl Request { /// Creates a new `Request` with the given content. pub fn new(content: String) -> Self { Self { content } } } /// Response type for the `POST` `rendezvous` endpoint. #[derive(Debug, Clone)] pub struct Response { /// The absolute URL of the rendezvous session. pub url: Url, /// ETag for the current payload at the rendezvous session as /// per [RFC7232](https://httpwg.org/specs/rfc7232.html#header.etag). pub etag: String, /// The expiry time of the rendezvous as per /// [RFC7234](https://httpwg.org/specs/rfc7234.html#header.expires). pub expires: SystemTime, /// The last modified date of the payload as /// per [RFC7232](https://httpwg.org/specs/rfc7232.html#header.last-modified) pub last_modified: SystemTime, } #[derive(Serialize, Deserialize)] struct ResponseBody { url: Url, } #[cfg(feature = "client")] impl crate::api::IncomingResponse for Response { type EndpointError = crate::Error; fn try_from_http_response<T: AsRef<[u8]>>( response: http::Response<T>, ) -> Result<Self, FromHttpResponseError<Self::EndpointError>> { use crate::api::EndpointError; if response.status().as_u16() >= 400 { return Err(FromHttpResponseError::Server( Self::EndpointError::from_http_response(response), )); } let get_date = |header: http::HeaderName| -> Result<SystemTime, FromHttpResponseError<Self::EndpointError>> { let date = response .headers() .get(&header) .ok_or_else(|| HeaderDeserializationError::MissingHeader(header.to_string()))?; let date = crate::http_headers::http_date_to_system_time(date)?; Ok(date) }; let etag = response .headers() .get(ETAG) .ok_or(HeaderDeserializationError::MissingHeader(ETAG.to_string()))? .to_str()? .to_owned(); let expires = get_date(EXPIRES)?; let last_modified = get_date(LAST_MODIFIED)?; let body: ResponseBody = serde_json::from_slice(response.body().as_ref())?; Ok(Self { url: body.url, etag, expires, last_modified }) } } #[cfg(feature = "server")] impl crate::api::OutgoingResponse for Response { fn try_into_http_response<T: Default + bytes::BufMut>( self, ) -> Result<http::Response<T>, crate::api::error::IntoHttpError> { use http::header::{CACHE_CONTROL, PRAGMA}; let body = ResponseBody { url: self.url }; let body = crate::serde::json_to_buf(&body)?; let expires = crate::http_headers::system_time_to_http_date(&self.expires)?; let last_modified = crate::http_headers::system_time_to_http_date(&self.last_modified)?; Ok(http::Response::builder() .status(http::StatusCode::OK) .header(CONTENT_TYPE, crate::http_headers::APPLICATION_JSON) .header(PRAGMA, "no-cache") .header(CACHE_CONTROL, "no-store") .header(ETAG, self.etag) .header(EXPIRES, expires) .header(LAST_MODIFIED, last_modified) .body(body)?) } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/serde.rs
crates/core/src/federation/serde.rs
//! Modules for custom serde de/-serialization implementations. pub(crate) mod pdu_process_response; pub(crate) mod v1_pdu;
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/event.rs
crates/core/src/federation/event.rs
use reqwest::Url; use salvo::prelude::*; use serde::{Deserialize, Serialize}; use crate::identifiers::*; use crate::room::TimestampToEventReqArgs; use crate::sending::{SendRequest, SendResult}; use crate::{Direction, UnixMillis, serde::RawJsonValue}; // /// `GET /_matrix/federation/*/timestamp_to_event/{room_id}` // /// // /// Get the ID of the event closest to the given timestamp. // // /// `/v1/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/server-server-api/#get_matrixfederationv1timestamp_to_eventroomid // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: ServerSignatures, // history: { // unstable => "/_matrix/federation/unstable/org.matrix.msc3030/timestamp_to_event/:room_id", // 1.6 => "/_matrix/federation/v1/timestamp_to_event/:room_id", // } // }; pub fn timestamp_to_event_request( origin: &str, args: TimestampToEventReqArgs, ) -> SendResult<SendRequest> { let mut url = Url::parse(&format!( "{origin}/_matrix/federation/v1/timestamp_to_event/{}", args.room_id ))?; url.query_pairs_mut() .append_pair( "dir", match args.dir { Direction::Forward => "f", Direction::Backward => "b", }, ) .append_pair("ts", &args.ts.to_string()); Ok(crate::sending::get(url)) } // /// `GET /_matrix/federation/*/event/{event_id}` // /// // /// Retrieves a single event. // /// `/v1/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/server-server-api/#get_matrixfederationv1eventeventid // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: ServerSignatures, // history: { // 1.0 => "/_matrix/federation/v1/event/:event_id", // } // }; // /// Request type for the `get_event` endpoint. // pub struct Request { // /// The event ID to get. // #[salvo(parameter(parameter_in = Path))] // pub event_id: OwnedEventId, // } pub fn event_request(origin: &str, args: EventReqArgs) -> SendResult<SendRequest> { let url = Url::parse(&format!( "{origin}/_matrix/federation/v1/event/{}", args.event_id ))?; Ok(crate::sending::get(url)) } #[derive(ToParameters, Deserialize, Debug)] pub struct EventReqArgs { #[salvo(parameter(parameter_in = Path))] pub event_id: OwnedEventId, /// Event to report. #[salvo(parameter(parameter_in = Path))] pub include_unredacted_content: Option<bool>, } impl EventReqArgs { pub fn new(event_id: impl Into<OwnedEventId>) -> Self { Self { event_id: event_id.into(), include_unredacted_content: None, } } } /// Response type for the `get_event` endpoint. #[derive(ToSchema, Serialize, Deserialize, Debug)] pub struct EventResBody { /// The `server_name` of the homeserver sending this transaction. pub origin: OwnedServerName, /// Time on originating homeserver when this transaction started. pub origin_server_ts: UnixMillis, /// The event. #[serde(rename = "pdus", with = "crate::serde::single_element_seq")] #[salvo(schema(value_type = Object, additional_properties = true))] pub pdu: Box<RawJsonValue>, } impl EventResBody { /// Creates a new `Response` with the given server name, timestamp, and /// event. pub fn new( origin: OwnedServerName, origin_server_ts: UnixMillis, pdu: Box<RawJsonValue>, ) -> Self { Self { origin, origin_server_ts, pdu, } } } // /// `POST /_matrix/federation/*/get_missing_events/{room_id}` // /// // /// Retrieves previous events that the sender is missing. // /// `/v1/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/server-server-api/#post_matrixfederationv1get_missing_eventsroomid // const METADATA: Metadata = metadata! { // method: POST, // rate_limited: false, // authentication: ServerSignatures, // history: { // 1.0 => "/_matrix/federation/v1/get_missing_events/:room_id", // } // }; pub fn missing_events_request( origin: &str, room_id: &RoomId, body: MissingEventsReqBody, ) -> SendResult<SendRequest> { let url = Url::parse(&format!( "{origin}/_matrix/federation/v1/get_missing_events/{room_id}" ))?; crate::sending::post(url).stuff(body) } /// Request type for the `get_missing_events` endpoint. #[derive(ToSchema, Deserialize, Serialize, Debug)] pub struct MissingEventsReqBody { /// The room ID to search in. // #[salvo(parameter(parameter_in = Path))] // pub room_id: OwnedRoomId, /// The maximum number of events to retrieve. /// /// Defaults to 10. #[serde(default = "default_limit", skip_serializing_if = "is_default_limit")] pub limit: usize, /// The minimum depth of events to retrieve. /// /// Defaults to 0. #[serde(default, skip_serializing_if = "crate::serde::is_default")] pub min_depth: u64, /// The latest event IDs that the sender already has. /// /// These are skipped when retrieving the previous events of /// `latest_events`. pub earliest_events: Vec<OwnedEventId>, /// The event IDs to retrieve the previous events for. pub latest_events: Vec<OwnedEventId>, } crate::json_body_modifier!(MissingEventsReqBody); /// Response type for the `get_missing_events` endpoint. #[derive(ToSchema, Serialize, Deserialize, Debug)] pub struct MissingEventsResBody { /// The missing PDUs. #[salvo(schema(value_type = Vec<Object>))] pub events: Vec<Box<RawJsonValue>>, } impl MissingEventsResBody { /// Creates a new `Response` with the given events. pub fn new(events: Vec<Box<RawJsonValue>>) -> Self { Self { events } } } fn default_limit() -> usize { 10 } fn is_default_limit(val: &usize) -> bool { *val == default_limit() } // /// `GET /_matrix/federation/*/state_ids/{room_id}` // /// // /// Retrieves a snapshot of a room's state at a given event, in the form of // /// event IDs. `/v1/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/server-server-api/#get_matrixfederationv1state_idsroomid // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: ServerSignatures, // history: { // 1.0 => "/_matrix/federation/v1/state_ids/:room_id", // } // }; pub fn room_state_ids_request( origin: &str, args: RoomStateAtEventReqArgs, ) -> SendResult<SendRequest> { let mut url = Url::parse(&format!( "{origin}/_matrix/federation/v1/state_ids/{}", args.room_id ))?; url.query_pairs_mut() .append_pair("event_id", args.event_id.as_str()); Ok(crate::sending::get(url)) } /// Request type for the `get_state_ids` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct RoomStateAtEventReqArgs { /// The room ID to get state for. #[salvo(parameter(parameter_in = Path))] pub room_id: OwnedRoomId, /// An event ID in the room to retrieve the state at. #[salvo(parameter(parameter_in = Query))] pub event_id: OwnedEventId, } /// Response type for the `get_state_ids` endpoint. #[derive(ToSchema, Deserialize, Serialize, Debug)] pub struct RoomStateIdsResBody { /// The full set of authorization events that make up the state of the /// room, and their authorization events, recursively. pub auth_chain_ids: Vec<OwnedEventId>, /// The fully resolved state of the room at the given event. pub pdu_ids: Vec<OwnedEventId>, } impl RoomStateIdsResBody { /// Creates a new `Response` with the given auth chain IDs and room state /// IDs. pub fn new(auth_chain_ids: Vec<OwnedEventId>, pdu_ids: Vec<OwnedEventId>) -> Self { Self { auth_chain_ids, pdu_ids, } } } // /// `GET /_matrix/federation/*/state/{room_id}` // /// // /// Retrieves a snapshot of a room's state at a given event. // /// `/v1/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/server-server-api/#get_matrixfederationv1stateroomid // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: ServerSignatures, // history: { // 1.0 => "/_matrix/federation/v1/state/:room_id", // } // }; pub fn room_state_request(origin: &str, args: RoomStateReqArgs) -> SendResult<SendRequest> { let mut url = Url::parse(&format!( "{origin}/_matrix/federation/v1/state/{}", args.room_id ))?; url.query_pairs_mut() .append_pair("event_id", args.event_id.as_str()); Ok(crate::sending::get(url)) } /// Request type for the `get_state` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct RoomStateReqArgs { /// The room ID to get state for. #[salvo(parameter(parameter_in = Path))] pub room_id: OwnedRoomId, /// An event ID in the room to retrieve the state at. #[salvo(parameter(parameter_in = Query))] pub event_id: OwnedEventId, } /// Response type for the `get_state` endpoint. #[derive(ToSchema, Serialize, Deserialize, Debug)] pub struct RoomStateResBody { /// The full set of authorization events that make up the state of the /// room, and their authorization events, recursively. #[salvo(schema(value_type = Object))] pub auth_chain: Vec<Box<RawJsonValue>>, /// The fully resolved state of the room at the given event. #[salvo(schema(value_type = Vec<Object>))] pub pdus: Vec<Box<RawJsonValue>>, } // /// `PUT /_matrix/app/*/ping` // /// // /// Endpoint to ping the application service. // /// `/v1/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/application-service-api/#post_matrixappv1ping // const METADATA: Metadata = metadata! { // method: POST, // rate_limited: false, // authentication: AccessToken, // history: { // unstable => "/_matrix/app/unstable/fi.mau.msc2659/ping", // 1.7 => "/_matrix/app/v1/ping", // } // }; /// Request type for the `send_ping` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct PingReqBody { /// A transaction ID for the ping, copied directly from the `POST /// /_matrix/client/v1/appservice/{appserviceId}/ping` call. #[serde(skip_serializing_if = "Option::is_none")] pub transaction_id: Option<OwnedTransactionId>, }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/discovery.rs
crates/core/src/federation/discovery.rs
//! Server discovery endpoints. use std::collections::BTreeMap; use salvo::prelude::*; use serde::{Deserialize, Serialize}; use crate::{OwnedServerName, OwnedServerSigningKeyId, UnixMillis, serde::Base64}; /// Public key of the homeserver for verifying digital signatures. #[derive(ToSchema, Deserialize, Serialize, Clone, Debug)] pub struct VerifyKey { /// The unpadded base64-encoded key. #[salvo(schema(value_type = String))] pub key: Base64, } impl VerifyKey { /// Creates a new `VerifyKey` from the given key. pub fn new(key: Base64) -> Self { Self { key } } pub fn from_bytes(bytes: Vec<u8>) -> Self { Self { key: Base64::new(bytes), } } } /// A key the server used to use, but stopped using. #[derive(Clone, Debug, Deserialize, Serialize)] pub struct OldVerifyKey { /// Timestamp when this key expired. pub expired_ts: UnixMillis, /// The unpadded base64-encoded key. pub key: Base64, } impl OldVerifyKey { /// Creates a new `OldVerifyKey` with the given expiry time and key. pub fn new(expired_ts: UnixMillis, key: Base64) -> Self { Self { expired_ts, key } } } // Spec is wrong, all fields are required (see https://github.com/matrix-org/matrix-spec/issues/613) /// Queried server key, signed by the notary server. #[derive(ToSchema, Deserialize, Serialize, Clone, Debug)] pub struct ServerSigningKeys { /// DNS name of the homeserver. pub server_name: OwnedServerName, /// Public keys of the homeserver for verifying digital signatures. pub verify_keys: BTreeMap<OwnedServerSigningKeyId, VerifyKey>, /// Public keys that the homeserver used to use and when it stopped using /// them. pub old_verify_keys: BTreeMap<OwnedServerSigningKeyId, OldVerifyKey>, /// Digital signatures of this object signed using the verify_keys. /// /// Map of server name to keys by key ID. pub signatures: BTreeMap<OwnedServerName, BTreeMap<OwnedServerSigningKeyId, String>>, /// Timestamp when the keys should be refreshed. /// /// This field MUST be ignored in room versions 1, 2, 3, and 4. pub valid_until_ts: UnixMillis, } impl ServerSigningKeys { /// Creates a new `ServerSigningKeys` with the given server name and /// validity timestamp. /// /// All other fields will be empty. pub fn new(server_name: OwnedServerName, valid_until_ts: UnixMillis) -> Self { Self { server_name, verify_keys: BTreeMap::new(), old_verify_keys: BTreeMap::new(), signatures: BTreeMap::new(), valid_until_ts, } } } // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: None, // history: { // 1.0 => "/.well-known/matrix/server", // } // }; /// Response type for the `discover_homeserver` endpoint. #[derive(ToSchema, Serialize, Debug)] pub struct ServerResBody { /// The server name to delegate server-server communications to, with /// optional port. #[serde(rename = "m.server")] pub server: OwnedServerName, } impl ServerResBody { /// Creates a new `Response` with the given homeserver. pub fn new(server: OwnedServerName) -> Self { Self { server } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/key.rs
crates/core/src/federation/key.rs
/// Endpoints for handling keys for end-to-end encryption /// /// `POST /_matrix/federation/*/user/keys/claim` /// /// Claim one-time keys for use in pre-key messages. /// `/v1/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/server-server-api/#post_matrixfederationv1userkeysclaim use std::collections::BTreeMap; use std::time::Duration; use reqwest::Url; use salvo::prelude::*; use serde::{Deserialize, Serialize}; use crate::{ DeviceKeyAlgorithm, OwnedDeviceId, OwnedDeviceKeyId, OwnedUserId, encryption::{CrossSigningKey, DeviceKeys, OneTimeKey}, sending::{SendRequest, SendResult}, serde::Base64, }; pub fn get_server_key_request(origin: &str) -> SendResult<SendRequest> { let url = Url::parse(&format!("{origin}/_matrix/key/v2/server"))?; Ok(crate::sending::get(url)) } // const METADATA: Metadata = metadata! { // method: POST, // rate_limited: false, // authentication: ServerSignatures, // history: { // 1.0 => "/_matrix/federation/v1/user/keys/claim", // } // }; // pub fn claim_keys_request(txn_id: &str, body: ClaimKeysReqBody) -> // SendRequest { let url = registration // .build_url(&format!("/app/v1/transactions/{}", txn_id)) // crate::sending::post(url) // .stuff(req_body) // } pub fn claim_keys_request(origin: &str, body: ClaimKeysReqBody) -> SendResult<SendRequest> { let url = Url::parse(&format!("{origin}/_matrix/federation/v1/user/keys/claim"))?; crate::sending::post(url).stuff(body) } /// Request type for the `claim_keys` endpoint. #[derive(ToSchema, Deserialize, Serialize, Debug)] pub struct ClaimKeysReqBody { #[serde( with = "crate::serde::duration::opt_ms", default, skip_serializing_if = "Option::is_none" )] pub timeout: Option<Duration>, /// The keys to be claimed. #[salvo(schema(value_type = Object, additional_properties = true))] pub one_time_keys: OneTimeKeyClaims, } crate::json_body_modifier!(ClaimKeysReqBody); /// Response type for the `claim_keys` endpoint. #[derive(ToSchema, Deserialize, Serialize, Debug)] pub struct ClaimKeysResBody { /// One-time keys for the queried devices #[salvo(schema(value_type = Object, additional_properties = true))] pub one_time_keys: OneTimeKeys, } impl ClaimKeysResBody { /// Creates a new `Response` with the given one time keys. pub fn new(one_time_keys: OneTimeKeys) -> Self { Self { one_time_keys } } } /// A claim for one time keys pub type OneTimeKeyClaims = BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceId, DeviceKeyAlgorithm>>; /// One time keys for use in pre-key messages pub type OneTimeKeys = BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceId, BTreeMap<OwnedDeviceKeyId, OneTimeKey>>>; /// A key and its signature #[derive(Debug, Clone, Serialize, Deserialize)] pub struct KeyObject { /// The key, encoded using unpadded base64. pub key: Base64, /// Signature of the key object. pub signatures: BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceKeyId, String>>, } impl KeyObject { /// Creates a new `KeyObject` with the given key and signatures. pub fn new( key: Base64, signatures: BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceKeyId, String>>, ) -> Self { Self { key, signatures } } } // /// `POST /_matrix/federation/*/user/keys/query` // /// // /// Get the current devices and identity keys for the given users. // /// `/v1/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/server-server-api/#post_matrixfederationv1userkeysquery // const METADATA: Metadata = metadata! { // method: POST, // rate_limited: false, // authentication: ServerSignatures, // history: { // 1.0 => "/_matrix/federation/v1/user/keys/query", // } // }; pub fn query_keys_request(origin: &str, body: QueryKeysReqBody) -> SendResult<SendRequest> { let url = Url::parse(&format!("{origin}/_matrix/federation/v1/user/keys/query"))?; crate::sending::post(url).stuff(body) } /// Request type for the `get_keys` endpoint. #[derive(ToSchema, Deserialize, Serialize, Debug)] pub struct QueryKeysReqBody { /// The keys to be downloaded. /// /// Gives all keys for a given user if the list of device ids is empty. pub device_keys: BTreeMap<OwnedUserId, Vec<OwnedDeviceId>>, } crate::json_body_modifier!(QueryKeysReqBody); /// Response type for the `get_keys` endpoint. #[derive(ToSchema, Deserialize, Serialize, Default, Debug)] pub struct QueryKeysResBody { /// Keys from the queried devices. pub device_keys: BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceId, DeviceKeys>>, /// Information on the master cross-signing keys of the queried users. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub master_keys: BTreeMap<OwnedUserId, CrossSigningKey>, /// Information on the self-signing keys of the queried users. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub self_signing_keys: BTreeMap<OwnedUserId, CrossSigningKey>, } impl QueryKeysResBody { /// Creates a new `Response` with the given device keys. pub fn new(device_keys: BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceId, DeviceKeys>>) -> Self { Self { device_keys, ..Default::default() } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/device.rs
crates/core/src/federation/device.rs
//! Endpoints to retrieve information about user devices //! `GET /_matrix/federation/*/user/devices/{user_id}` //! //! Get information about a user's devices. //! `/v1/` ([spec]) //! //! [spec]: https://spec.matrix.org/latest/server-server-api/#get_matrixfederationv1userdevicesuser_id use salvo::prelude::*; use serde::{Deserialize, Serialize}; use crate::{ OwnedDeviceId, OwnedUserId, encryption::{CrossSigningKey, DeviceKeys}, }; // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: ServerSignatures, // history: { // 1.0 => "/_matrix/federation/v1/user/devices/:user_id", // } // }; // /// Request type for the `get_devices` endpoint. // pub struct DeviceReqBody { // /// The user ID to retrieve devices for. // /// // /// Must be a user local to the receiving homeserver. // #[salvo(parameter(parameter_in = Path))] // pub user_id: OwnedUserId, // } /// Response type for the `get_devices` endpoint. #[derive(ToSchema, Serialize, Debug)] pub struct DevicesResBody { /// The user ID devices were requested for. pub user_id: OwnedUserId, /// A unique ID for a given user_id which describes the version of the /// returned device list. /// /// This is matched with the `stream_id` field in `m.device_list_update` /// EDUs in order to incrementally update the returned device_list. pub stream_id: u64, /// The user's devices. pub devices: Vec<Device>, /// The user's master key. #[serde(skip_serializing_if = "Option::is_none")] pub master_key: Option<CrossSigningKey>, /// The users's self-signing key. #[serde(skip_serializing_if = "Option::is_none")] pub self_signing_key: Option<CrossSigningKey>, } impl DevicesResBody { /// Creates a new `Response` with the given user id and stream id. /// /// The device list will be empty. pub fn new(user_id: OwnedUserId, stream_id: u64) -> Self { Self { user_id, stream_id, devices: Vec::new(), master_key: None, self_signing_key: None, } } } /// Information about a user's device. #[derive(ToSchema, Clone, Debug, Serialize, Deserialize)] pub struct Device { /// The device ID. pub device_id: OwnedDeviceId, /// Identity keys for the device. pub keys: DeviceKeys, /// Optional display name for the device #[serde(skip_serializing_if = "Option::is_none")] pub device_display_name: Option<String>, } impl Device { /// Creates a new `Device` with the given device id and keys. pub fn new(device_id: OwnedDeviceId, keys: DeviceKeys) -> Self { Self { device_id, keys, device_display_name: None, } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/third_party.rs
crates/core/src/federation/third_party.rs
/// Module for dealing with third party identifiers /// /// `PUT /_matrix/federation/*/3pid/onbind` /// /// Used by identity servers to notify the homeserver that one of its users has /// bound a third party identifier successfully, including any pending room /// invites the identity server has been made aware of. /// `/v1/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/server-server-api/#put_matrixfederationv13pidonbind use std::collections::BTreeMap; use salvo::prelude::*; use serde::{Deserialize, Serialize}; use crate::{ OwnedRoomId, OwnedServerName, OwnedServerSigningKeyId, OwnedUserId, events::StateEventType, third_party::Medium, }; // const METADATA: Metadata = metadata! { // method: PUT, // rate_limited: false, // authentication: None, // history: { // 1.0 => "/_matrix/federation/v1/3pid/onbind", // } // }; /// Request type for the `bind_callback` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct BindCallbackReqBody { /// The type of third party identifier. /// /// Currently only `Medium::Email` is supported. pub medium: Medium, /// The third party identifier itself. /// /// For example: an email address. pub address: String, /// The user that is now bound to the third party identifier. pub mxid: OwnedUserId, /// A list of pending invites that the third party identifier has received. pub invites: Vec<ThirdPartyInvite>, } /// A pending invite the third party identifier has received. #[derive(ToSchema, Debug, Clone, Deserialize, Serialize)] pub struct ThirdPartyInvite { /// The type of third party invite issues. /// /// Currently only `Medium::Email` is used. pub medium: Medium, /// The third party identifier that received the invite. pub address: String, /// The now-bound user ID that received the invite. pub mxid: OwnedUserId, /// The room ID the invite is valid for. pub room_id: OwnedRoomId, /// The user ID that sent the invite. pub sender: OwnedUserId, /// Signature from the identity server using a long-term private key. pub signed: BTreeMap<OwnedServerName, BTreeMap<OwnedServerSigningKeyId, String>>, } impl ThirdPartyInvite { /// Creates a new third party invite with the given parameters. pub fn new( address: String, mxid: OwnedUserId, room_id: OwnedRoomId, sender: OwnedUserId, signed: BTreeMap<OwnedServerName, BTreeMap<OwnedServerSigningKeyId, String>>, ) -> Self { Self { medium: Medium::Email, address, mxid, room_id, sender, signed, } } } // /// `PUT /_matrix/federation/*/exchange_third_party_invite/{room_id}` // /// // /// The receiving server will verify the partial `m.room.member` event given in // /// the request body. If valid, the receiving server will issue an invite as per // /// the [Inviting to a room] section before returning a response to this // /// request. // /// // /// [Inviting to a room]: https://spec.matrix.org/latest/server-server-api/#inviting-to-a-room // /// `/v1/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/server-server-api/#put_matrixfederationv1exchange_third_party_inviteroomid // const METADATA: Metadata = metadata! { // method: PUT, // rate_limited: false, // authentication: AccessToken, // history: { // 1.0 => "/_matrix/federation/v1/exchange_third_party_invite/:room_id", // } // }; /// Request type for the `exchange_invite` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct ExchangeInviteReqBody { /// The room ID to exchange a third party invite in. #[salvo(parameter(parameter_in = Path))] pub room_id: OwnedRoomId, /// The event type. /// /// Must be `StateEventType::RoomMember`. #[serde(rename = "type")] pub kind: StateEventType, /// The user ID of the user who sent the original invite event. pub sender: OwnedUserId, /// The user ID of the invited user. pub state_key: OwnedUserId, /// The content of the invite event. pub content: ThirdPartyInvite, } impl ExchangeInviteReqBody { /// Creates a new `Request` for a third party invite exchange pub fn new( room_id: OwnedRoomId, sender: OwnedUserId, state_key: OwnedUserId, content: ThirdPartyInvite, ) -> Self { Self { room_id, kind: StateEventType::RoomMember, sender, state_key, content, } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/media.rs
crates/core/src/federation/media.rs
use std::fmt::Write; /// Endpoints for the media repository. use std::time::Duration; use bytes::BytesMut; use reqwest::Url; use salvo::{ oapi::{ToParameters, ToSchema}, prelude::*, }; use serde::{Deserialize, Serialize}; use crate::{ http_headers::ContentDisposition, media::ResizeMethod, sending::{SendRequest, SendResult}, }; /// The `multipart/mixed` mime "essence". const MULTIPART_MIXED: &str = "multipart/mixed"; /// The maximum number of headers to parse in a body part. const MAX_HEADERS_COUNT: usize = 32; /// The length of the generated boundary. const GENERATED_BOUNDARY_LENGTH: usize = 30; /// `/v1/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/server-server-api/#get_matrixfederationv1mediathumbnailmediaid pub fn thumbnail_request(origin: &str, args: ThumbnailReqArgs) -> SendResult<SendRequest> { let mut url = Url::parse(&format!( "{origin}/_matrix/federation/v1/media/thumbnail/{}", args.media_id ))?; { let mut query = url.query_pairs_mut(); query.append_pair("width", &args.width.to_string()); query.append_pair("height", &args.height.to_string()); query.append_pair("timeout_ms", &args.timeout_ms.as_millis().to_string()); } Ok(crate::sending::get(url)) } /// Request type for the `get_content_thumbnail` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct ThumbnailReqArgs { /// The media ID from the mxc:// URI (the path component). #[salvo(parameter(parameter_in = Path))] pub media_id: String, /// The desired resizing method. #[salvo(parameter(parameter_in = Query))] #[serde(default, skip_serializing_if = "Option::is_none")] pub method: Option<ResizeMethod>, /// The *desired* width of the thumbnail. /// /// The actual thumbnail may not match the size specified. #[salvo(parameter(parameter_in = Query))] pub width: u32, /// The *desired* height of the thumbnail. /// /// The actual thumbnail may not match the size specified. #[salvo(parameter(parameter_in = Query))] pub height: u32, /// The maximum duration that the client is willing to wait to start /// receiving data, in the case that the content has not yet been /// uploaded. /// /// The default value is 20 seconds. #[salvo(parameter(parameter_in = Query))] #[serde( with = "crate::serde::duration::ms", default = "crate::client::media::default_download_timeout", skip_serializing_if = "crate::media::is_default_download_timeout" )] pub timeout_ms: Duration, /// Whether the server should return an animated thumbnail. /// /// When `Some(true)`, the server should return an animated thumbnail if /// possible and supported. When `Some(false)`, the server must not /// return an animated thumbnail. When `None`, the server should not /// return an animated thumbnail. #[salvo(parameter(parameter_in = Query))] #[serde(skip_serializing_if = "Option::is_none")] pub animated: Option<bool>, } /// Response type for the `get_content_thumbnail` endpoint. #[derive(ToSchema, Debug)] pub struct ThumbnailResBody { /// The metadata of the thumbnail. pub metadata: ContentMetadata, /// The content of the thumbnail. pub content: FileOrLocation, } impl Scribe for ThumbnailResBody { /// Serialize the given metadata and content into a `http::Response` /// `multipart/mixed` body. /// /// Returns a tuple containing the boundary used fn render(self, res: &mut Response) { use rand::Rng as _; let boundary = rand::rng() .sample_iter(&rand::distr::Alphanumeric) .map(char::from) .take(GENERATED_BOUNDARY_LENGTH) .collect::<String>(); let mut body_writer = BytesMut::new(); // Add first boundary separator and header for the metadata. let _ = write!( body_writer, "\r\n--{boundary}\r\n{}: {}\r\n\r\n", http::header::CONTENT_TYPE, mime::APPLICATION_JSON ); // Add serialized metadata. match serde_json::to_vec(&self.metadata) { Ok(bytes) => { body_writer.extend_from_slice(&bytes); } Err(e) => { error!("Failed to serialize metadata: {}", e); res.render( StatusError::internal_server_error().brief("Failed to serialize metadata"), ); return; } } // Add second boundary separator. let _ = write!(body_writer, "\r\n--{boundary}\r\n"); // Add content. match self.content { FileOrLocation::File(content) => { // Add headers. let content_type = content .content_type .as_deref() .unwrap_or(mime::APPLICATION_OCTET_STREAM.as_ref()); let _ = write!( body_writer, "{}: {content_type}\r\n", http::header::CONTENT_TYPE ); if let Some(content_disposition) = &content.content_disposition { let _ = write!( body_writer, "{}: {content_disposition}\r\n", http::header::CONTENT_DISPOSITION ); } // Add empty line separator after headers. body_writer.extend_from_slice(b"\r\n"); // Add bytes. body_writer.extend_from_slice(&content.file); } FileOrLocation::Location(location) => { // Only add location header and empty line separator. let _ = write!( body_writer, "{}: {location}\r\n\r\n", http::header::LOCATION ); } } // Add final boundary. let _ = write!(body_writer, "\r\n--{boundary}--"); let content_type = format!("{MULTIPART_MIXED}; boundary={boundary}"); let _ = res.add_header(http::header::CONTENT_TYPE, content_type, true); if let Err(e) = res.write_body(body_writer) { res.render(StatusError::internal_server_error().brief("Failed to set response body")); error!("Failed to set response body: {}", e); } } } // /// `/v1/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/server-server-api/#get_matrixfederationv1mediadownloadmediaid // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: None, // history: { // 1.0 => "/_matrix/media/r0/download/:server_name/:media_id", // 1.1 => "/_matrix/media/v3/download/:server_name/:media_id", // } // }; pub fn content_request(origin: &str, args: ContentReqArgs) -> SendResult<SendRequest> { let url = Url::parse(&format!( "{origin}/_matrix/federation/v1/media/download/{}?timeout_ms={}", args.media_id, args.timeout_ms.as_millis() ))?; Ok(crate::sending::get(url)) } /// Request type for the `get_media_content` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct ContentReqArgs { /// The media ID from the mxc:// URI (the path component). #[salvo(parameter(parameter_in = Path))] pub media_id: String, /// The maximum duration that the client is willing to wait to start /// receiving data, in the case that the content has not yet been /// uploaded. /// /// The default value is 20 seconds. #[salvo(parameter(parameter_in = Query))] #[serde( with = "crate::serde::duration::ms", default = "crate::client::media::default_download_timeout", skip_serializing_if = "crate::client::media::is_default_download_timeout" )] pub timeout_ms: Duration, } /// Response type for the `get_content` endpoint. #[derive(ToSchema, Serialize, Debug)] pub struct ContentResBody { /// The metadata of the media. pub metadata: ContentMetadata, /// The content of the media. pub content: FileOrLocation, } /// A file from the content repository or the location where it can be found. #[derive(ToSchema, Serialize, Debug, Clone)] pub enum FileOrLocation { /// The content of the file. File(Content), /// The file is at the given URL. Location(String), } /// The content of a file from the content repository. #[derive(ToSchema, Serialize, Debug, Clone)] pub struct Content { /// The content of the file as bytes. pub file: Vec<u8>, /// The content type of the file that was previously uploaded. pub content_type: Option<String>, /// The value of the `Content-Disposition` HTTP header, possibly containing /// the name of the file that was previously uploaded. pub content_disposition: Option<ContentDisposition>, } /// The metadata of a file from the content repository. #[derive(ToSchema, Serialize, Deserialize, Debug, Clone, Default)] pub struct ContentMetadata {} impl ContentMetadata { /// Creates a new empty `ContentMetadata`. pub fn new() -> Self { Self {} } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/backfill.rs
crates/core/src/federation/backfill.rs
//! Endpoints to request more history from another homeserver. //! `GET /_matrix/federation/*/backfill/{room_id}` //! //! Get more history from another homeserver. //! `/v1/` ([spec]) //! //! [spec]: https://spec.matrix.org/latest/server-server-api/#get_matrixfederationv1backfillroomid use reqwest::Url; use salvo::prelude::*; use serde::{Deserialize, Serialize}; use crate::{ OwnedEventId, OwnedRoomId, OwnedServerName, UnixMillis, sending::{SendRequest, SendResult}, serde::RawJsonValue, }; // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: ServerSignatures, // history: { // 1.0 => "/_matrix/federation/v1/backfill/:room_id", // } // }; pub fn backfill_request(origin: &str, args: BackfillReqArgs) -> SendResult<SendRequest> { let mut url = Url::parse(&format!( "{origin}/_matrix/federation/v1/backfill/{}", &args.room_id, ))?; url.query_pairs_mut() .append_pair("limit", &args.limit.to_string()); for event_id in args.v { url.query_pairs_mut().append_pair("v", event_id.as_ref()); } Ok(crate::sending::get(url)) } /// Request type for the `get_backfill` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct BackfillReqArgs { /// The room ID to backfill. #[salvo(parameter(parameter_in = Path))] pub room_id: OwnedRoomId, /// The event IDs to backfill from. #[salvo(parameter(parameter_in = Query))] pub v: Vec<OwnedEventId>, /// The maximum number of PDUs to retrieve, including the given events. #[salvo(parameter(parameter_in = Query))] pub limit: usize, } /// Response type for the `get_backfill` endpoint. #[derive(ToSchema, Serialize, Deserialize, Debug)] pub struct BackfillResBody { /// The `server_name` of the homeserver sending this transaction. pub origin: OwnedServerName, /// POSIX timestamp in milliseconds on originating homeserver when this /// transaction started. pub origin_server_ts: UnixMillis, /// List of persistent updates to rooms. #[salvo(schema(value_type = Vec<Object>))] pub pdus: Vec<Box<RawJsonValue>>, } impl BackfillResBody { /// Creates a new `Response` with: /// * the `server_name` of the homeserver. /// * the timestamp in milliseconds of when this transaction started. /// * the list of persistent updates to rooms. pub fn new( origin: OwnedServerName, origin_server_ts: UnixMillis, pdus: Vec<Box<RawJsonValue>>, ) -> Self { Self { origin, origin_server_ts, pdus, } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/knock.rs
crates/core/src/federation/knock.rs
use itertools::Itertools; use reqwest::Url; /// Endpoints for handling room knocking. /// `GET /_matrix/federation/*/make_knock/{room_id}/{user_id}` /// /// Send a request for a knock event template to a resident server. /// `/v1/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/server-server-api/#get_matrixfederationv1make_knockroomiduser_id use salvo::prelude::*; use serde::{Deserialize, Serialize}; use crate::{ OwnedEventId, OwnedRoomId, OwnedUserId, RoomVersionId, events::AnyStrippedStateEvent, sending::{SendRequest, SendResult}, serde::{RawJson, RawJsonValue}, }; // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: ServerSignatures, // history: { // unstable => // "/_matrix/federation/unstable/xyz.amorgan.knock/make_knock/:room_id/:user_id" // , 1.1 => "/_matrix/federation/v1/make_knock/:room_id/:user_id", // } // }; pub fn make_knock_request(origin: &str, args: MakeKnockReqArgs) -> SendResult<SendRequest> { let ver = args.ver.iter().map(|v| format!("ver={v}")).join("&"); let ver = if ver.is_empty() { "" } else { &*format!("?{ver}") }; let url = Url::parse(&format!( "{origin}/_matrix/federation/v1/make_knock/{}/{}{ver}", args.room_id, args.user_id ))?; Ok(crate::sending::get(url)) } /// Request type for the `create_knock_event_template` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct MakeKnockReqArgs { /// The room ID that should receive the knock. #[salvo(parameter(parameter_in = Path))] pub room_id: OwnedRoomId, /// The user ID the knock event will be for. #[salvo(parameter(parameter_in = Path))] pub user_id: OwnedUserId, /// The room versions the sending has support for. /// /// Defaults to `vec![RoomVersionId::V1]`. #[salvo(parameter(parameter_in = Query))] pub ver: Vec<RoomVersionId>, } /// Response type for the `create_knock_event_template` endpoint. #[derive(ToSchema, Serialize, Deserialize, Debug)] pub struct MakeKnockResBody { /// The version of the room where the server is trying to knock. pub room_version: RoomVersionId, /// An unsigned template event. /// /// May differ between room versions. #[salvo(schema(value_type = Object, additional_properties = true))] pub event: Box<RawJsonValue>, } impl MakeKnockResBody { /// Creates a new `Response` with the given room version ID and event. pub fn new(room_version: RoomVersionId, event: Box<RawJsonValue>) -> Self { Self { room_version, event, } } } // /// `PUT /_matrix/federation/*/send_knock/{room_id}/{event_id}` // /// // /// Submits a signed knock event to the resident homeserver for it to accept // /// into the room's graph. `/v1/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/server-server-api/#put_matrixfederationv1send_knockroomideventid // const METADATA: Metadata = metadata! { // method: PUT, // rate_limited: false, // authentication: ServerSignatures, // history: { // unstable => // "/_matrix/federation/unstable/xyz.amorgan.knock/send_knock/:room_id/: // event_id", 1.1 => // "/_matrix/federation/v1/send_knock/:room_id/:event_id", } // }; pub fn send_knock_request( origin: &str, args: SendKnockReqArgs, body: SendKnockReqBody, ) -> SendResult<SendRequest> { let url = Url::parse(&format!( "{origin}/_matrix/federation/v1/send_knock/{}/{}", args.room_id, args.event_id ))?; crate::sending::put(url).stuff(body) } #[derive(ToParameters, Deserialize, Debug)] pub struct SendKnockReqArgs { /// The room ID that should receive the knock. #[salvo(parameter(parameter_in = Path))] pub room_id: OwnedRoomId, /// The user ID the knock event will be for. #[salvo(parameter(parameter_in = Path))] pub event_id: OwnedEventId, } /// Request type for the `send_knock` endpoint. #[derive(ToSchema, Serialize, Deserialize, Debug)] #[salvo(schema(value_type = Object))] pub struct SendKnockReqBody(pub Box<RawJsonValue>); impl SendKnockReqBody { /// Creates a new `Request` with the given PDU. pub fn new(pdu: Box<RawJsonValue>) -> Self { Self(pdu) } } crate::json_body_modifier!(SendKnockReqBody); /// Response type for the `send_knock` endpoint. #[derive(ToSchema, Serialize, Deserialize, Debug)] pub struct SendKnockResBody { /// State events providing public room metadata. pub knock_room_state: Vec<RawJson<AnyStrippedStateEvent>>, } impl SendKnockResBody { /// Creates a new `Response` with the given public room metadata state /// events. pub fn new(knock_room_state: Vec<RawJson<AnyStrippedStateEvent>>) -> Self { Self { knock_room_state } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/membership.rs
crates/core/src/federation/membership.rs
//! Room membership endpoints. use itertools::Itertools; use reqwest::Url; use salvo::prelude::*; use serde::{Deserialize, Serialize}; use crate::{ UnixMillis, events::{AnyStrippedStateEvent, StateEventType, room::member::RoomMemberEventContent}, identifiers::*, sending::{SendRequest, SendResult}, serde::{RawJson, RawJsonValue}, }; pub fn invite_user_request_v2( origin: &str, args: InviteUserReqArgs, body: InviteUserReqBodyV2, ) -> SendResult<SendRequest> { let url = Url::parse(&format!( "{origin}/_matrix/federation/v2/invite/{}/{}", args.room_id, args.event_id ))?; crate::sending::put(url).stuff(body) } #[derive(ToParameters, Deserialize, Debug)] pub struct InviteUserReqArgs { /// The room ID that is about to be joined. /// /// Do not use this. Instead, use the `room_id` field inside the PDU. #[salvo(parameter(parameter_in = Path))] pub room_id: OwnedRoomId, /// The event ID for the join event. #[salvo(parameter(parameter_in = Path))] pub event_id: OwnedEventId, } #[derive(ToSchema, Deserialize, Serialize, Debug)] pub struct InviteUserReqBodyV2 { // /// The room ID that the user is being invited to. // #[salvo(parameter(parameter_in = Path))] // pub room_id: OwnedRoomId, // /// The event ID for the invite event, generated by the inviting server. // #[salvo(parameter(parameter_in = Path))] // pub event_id: OwnedEventId, /// The version of the room where the user is being invited to. pub room_version: RoomVersionId, /// The invite event which needs to be signed. #[salvo(schema(value_type = Object, additional_properties = true))] pub event: Box<RawJsonValue>, /// An optional list of simplified events to help the receiver of the invite /// identify the room. pub invite_room_state: Vec<RawJson<AnyStrippedStateEvent>>, /// An optional list of servers the invited homeserver should attempt to /// join or leave via, according to [MSC4125](https://github.com/matrix-org/matrix-spec-proposals/pull/4125). /// /// If present, it must not be empty. #[serde( skip_serializing_if = "Option::is_none", rename = "org.matrix.msc4125.via" )] pub via: Option<Vec<OwnedServerName>>, } crate::json_body_modifier!(InviteUserReqBodyV2); #[derive(ToSchema, Deserialize, Debug)] pub struct InviteUserReqBodyV1 { /// The matrix ID of the user who sent the original /// `m.room.third_party_invite`. pub sender: OwnedUserId, /// The name of the inviting homeserver. pub origin: OwnedServerName, /// A timestamp added by the inviting homeserver. pub origin_server_ts: UnixMillis, /// The value `m.room.member`. #[serde(rename = "type")] pub kind: StateEventType, /// The user ID of the invited member. pub state_key: OwnedUserId, /// The content of the event. pub content: RoomMemberEventContent, /// Information included alongside the event that is not signed. #[serde(default, skip_serializing_if = "UnsignedEventContent::is_empty")] pub unsigned: UnsignedEventContentV1, } #[derive(ToSchema, Serialize, Deserialize, Debug)] pub struct InviteUserResBodyV2 { /// The signed invite event. #[salvo(schema(value_type = Object))] pub event: Box<RawJsonValue>, } #[derive(ToSchema, Serialize, Debug)] pub struct InviteUserResBodyV1 { /// The signed invite event. #[serde(with = "crate::federation::serde::v1_pdu")] #[salvo(schema(value_type = Object))] pub event: Box<RawJsonValue>, } #[derive(ToSchema, Deserialize, Serialize, Debug)] #[salvo(schema(value_type = Object))] pub struct SendJoinReqBody( /// The invite event which needs to be signed. pub Box<RawJsonValue>, ); crate::json_body_modifier!(SendJoinReqBody); #[derive(ToSchema, Deserialize, Serialize, Debug)] pub struct SendJoinResBodyV2( /// The signed invite event. pub RoomStateV2, ); #[derive(ToSchema, Serialize, Debug)] pub struct SendJoinResBodyV1( /// Full state of the room. pub RoomStateV1, ); impl SendJoinResBodyV1 { /// Creates a new `Response` with the given room state. pub fn new(room_state: RoomStateV1) -> Self { Self(room_state) } } /// Full state of the room. #[derive(ToSchema, Deserialize, Serialize, Default, Clone, Debug)] pub struct RoomStateV2 { /// Whether `m.room.member` events have been omitted from `state`. /// /// Defaults to `false`. #[serde(default, skip_serializing_if = "crate::serde::is_default")] pub members_omitted: bool, /// The full set of authorization events that make up the state of the room, /// and their authorization events, recursively. /// /// If the request had `omit_members` set to `true`, then any events that /// are returned in `state` may be omitted from `auth_chain`, whether or /// not membership events are omitted from `state`. #[salvo(schema(value_type = Vec<Object>))] pub auth_chain: Vec<Box<RawJsonValue>>, /// The room state. /// /// If the request had `omit_members` set to `true`, events of type /// `m.room.member` may be omitted from the response to reduce the size /// of the response. If this is done, `members_omitted` must be set to /// `true`. #[salvo(schema(value_type = Object))] pub state: Vec<Box<RawJsonValue>>, /// The signed copy of the membership event sent to other servers by the /// resident server, including the resident server's signature. /// /// Required if the room version supports restricted join rules. #[serde(skip_serializing_if = "Option::is_none")] #[salvo(schema(value_type = Object))] pub event: Option<Box<RawJsonValue>>, /// A list of the servers active in the room (ie, those with joined members) /// before the join. /// /// Required if `members_omitted` is set to `true`. #[serde(skip_serializing_if = "Option::is_none")] pub servers_in_room: Option<Vec<String>>, } impl RoomStateV2 { /// Creates an empty `RoomState` with the given `origin`. /// /// With the `unstable-unspecified` feature, this method doesn't take any /// parameters. See [matrix-spec#374](https://github.com/matrix-org/matrix-spec/issues/374). pub fn new() -> Self { Default::default() } } /// Full state of the room. #[derive(ToSchema, Deserialize, Serialize, Default, Clone, Debug)] pub struct RoomStateV1 { /// The full set of authorization events that make up the state of the room, /// and their authorization events, recursively. #[salvo(schema(value_type = Vec<Object>))] pub auth_chain: Vec<Box<RawJsonValue>>, /// The room state. #[salvo(schema(value_type = Vec<Object>))] pub state: Vec<Box<RawJsonValue>>, /// The signed copy of the membership event sent to other servers by the /// resident server, including the resident server's signature. /// /// Required if the room version supports restricted join rules. #[serde(skip_serializing_if = "Option::is_none")] #[salvo(schema(value_type = Vec<Object>))] pub event: Option<Box<RawJsonValue>>, } impl RoomStateV1 { /// Creates an empty `RoomState` with the given `origin`. /// /// With the `unstable-unspecified` feature, this method doesn't take any /// parameters. See [matrix-spec#374](https://github.com/matrix-org/matrix-spec/issues/374). pub fn new() -> Self { Default::default() } } /// Information included alongside an event that is not signed. #[derive(ToSchema, Clone, Debug, Default, Serialize, Deserialize)] pub struct UnsignedEventContentV1 { /// An optional list of simplified events to help the receiver of the invite /// identify the room. The recommended events to include are the join /// rules, canonical alias, avatar, and name of the room. #[serde(skip_serializing_if = "<[_]>::is_empty")] #[salvo(schema(value_type = Vec<Object>))] pub invite_room_state: Vec<RawJson<AnyStrippedStateEvent>>, } impl UnsignedEventContentV1 { /// Creates an empty `UnsignedEventContent`. pub fn new() -> Self { Default::default() } /// Checks whether all of the fields are empty. pub fn is_empty(&self) -> bool { self.invite_room_state.is_empty() } } // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: ServerSignatures, // history: { // 1.0 => "/_matrix/federation/v1/make_leave/:room_id/:user_id", // } // }; pub fn make_leave_request( origin: &str, room_id: &RoomId, user_id: &UserId, ) -> SendResult<SendRequest> { let url = Url::parse(&format!( "{origin}/_matrix/federation/v1/make_leave/{room_id}/{user_id}" ))?; Ok(crate::sending::get(url)) } #[derive(ToParameters, Deserialize, Debug)] pub struct MakeLeaveReqArgs { /// Room in which the event to be reported is located. #[salvo(parameter(parameter_in = Path))] pub room_id: OwnedRoomId, /// Event to report. #[salvo(parameter(parameter_in = Path))] pub user_id: OwnedUserId, } /// Response type for the `get_leave_event` endpoint. #[derive(ToSchema, Serialize, Deserialize, Debug)] pub struct MakeLeaveResBody { /// The version of the room where the server is trying to leave. /// /// If not provided, the room version is assumed to be either "1" or "2". pub room_version: Option<RoomVersionId>, /// An unsigned template event. /// /// Note that events have a different format depending on the room version - /// check the room version specification for precise event formats. #[salvo(schema(value_type = Object, additional_properties = true))] pub event: Box<RawJsonValue>, } impl MakeLeaveResBody { /// Creates a new `Response` with: /// * the version of the room where the server is trying to leave. /// * an unsigned template event. pub fn new(room_version: Option<RoomVersionId>, event: Box<RawJsonValue>) -> Self { Self { room_version, event, } } } // const METADATA: Metadata = metadata! { // method: PUT, // rate_limited: false, // authentication: ServerSignatures, // history: { // 1.0 => "/_matrix/federation/v2/send_leave/:room_id/:event_id", // } // }; pub fn send_leave_request_v2( origin: &str, args: SendLeaveReqArgsV2, body: SendLeaveReqBody, ) -> SendResult<SendRequest> { let url = Url::parse(&format!( "{origin}/_matrix/federation/v2/send_leave/{}/{}", args.room_id, args.event_id ))?; crate::sending::put(url).stuff(body) } #[derive(ToParameters, Deserialize, Serialize, Debug)] pub struct SendLeaveReqArgsV2 { /// The room ID that is about to be left. /// /// Do not use this. Instead, use the `room_id` field inside the PDU. #[salvo(parameter(parameter_in = Path))] pub room_id: OwnedRoomId, /// The event ID for the leave event. #[salvo(parameter(parameter_in = Path))] pub event_id: OwnedEventId, } /// Request type for the `create_leave_event` endpoint. #[derive(ToSchema, Deserialize, Serialize, Debug)] #[salvo(schema(value_type = Object))] pub struct SendLeaveReqBody( /// The PDU. pub Box<RawJsonValue>, ); crate::json_body_modifier!(SendLeaveReqBody); // /// `PUT /_matrix/federation/*/send_join/{room_id}/{event_id}` // /// // /// Send a join event to a resident server. // const METADATA: Metadata = metadata! { // method: PUT, // rate_limited: false, // authentication: ServerSignatures, // history: { // 1.0 => "/_matrix/federation/v2/send_join/:room_id/:event_id", // } // }; pub fn send_join_request( origin: &str, args: SendJoinArgs, body: SendJoinReqBody, ) -> SendResult<SendRequest> { let url = Url::parse(&format!( "{origin}/_matrix/federation/v2/send_join/{}/{}?omit_members={}", &args.room_id, &args.event_id, args.omit_members ))?; crate::sending::put(url).stuff(body) } /// Request type for the `create_join_event` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct SendJoinArgs { /// The room ID that is about to be joined. /// /// Do not use this. Instead, use the `room_id` field inside the PDU. #[salvo(parameter(parameter_in = Path))] pub room_id: OwnedRoomId, /// The event ID for the join event. #[salvo(parameter(parameter_in = Path))] pub event_id: OwnedEventId, /// Indicates whether the calling server can accept a reduced response. /// /// If `true`, membership events are omitted from `state` and redundant /// events are omitted from `auth_chain` in the response. /// /// If the room to be joined has no `m.room.name` nor /// `m.room.canonical_alias` events in its current state, the resident /// server should determine the room members who would be included in /// the `m.heroes` property of the room summary as defined in the /// [Client-Server `/sync` response]. The resident server should include /// these members' membership events in the response `state` field, and /// include the auth chains for these membership events in the response /// `auth_chain` field. /// /// [Client-Server `/sync` response]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3sync #[salvo(parameter(parameter_in = Query))] #[serde(default, skip_serializing_if = "crate::serde::is_default")] pub omit_members: bool, } // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: ServerSignatures, // history: { // 1.0 => "/_matrix/federation/v1/make_join/:room_id/:user_id", // } // }; pub fn make_join_request(origin: &str, args: MakeJoinReqArgs) -> SendResult<SendRequest> { let ver = args.ver.iter().map(|v| format!("ver={v}")).join("&"); let ver = if ver.is_empty() { "" } else { &*format!("?{ver}") }; let url = Url::parse(&format!( "{origin}/_matrix/federation/v1/make_join/{}/{}{}", args.room_id, args.user_id, ver ))?; Ok(crate::sending::get(url)) } /// Request type for the `create_join_event_template` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct MakeJoinReqArgs { /// The room ID that is about to be joined. #[salvo(parameter(parameter_in = Path))] pub room_id: OwnedRoomId, /// The user ID the join event will be for. #[salvo(parameter(parameter_in = Path))] pub user_id: OwnedUserId, /// The room versions the sending server has support for. /// /// Defaults to `&[RoomVersionId::V1]`. #[salvo(parameter(parameter_in = Query))] #[serde(default = "default_ver", skip_serializing_if = "is_default_ver")] pub ver: Vec<RoomVersionId>, } /// Response type for the `create_join_event_template` endpoint. #[derive(ToSchema, Serialize, Deserialize, Debug)] pub struct MakeJoinResBody { /// The version of the room where the server is trying to join. #[serde(skip_serializing_if = "Option::is_none")] pub room_version: Option<RoomVersionId>, /// An unsigned template event. #[salvo(schema(value_type = Object, additional_properties = true))] pub event: Box<RawJsonValue>, } impl MakeJoinResBody { /// Creates a new `Response` with the given template event. pub fn new(event: Box<RawJsonValue>) -> Self { Self { room_version: None, event, } } } fn default_ver() -> Vec<RoomVersionId> { vec![RoomVersionId::V1] } fn is_default_ver(ver: &[RoomVersionId]) -> bool { *ver == [RoomVersionId::V1] }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/authentication.rs
crates/core/src/federation/authentication.rs
//! Common types for implementing federation authorization. use std::{fmt, str::FromStr}; use crate::serde::CanonicalJsonObject; use crate::signatures::{Ed25519KeyPair, KeyPair, PublicKeyMap}; use crate::{ IdParseError, OwnedServerName, OwnedServerSigningKeyId, ServerName, auth_scheme::AuthScheme, http_headers::quote_ascii_string_if_required, serde::{Base64, Base64DecodeError}, }; use http::HeaderValue; use http_auth::ChallengeParser; use salvo::http::headers::authorization::Credentials; use thiserror::Error; use tracing::debug; /// Authentication is performed by adding an `X-Matrix` header including a signature in the request /// headers, as defined in the [Matrix Server-Server API][spec]. /// /// [spec]: https://spec.matrix.org/latest/server-server-api/#request-authentication #[derive(Debug, Clone, Copy, Default)] #[allow(clippy::exhaustive_structs)] pub struct ServerSignatures; impl AuthScheme for ServerSignatures { type Input<'a> = ServerSignaturesInput<'a>; type AddAuthenticationError = XMatrixFromRequestError; type Output = XMatrix; type ExtractAuthenticationError = XMatrixExtractError; fn add_authentication<T: AsRef<[u8]>>( request: &mut http::Request<T>, input: ServerSignaturesInput<'_>, ) -> Result<(), Self::AddAuthenticationError> { let authorization = HeaderValue::from(&XMatrix::try_from_http_request(request, input)?); request .headers_mut() .insert(http::header::AUTHORIZATION, authorization); Ok(()) } fn extract_authentication<T: AsRef<[u8]>>( request: &http::Request<T>, ) -> Result<Self::Output, Self::ExtractAuthenticationError> { let value = request .headers() .get(http::header::AUTHORIZATION) .ok_or(XMatrixExtractError::MissingAuthorizationHeader)?; Ok(value.try_into()?) } } /// The input necessary to generate the [`ServerSignatures`] authentication scheme. #[derive(Debug, Clone)] #[non_exhaustive] pub struct ServerSignaturesInput<'a> { /// The server making the request. pub origin: OwnedServerName, /// The server receiving the request. pub destination: OwnedServerName, /// The key pair to use to sign the request. pub key_pair: &'a Ed25519KeyPair, } impl<'a> ServerSignaturesInput<'a> { /// Construct a new `ServerSignaturesInput` with the given origin and key pair. pub fn new( origin: OwnedServerName, destination: OwnedServerName, key_pair: &'a Ed25519KeyPair, ) -> Self { Self { origin, destination, key_pair, } } } /// Typed representation of an `Authorization` header of scheme `X-Matrix`, as defined in the /// [Matrix Server-Server API][spec]. /// /// [spec]: https://spec.matrix.org/latest/server-server-api/#request-authentication #[derive(Clone)] #[non_exhaustive] pub struct XMatrix { /// The server name of the sending server. pub origin: OwnedServerName, /// The server name of the receiving sender. /// /// For compatibility with older servers, recipients should accept requests without this /// parameter, but MUST always send it. If this property is included, but the value does /// not match the receiving server's name, the receiving server must deny the request with /// an HTTP status code 401 Unauthorized. pub destination: Option<OwnedServerName>, /// The ID - including the algorithm name - of the sending server's key that was used to sign /// the request. pub key: OwnedServerSigningKeyId, /// The signature of the JSON. pub sig: Base64, } impl XMatrix { /// Construct a new X-Matrix Authorization header. pub fn new( origin: OwnedServerName, destination: OwnedServerName, key: OwnedServerSigningKeyId, sig: Base64, ) -> Self { Self { origin, destination: Some(destination), key, sig, } } /// Parse an X-Matrix Authorization header from the given string. pub fn parse(s: impl AsRef<str>) -> Result<Self, XMatrixParseError> { let parser = ChallengeParser::new(s.as_ref()); let mut xmatrix = None; for challenge in parser { let challenge = challenge?; if challenge.scheme.eq_ignore_ascii_case(XMatrix::SCHEME) { xmatrix = Some(challenge); break; } } let Some(xmatrix) = xmatrix else { return Err(XMatrixParseError::NotFound); }; let mut origin = None; let mut destination = None; let mut key = None; let mut sig = None; for (name, value) in xmatrix.params { if name.eq_ignore_ascii_case("origin") { if origin.is_some() { return Err(XMatrixParseError::DuplicateParameter("origin".to_owned())); } else { origin = Some(OwnedServerName::try_from(value.to_unescaped())?); } } else if name.eq_ignore_ascii_case("destination") { if destination.is_some() { return Err(XMatrixParseError::DuplicateParameter( "destination".to_owned(), )); } else { destination = Some(OwnedServerName::try_from(value.to_unescaped())?); } } else if name.eq_ignore_ascii_case("key") { if key.is_some() { return Err(XMatrixParseError::DuplicateParameter("key".to_owned())); } else { key = Some(OwnedServerSigningKeyId::try_from(value.to_unescaped())?); } } else if name.eq_ignore_ascii_case("sig") { if sig.is_some() { return Err(XMatrixParseError::DuplicateParameter("sig".to_owned())); } else { sig = Some(Base64::parse(value.to_unescaped())?); } } else { debug!("Unknown parameter {name} in X-Matrix Authorization header"); } } Ok(Self { origin: origin .ok_or_else(|| XMatrixParseError::MissingParameter("origin".to_owned()))?, destination, key: key.ok_or_else(|| XMatrixParseError::MissingParameter("key".to_owned()))?, sig: sig.ok_or_else(|| XMatrixParseError::MissingParameter("sig".to_owned()))?, }) } /// Construct the canonical JSON object representation of the request to sign for the `XMatrix` /// scheme. pub fn request_object<T: AsRef<[u8]>>( request: &http::Request<T>, origin: &ServerName, destination: &ServerName, ) -> Result<CanonicalJsonObject, serde_json::Error> { let body = request.body().as_ref(); let uri = request .uri() .path_and_query() .expect("http::Request should have a path"); let mut request_object = CanonicalJsonObject::from([ ("destination".to_owned(), destination.as_str().into()), ("method".to_owned(), request.method().as_str().into()), ("origin".to_owned(), origin.as_str().into()), ("uri".to_owned(), uri.as_str().into()), ]); if !body.is_empty() { let content = serde_json::from_slice(body)?; request_object.insert("content".to_owned(), content); } Ok(request_object) } /// Try to construct this header from the given HTTP request and input. pub fn try_from_http_request<T: AsRef<[u8]>>( request: &http::Request<T>, input: ServerSignaturesInput<'_>, ) -> Result<Self, XMatrixFromRequestError> { let ServerSignaturesInput { origin, destination, key_pair, } = input; let request_object = Self::request_object(request, &origin, &destination)?; // The spec says to use the algorithm to sign JSON, so we could use // crate::signatures::sign_json, however since we would need to extract the signature from the // JSON afterwards let's be a bit more efficient about it. let serialized_request_object = serde_json::to_vec(&request_object)?; let (key_id, signature) = key_pair.sign(&serialized_request_object).into_parts(); let key = OwnedServerSigningKeyId::try_from(key_id.as_str()) .map_err(XMatrixFromRequestError::SigningKeyId)?; let sig = Base64::new(signature); Ok(Self { origin, destination: Some(destination), key, sig, }) } /// Verify that the signature in the `sig` field is valid for the given incoming HTTP request, /// with the given public keys map from the origin. pub fn verify_request<T: AsRef<[u8]>>( &self, request: &http::Request<T>, destination: &ServerName, public_key_map: &PublicKeyMap, ) -> Result<(), XMatrixVerificationError> { if self .destination .as_deref() .is_some_and(|xmatrix_destination| xmatrix_destination != destination) { return Err(XMatrixVerificationError::DestinationMismatch); } let mut request_object = Self::request_object(request, &self.origin, destination) .map_err(|error| crate::signatures::Error::Json(error.into()))?; let entity_signature = CanonicalJsonObject::from([(self.key.to_string(), self.sig.encode().into())]); let signatures = CanonicalJsonObject::from([(self.origin.to_string(), entity_signature.into())]); request_object.insert("signatures".to_owned(), signatures.into()); Ok(crate::signatures::verify_json( public_key_map, &request_object, )?) } } impl fmt::Debug for XMatrix { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("XMatrix") .field("origin", &self.origin) .field("destination", &self.destination) .field("key", &self.key) .finish_non_exhaustive() } } impl fmt::Display for XMatrix { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let Self { origin, destination, key, sig, } = self; let origin = quote_ascii_string_if_required(origin.as_str()); let key = quote_ascii_string_if_required(key.as_str()); let sig = sig.encode(); let sig = quote_ascii_string_if_required(&sig); write!(f, r#"{} "#, Self::SCHEME)?; if let Some(destination) = destination { let destination = quote_ascii_string_if_required(destination.as_str()); write!(f, r#"destination={destination},"#)?; } write!(f, "key={key},origin={origin},sig={sig}") } } impl FromStr for XMatrix { type Err = XMatrixParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { Self::parse(s) } } impl TryFrom<&HeaderValue> for XMatrix { type Error = XMatrixParseError; fn try_from(value: &HeaderValue) -> Result<Self, Self::Error> { Self::parse(value.to_str()?) } } impl From<&XMatrix> for HeaderValue { fn from(value: &XMatrix) -> Self { value .to_string() .try_into() .expect("header format is static") } } impl Credentials for XMatrix { const SCHEME: &'static str = "X-Matrix"; fn decode(value: &HeaderValue) -> Option<Self> { value.try_into().ok() } fn encode(&self) -> HeaderValue { self.into() } } /// An error when trying to construct an [`XMatrix`] from a [`http::Request`]. #[derive(Debug, Error)] #[non_exhaustive] pub enum XMatrixFromRequestError { /// Failed to construct the request object to sign. #[error("failed to construct request object to sign: {0}")] IntoJson(#[from] serde_json::Error), /// The signing key ID is invalid. #[error("invalid signing key ID: {0}")] SigningKeyId(IdParseError), } /// An error when trying to parse an X-Matrix Authorization header. #[derive(Debug, Error)] #[non_exhaustive] pub enum XMatrixParseError { /// The `HeaderValue` could not be converted to a `str`. #[error(transparent)] ToStr(#[from] http::header::ToStrError), /// The string could not be parsed as a valid Authorization string. #[error("{0}")] ParseStr(String), /// The credentials with the X-Matrix scheme were not found. #[error("X-Matrix credentials not found")] NotFound, /// The parameter value could not be parsed as a Matrix ID. #[error(transparent)] ParseId(#[from] IdParseError), /// The parameter value could not be parsed as base64. #[error(transparent)] ParseBase64(#[from] Base64DecodeError), /// The parameter with the given name was not found. #[error("missing parameter '{0}'")] MissingParameter(String), /// The parameter with the given name was found more than once. #[error("duplicate parameter '{0}'")] DuplicateParameter(String), } impl<'a> From<http_auth::parser::Error<'a>> for XMatrixParseError { fn from(value: http_auth::parser::Error<'a>) -> Self { Self::ParseStr(value.to_string()) } } /// An error when trying to extract an [`XMatrix`] from an HTTP request. #[derive(Debug, Error)] #[non_exhaustive] pub enum XMatrixExtractError { /// No Authorization HTTP header was found, but the endpoint requires a server signature. #[error("no Authorization HTTP header found, but this endpoint requires a server signature")] MissingAuthorizationHeader, /// Failed to convert the header value to an [`XMatrix`]. #[error("failed to parse header value: {0}")] Parse(#[from] XMatrixParseError), } /// An error when trying to verify the signature in an [`XMatrix`] for an HTTP request. #[derive(Debug, Error)] #[non_exhaustive] pub enum XMatrixVerificationError { /// The `destination` in [`XMatrix`] doesn't match the one to verify. #[error("destination in XMatrix doesn't match the one to verify")] DestinationMismatch, /// The signature verification failed. #[error("signature verification failed: {0}")] Signature(#[from] crate::signatures::Error), } // #[cfg(test)] // mod tests { // use crate::{OwnedServerName, serde::Base64}; // use headers::{HeaderValue, authorization::Credentials}; // use super::XMatrix; // #[test] // fn xmatrix_auth_pre_1_3() { // let header = HeaderValue::from_static( // "X-Matrix origin=\"origin.hs.example.com\",key=\"ed25519:key1\",sig=\"dGVzdA==\"", // ); // let origin = "origin.hs.example.com".try_into().unwrap(); // let key = "ed25519:key1".try_into().unwrap(); // let sig = Base64::new(b"test".to_vec()); // let credentials = XMatrix::try_from(&header).unwrap(); // assert_eq!(credentials.origin, origin); // assert_eq!(credentials.destination, None); // assert_eq!(credentials.key, key); // assert_eq!(credentials.sig, sig); // let credentials = XMatrix { // origin, // destination: None, // key, // sig, // }; // assert_eq!( // credentials.encode(), // "X-Matrix key=\"ed25519:key1\",origin=origin.hs.example.com,sig=dGVzdA" // ); // } // #[test] // fn xmatrix_auth_1_3() { // let header = HeaderValue::from_static( // "X-Matrix origin=\"origin.hs.example.com\",destination=\"destination.hs.example.com\",key=\"ed25519:key1\",sig=\"dGVzdA==\"", // ); // let origin: OwnedServerName = "origin.hs.example.com".try_into().unwrap(); // let destination: OwnedServerName = "destination.hs.example.com".try_into().unwrap(); // let key = "ed25519:key1".try_into().unwrap(); // let sig = Base64::new(b"test".to_vec()); // let credentials = XMatrix::try_from(&header).unwrap(); // assert_eq!(credentials.origin, origin); // assert_eq!(credentials.destination, Some(destination.clone())); // assert_eq!(credentials.key, key); // assert_eq!(credentials.sig, sig); // let credentials = XMatrix::new(origin, destination, key, sig); // assert_eq!( // credentials.encode(), // "X-Matrix destination=destination.hs.example.com,key=\"ed25519:key1\",origin=origin.hs.example.com,sig=dGVzdA" // ); // } // #[test] // fn xmatrix_quoting() { // let header = HeaderValue::from_static( // r#"X-Matrix origin="example.com:1234",key="abc\"def\\:ghi",sig=dGVzdA,"#, // ); // let origin: OwnedServerName = "example.com:1234".try_into().unwrap(); // let key = r#"abc"def\:ghi"#.try_into().unwrap(); // let sig = Base64::new(b"test".to_vec()); // let credentials = XMatrix::try_from(&header).unwrap(); // assert_eq!(credentials.origin, origin); // assert_eq!(credentials.destination, None); // assert_eq!(credentials.key, key); // assert_eq!(credentials.sig, sig); // let credentials = XMatrix { // origin, // destination: None, // key, // sig, // }; // assert_eq!( // credentials.encode(), // r#"X-Matrix key="abc\"def\\:ghi",origin="example.com:1234",sig=dGVzdA"# // ); // } // #[test] // fn xmatrix_auth_1_3_with_extra_spaces() { // let header = HeaderValue::from_static( // "X-Matrix origin=\"origin.hs.example.com\" , destination=\"destination.hs.example.com\",key=\"ed25519:key1\", sig=\"dGVzdA\"", // ); // let credentials = XMatrix::try_from(&header).unwrap(); // let sig = Base64::new(b"test".to_vec()); // assert_eq!(credentials.origin, "origin.hs.example.com"); // assert_eq!( // credentials.destination.unwrap(), // "destination.hs.example.com" // ); // assert_eq!(credentials.key, "ed25519:key1"); // assert_eq!(credentials.sig, sig); // } // }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/query.rs
crates/core/src/federation/query.rs
/// Endpoints to retrieve information from a homeserver about a resource. /// /// `GET /_matrix/federation/*/query/directory` /// /// Get mapped room ID and resident homeservers for a given room alias. use std::collections::BTreeMap; use reqwest::Url; use salvo::prelude::*; use serde::{Deserialize, Serialize}; use serde_json::Value as JsonValue; use crate::{ OwnedRoomId, OwnedServerName, OwnedUserId, RoomAliasId, sending::{SendRequest, SendResult}, user::ProfileField, }; // /// `/v1/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/server-server-api/#get_matrixfederationv1querydirectory // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: ServerSignatures, // history: { // 1.0 => "/_matrix/federation/v1/query/directory", // } // }; pub fn directory_request(origin: &str, room_alias: &RoomAliasId) -> SendResult<SendRequest> { let mut url = Url::parse(&format!("{origin}/_matrix/federation/v1/query/directory"))?; url.query_pairs_mut() .append_pair("room_alias", room_alias.as_str()); Ok(crate::sending::get(url)) } // /// Request type for the `get_room_information` endpoint. // #[derive(ToSchema, Deserialize, Debug)] // pub struct RoomInfoReqArgs { // /// Room alias to query. // #[salvo(parameter(parameter_in = Query))] // pub room_alias: OwnedRoomAliasId, // } /// Response type for the `get_room_information` endpoint. #[derive(ToSchema, Serialize, Deserialize, Debug)] pub struct RoomInfoResBody { /// Room ID mapped to queried alias. pub room_id: OwnedRoomId, /// An array of server names that are likely to hold the given room. pub servers: Vec<OwnedServerName>, } impl RoomInfoResBody { /// Creates a new `Response` with the given room IDs and servers. pub fn new(room_id: OwnedRoomId, servers: Vec<OwnedServerName>) -> Self { Self { room_id, servers } } } // /// `GET /_matrix/federation/*/query/profile` // /// // /// Get profile information, such as a display name or avatar, for a given user. // /// `/v1/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/server-server-api/#get_matrixfederationv1queryprofile // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: ServerSignatures, // history: { // 1.0 => "/_matrix/federation/v1/query/profile", // } // }; pub fn profile_request(origin: &str, args: ProfileReqArgs) -> SendResult<SendRequest> { let mut url = Url::parse(&format!("{origin}/_matrix/federation/v1/query/profile"))?; url.query_pairs_mut() .append_pair("user_id", args.user_id.as_str()); if let Some(field) = &args.field { url.query_pairs_mut().append_pair("field", field.as_ref()); } Ok(crate::sending::get(url)) } /// Request type for the `get_profile_information` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct ProfileReqArgs { /// User ID to query. #[salvo(parameter(parameter_in = Query))] pub user_id: OwnedUserId, /// Profile field to query. #[salvo(parameter(parameter_in = Query))] #[serde(skip_serializing_if = "Option::is_none")] pub field: Option<ProfileField>, } // /// `GET /_matrix/federation/*/query/{queryType}` // /// // /// Performs a single query request on the receiving homeserver. The query // /// arguments are dependent on which type of query is being made. // /// `/v1/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/server-server-api/#get_matrixfederationv1queryquerytype // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: AccessToken, // history: { // 1.0 => "/_matrix/federation/v1/query/:query_type", // } // }; /// Request type for the `get_custom_information` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct CustomReqBody { /// The type of query to make. #[salvo(parameter(parameter_in = Path))] pub query_type: String, /// The query parameters. pub params: BTreeMap<String, String>, } /// Response type for the `get_custom_information` endpoint. #[derive(ToSchema, Serialize, Debug)] #[salvo(schema(value_type = Object))] pub struct CustomResBody( /// The body of the response. pub JsonValue, ); impl CustomResBody { /// Creates a new response with the given body. pub fn new(body: JsonValue) -> Self { Self(body) } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/authorization.rs
crates/core/src/federation/authorization.rs
//! Endpoints to retrieve the complete auth chain for a given event. //! `GET /_matrix/federation/*/event_auth/{room_id}/{event_id}` //! //! Get the complete auth chain for a given event. //! `/v1/` ([spec]) //! //! [spec]: https://spec.matrix.org/latest/server-server-api/#get_matrixfederationv1event_authroomideventid use salvo::prelude::*; use serde::{Deserialize, Serialize}; use url::Url; use crate::identifiers::*; use crate::sending::{SendRequest, SendResult}; use crate::serde::RawJsonValue; // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: ServerSignatures, // history: { // 1.0 => "/_matrix/federation/v1/event_auth/:room_id/:event_id", // } // }; pub fn event_auth_request( origin: &str, room_id: &RoomId, event_id: &EventId, ) -> SendResult<SendRequest> { let url = Url::parse(&format!( "{origin}/_matrix/federation/v1/event_auth/{room_id}/{event_id}" ))?; Ok(crate::sending::get(url)) } /// Request type for the `get_event_authorization` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct EventAuthReqArgs { /// The room ID to get the auth chain for. #[salvo(parameter(parameter_in = Path))] pub room_id: OwnedRoomId, /// The event ID to get the auth chain for. #[salvo(parameter(parameter_in = Path))] pub event_id: OwnedEventId, } /// Response type for the `get_event_authorization` endpoint. #[derive(ToSchema, Deserialize, Serialize, Debug)] pub struct EventAuthResBody { /// The full set of authorization events that make up the state of the room, /// and their authorization events, recursively. #[salvo(schema(value_type = Vec<Object>))] pub auth_chain: Vec<Box<RawJsonValue>>, } impl EventAuthResBody { /// Creates a new `Response` with the given auth chain. pub fn new(auth_chain: Vec<Box<RawJsonValue>>) -> Self { Self { auth_chain } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/openid.rs
crates/core/src/federation/openid.rs
//! OpenID endpoints. //! `GET /_matrix/federation/*/openid/userinfo` //! //! Exchange an OpenID access token for information about the user who generated //! the token. `/v1/` ([spec]) //! //! [spec]: https://spec.matrix.org/latest/server-server-api/#get_matrixfederationv1openiduserinfo use salvo::prelude::*; use serde::{Deserialize, Serialize}; use crate::OwnedUserId; // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: None, // history: { // 1.0 => "/_matrix/federation/v1/openid/userinfo", // } // }; /// Request type for the `get_openid_userinfo` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct UserInfoReqArgs { /// The OpenID access token to get information about the owner for. #[salvo(parameter(parameter_in = Query))] pub access_token: String, } /// Response type for the `get_openid_userinfo` endpoint. #[derive(ToSchema, Serialize, Debug)] pub struct UserInfoResBody { /// The Matrix User ID who generated the token. pub sub: OwnedUserId, } impl UserInfoResBody { /// Creates a new `Response` with the given user id. pub fn new(sub: OwnedUserId) -> Self { Self { sub } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/authenticated_media.rs
crates/core/src/federation/authenticated_media.rs
//! Authenticated endpoints for the content repository, according to [MSC3916]. //! //! [MSC3916]: https://github.com/matrix-org/matrix-spec-proposals/pull/3916 use crate::http_headers::ContentDisposition; use serde::{Deserialize, Serialize}; pub mod get_content; pub mod get_content_thumbnail; /// The `multipart/mixed` mime "essence". const MULTIPART_MIXED: &str = "multipart/mixed"; /// The maximum number of headers to parse in a body part. // #[cfg(feature = "client")] // const MAX_HEADERS_COUNT: usize = 32; /// The length of the generated boundary. const GENERATED_BOUNDARY_LENGTH: usize = 30; /// The metadata of a file from the content repository. #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct ContentMetadata {} impl ContentMetadata { /// Creates a new empty `ContentMetadata`. pub fn new() -> Self { Self {} } } /// A file from the content repository or the location where it can be found. #[derive(Debug, Clone)] pub enum FileOrLocation { /// The content of the file. File(Content), /// The file is at the given URL. Location(String), } /// The content of a file from the content repository. #[derive(Debug, Clone)] pub struct Content { /// The content of the file as bytes. pub file: Vec<u8>, /// The content type of the file that was previously uploaded. pub content_type: Option<String>, /// The value of the `Content-Disposition` HTTP header, possibly containing the name of the /// file that was previously uploaded. pub content_disposition: Option<ContentDisposition>, } impl Content { /// Creates a new `Content` with the given bytes. pub fn new( file: Vec<u8>, content_type: String, content_disposition: ContentDisposition, ) -> Self { Self { file, content_type: Some(content_type), content_disposition: Some(content_disposition), } } } // /// Serialize the given metadata and content into a `http::Response` `multipart/mixed` body. // /// // /// Returns a tuple containing the boundary used // #[cfg(feature = "server")] // fn try_into_multipart_mixed_response<T: Default + bytes::BufMut>( // metadata: &ContentMetadata, // content: &FileOrLocation, // ) -> Result<http::Response<T>, crate::api::error::IntoHttpError> { // use std::io::Write as _; // use rand::Rng as _; // let boundary = rand::thread_rng() // .sample_iter(&rand::distributions::Alphanumeric) // .map(char::from) // .take(GENERATED_BOUNDARY_LENGTH) // .collect::<String>(); // let mut body_writer = T::default().writer(); // // Add first boundary separator and header for the metadata. // let _ = write!( // body_writer, // "\r\n--{boundary}\r\n{}: {}\r\n\r\n", // http::header::CONTENT_TYPE, // mime::APPLICATION_JSON // ); // // Add serialized metadata. // serde_json::to_writer(&mut body_writer, metadata)?; // // Add second boundary separator. // let _ = write!(body_writer, "\r\n--{boundary}\r\n"); // // Add content. // match content { // FileOrLocation::File(content) => { // // Add headers. // let content_type = content // .content_type // .as_deref() // .unwrap_or(mime::APPLICATION_OCTET_STREAM.as_ref()); // let _ = write!( // body_writer, // "{}: {content_type}\r\n", // http::header::CONTENT_TYPE // ); // if let Some(content_disposition) = &content.content_disposition { // let _ = write!( // body_writer, // "{}: {content_disposition}\r\n", // http::header::CONTENT_DISPOSITION // ); // } // // Add empty line separator after headers. // let _ = body_writer.write_all(b"\r\n"); // // Add bytes. // let _ = body_writer.write_all(&content.file); // } // FileOrLocation::Location(location) => { // // Only add location header and empty line separator. // let _ = write!( // body_writer, // "{}: {location}\r\n\r\n", // http::header::LOCATION // ); // } // } // // Add final boundary. // let _ = write!(body_writer, "\r\n--{boundary}--"); // let content_type = format!("{MULTIPART_MIXED}; boundary={boundary}"); // let body = body_writer.into_inner(); // Ok(http::Response::builder() // .header(http::header::CONTENT_TYPE, content_type) // .body(body)?) // } // /// Deserialize the given metadata and content from a `http::Response` with a `multipart/mixed` // /// body. // #[cfg(feature = "client")] // fn try_from_multipart_mixed_response<T: AsRef<[u8]>>( // http_response: http::Response<T>, // ) -> Result< // (ContentMetadata, FileOrLocation), // crate::api::error::FromHttpResponseError<crate::api::error::MatrixError>, // > { // use crate::api::error::{HeaderDeserializationError, MultipartMixedDeserializationError}; // // First, get the boundary from the content type header. // let body_content_type = http_response // .headers() // .get(http::header::CONTENT_TYPE) // .ok_or_else(|| HeaderDeserializationError::MissingHeader("Content-Type".to_owned()))? // .to_str()? // .parse::<mime::Mime>() // .map_err(|e| HeaderDeserializationError::InvalidHeader(e.into()))?; // if !body_content_type // .essence_str() // .eq_ignore_ascii_case(MULTIPART_MIXED) // { // return Err(HeaderDeserializationError::InvalidHeaderValue { // header: "Content-Type".to_owned(), // expected: MULTIPART_MIXED.to_owned(), // unexpected: body_content_type.essence_str().to_owned(), // } // .into()); // } // let boundary = body_content_type // .get_param("boundary") // .ok_or(HeaderDeserializationError::MissingMultipartBoundary)? // .as_str() // .as_bytes(); // // Split the body with the boundary. // let body = http_response.body().as_ref(); // let mut full_boundary = Vec::with_capacity(boundary.len() + 4); // full_boundary.extend_from_slice(b"\r\n--"); // full_boundary.extend_from_slice(boundary); // let full_boundary_no_crlf = full_boundary.strip_prefix(b"\r\n").unwrap(); // let mut boundaries = memchr::memmem::find_iter(body, &full_boundary); // let metadata_start = if body.starts_with(full_boundary_no_crlf) { // // If there is no preamble before the first boundary, it may omit the // // preceding CRLF. // full_boundary_no_crlf.len() // } else { // boundaries // .next() // .ok_or_else(|| MultipartMixedDeserializationError::MissingBodyParts { // expected: 2, // found: 0, // })? // + full_boundary.len() // }; // let metadata_end = // boundaries // .next() // .ok_or_else(|| MultipartMixedDeserializationError::MissingBodyParts { // expected: 2, // found: 0, // })?; // let (_raw_metadata_headers, serialized_metadata) = // parse_multipart_body_part(body, metadata_start, metadata_end)?; // // Don't search for anything in the headers, just deserialize the content that should be JSON. // let metadata = serde_json::from_slice(serialized_metadata)?; // // Look at the part containing the media content now. // let content_start = metadata_end + full_boundary.len(); // let content_end = // boundaries // .next() // .ok_or_else(|| MultipartMixedDeserializationError::MissingBodyParts { // expected: 2, // found: 1, // })?; // let (raw_content_headers, file) = parse_multipart_body_part(body, content_start, content_end)?; // // Parse the headers to retrieve the content type and content disposition. // let mut content_headers = [httparse::EMPTY_HEADER; MAX_HEADERS_COUNT]; // httparse::parse_headers(raw_content_headers, &mut content_headers) // .map_err(|e| MultipartMixedDeserializationError::InvalidHeader(e.into()))?; // let mut location = None; // let mut content_type = None; // let mut content_disposition = None; // for header in content_headers { // if header.name.is_empty() { // // This is a empty header, we have reached the end of the parsed headers. // break; // } // if header.name == http::header::LOCATION { // location = Some( // String::from_utf8(header.value.to_vec()) // .map_err(|e| MultipartMixedDeserializationError::InvalidHeader(e.into()))?, // ); // // This is the only header we need, stop parsing. // break; // } else if header.name == http::header::CONTENT_TYPE { // content_type = Some( // String::from_utf8(header.value.to_vec()) // .map_err(|e| MultipartMixedDeserializationError::InvalidHeader(e.into()))?, // ); // } else if header.name == http::header::CONTENT_DISPOSITION { // content_disposition = Some( // ContentDisposition::try_from(header.value) // .map_err(|e| MultipartMixedDeserializationError::InvalidHeader(e.into()))?, // ); // } // } // let content = if let Some(location) = location { // FileOrLocation::Location(location) // } else { // FileOrLocation::File(Content { // file: file.to_owned(), // content_type, // content_disposition, // }) // }; // Ok((metadata, content)) // } // /// Parse the multipart body part in the given bytes, starting and ending at the given positions. // /// // /// Returns a `(headers_bytes, content_bytes)` tuple. Returns an error if the separation between the // /// headers and the content could not be found. // #[cfg(feature = "client")] // fn parse_multipart_body_part( // bytes: &[u8], // start: usize, // end: usize, // ) -> Result<(&[u8], &[u8]), crate::api::error::MultipartMixedDeserializationError> { // use crate::api::error::MultipartMixedDeserializationError; // // The part should start with a newline after the boundary. We need to ignore characters before // // it in case of extra whitespaces, and for compatibility it might not have a CR. // let headers_start = memchr::memchr(b'\n', &bytes[start..end]) // .expect("the end boundary contains a newline") // + start // + 1; // // Let's find an empty line now. // let mut line_start = headers_start; // let mut line_end; // loop { // line_end = memchr::memchr(b'\n', &bytes[line_start..end]) // .ok_or(MultipartMixedDeserializationError::MissingBodyPartInnerSeparator)? // + line_start // + 1; // if matches!(&bytes[line_start..line_end], b"\r\n" | b"\n") { // break; // } // line_start = line_end; // } // Ok((&bytes[headers_start..line_start], &bytes[line_end..end])) // } // #[cfg(all(test, feature = "client", feature = "server"))] // mod tests { // use assert_matches2::assert_matches; // use crate::http_headers::{ContentDisposition, ContentDispositionType}; // use super::{ // Content, ContentMetadata, FileOrLocation, try_from_multipart_mixed_response, // try_into_multipart_mixed_response, // }; // #[test] // fn multipart_mixed_content_ascii_filename_conversions() { // let file = "s⌽me UTF-8 Ťext".as_bytes(); // let content_type = "text/plain"; // let content_disposition = ContentDisposition::new(ContentDispositionType::Attachment) // .with_filename(Some("filename.txt".to_owned())); // let outgoing_metadata = ContentMetadata::new(); // let outgoing_content = FileOrLocation::File(Content { // file: file.to_vec(), // content_type: Some(content_type.to_owned()), // content_disposition: Some(content_disposition.clone()), // }); // let response = // try_into_multipart_mixed_response::<Vec<u8>>(&outgoing_metadata, &outgoing_content) // .unwrap(); // let (_incoming_metadata, incoming_content) = // try_from_multipart_mixed_response(response).unwrap(); // assert_matches!(incoming_content, FileOrLocation::File(incoming_content)); // assert_eq!(incoming_content.file, file); // assert_eq!(incoming_content.content_type.unwrap(), content_type); // assert_eq!( // incoming_content.content_disposition, // Some(content_disposition) // ); // } // #[test] // fn multipart_mixed_content_utf8_filename_conversions() { // let file = "s⌽me UTF-8 Ťext".as_bytes(); // let content_type = "text/plain"; // let content_disposition = ContentDisposition::new(ContentDispositionType::Attachment) // .with_filename(Some("fȈlƩnąmǝ.txt".to_owned())); // let outgoing_metadata = ContentMetadata::new(); // let outgoing_content = FileOrLocation::File(Content { // file: file.to_vec(), // content_type: Some(content_type.to_owned()), // content_disposition: Some(content_disposition.clone()), // }); // let response = // try_into_multipart_mixed_response::<Vec<u8>>(&outgoing_metadata, &outgoing_content) // .unwrap(); // let (_incoming_metadata, incoming_content) = // try_from_multipart_mixed_response(response).unwrap(); // assert_matches!(incoming_content, FileOrLocation::File(incoming_content)); // assert_eq!(incoming_content.file, file); // assert_eq!(incoming_content.content_type.unwrap(), content_type); // assert_eq!( // incoming_content.content_disposition, // Some(content_disposition) // ); // } // #[test] // fn multipart_mixed_location_conversions() { // let location = "https://server.local/media/filename.txt"; // let outgoing_metadata = ContentMetadata::new(); // let outgoing_content = FileOrLocation::Location(location.to_owned()); // let response = // try_into_multipart_mixed_response::<Vec<u8>>(&outgoing_metadata, &outgoing_content) // .unwrap(); // let (_incoming_metadata, incoming_content) = // try_from_multipart_mixed_response(response).unwrap(); // assert_matches!( // incoming_content, // FileOrLocation::Location(incoming_location) // ); // assert_eq!(incoming_location, location); // } // #[test] // fn multipart_mixed_deserialize_invalid() { // // Missing boundary in headers. // let body = "\r\n--abcdef\r\n\r\n{}\r\n--abcdef\r\nContent-Type: text/plain\r\n\r\nsome plain text\r\n--abcdef--"; // let response = http::Response::builder() // .header(http::header::CONTENT_TYPE, "multipart/mixed") // .body(body) // .unwrap(); // try_from_multipart_mixed_response(response).unwrap_err(); // // Wrong boundary. // let body = "\r\n--abcdef\r\n\r\n{}\r\n--abcdef\r\nContent-Type: text/plain\r\n\r\nsome plain text\r\n--abcdef--"; // let response = http::Response::builder() // .header( // http::header::CONTENT_TYPE, // "multipart/mixed; boundary=012345", // ) // .body(body) // .unwrap(); // try_from_multipart_mixed_response(response).unwrap_err(); // // Missing boundary in body. // let body = // "\r\n--abcdef\r\n\r\n{}\r\n--abcdef\r\nContent-Type: text/plain\r\n\r\nsome plain text"; // let response = http::Response::builder() // .header( // http::header::CONTENT_TYPE, // "multipart/mixed; boundary=abcdef", // ) // .body(body) // .unwrap(); // try_from_multipart_mixed_response(response).unwrap_err(); // // Missing header and content empty line separator in body part. // let body = "\r\n--abcdef\r\n{}\r\n--abcdef\r\nContent-Type: text/plain\r\n\r\nsome plain text\r\n--abcdef--"; // let response = http::Response::builder() // .header( // http::header::CONTENT_TYPE, // "multipart/mixed; boundary=abcdef", // ) // .body(body) // .unwrap(); // try_from_multipart_mixed_response(response).unwrap_err(); // // Control character in header. // let body = "\r\n--abcdef\r\n\r\n{}\r\n--abcdef\r\nContent-Type: text/plain\r\nContent-Disposition: inline; filename=\"my\nfile\"\r\nsome plain text\r\n--abcdef--"; // let response = http::Response::builder() // .header( // http::header::CONTENT_TYPE, // "multipart/mixed; boundary=abcdef", // ) // .body(body) // .unwrap(); // try_from_multipart_mixed_response(response).unwrap_err(); // // Boundary without CRLF with preamble. // let body = "foo--abcdef\r\n\r\n{}\r\n--abcdef\r\n\r\nsome plain text\r\n--abcdef--"; // let response = http::Response::builder() // .header( // http::header::CONTENT_TYPE, // "multipart/mixed; boundary=abcdef", // ) // .body(body) // .unwrap(); // try_from_multipart_mixed_response(response).unwrap_err(); // } // #[test] // fn multipart_mixed_deserialize_valid() { // // Simple. // let body = "\r\n--abcdef\r\ncontent-type: application/json\r\n\r\n{}\r\n--abcdef\r\ncontent-type: text/plain\r\n\r\nsome plain text\r\n--abcdef--"; // let response = http::Response::builder() // .header( // http::header::CONTENT_TYPE, // "multipart/mixed; boundary=abcdef", // ) // .body(body) // .unwrap(); // let (_metadata, content) = try_from_multipart_mixed_response(response).unwrap(); // assert_matches!(content, FileOrLocation::File(file_content)); // assert_eq!(file_content.file, b"some plain text"); // assert_eq!(file_content.content_type.unwrap(), "text/plain"); // assert_eq!(file_content.content_disposition, None); // // Case-insensitive headers. // let body = "\r\n--abcdef\r\nCONTENT-type: application/json\r\n\r\n{}\r\n--abcdef\r\nCONTENT-TYPE: text/plain\r\ncoNtenT-disPosItioN: attachment; filename=my_file.txt\r\n\r\nsome plain text\r\n--abcdef--"; // let response = http::Response::builder() // .header( // http::header::CONTENT_TYPE, // "multipart/mixed; boundary=abcdef", // ) // .body(body) // .unwrap(); // let (_metadata, content) = try_from_multipart_mixed_response(response).unwrap(); // assert_matches!(content, FileOrLocation::File(file_content)); // assert_eq!(file_content.file, b"some plain text"); // assert_eq!(file_content.content_type.unwrap(), "text/plain"); // let content_disposition = file_content.content_disposition.unwrap(); // assert_eq!( // content_disposition.disposition_type, // ContentDispositionType::Attachment // ); // assert_eq!(content_disposition.filename.unwrap(), "my_file.txt"); // // Extra whitespace. // let body = " \r\n--abcdef\r\ncontent-type: application/json \r\n\r\n {} \r\n--abcdef\r\ncontent-type: text/plain \r\n\r\nsome plain text\r\n--abcdef-- "; // let response = http::Response::builder() // .header( // http::header::CONTENT_TYPE, // "multipart/mixed; boundary=abcdef", // ) // .body(body) // .unwrap(); // let (_metadata, content) = try_from_multipart_mixed_response(response).unwrap(); // assert_matches!(content, FileOrLocation::File(file_content)); // assert_eq!(file_content.file, b"some plain text"); // assert_eq!(file_content.content_type.unwrap(), "text/plain"); // assert_eq!(file_content.content_disposition, None); // // Missing CR except in boundaries. // let body = "\r\n--abcdef\ncontent-type: application/json\n\n{}\r\n--abcdef\ncontent-type: text/plain \n\nsome plain text\r\n--abcdef--"; // let response = http::Response::builder() // .header( // http::header::CONTENT_TYPE, // "multipart/mixed; boundary=abcdef", // ) // .body(body) // .unwrap(); // let (_metadata, content) = try_from_multipart_mixed_response(response).unwrap(); // assert_matches!(content, FileOrLocation::File(file_content)); // assert_eq!(file_content.file, b"some plain text"); // assert_eq!(file_content.content_type.unwrap(), "text/plain"); // assert_eq!(file_content.content_disposition, None); // // No leading CRLF (and no preamble) // let body = "--abcdef\r\n\r\n{}\r\n--abcdef\r\n\r\nsome plain text\r\n--abcdef--"; // let response = http::Response::builder() // .header( // http::header::CONTENT_TYPE, // "multipart/mixed; boundary=abcdef", // ) // .body(body) // .unwrap(); // let (_metadata, content) = try_from_multipart_mixed_response(response).unwrap(); // assert_matches!(content, FileOrLocation::File(file_content)); // assert_eq!(file_content.file, b"some plain text"); // assert_eq!(file_content.content_type, None); // assert_eq!(file_content.content_disposition, None); // // Boundary text in preamble, but no leading CRLF, so it should be // // ignored. // let body = // "foo--abcdef\r\n--abcdef\r\n\r\n{}\r\n--abcdef\r\n\r\nsome plain text\r\n--abcdef--"; // let response = http::Response::builder() // .header( // http::header::CONTENT_TYPE, // "multipart/mixed; boundary=abcdef", // ) // .body(body) // .unwrap(); // let (_metadata, content) = try_from_multipart_mixed_response(response).unwrap(); // assert_matches!(content, FileOrLocation::File(file_content)); // assert_eq!(file_content.file, b"some plain text"); // assert_eq!(file_content.content_type, None); // assert_eq!(file_content.content_disposition, None); // // No body part headers. // let body = "\r\n--abcdef\r\n\r\n{}\r\n--abcdef\r\n\r\nsome plain text\r\n--abcdef--"; // let response = http::Response::builder() // .header( // http::header::CONTENT_TYPE, // "multipart/mixed; boundary=abcdef", // ) // .body(body) // .unwrap(); // let (_metadata, content) = try_from_multipart_mixed_response(response).unwrap(); // assert_matches!(content, FileOrLocation::File(file_content)); // assert_eq!(file_content.file, b"some plain text"); // assert_eq!(file_content.content_type, None); // assert_eq!(file_content.content_disposition, None); // // Raw UTF-8 filename (some kind of compatibility with multipart/form-data). // let body = "\r\n--abcdef\r\ncontent-type: application/json\r\n\r\n{}\r\n--abcdef\r\ncontent-type: text/plain\r\ncontent-disposition: inline; filename=\"ȵ⌾Ⱦԩ💈Ňɠ\"\r\n\r\nsome plain text\r\n--abcdef--"; // let response = http::Response::builder() // .header( // http::header::CONTENT_TYPE, // "multipart/mixed; boundary=abcdef", // ) // .body(body) // .unwrap(); // let (_metadata, content) = try_from_multipart_mixed_response(response).unwrap(); // assert_matches!(content, FileOrLocation::File(file_content)); // assert_eq!(file_content.file, b"some plain text"); // assert_eq!(file_content.content_type.unwrap(), "text/plain"); // let content_disposition = file_content.content_disposition.unwrap(); // assert_eq!( // content_disposition.disposition_type, // ContentDispositionType::Inline // ); // assert_eq!(content_disposition.filename.unwrap(), "ȵ⌾Ⱦԩ💈Ňɠ"); // } // }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/space.rs
crates/core/src/federation/space.rs
use reqwest::Url; use salvo::prelude::*; /// Spaces endpoints. use serde::{Deserialize, Serialize}; use crate::{ EventEncryptionAlgorithm, OwnedMxcUri, OwnedRoomAliasId, OwnedRoomId, RoomVersionId, events::space::child::HierarchySpaceChildEvent, room::RoomType, sending::{SendRequest, SendResult}, serde::RawJson, space::SpaceRoomJoinRule, }; /// The summary of a parent space. #[derive(ToSchema, Deserialize, Serialize, Clone, Debug)] pub struct SpaceHierarchyParentSummary { /// The canonical alias of the room, if any. #[serde( skip_serializing_if = "Option::is_none", default, deserialize_with = "crate::serde::empty_string_as_none" )] pub canonical_alias: Option<OwnedRoomAliasId>, /// The name of the room, if any. #[serde(skip_serializing_if = "Option::is_none")] pub name: Option<String>, /// The number of members joined to the room. pub num_joined_members: u64, /// The ID of the room. pub room_id: OwnedRoomId, /// The topic of the room, if any. #[serde(skip_serializing_if = "Option::is_none")] pub topic: Option<String>, /// Whether the room may be viewed by guest users without joining. pub world_readable: bool, /// Whether guest users may join the room and participate in it. /// /// If they can, they will be subject to ordinary power level rules like any /// other user. pub guest_can_join: bool, /// The URL for the room's avatar, if one is set. #[serde( skip_serializing_if = "Option::is_none", default, deserialize_with = "crate::serde::empty_string_as_none" )] pub avatar_url: Option<OwnedMxcUri>, /// The join rule of the room. #[serde(default, skip_serializing_if = "crate::serde::is_default")] pub join_rule: SpaceRoomJoinRule, /// The type of room from `m.room.create`, if any. #[serde(skip_serializing_if = "Option::is_none")] pub room_type: Option<RoomType>, /// The stripped `m.space.child` events of the space-room. /// /// If the room is not a space-room, this should be empty. pub children_state: Vec<RawJson<HierarchySpaceChildEvent>>, /// If the room is a restricted room, these are the room IDs which are /// specified by the join rules. #[serde(default, skip_serializing_if = "crate::serde::is_default")] pub allowed_room_ids: Vec<OwnedRoomId>, /// If the room is encrypted, the algorithm used for this room. #[serde( skip_serializing_if = "Option::is_none", rename = "im.nheko.summary.encryption", alias = "encryption" )] pub encryption: Option<EventEncryptionAlgorithm>, /// Version of the room. #[serde( skip_serializing_if = "Option::is_none", rename = "im.nheko.summary.room_version", alias = "im.nheko.summary.version", alias = "room_version" )] pub room_version: Option<RoomVersionId>, } /// The summary of a space's child. /// /// To create an instance of this type. #[derive(ToSchema, Deserialize, Serialize, Clone, Debug)] pub struct SpaceHierarchyChildSummary { /// The canonical alias of the room, if any. #[serde( skip_serializing_if = "Option::is_none", default, deserialize_with = "crate::serde::empty_string_as_none" )] pub canonical_alias: Option<OwnedRoomAliasId>, /// The name of the room, if any. #[serde(skip_serializing_if = "Option::is_none")] pub name: Option<String>, /// The number of members joined to the room. pub num_joined_members: u64, /// The ID of the room. pub room_id: OwnedRoomId, /// The topic of the room, if any. #[serde(skip_serializing_if = "Option::is_none")] pub topic: Option<String>, /// Whether the room may be viewed by guest users without joining. pub world_readable: bool, /// Whether guest users may join the room and participate in it. /// /// If they can, they will be subject to ordinary power level rules like any /// other user. pub guest_can_join: bool, /// The URL for the room's avatar, if one is set. #[serde( skip_serializing_if = "Option::is_none", default, deserialize_with = "crate::serde::empty_string_as_none" )] pub avatar_url: Option<OwnedMxcUri>, /// The join rule of the room. #[serde(default, skip_serializing_if = "crate::serde::is_default")] pub join_rule: SpaceRoomJoinRule, /// The type of room from `m.room.create`, if any. #[serde(skip_serializing_if = "Option::is_none")] pub room_type: Option<RoomType>, /// If the room is a restricted room, these are the room IDs which are /// specified by the join rules. #[serde(default, skip_serializing_if = "crate::serde::is_default")] pub allowed_room_ids: Vec<OwnedRoomId>, /// If the room is encrypted, the algorithm used for this room. #[serde( skip_serializing_if = "Option::is_none", rename = "im.nheko.summary.encryption", alias = "encryption" )] pub encryption: Option<EventEncryptionAlgorithm>, /// Version of the room. #[serde( skip_serializing_if = "Option::is_none", rename = "im.nheko.summary.room_version", alias = "im.nheko.summary.version", alias = "room_version" )] pub room_version: Option<RoomVersionId>, } impl From<SpaceHierarchyParentSummary> for SpaceHierarchyChildSummary { fn from(parent: SpaceHierarchyParentSummary) -> Self { let SpaceHierarchyParentSummary { canonical_alias, name, num_joined_members, room_id, topic, world_readable, guest_can_join, avatar_url, join_rule, room_type, children_state: _, allowed_room_ids, encryption, room_version, } = parent; Self { canonical_alias, name, num_joined_members, room_id, topic, world_readable, guest_can_join, avatar_url, join_rule, room_type, allowed_room_ids, encryption, room_version, } } } // /// `GET /_matrix/federation/*/hierarchy/{room_id}` // /// // /// Get the space tree in a depth-first manner to locate child rooms of a given // /// space. `/v1/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/server-server-api/#get_matrixfederationv1hierarchyroomid // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: ServerSignatures, // history: { // unstable => // "/_matrix/federation/unstable/org.matrix.msc2946/hierarchy/:room_id", // 1.2 => "/_matrix/federation/v1/hierarchy/:room_id", // } // }; pub fn hierarchy_request(origin: &str, args: HierarchyReqArgs) -> SendResult<SendRequest> { let url = Url::parse(&format!( "{origin}/_matrix/federation/v1/hierarchy/{}?suggested_only={}", args.room_id, args.suggested_only ))?; Ok(crate::sending::get(url)) } /// Request type for the `hierarchy` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct HierarchyReqArgs { /// The room ID of the space to get a hierarchy for. #[salvo(parameter(parameter_in = Path))] pub room_id: OwnedRoomId, /// Whether or not the server should only consider suggested rooms. /// /// Suggested rooms are annotated in their `m.space.child` event contents. #[salvo(parameter(parameter_in = Query))] #[serde(default, skip_serializing_if = "crate::serde::is_default")] pub suggested_only: bool, } /// Response type for the `hierarchy` endpoint. #[derive(ToSchema, Serialize, Deserialize, Debug)] pub struct HierarchyResBody { /// A summary of the space’s children. /// /// Rooms which the requesting server cannot peek/join will be excluded. pub children: Vec<SpaceHierarchyChildSummary>, /// The list of room IDs the requesting server doesn’t have a viable way to /// peek/join. /// /// Rooms which the responding server cannot provide details on will be /// outright excluded from the response instead. pub inaccessible_children: Vec<OwnedRoomId>, /// A summary of the requested room. pub room: SpaceHierarchyParentSummary, } impl HierarchyResBody { /// Creates a new `Response` with the given room summary. pub fn new(room_summary: SpaceHierarchyParentSummary) -> Self { Self { children: Vec::new(), inaccessible_children: Vec::new(), room: room_summary, } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/room.rs
crates/core/src/federation/room.rs
/// Endpoints for room management. use salvo::prelude::*; use serde::{Deserialize, Serialize}; use crate::{ OwnedEventId, OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, client::filter::RoomEventFilter, events::{AnyStateEvent, AnyTimelineEvent}, serde::RawJson, }; // /// `GET /_matrix/client/*/rooms/{room_id}/event/{event_id}` // /// // /// Get a single event based on roomId/eventId // /// `/v3/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3roomsroomideventeventid // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: AccessToken, // history: { // 1.0 => "/_matrix/client/r0/rooms/:room_id/event/:event_id", // 1.1 => "/_matrix/client/v3/rooms/:room_id/event/:event_id", // } // }; /// Response type for the `get_room_event` endpoint. #[derive(ToSchema, Serialize, Debug)] pub struct RoomEventResBody { /// Arbitrary JSON of the event body. #[salvo(schema(value_type = Object, additional_properties = true))] pub event: RawJson<AnyTimelineEvent>, } impl RoomEventResBody { /// Creates a new `Response` with the given event. pub fn new(event: RawJson<AnyTimelineEvent>) -> Self { Self { event } } } // /// Request type for the `get_context` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct ContextReqArgs { /// The room to get events from. #[salvo(parameter(parameter_in = Path))] pub room_id: OwnedRoomId, /// The event to get context around. #[salvo(parameter(parameter_in = Path))] pub event_id: OwnedEventId, /// The maximum number of context events to return. /// /// This limit applies to the sum of the `events_before` and `events_after` /// arrays. The requested event ID is always returned in `event` even if /// the limit is `0`. /// /// Defaults to 10. #[salvo(parameter(parameter_in = Query))] #[serde(default = "default_limit", skip_serializing_if = "is_default_limit")] pub limit: usize, /// A RoomEventFilter to filter returned events with. #[salvo(parameter(parameter_in = Query))] #[serde( with = "crate::serde::json_string", default, skip_serializing_if = "RoomEventFilter::is_empty" )] pub filter: RoomEventFilter, } fn default_limit() -> usize { 10 } /// Response type for the `get_context` endpoint. #[derive(ToSchema, Serialize, Default, Debug)] pub struct ContextResBody { /// A token that can be used to paginate backwards with. #[serde(skip_serializing_if = "Option::is_none")] pub start: Option<String>, /// A token that can be used to paginate forwards with. #[serde(skip_serializing_if = "Option::is_none")] pub end: Option<String>, /// A list of room events that happened just before the requested event, /// in reverse-chronological order. #[serde(default, skip_serializing_if = "Vec::is_empty")] #[salvo(schema(value_type = Object, additional_properties = true))] pub events_before: Vec<RawJson<AnyTimelineEvent>>, /// Details of the requested event. #[serde(skip_serializing_if = "Option::is_none")] #[salvo(schema(value_type = Object, additional_properties = true))] pub event: Option<RawJson<AnyTimelineEvent>>, /// A list of room events that happened just after the requested event, /// in chronological order. #[serde(default, skip_serializing_if = "Vec::is_empty")] #[salvo(schema(value_type = Object, additional_properties = true))] pub events_after: Vec<RawJson<AnyTimelineEvent>>, /// The state of the room at the last event returned. #[serde(default, skip_serializing_if = "Vec::is_empty")] #[salvo(schema(value_type = Object, additional_properties = true))] pub state: Vec<RawJson<AnyStateEvent>>, } impl ContextResBody { /// Creates an empty `Response`. pub fn new() -> Self { Default::default() } } // const METADATA: Metadata = metadata! { // method: POST, // rate_limited: true, // authentication: AccessToken, // history: { // unstable => // "/_matrix/client/unstable/xyz.amorgan.knock/knock/:room_id_or_alias", // 1.1 => "/_matrix/client/v3/knock/:room_id_or_alias", // } // }; /// Request type for the `knock_room` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct KnockReqArgs { /// The room the user should knock on. #[salvo(parameter(parameter_in = Path))] pub room_id_or_alias: OwnedRoomOrAliasId, /// The reason for joining a room. #[serde(skip_serializing_if = "Option::is_none")] pub reason: Option<String>, /// The servers to attempt to knock on the room through. /// /// One of the servers must be participating in the room. #[salvo(parameter(parameter_in = Query))] #[serde(default, skip_serializing_if = "<[_]>::is_empty")] pub server_name: Vec<OwnedServerName>, } /// Response type for the `knock_room` endpoint. #[derive(ToSchema, Serialize, Debug)] pub struct KnockResBody { /// The room that the user knocked on. pub room_id: OwnedRoomId, } impl KnockResBody { /// Creates a new `Response` with the given room ID. pub fn new(room_id: OwnedRoomId) -> Self { Self { room_id } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/directory.rs
crates/core/src/federation/directory.rs
/// Room directory endpoints. /// /// `GET /_matrix/federation/*/publicRooms` /// /// Get all the public rooms for the homeserver. use std::collections::BTreeMap; use reqwest::Url; use salvo::prelude::*; use serde::{Deserialize, Serialize, Serializer, ser::SerializeStruct}; use crate::{ OwnedServerName, OwnedServerSigningKeyId, UnixMillis, directory::{PublicRoomFilter, QueryCriteria, RoomNetwork, Server}, federation::discovery::ServerSigningKeys, sending::{SendRequest, SendResult}, }; // /// `POST /_matrix/federation/*/publicRooms` // /// // /// Get a homeserver's public rooms with an optional filter. // /// `/v1/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/server-server-api/#post_matrixfederationv1publicrooms // const METADATA: Metadata = metadata! { // method: POST, // rate_limited: false, // authentication: ServerSignatures, // history: { // 1.0 => "/_matrix/federation/v1/publicRooms", // } // }; pub fn public_rooms_request(origin: &str, body: PublicRoomsReqBody) -> SendResult<SendRequest> { let url = Url::parse(&format!("{origin}/_matrix/federation/v1/publicRooms"))?; crate::sending::post(url).stuff(body) } /// Request type for the `get_filtered_public_rooms` endpoint. #[derive(ToSchema, Deserialize, Serialize, Debug)] pub struct PublicRoomsReqBody { /// Limit for the number of results to return. #[serde(skip_serializing_if = "Option::is_none")] pub limit: Option<usize>, /// Pagination token from a previous request. #[serde(skip_serializing_if = "Option::is_none")] pub since: Option<String>, /// Filter to apply to the results. #[serde(default, skip_serializing_if = "PublicRoomFilter::is_empty")] pub filter: PublicRoomFilter, /// Network to fetch the public room lists from. #[serde(flatten, skip_serializing_if = "crate::serde::is_default")] pub room_network: RoomNetwork, } crate::json_body_modifier!(PublicRoomsReqBody); // /// `GET /.well-known/matrix/server` ([spec]) // /// // /// Get discovery information about the domain. // /// // /// [spec]: https://spec.matrix.org/latest/server-server-api/#getwell-knownmatrixserver // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: None, // history: { // 1.0 => "/.well-known/matrix/server", // } // }; /// Response type for the `discover_homeserver` endpoint. #[derive(ToSchema, Serialize, Debug)] pub struct ServerResBody { /// The server name to delegate server-server communications to, with /// optional port. #[serde(rename = "m.server")] pub server: OwnedServerName, } impl ServerResBody { /// Creates a new `Response` with the given homeserver. pub fn new(server: OwnedServerName) -> Self { Self { server } } } // /// `POST /_matrix/key/*/query` // /// // /// Query for keys from multiple servers in a batch format. The receiving // /// (notary) server must sign the keys returned by the queried servers. // /// `/v2/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/server-server-api/#post_matrixkeyv2query // const METADATA: Metadata = metadata! { // method: POST, // rate_limited: false, // authentication: None, // history: { // 1.0 => "/_matrix/key/v2/query", // } // }; pub fn remote_server_keys_batch_request( origin: &str, body: RemoteServerKeysBatchReqBody, ) -> SendResult<SendRequest> { let url = Url::parse(&format!("{origin}/_matrix/key/v2/query",))?; crate::sending::post(url).stuff(body) } /// Request type for the `fetch_remote_server_keys_batch` endpoint. #[derive(ToSchema, Deserialize, Serialize, Debug)] pub struct RemoteServerKeysBatchReqBody { /// The query criteria. /// /// The outer string key on the object is the server name (eg: matrix.org). /// The inner string key is the Key ID to query for the particular /// server. If no key IDs are given to be queried, the notary server /// should query for all keys. If no servers are given, the /// notary server must return an empty server_keys array in the response. /// /// The notary server may return multiple keys regardless of the Key IDs /// given. pub server_keys: BTreeMap<OwnedServerName, BTreeMap<OwnedServerSigningKeyId, QueryCriteria>>, } crate::json_body_modifier!(RemoteServerKeysBatchReqBody); /// Response type for the `fetch_remote_server_keys_batch` endpoint. #[derive(ToSchema, Serialize, Deserialize, Debug)] pub struct RemoteServerKeysBatchResBody { /// The queried server's keys, signed by the notary server. pub server_keys: Vec<ServerSigningKeys>, } impl RemoteServerKeysBatchResBody { /// Creates a new `Response` with the given keys. pub fn new(server_keys: Vec<ServerSigningKeys>) -> Self { Self { server_keys } } } // /// `GET /_matrix/key/*/query/{serverName}` // /// // /// Query for another server's keys. The receiving (notary) server must sign the // /// keys returned by the queried server. // /// `/v2/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/server-server-api/#get_matrixkeyv2queryservername // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: None, // history: { // 1.0 => "/_matrix/key/v2/query/:server_name", // } // }; pub fn remote_server_keys_request( origin: &str, args: RemoteServerKeysReqArgs, ) -> SendResult<SendRequest> { let url = Url::parse(&format!( "{origin}/_matrix/key/v2/query/{}?minimum_valid_until_ts={}", args.server_name, args.minimum_valid_until_ts ))?; Ok(crate::sending::get(url)) } /// Request type for the `fetch_remote_server_keys` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct RemoteServerKeysReqArgs { /// The server's DNS name to query #[salvo(parameter(parameter_in = Path))] pub server_name: OwnedServerName, /// A millisecond POSIX timestamp in milliseconds indicating when the /// returned certificates will need to be valid until to be useful to /// the requesting server. /// /// If not supplied, the current time as determined by the receiving server /// is used. #[salvo(parameter(parameter_in = Query))] #[serde(default = "UnixMillis::now")] pub minimum_valid_until_ts: UnixMillis, } /// Response type for the `fetch_remote_server_keys` endpoint. #[derive(ToSchema, Deserialize, Serialize, Debug)] pub struct RemoteServerKeysResBody { /// The queried server's keys, signed by the notary server. pub server_keys: Vec<ServerSigningKeys>, } impl RemoteServerKeysResBody { /// Creates a new `Response` with the given keys. pub fn new(server_keys: Vec<ServerSigningKeys>) -> Self { Self { server_keys } } } // /// `GET /_matrix/federation/*/version` // /// // /// Get the implementation name and version of this homeserver. // /// `/v1/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/server-server-api/#get_matrixfederationv1version // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: None, // history: { // 1.0 => "/_matrix/federation/v1/version", // } // }; /// Response type for the `get_server_version` endpoint. #[derive(ToSchema, Serialize, Default, Debug)] pub struct ServerVersionResBody { /// Information about the homeserver implementation #[serde(skip_serializing_if = "Option::is_none")] pub server: Option<Server>, } impl ServerVersionResBody { /// Creates an empty `Response`. pub fn new() -> Self { Default::default() } } // /// Endpoint to receive metadata about implemented matrix versions. // /// // /// Get the supported matrix versions of this homeserver // /// [GET /_matrix/federation/versions](https://github.com/matrix-org/matrix-spec-proposals/pull/3723) // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: None, // history: { // unstable => "/_matrix/federation/unstable/org.matrix.msc3723/versions", // } // }; /// Response type for the `get_server_versions` endpoint. #[derive(ToSchema, Serialize, Default, Debug)] pub struct ServerVersionsResBody { /// A list of Matrix Server API protocol versions supported by the /// homeserver. pub versions: Vec<String>, } impl ServerVersionsResBody { /// Creates an empty `Response`. pub fn new() -> Self { Default::default() } } // /// `GET /_matrix/key/*/server` // /// // /// Get the homeserver's published signing keys. // /// `/v2/` ([spec]) // /// // /// [spec]: https://spec.matrix.org/latest/server-server-api/#get_matrixkeyv2server // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: None, // history: { // 1.0 => "/_matrix/key/v2/server", // } // }; pub fn server_keys_request(origin: &str) -> SendResult<SendRequest> { let url = Url::parse(&format!("{origin}/_matrix/key/v2/server",))?; Ok(crate::sending::get(url)) } /// Response type for the `get_server_keys` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct ServerKeysResBody( /// Queried server key, signed by the notary server. pub ServerSigningKeys, ); impl ServerKeysResBody { /// Creates a new `Response` with the given server key. pub fn new(server_key: ServerSigningKeys) -> Self { Self(server_key) } } impl From<ServerSigningKeys> for ServerKeysResBody { fn from(server_key: ServerSigningKeys) -> Self { Self::new(server_key) } } impl Serialize for ServerKeysResBody { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut st = serializer.serialize_struct("server_keys_res_body", 2)?; st.serialize_field("old_verify_keys", &self.0.old_verify_keys)?; st.serialize_field("server_name", &self.0.server_name)?; st.serialize_field("signatures", &self.0.signatures)?; st.serialize_field("valid_until_ts", &self.0.valid_until_ts)?; st.serialize_field("verify_keys", &self.0.verify_keys)?; st.end() } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/transaction.rs
crates/core/src/federation/transaction.rs
/// Endpoints for exchanging transaction messages between homeservers. /// /// `PUT /_matrix/federation/*/send/{txn_id}` /// /// Send live activity messages to another server. /// `/v1/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/server-server-api/#put_matrixfederationv1sendtxnid use std::collections::BTreeMap; use reqwest::Url; use salvo::prelude::*; use serde::{Deserialize, Serialize, de}; use crate::{ OwnedServerName, UnixMillis, device::{DeviceListUpdateContent, DirectDeviceContent}, encryption::CrossSigningKey, events::{ receipt::{Receipt, ReceiptContent}, typing::TypingContent, }, identifiers::*, presence::PresenceContent, sending::{SendRequest, SendResult}, serde::{JsonValue, RawJsonValue, from_raw_json_value}, }; // const METADATA: Metadata = metadata! { // method: PUT, // rate_limited: false, // authentication: ServerSignatures, // history: { // 1.0 => "/_matrix/federation/v1/send/:transaction_id", // } // }; pub fn send_message_request( origin: &str, txn_id: &str, body: SendMessageReqBody, ) -> SendResult<SendRequest> { let url = Url::parse(&format!("{origin}/_matrix/federation/v1/send/{txn_id}"))?; crate::sending::put(url).stuff(body) } /// Request type for the `send_transaction_message` endpoint. #[derive(ToSchema, Deserialize, Serialize, Debug)] pub struct SendMessageReqBody { // /// A transaction ID unique between sending and receiving homeservers. // #[salvo(parameter(parameter_in = Path))] // pub transaction_id: OwnedTransactionId, /// The server_name of the homeserver sending this transaction. pub origin: OwnedServerName, /// POSIX timestamp in milliseconds on the originating homeserver when this /// transaction started. pub origin_server_ts: UnixMillis, /// List of persistent updates to rooms. /// /// Must not be more than 50 items. /// /// With the `unstable-unspecified` feature, sending `pdus` is optional. /// See [matrix-spec#705](https://github.com/matrix-org/matrix-spec/issues/705). #[cfg_attr( feature = "unstable-unspecified", serde(default, skip_serializing_if = "<[_]>::is_empty") )] #[salvo(schema(value_type = Vec<Object>))] pub pdus: Vec<Box<RawJsonValue>>, /// List of ephemeral messages. /// /// Must not be more than 100 items. #[serde(default, skip_serializing_if = "<[_]>::is_empty")] pub edus: Vec<Edu>, } crate::json_body_modifier!(SendMessageReqBody); /// Response type for the `send_transaction_message` endpoint. #[derive(ToSchema, Serialize, Deserialize, Debug)] pub struct SendMessageResBody { /// Map of event IDs and response for each PDU given in the request. /// /// With the `unstable-msc3618` feature, returning `pdus` is optional. /// See [MSC3618](https://github.com/matrix-org/matrix-spec-proposals/pull/3618). #[serde(default, with = "crate::serde::pdu_process_response")] pub pdus: BTreeMap<OwnedEventId, Result<(), String>>, } crate::json_body_modifier!(SendMessageResBody); impl SendMessageResBody { /// Creates a new `Response` with the given PDUs. pub fn new(pdus: BTreeMap<OwnedEventId, Result<(), String>>) -> Self { Self { pdus } } } /// Type for passing ephemeral data to homeservers. #[derive(ToSchema, Clone, Debug, Serialize)] #[serde(tag = "edu_type", content = "content")] pub enum Edu { /// An EDU representing presence updates for users of the sending /// homeserver. #[serde(rename = "m.presence")] Presence(PresenceContent), /// An EDU representing receipt updates for users of the sending homeserver. #[serde(rename = "m.receipt")] Receipt(ReceiptContent), /// A typing notification EDU for a user in a room. #[serde(rename = "m.typing")] Typing(TypingContent), /// An EDU that lets servers push details to each other when one of their /// users adds a new device to their account, required for E2E /// encryption to correctly target the current set of devices for a /// given user. #[serde(rename = "m.device_list_update")] DeviceListUpdate(DeviceListUpdateContent), /// An EDU that lets servers push send events directly to a specific device /// on a remote server - for instance, to maintain an Olm E2E encrypted /// message channel between a local and remote device. #[serde(rename = "m.direct_to_device")] DirectToDevice(DirectDeviceContent), /// An EDU that lets servers push details to each other when one of their /// users updates their cross-signing keys. #[serde(rename = "m.signing_key_update")] #[salvo(schema(value_type = Object))] SigningKeyUpdate(SigningKeyUpdateContent), #[doc(hidden)] #[salvo(schema(value_type = Object))] _Custom(JsonValue), } #[derive(Debug, Deserialize)] struct EduDeHelper { /// The message type field edu_type: String, content: Box<RawJsonValue>, } impl<'de> Deserialize<'de> for Edu { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: de::Deserializer<'de>, { let json = Box::<RawJsonValue>::deserialize(deserializer)?; let EduDeHelper { edu_type, content } = from_raw_json_value(&json)?; Ok(match edu_type.as_ref() { "m.presence" => Self::Presence(from_raw_json_value(&content)?), "m.receipt" => Self::Receipt(from_raw_json_value(&content)?), "m.typing" => Self::Typing(from_raw_json_value(&content)?), "m.device_list_update" => Self::DeviceListUpdate(from_raw_json_value(&content)?), "m.direct_to_device" => Self::DirectToDevice(from_raw_json_value(&content)?), "m.signing_key_update" => Self::SigningKeyUpdate(from_raw_json_value(&content)?), _ => Self::_Custom(from_raw_json_value(&content)?), }) } } /// Mapping between user and `ReceiptData`. #[derive(ToSchema, Deserialize, Serialize, Clone, Debug)] pub struct ReceiptMap { /// Read receipts for users in the room. #[serde(rename = "m.read")] pub read: BTreeMap<OwnedUserId, ReceiptData>, } impl ReceiptMap { /// Creates a new `ReceiptMap`. pub fn new(read: BTreeMap<OwnedUserId, ReceiptData>) -> Self { Self { read } } } /// Metadata about the event that was last read and when. #[derive(Clone, Debug, Deserialize, Serialize)] pub struct ReceiptData { /// Metadata for the read receipt. pub data: Receipt, /// The extremity event ID the user has read up to. pub event_ids: Vec<OwnedEventId>, } impl ReceiptData { /// Creates a new `ReceiptData`. pub fn new(data: Receipt, event_ids: Vec<OwnedEventId>) -> Self { Self { data, event_ids } } } /// The content for an `m.signing_key_update` EDU. #[derive(ToSchema, Deserialize, Serialize, Clone, Debug)] pub struct SigningKeyUpdateContent { /// The user ID whose cross-signing keys have changed. pub user_id: OwnedUserId, /// The user's master key, if it was updated. #[serde(skip_serializing_if = "Option::is_none")] pub master_key: Option<CrossSigningKey>, /// The users's self-signing key, if it was updated. #[serde(skip_serializing_if = "Option::is_none")] pub self_signing_key: Option<CrossSigningKey>, } impl SigningKeyUpdateContent { /// Creates a new `SigningKeyUpdateContent`. pub fn new(user_id: OwnedUserId) -> Self { Self { user_id, master_key: None, self_signing_key: None, } } } // #[cfg(test)] // mod tests { // use crate::events::ToDeviceEventType; // use crate::{room_id, user_id}; // use assert_matches2::assert_matches; // use serde_json::json; // use super::{DeviceListUpdateContent, Edu, ReceiptContent}; // #[test] // fn device_list_update_edu() { // let json = json!({ // "content": { // "deleted": false, // "device_display_name": "Mobile", // "device_id": "QBUAZIFURK", // "keys": { // "algorithms": [ // "m.olm.v1.curve25519-aes-sha2", // "m.megolm.v1.aes-sha2" // ], // "device_id": "JLAFKJWSCS", // "keys": { // "curve25519:JLAFKJWSCS": // "3C5BFWi2Y8MaVvjM8M22DBmh24PmgR0nPvJOIArzgyI", // "ed25519:JLAFKJWSCS": "lEuiRJBit0IG6nUf5pUzWTUEsRVVe/HJkoKuEww9ULI" // }, // "signatures": { // "@alice:example.com": { // "ed25519:JLAFKJWSCS": // "dSO80A01XiigH3uBiDVx/EjzaoycHcjq9lfQX0uWsqxl2giMIiSPR8a4d291W1ihKJL/ // a+myXS367WT6NAIcBA" } // }, // "user_id": "@alice:example.com" // }, // "stream_id": 6, // "user_id": "@john:example.com" // }, // "edu_type": "m.device_list_update" // }); // let edu = serde_json::from_value::<Edu>(json.clone()).unwrap(); // assert_matches!( // &edu, // Edu::DeviceListUpdate(DeviceListUpdateContent { // user_id, // device_id, // device_display_name, // stream_id, // prev_id, // deleted, // keys, // }) // ); // assert_eq!(user_id, "@john:example.com"); // assert_eq!(device_id, "QBUAZIFURK"); // assert_eq!(device_display_name.as_deref(), Some("Mobile")); // assert_eq!(*stream_id, u6); // assert_eq!(*prev_id, vec![]); // assert_eq!(*deleted, Some(false)); // assert_matches!(keys, Some(_)); // assert_eq!(serde_json::to_value(&edu).unwrap(), json); // } // #[test] // fn minimal_device_list_update_edu() { // let json = json!({ // "content": { // "device_id": "QBUAZIFURK", // "stream_id": 6, // "user_id": "@john:example.com" // }, // "edu_type": "m.device_list_update" // }); // let edu = serde_json::from_value::<Edu>(json.clone()).unwrap(); // assert_matches!( // &edu, // Edu::DeviceListUpdate(DeviceListUpdateContent { // user_id, // device_id, // device_display_name, // stream_id, // prev_id, // deleted, // keys, // }) // ); // assert_eq!(user_id, "@john:example.com"); // assert_eq!(device_id, "QBUAZIFURK"); // assert_eq!(*device_display_name, None); // assert_eq!(*stream_id, u6); // assert_eq!(*prev_id, vec![]); // assert_eq!(*deleted, None); // assert_matches!(keys, None); // assert_eq!(serde_json::to_value(&edu).unwrap(), json); // } // #[test] // fn receipt_edu() { // let json = json!({ // "content": { // "!some_room:example.org": { // "m.read": { // "@john:matrix.org": { // "data": { // "ts": 1_533_358 // }, // "event_ids": [ // "$read_this_event:matrix.org" // ] // } // } // } // }, // "edu_type": "m.receipt" // }); // let edu = serde_json::from_value::<Edu>(json.clone()).unwrap(); // assert_matches!(&edu, Edu::Receipt(ReceiptContent { receipts })); // assert!(receipts.get(room_id!("!some_room:example.org")).is_some()); // assert_eq!(serde_json::to_value(&edu).unwrap(), json); // } // #[test] // fn typing_edu() { // let json = json!({ // "content": { // "room_id": "!somewhere:matrix.org", // "typing": true, // "user_id": "@john:matrix.org" // }, // "edu_type": "m.typing" // }); // let edu = serde_json::from_value::<Edu>(json.clone()).unwrap(); // assert_matches!(&edu, Edu::Typing(content)); // assert_eq!(content.room_id, "!somewhere:matrix.org"); // assert_eq!(content.user_id, "@john:matrix.org"); // assert!(content.typing); // assert_eq!(serde_json::to_value(&edu).unwrap(), json); // } // #[test] // fn direct_to_device_edu() { // let json = json!({ // "content": { // "message_id": "hiezohf6Hoo7kaev", // "messages": { // "@alice:example.org": { // "IWHQUZUIAH": { // "algorithm": "m.megolm.v1.aes-sha2", // "room_id": "!Cuyf34gef24t:localhost", // "session_id": // "X3lUlvLELLYxeTx4yOVu6UDpasGEVO0Jbu+QFnm0cKQ", // "session_key": "AgAAAADxKHa9uFxcXzwYoNueL5Xqi69IkD4sni8LlfJL7qNBEY..." // } // } // }, // "sender": "@john:example.com", // "type": "m.room_key_request" // }, // "edu_type": "m.direct_to_device" // }); // let edu = serde_json::from_value::<Edu>(json.clone()).unwrap(); // assert_matches!(&edu, Edu::DirectToDevice(content)); // assert_eq!(content.sender, "@john:example.com"); // assert_eq!(content.ev_type, ToDeviceEventType::RoomKeyRequest); // assert_eq!(content.message_id, "hiezohf6Hoo7kaev"); // assert!(content.messages.get(user_id!("@alice:example.org")). // is_some()); // assert_eq!(serde_json::to_value(&edu).unwrap(), json); // } // #[test] // fn signing_key_update_edu() { // let json = json!({ // "content": { // "master_key": { // "keys": { // "ed25519:alice+base64+public+key": // "alice+base64+public+key", // "ed25519:base64+master+public+key": "base64+master+public+key" // }, "signatures": { // "@alice:example.com": { // "ed25519:alice+base64+master+key": // "signature+of+key" } // }, // "usage": [ // "master" // ], // "user_id": "@alice:example.com" // }, // "self_signing_key": { // "keys": { // "ed25519:alice+base64+public+key": // "alice+base64+public+key", // "ed25519:base64+self+signing+public+key": // "base64+self+signing+master+public+key" }, // "signatures": { // "@alice:example.com": { // "ed25519:alice+base64+master+key": // "signature+of+key", // "ed25519:base64+master+public+key": "signature+of+self+signing+key" // } // }, // "usage": [ // "self_signing" // ], // "user_id": "@alice:example.com" // }, // "user_id": "@alice:example.com" // }, // "edu_type": "m.signing_key_update" // }); // let edu = serde_json::from_value::<Edu>(json.clone()).unwrap(); // assert_matches!(&edu, Edu::SigningKeyUpdate(content)); // assert_eq!(content.user_id, "@alice:example.com"); // assert!(content.master_key.is_some()); // assert!(content.self_signing_key.is_some()); // assert_eq!(serde_json::to_value(&edu).unwrap(), json); // } // }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/serde/v1_pdu.rs
crates/core/src/federation/serde/v1_pdu.rs
//! A module to deserialize a response from incorrectly specified endpoint: //! //! - [PUT /_matrix/federation/v1/send_join/{room_id}/{event_id}](https://spec.matrix.org/latest/server-server-api/#put_matrixfederationv1send_joinroomideventid) //! - [PUT /_matrix/federation/v1/invite/{room_id}/{event_id}](https://spec.matrix.org/latest/server-server-api/#put_matrixfederationv1inviteroomideventid) //! - [PUT /_matrix/federation/v1/send_leave/{room_id}/{event_id}](https://spec.matrix.org/latest/server-server-api/#put_matrixfederationv1send_leaveroomideventid) //! //! For more information, see this [GitHub issue][issue]. //! //! [issue]: https://github.com/matrix-org/matrix-spec-proposals/issues/2541 use std::{fmt, marker::PhantomData}; use serde::{ de::{Deserialize, Deserializer, Error, IgnoredAny, SeqAccess, Visitor}, ser::{Serialize, SerializeSeq, Serializer}, }; pub(crate) fn serialize<T, S>(val: &T, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, T: Serialize, { let mut seq = serializer.serialize_seq(Some(2))?; seq.serialize_element(&200)?; seq.serialize_element(val)?; seq.end() } pub(crate) fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error> where D: Deserializer<'de>, T: Deserialize<'de>, { deserializer.deserialize_seq(PduVisitor { phantom: PhantomData, }) } struct PduVisitor<T> { phantom: PhantomData<T>, } impl<'de, T> Visitor<'de> for PduVisitor<T> where T: Deserialize<'de>, { type Value = T; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("a PDU wrapped in an array.") } fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> where A: SeqAccess<'de>, { let expected = "a two-element list in the response"; if seq.next_element::<IgnoredAny>()?.is_none() { return Err(A::Error::invalid_length(0, &expected)); } let val = seq .next_element()? .ok_or_else(|| A::Error::invalid_length(1, &expected))?; while let Some(IgnoredAny) = seq.next_element()? { // ignore extra elements } Ok(val) } } // #[cfg(not(feature = "unstable-unspecified"))] // #[cfg(test)] // mod tests { // use assert_matches2::assert_matches; // use serde_json::json; // use super::{deserialize, serialize}; // use crate::membership::create_join_event::v1::RoomState; // #[test] // fn deserialize_response() { // let response = json!([ // 200, // { // "origin": "example.com", // "auth_chain": [], // "state": [] // } // ]); // let RoomState { // origin, // auth_chain, // state, // event, // } = deserialize(response).unwrap(); // assert_eq!(origin, "example.com"); // assert_matches!(auth_chain.as_slice(), []); // assert_matches!(state.as_slice(), []); // assert_matches!(event, None); // } // #[test] // fn serialize_response() { // let room_state = RoomState { // origin: "matrix.org".into(), // auth_chain: Vec::new(), // state: Vec::new(), // event: None, // }; // let serialized = serialize(&room_state, // serde_json::value::Serializer).unwrap(); let expected = json!( // [ // 200, // { // "origin": "matrix.org", // "auth_chain": [], // "state": [] // } // ] // ); // assert_eq!(serialized, expected); // } // #[test] // fn too_short_array() { // let json = json!([200]); // let failed_room_state = deserialize::<RoomState, _>(json); // assert_eq!( // failed_room_state.unwrap_err().to_string(), // "invalid length 1, expected a two-element list in the response" // ); // } // #[test] // fn not_an_array() { // let json = json!({ // "origin": "matrix.org", // "auth_chain": [], // "state": [] // }); // let failed_room_state = deserialize::<RoomState, _>(json); // assert_eq!( // failed_room_state.unwrap_err().to_string(), // "invalid type: map, expected a PDU wrapped in an array.", // ); // } // #[test] // fn too_long_array() { // let json = json!([200, { "origin": "", "auth_chain": [], "state": [] // }, 200]); let RoomState { // origin, // auth_chain, // state, // event, // } = deserialize(json).unwrap(); // assert_eq!(origin, ""); // assert_matches!(auth_chain.as_slice(), []); // assert_matches!(state.as_slice(), []); // assert_matches!(event, None); // } // }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/serde/pdu_process_response.rs
crates/core/src/federation/serde/pdu_process_response.rs
use std::{collections::BTreeMap, fmt}; use serde::{ Deserialize, Serialize, de::{Deserializer, MapAccess, Visitor}, ser::{SerializeMap, Serializer}, }; use crate::OwnedEventId; #[derive(Deserialize, Serialize)] struct WrappedError { #[serde(skip_serializing_if = "Option::is_none")] error: Option<String>, } pub(crate) fn serialize<S>( response: &BTreeMap<OwnedEventId, Result<(), String>>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { let mut map = serializer.serialize_map(Some(response.len()))?; for (key, value) in response { let wrapped_error = WrappedError { error: value.clone().err(), }; map.serialize_entry(&key, &wrapped_error)?; } map.end() } #[allow(clippy::type_complexity)] pub(crate) fn deserialize<'de, D>( deserializer: D, ) -> Result<BTreeMap<OwnedEventId, Result<(), String>>, D::Error> where D: Deserializer<'de>, { struct PduProcessResponseVisitor; impl<'de> Visitor<'de> for PduProcessResponseVisitor { type Value = BTreeMap<OwnedEventId, Result<(), String>>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("A map of EventIds to a map of optional errors") } fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error> where M: MapAccess<'de>, { let mut map = BTreeMap::new(); while let Some((key, value)) = access.next_entry::<OwnedEventId, WrappedError>()? { let v = match value.error { None => Ok(()), Some(error) => Err(error), }; map.insert(key, v); } Ok(map) } } deserializer.deserialize_map(PduProcessResponseVisitor) } #[cfg(test)] mod tests { use std::collections::BTreeMap; use serde_json::{json, value::Serializer as JsonSerializer}; use super::{deserialize, serialize}; use crate::{OwnedEventId, event_id, owned_event_id}; #[test] fn serialize_error() { let mut response: BTreeMap<OwnedEventId, Result<(), String>> = BTreeMap::new(); response.insert( owned_event_id!("$someevent:matrix.org"), Err("Some processing error.".into()), ); let serialized = serialize(&response, JsonSerializer).unwrap(); let json = json!({ "$someevent:matrix.org": { "error": "Some processing error." } }); assert_eq!(serialized, json); } #[test] fn serialize_ok() { let mut response: BTreeMap<OwnedEventId, Result<(), String>> = BTreeMap::new(); response.insert(owned_event_id!("$someevent:matrix.org"), Ok(())); let serialized = serialize(&response, serde_json::value::Serializer).unwrap(); let json = json!({ "$someevent:matrix.org": {} }); assert_eq!(serialized, json); } #[test] fn deserialize_error() { let json = json!({ "$someevent:matrix.org": { "error": "Some processing error." } }); let response = deserialize(json).unwrap(); let event_id = event_id!("$someevent:matrix.org"); let event_response = response.get(event_id).unwrap().clone().unwrap_err(); assert_eq!(event_response, "Some processing error."); } #[test] fn deserialize_null_error_is_ok() { let json = json!({ "$someevent:matrix.org": { "error": null } }); let response = deserialize(json).unwrap(); let event_id = event_id!("$someevent:matrix.org"); response.get(event_id).unwrap().as_ref().unwrap(); } #[test] fn deserialize_empty_error_is_err() { let json = json!({ "$someevent:matrix.org": { "error": "" } }); let response = deserialize(json).unwrap(); let event_id = event_id!("$someevent:matrix.org"); let event_response = response.get(event_id).unwrap().clone().unwrap_err(); assert_eq!(event_response, ""); } #[test] fn deserialize_ok() { let json = json!({ "$someevent:matrix.org": {} }); let response = deserialize(json).unwrap(); response .get(event_id!("$someevent:matrix.org")) .unwrap() .as_ref() .unwrap(); } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/authenticated_media/get_content.rs
crates/core/src/federation/authenticated_media/get_content.rs
//! `GET /_matrix/federation/*/media/download/{mediaId}` //! //! Retrieve content from the media store. pub mod unstable; pub mod v1;
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/authenticated_media/get_content_thumbnail.rs
crates/core/src/federation/authenticated_media/get_content_thumbnail.rs
//! `GET /_matrix/federation/*/media/thumbnail/{mediaId}` //! //! Get a thumbnail of content from the media repository. pub mod unstable; pub mod v1;
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/authenticated_media/get_content/unstable.rs
crates/core/src/federation/authenticated_media/get_content/unstable.rs
//! `/unstable/org.matrix.msc3916.v2/` ([MSC]) //! //! [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/3916 use std::time::Duration; use salvo::oapi::ToParameters; use serde::Deserialize; /// Request type for the `get_content` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct GetMediaContentArgs { /// The media ID from the `mxc://` URI (the path component). #[salvo(parameter(parameter_in = Path))] pub media_id: String, /// The maximum duration that the client is willing to wait to start receiving data, in the /// case that the content has not yet been uploaded. /// /// The default value is 20 seconds. #[salvo(parameter(parameter_in = Query))] #[serde( with = "crate::serde::duration::ms", default = "crate::media::default_download_timeout", skip_serializing_if = "crate::media::is_default_download_timeout" )] pub timeout_ms: Duration, } impl GetMediaContentArgs { /// Creates a new `GetMediaContentArgs` with the given media ID. pub fn new(media_id: String) -> Self { Self { media_id, timeout_ms: crate::media::default_download_timeout(), } } } // impl Metadata for Request { // const METHOD: http::Method = super::v1::Request::METHOD; // const RATE_LIMITED: bool = super::v1::Request::RATE_LIMITED; // type Authentication = <super::v1::Request as Metadata>::Authentication; // type PathBuilder = <super::v1::Request as Metadata>::PathBuilder; // const PATH_BUILDER: Self::PathBuilder = SinglePath::new( // "/_matrix/federation/unstable/org.matrix.msc3916.v2/media/download/{media_id}", // ); // } // impl From<super::v1::Request> for Request { // fn from(value: super::v1::Request) -> Self { // let super::v1::Request { // media_id, // timeout_ms, // } = value; // Self { // media_id, // timeout_ms, // } // } // } // impl From<Request> for super::v1::Request { // fn from(value: Request) -> Self { // let Request { // media_id, // timeout_ms, // } = value; // Self { // media_id, // timeout_ms, // } // } // } // /// Response type for the `get_content` endpoint. // #[derive(ToSchema, Serialize, Clone, Debug)] // pub struct GetMediaContentResBody { // /// The metadata of the media. // pub metadata: ContentMetadata, // /// The content of the media. // pub content: FileOrLocation, // } // impl GetMediaContentResBody { // /// Creates a new `GetMediaContentResBody` with the given metadata and content. // pub fn new(metadata: ContentMetadata, content: FileOrLocation) -> Self { // Self { metadata, content } // } // } // #[cfg(feature = "client")] // impl crate::api::IncomingResponse for Response { // type EndpointError = <super::v1::Response as crate::api::IncomingResponse>::EndpointError; // fn try_from_http_response<T: AsRef<[u8]>>( // http_response: http::Response<T>, // ) -> Result<Self, crate::api::error::FromHttpResponseError<Self::EndpointError>> { // // Reuse the custom deserialization. // Ok(super::v1::Response::try_from_http_response(http_response)?.into()) // } // } // #[cfg(feature = "server")] // impl crate::api::OutgoingResponse for Response { // fn try_into_http_response<T: Default + bytes::BufMut>( // self, // ) -> Result<http::Response<T>, crate::api::error::IntoHttpError> { // // Reuse the custom serialization. // super::v1::Response::from(self).try_into_http_response() // } // } // impl From<super::v1::Response> for Response { // fn from(value: super::v1::Response) -> Self { // let super::v1::Response { metadata, content } = value; // Self { metadata, content } // } // } // impl From<Response> for super::v1::Response { // fn from(value: Response) -> Self { // let Response { metadata, content } = value; // Self { metadata, content } // } // }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/authenticated_media/get_content/v1.rs
crates/core/src/federation/authenticated_media/get_content/v1.rs
//! `/v1/` ([spec]) //! //! [spec]: https://spec.matrix.org/latest/server-server-api/#get_matrixfederationv1mediadownloadmediaid use std::time::Duration; use salvo::oapi::ToParameters; use serde::Deserialize; // metadata! { // method: GET, // rate_limited: true, // authentication: ServerSignatures, // path: "/_matrix/federation/v1/media/download/{media_id}", // } /// Request type for the `get_content` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct MediaDownloadArgs { /// The media ID from the `mxc://` URI (the path component). #[salvo(parameter(parameter_in = Path))] pub media_id: String, /// The maximum duration that the client is willing to wait to start receiving data, in the /// case that the content has not yet been uploaded. /// /// The default value is 20 seconds. #[salvo(parameter(parameter_in = Query))] #[serde( with = "crate::serde::duration::ms", default = "crate::media::default_download_timeout", skip_serializing_if = "crate::media::is_default_download_timeout" )] pub timeout_ms: Duration, } impl MediaDownloadArgs { /// Creates a new `Request` with the given media ID. pub fn new(media_id: String) -> Self { Self { media_id, timeout_ms: crate::media::default_download_timeout(), } } } // /// Response type for the `get_content` endpoint. // #[derive(ToSchema, Serialize, Clone, Debug)] // pub struct MediaDownloadResBody { // /// The metadata of the media. // pub metadata: ContentMetadata, // /// The content of the media. // pub content: FileOrLocation, // } // impl MediaDownloadResBody { // /// Creates a new `Response` with the given metadata and content. // pub fn new(metadata: ContentMetadata, content: FileOrLocation) -> Self { // Self { metadata, content } // } // }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/authenticated_media/get_content_thumbnail/unstable.rs
crates/core/src/federation/authenticated_media/get_content_thumbnail/unstable.rs
//! `/unstable/org.matrix.msc3916.v2/` ([MSC]) //! //! [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/3916 use std::time::Duration; use salvo::oapi::ToParameters; use serde::Deserialize; use crate::federation::authenticated_media::{ContentMetadata, FileOrLocation}; use crate::media::ResizeMethod; /// Request type for the `get_content_thumbnail` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct GetContentThumbnailArgs { /// The media ID from the `mxc://` URI (the path component). #[salvo(parameter(parameter_in = Path))] pub media_id: String, /// The desired resizing method. #[salvo(parameter(parameter_in = Query))] #[serde(skip_serializing_if = "Option::is_none")] pub method: Option<ResizeMethod>, /// The *desired* width of the thumbnail. /// /// The actual thumbnail may not match the size specified. #[salvo(parameter(parameter_in = Query))] pub width: u32, /// The *desired* height of the thumbnail. /// /// The actual thumbnail may not match the size specified. #[salvo(parameter(parameter_in = Query))] pub height: u32, /// The maximum duration that the client is willing to wait to start receiving data, in the /// case that the content has not yet been uploaded. /// /// The default value is 20 seconds. #[salvo(parameter(parameter_in = Query))] #[serde( with = "crate::serde::duration::ms", default = "crate::media::default_download_timeout", skip_serializing_if = "crate::media::is_default_download_timeout" )] pub timeout_ms: Duration, /// Whether the server should return an animated thumbnail. /// /// When `Some(true)`, the server should return an animated thumbnail if possible and /// supported. When `Some(false)`, the server must not return an animated /// thumbnail. When `None`, the server should not return an animated thumbnail. #[salvo(parameter(parameter_in = Query))] #[serde(skip_serializing_if = "Option::is_none")] pub animated: Option<bool>, } impl GetContentThumbnailArgs { /// Creates a new `Request` with the given media ID, desired thumbnail width /// and desired thumbnail height. pub fn new(media_id: String, width: u32, height: u32) -> Self { Self { media_id, method: None, width, height, timeout_ms: crate::media::default_download_timeout(), animated: None, } } } // impl Metadata for GetContentThumbnailArgs { // const METHOD: http::Method = super::v1::Request::METHOD; // const RATE_LIMITED: bool = super::v1::Request::RATE_LIMITED; // type Authentication = <super::v1::Request as Metadata>::Authentication; // type PathBuilder = <super::v1::Request as Metadata>::PathBuilder; // const PATH_BUILDER: Self::PathBuilder = SinglePath::new( // "/_matrix/federation/unstable/org.matrix.msc3916.v2/media/thumbnail/{media_id}", // ); // } // /// Response type for the `get_content_thumbnail` endpoint. // #[derive(ToSchema, Serialize, Clone, Debug)] // pub struct GetContentThumbnailResBody { // /// The metadata of the media. // pub metadata: ContentMetadata, // /// The content of the media. // pub content: FileOrLocation, // } // impl GetContentThumbnailResBody { // /// Creates a new `GetContentThumbnailResBody` with the given metadata and content. // pub fn new(metadata: ContentMetadata, content: FileOrLocation) -> Self { // Self { metadata, content } // } // }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/federation/authenticated_media/get_content_thumbnail/v1.rs
crates/core/src/federation/authenticated_media/get_content_thumbnail/v1.rs
//! `/v1/` ([spec]) //! //! [spec]: https://spec.matrix.org/latest/server-server-api/#get_matrixfederationv1mediathumbnailmediaid use std::time::Duration; use salvo::oapi::ToParameters; use serde::Deserialize; use crate::media::ResizeMethod; // metadata! { // method: GET, // rate_limited: true, // authentication: ServerSignatures, // path: "/_matrix/federation/v1/media/thumbnail/{media_id}", // } /// Request type for the `get_content_thumbnail` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct GetContentThumbnailArgs { /// The media ID from the `mxc://` URI (the path component). #[salvo(parameter(parameter_in = Path))] pub media_id: String, /// The desired resizing method. #[salvo(parameter(parameter_in = Query))] #[serde(skip_serializing_if = "Option::is_none")] pub method: Option<ResizeMethod>, /// The *desired* width of the thumbnail. /// /// The actual thumbnail may not match the size specified. #[salvo(parameter(parameter_in = Query))] pub width: u32, /// The *desired* height of the thumbnail. /// /// The actual thumbnail may not match the size specified. #[salvo(parameter(parameter_in = Query))] pub height: u32, /// The maximum duration that the client is willing to wait to start receiving data, in the /// case that the content has not yet been uploaded. /// /// The default value is 20 seconds. #[salvo(parameter(parameter_in = Query))] #[serde( with = "crate::serde::duration::ms", default = "crate::media::default_download_timeout", skip_serializing_if = "crate::media::is_default_download_timeout" )] pub timeout_ms: Duration, /// Whether the server should return an animated thumbnail. /// /// When `Some(true)`, the server should return an animated thumbnail if possible and /// supported. When `Some(false)`, the server must not return an animated /// thumbnail. When `None`, the server should not return an animated thumbnail. #[salvo(parameter(parameter_in = Query))] #[serde(skip_serializing_if = "Option::is_none")] pub animated: Option<bool>, } impl GetContentThumbnailArgs { /// Creates a new `GetContentThumbnailArgs` with the given media ID, desired thumbnail width /// and desired thumbnail height. pub fn new(media_id: String, width: u32, height: u32) -> Self { Self { media_id, method: None, width, height, timeout_ms: crate::media::default_download_timeout(), animated: None, } } } // /// Response type for the `get_content_thumbnail` endpoint. // #[derive(ToSchema, Serialize, Clone, Debug)] // pub struct GetContentThumbnailResBody { // /// The metadata of the thumbnail. // pub metadata: ContentMetadata, // /// The content of the thumbnail. // pub content: FileOrLocation, // } // impl GetContentThumbnailResBody { // /// Creates a new `GetContentThumbnailResBody` with the given metadata and content. // pub fn new(metadata: ContentMetadata, content: FileOrLocation) -> Self { // Self { metadata, content } // } // }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identity/discovery.rs
crates/core/src/identity/discovery.rs
//! `GET /_matrix/identity/versions` ([spec]) //! //! Get the versions of the identity service API supported by this endpoint. //! //! Note: This endpoint was only implemented in/after 1.1, so a 404 could indicate the server only //! supports 1.0 endpoints. Please use [`server_status`](super::get_server_status) to //! double-check. //! //! Note: This endpoint does not contain an unstable variant for 1.0. //! //! [spec]: https://spec.matrix.org/latest/identity-service-api/#get_matrixidentityversions use std::collections::BTreeMap; use crate::{ api::{MatrixVersion}, metadata, }; // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: None, // history: { // 1.1 => "/_matrix/identity/versions", // } // }; /// Response type for the `versions` endpoint. pub struct Response { /// A list of Matrix client API protocol versions supported by the endpoint. pub versions: Vec<String>, } impl Request { /// Creates an empty `Request`. pub fn new() -> Self { Self {} } } impl Response { /// Creates a new `Response` with the given `versions`. pub fn new(versions: Vec<String>) -> Self { Self { versions } } /// Extracts known Matrix versions from this response. /// /// Matrix versions that Palpo cannot parse, or does not know about, are discarded. /// /// The versions returned will be sorted from oldest to latest. Use [`.find()`][Iterator::find] /// or [`.rfind()`][DoubleEndedIterator::rfind] to look for a minimum or maximum version to use /// given some constraint. pub fn known_versions(&self) -> impl Iterator<Item = MatrixVersion> + DoubleEndedIterator { self.versions .iter() // Parse, discard unknown versions .flat_map(|s| s.parse::<MatrixVersion>()) // Map to key-value pairs where the key is the major-minor representation // (which can be used as a BTreeMap unlike MatrixVersion itself) .map(|v| (v.into_parts(), v)) // Collect to BTreeMap .collect::<BTreeMap<_, _>>() // Return an iterator over just the values (`MatrixVersion`s) .into_values() } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identity/key.rs
crates/core/src/identity/key.rs
/// `GET /_matrix/identity/*/pubkey/isvalid` /// /// Check whether a long-term public key is valid. The response should always be the same, provided /// the key exists. /// `/v2/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/identity-service-api/#get_matrixidentityv2pubkeyisvalid use crate::{serde::Base64, OwnedServerSigningKeyId}; // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: None, // history: { // 1.0 => "/_matrix/identity/v2/pubkey/isvalid", // } // }; // /// Request type for the `check_public_key_validity` endpoint. // pub struct Requexst { // /// Base64-encoded (no padding) public key to check for validity. // #[salvo(parameter(parameter_in = Query))] // pub public_key: Base64, // } /// Response type for the `check_public_key_validity` endpoint. #[derive(ToSchema,Serialize, Debug)] pub struct ValidityResBody { /// Whether the public key is recognised and is currently valid. pub valid: bool, } impl ValidityResBody { /// Create a `Response` with the given bool indicating the validity of the public key. pub fn new(valid: bool) -> Self { Self { valid } } } /// `GET /_matrix/identity/*/pubkey/{keyId}` /// /// Get the public key for the given key ID. /// `/v2/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/identity-service-api/#get_matrixidentityv2pubkeykeyid // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: None, // history: { // 1.0 => "/_matrix/identity/v2/pubkey/:key_id", // } // }; // /// Request type for the `get_public_key` endpoint. // pub struct Requxest { // /// The ID of the key. // #[salvo(parameter(parameter_in = Path))] // pub key_id: OwnedServerSigningKeyId, // } /// Response type for the `get_public_key` endpoint. #[derive(ToSchema,Serialize, Debug)] pub struct PublicKeyResBody { /// Unpadded base64-encoded public key. pub public_key: Base64, } impl PublicKeyResBody { /// Create a `Response` with the given base64-encoded (unpadded) public key. pub fn new(public_key: Base64) -> Self { Self { public_key } } } /// `GET /_matrix/identity/*/pubkey/ephemeral/isvalid` /// /// Check whether a short-term public key is valid. /// `/v2/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/identity-service-api/#get_matrixidentityv2pubkeyephemeralisvalid // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: None, // history: { // 1.0 => "/_matrix/identity/v2/pubkey/ephemeral/isvalid", // } // }; // /// Request type for the `validate_ephemeral_key` endpoint. // pub struct Rexquest { // /// The unpadded base64-encoded short-term public key to check. // #[salvo(parameter(parameter_in = Query))] // pub public_key: Base64, // } /// Response type for the `validate_ephemeral_key` endpoint. // pub struct ValidateEphemeralKeyResBody { // /// Whether the short-term public key is recognised and is currently valid. // pub valid: bool, // } // impl ValidateEphemeralKeyResBody { // /// Create a `Response` with the given bool indicating the validity of the short-term public // /// key. // pub fn new(valid: bool) -> Self { // Self { valid } // } // }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identity/invitation.rs
crates/core/src/identity/invitation.rs
/// `POST /_matrix/identity/*/sign-ed25519` /// /// Sign invitation details. /// `/v2/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/identity-service-api/#post_matrixidentityv2sign-ed25519 use crate::{serde::Base64, OwnedUserId, ServerSignatures}; // const METADATA: Metadata = metadata! { // method: POST, // rate_limited: false, // authentication: AccessToken, // history: { // 1.0 => "/_matrix/identity/v2/sign-ed25519", // } // }; /// Request type for the `sign_invitation_ed25519` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct SignInvitationReqBody { /// The Matrix user ID of the user accepting the invitation. pub mxid: OwnedUserId, /// The token from the call to store-invite. pub token: String, /// The private key, encoded as unpadded base64. pub private_key: Base64, } /// Response type for the `sign_invitation_ed25519` endpoint. #[derive(ToSchema,Serialize, Debug)] pub struct SignInvitationResBody { /// The Matrix user ID of the user accepting the invitation. pub mxid: OwnedUserId, /// The Matrix user ID of the user who sent the invitation. pub sender: OwnedUserId, /// The signature of the mxid, sender and token. pub signatures: ServerSignatures, /// The token for the invitation. pub token: String, } impl SignInvitationResBody { /// Creates a `Response` with the given Matrix user ID, sender user ID, signatures and /// token. pub fn new(mxid: OwnedUserId, sender: OwnedUserId, signatures: ServerSignatures, token: String) -> Self { Self { mxid, sender, signatures, token, } } } /// `POST /_matrix/identity/*/store-invite` /// /// Store pending invitations to a user's third-party ID. /// `/v2/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/identity-service-api/#post_matrixidentityv2store-invite use crate::{room::RoomType, third_party::Medium, OwnedMxcUri, OwnedRoomAliasId, OwnedRoomId, OwnedUserId}; use serde::{ser::SerializeSeq, Deserialize, Serialize}; // const METADATA: Metadata = metadata! { // method: POST, // rate_limited: false, // authentication: AccessToken, // history: { // 1.0 => "/_matrix/identity/v2/store-invite", // } // }; /// Request type for the `store_invitation` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct StoreInvitationReqBody { /// The type of the third party identifier for the invited user. /// /// Currently, only `Medium::Email` is supported. pub medium: Medium, /// The email address of the invited user. pub address: String, /// The Matrix room ID to which the user is invited. pub room_id: OwnedRoomId, /// The Matrix user ID of the inviting user. pub sender: OwnedUserId, /// The Matrix room alias for the room to which the user is invited. /// /// This should be retrieved from the `m.room.canonical` state event. #[serde(skip_serializing_if = "Option::is_none")] pub room_alias: Option<OwnedRoomAliasId>, /// The Content URI for the room to which the user is invited. /// /// This should be retrieved from the `m.room.avatar` state event. #[serde(skip_serializing_if = "Option::is_none")] pub room_avatar_url: Option<OwnedMxcUri>, /// The `join_rule` for the room to which the user is invited. /// /// This should be retrieved from the `m.room.join_rules` state event. #[serde(skip_serializing_if = "Option::is_none")] pub room_join_rules: Option<String>, /// The name of the room to which the user is invited. /// /// This should be retrieved from the `m.room.name` state event. #[serde(skip_serializing_if = "Option::is_none")] pub room_name: Option<String>, /// The type of the room to which the user is invited. /// /// This should be retrieved from the `m.room.create` state event. #[serde(skip_serializing_if = "Option::is_none")] pub room_type: Option<RoomType>, /// The display name of the user ID initiating the invite. #[serde(skip_serializing_if = "Option::is_none")] pub sender_display_name: Option<String>, /// The Content URI for the avater of the user ID initiating the invite. #[serde(skip_serializing_if = "Option::is_none")] pub sender_avatar_url: Option<OwnedMxcUri>, } /// Response type for the `store_invitation` endpoint. #[derive(ToSchema,Serialize, Debug)] pub struct StoreInvitationResBody { /// The generated token. /// /// Must be a string consisting of the characters `[0-9a-zA-Z.=_-]`. Its length must not /// exceed 255 characters and it must not be empty. pub token: String, /// A list of [server's long-term public key, generated ephemeral public key]. pub public_keys: PublicKeys, /// The generated (redacted) display_name. /// /// An example is `f...@b...`. pub display_name: String, } impl StoreInvitationResBody { /// Creates a new `Response` with the given token, public keys and display name. pub fn new(token: String, public_keys: PublicKeys, display_name: String) -> Self { Self { token, public_keys, display_name, } } } /// The server's long-term public key and generated ephemeral public key. #[derive(Debug, Clone)] #[allow(clippy::exhaustive_structs)] pub struct PublicKeys { /// The server's long-term public key. pub server_key: PublicKey, /// The generated ephemeral public key. pub ephemeral_key: PublicKey, } /// A server's long-term or ephemeral public key. #[derive(Clone, Debug, Serialize, Deserialize)] #[non_exhaustive] pub struct PublicKey { /// The public key, encoded using [unpadded Base64](https://spec.matrix.org/latest/appendices/#unpadded-base64). pub public_key: String, /// The URI of an endpoint where the validity of this key can be checked by passing it as a /// `public_key` query parameter. pub key_validity_url: String, } impl PublicKey { /// Constructs a new `PublicKey` with the given encoded public key and key validity URL. pub fn new(public_key: String, key_validity_url: String) -> Self { Self { public_key, key_validity_url, } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identity/tos.rs
crates/core/src/identity/tos.rs
/// `POST /_matrix/identity/*/terms` /// /// Send acceptance of the terms of service of an identity server. /// `/v2/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/identity-service-api/#post_matrixidentityv2terms // const METADATA: Metadata = metadata! { // method: POST, // rate_limited: false, // authentication: AccessToken, // history: { // 1.0 => "/_matrix/identity/v2/terms", // } // }; use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; /// Request type for the `accept_terms_of_service` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct AcceptTosReqBody { /// The URLs the user is accepting in this request. /// /// An example is `https://example.org/somewhere/terms-2.0-en.html`. pub user_accepts: Vec<String>, } /// `GET /_matrix/identity/*/terms` /// /// Get the terms of service of an identity server. /// `/v2/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/identity-service-api/#get_matrixidentityv2terms // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: None, // history: { // 1.0 => "/_matrix/identity/v2/terms", // } // }; /// Response type for the `get_terms_of_service` endpoint. #[derive(ToSchema,Serialize, Debug)] pub struct TosResBody { /// The policies the server offers. /// /// Mapped from arbitrary ID (unused in this version of the specification) to a Policy /// Object. pub policies: BTreeMap<String, Policies>, } impl TosResBody { /// Creates a new `Response` with the given `Policies`. pub fn new(policies: BTreeMap<String, Policies>) -> Self { Self { policies } } } /// Collection of localized policies. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Policies { /// The version for the policy. /// /// There are no requirements on what this might be and could be /// "alpha", semantically versioned, or arbitrary. pub version: String, /// Available languages for the policy. /// /// The keys could be the language code corresponding to /// the given `LocalizedPolicy`, for example "en" or "fr". #[serde(flatten)] pub localized: BTreeMap<String, LocalizedPolicy>, } impl Policies { /// Create a new `Policies` with the given version and localized map. pub fn new(version: String, localized: BTreeMap<String, LocalizedPolicy>) -> Self { Self { version, localized } } } /// A localized policy offered by a server. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct LocalizedPolicy { /// The localized name of the policy. /// /// Examples are "Terms of Service", "Conditions d'utilisation". pub name: String, /// The URL at which the policy is available. /// /// Examples are `https://example.org/somewhere/terms-2.0-en.html /// and `https://example.org/somewhere/terms-2.0-fr.html`. pub url: String, } impl LocalizedPolicy { /// Create a new `LocalizedPolicy` with the given name and url. pub fn new(name: String, url: String) -> Self { Self { name, url } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identity/lookup.rs
crates/core/src/identity/lookup.rs
/// Endpoints to look up Matrix IDs bound to 3PIDs. use std::collections::BTreeMap; use crate::lookup::IdentifierHashingAlgorithm; use crate::serde::StringEnum; use crate::{OwnedUserId, PrivOwnedStr}; /// The algorithms that can be used to hash the identifiers used for lookup, as defined in the /// Matrix Spec. /// /// This type can hold an arbitrary string. To build this with a custom value, convert it from a /// string with `::from()` / `.into()`. To check for values that are not available as a documented /// variant here, use its string representation, obtained through [`.as_str()`](Self::as_str()). #[derive(Clone, StringEnum)] #[non_exhaustive] #[palpo_enum(rename_all = "snake_case")] pub enum IdentifierHashingAlgorithm { /// The SHA-256 hashing algorithm. Sha256, /// No algorithm is used, and identifier strings are directly used for lookup. None, #[doc(hidden)] _Custom(PrivOwnedStr), } /// `POST /_matrix/identity/*/lookup` /// /// Looks up the set of Matrix User IDs which have bound the 3PIDs given, if bindings are available. /// `/v2/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/identity-service-api/#post_matrixidentityv2lookup // const METADATA: Metadata = metadata! { // method: POST, // rate_limited: false, // authentication: AccessToken, // history: { // 1.0 => "/_matrix/identity/v2/lookup", // } // }; /// Request type for the `lookup_3pid` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct LookupThreepidReqBody { /// The algorithm the client is using to encode the `addresses`. This should be one of the /// available options from `/hash_details`. pub algorithm: IdentifierHashingAlgorithm, /// The pepper from `/hash_details`. This is required even when the `algorithm` does not /// make use of it. pub pepper: String, /// The addresses to look up. /// /// The format of the entries here depend on the `algorithm` used. Note that queries which /// have been incorrectly hashed or formatted will lead to no matches. pub addresses: Vec<String>, } /// Response type for the `lookup_3pid` endpoint. #[derive(ToSchema,Serialize, Debug)] pub struct LookupThreepidResBody { /// Any applicable mappings of `addresses` to Matrix User IDs. /// /// Addresses which do not have associations will not be included, which can make this /// property be an empty object. pub mappings: BTreeMap<String, OwnedUserId>, } impl LookupThreepidResBody { /// Create a `Response` with the BTreeMap which map addresses from the request which were /// found to their corresponding User IDs. pub fn new(mappings: BTreeMap<String, OwnedUserId>) -> Self { Self { mappings } } } /// `GET /_matrix/identity/*/hash_details` /// /// Gets parameters for hashing identifiers from the server. This can include any of the algorithms /// defined in the spec. /// `/v2/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/identity-service-api/#get_matrixidentityv2hash_details // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: AccessToken, // history: { // 1.0 => "/_matrix/identity/v2/hash_details", // } // }; /// Response type for the `get_hash_parameters` endpoint. #[derive(ToSchema,Serialize, Debug)] pub struct HashParametersResBody { /// The pepper the client MUST use in hashing identifiers, and MUST supply to the /lookup /// endpoint when performing lookups. /// /// Servers SHOULD rotate this string often. pub lookup_pepper: String, /// The algorithms the server supports. /// /// Must contain at least `sha256`. pub algorithms: Vec<IdentifierHashingAlgorithm>, } impl HashParametersResBody { /// Create a new `Response` using the given pepper and `Vec` of algorithms. pub fn new(lookup_pepper: String, algorithms: Vec<IdentifierHashingAlgorithm>) -> Self { Self { lookup_pepper, algorithms } } } #[cfg(test)] mod tests { use super::IdentifierHashingAlgorithm; #[test] fn parse_identifier_hashing_algorithm() { assert_eq!(IdentifierHashingAlgorithm::from("sha256"), IdentifierHashingAlgorithm::Sha256); assert_eq!(IdentifierHashingAlgorithm::from("none"), IdentifierHashingAlgorithm::None); } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identity/authentication.rs
crates/core/src/identity/authentication.rs
use std::time::Duration; use crate::{authentication::TokenType, OwnedServerName, OwnedUserId}; /// `GET /_matrix/identity/*/account` /// /// Get information about what user owns the access token used in the request. /// `/v2/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/identity-service-api/#get_matrixidentityv2account // const METADATA: Metadata = metadata! { // method: POST, // rate_limited: false, // authentication: AccessToken, // history: { // 1.0 => "/_matrix/identity/v2/account", // } // }; /// Response type for the `get_account_information` endpoint. #[derive(ToSchema,Serialize, Debug)] pub struct AccountInfoResBody { /// The user ID which registered the token. pub user_id: OwnedUserId, } impl AccountInfoResBody { /// Creates a new `Response` with the given `UserId`. pub fn new(user_id: OwnedUserId) -> Self { Self { user_id } } } /// `POST /_matrix/identity/*/account/register` /// /// Exchanges an OpenID token from the homeserver for an access token to access the identity server. /// `/v2/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/identity-service-api/#post_matrixidentityv2accountregister // const METADATA: Metadata = metadata! { // method: POST, // rate_limited: false, // authentication: None, // history: { // 1.0 => "/_matrix/identity/v2/account/register", // } // }; /// Request type for the `register_account` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct RegisterAccountReqBody { /// An access token the consumer may use to verify the identity of the person who generated /// the token. /// /// This is given to the federation API `GET /openid/userinfo` to verify the user's /// identity. pub access_token: String, /// The string `Bearer`. pub token_type: TokenType, /// The homeserver domain the consumer should use when attempting to verify the user's /// identity. pub matrix_server_name: OwnedServerName, /// The number of seconds before this token expires and a new one must be generated. #[serde(with = "crate::serde::duration::secs")] pub expires_in: Duration, } /// Response type for the `register_account` endpoint. #[derive(ToSchema,Serialize, Debug)] pub struct RegisterAccountResBody { /// An opaque string representing the token to authenticate future requests to the identity /// server with. pub token: String, } impl RegisterAccountResBody { /// Creates an empty `Response`. pub fn new(token: String) -> Self { Self { token } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identity/association.rs
crates/core/src/identity/association.rs
//! Endpoints to create associations with a Matrix ID on the identity server. pub mod threepid; pub mod email; pub mod msisdn;
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identity/association/email.rs
crates/core/src/identity/association/email.rs
/// `POST /_matrix/identity/*/validate/email/requestToken` /// /// Create a session for validating an email. use crate::{OwnedClientSecret, OwnedSessionId}; use crate::{OwnedClientSecret, OwnedSessionId}; /// `/v2/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/identity-service-api/#post_matrixidentityv2validateemailrequesttoken // const METADATA: Metadata = metadata! { // method: POST, // rate_limited: false, // authentication: AccessToken, // history: { // 1.0 => "/_matrix/identity/v2/validate/email/requestToken", // } // }; /// Request type for the `create_email_validation_session` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct CreateEmailValidationSessionReqBody { /// A unique string generated by the client, and used to identify the validation attempt. pub client_secret: OwnedClientSecret, /// The email address to validate. pub email: String, /// The server will only send an email if the send_attempt is a number greater than the /// most recent one which it has seen, scoped to that email + client_secret pair. pub send_attempt: u64, /// When the validation is completed, the identity server will redirect the user to this /// URL. #[serde(skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } /// Response type for the `create_email_validation_session` endpoint. #[derive(ToSchema,Serialize, Debug)] pub struct CreateEmailValidationSessionResBody { /// The session ID. /// /// Session IDs are opaque strings generated by the identity server. pub sid: OwnedSessionId, } impl CreateEmailValidationSessionResBody { /// Create a new `Response` with the given session ID. pub fn new(sid: OwnedSessionId) -> Self { Self { sid } } } /// `GET /_matrix/identity/*/validate/email/submitToken` /// /// Validate ownership of an email ID by the end-user, after creation of a session. /// `/v2/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/identity-service-api/#get_matrixidentityv2validateemailsubmittoken // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: AccessToken, // history: { // 1.0 => "/_matrix/identity/v2/validate/email/submitToken", // } // }; /// Request type for the `validate_email_by_end_user` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct ValidateEmailByEndUserReqArgs { /// The session ID, generated by the `requestToken` call. #[salvo(parameter(parameter_in = Query))] pub sid: OwnedSessionId, /// The client secret that was supplied to the `requestToken` call. #[salvo(parameter(parameter_in = Query))] pub client_secret: OwnedClientSecret, /// The token generated by the `requestToken` call and emailed to the user. #[salvo(parameter(parameter_in = Query))] pub token: String, } /// `POST /_matrix/identity/*/validate/email/submitToken` /// /// Validate an email ID after creation of a session. /// `/v2/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/identity-service-api/#post_matrixidentityv2validateemailsubmittoken // const METADATA: Metadata = metadata! { // method: POST, // rate_limited: false, // authentication: AccessToken, // history: { // 1.0 => "/_matrix/identity/v2/validate/email/submitToken", // } // }; /// Request type for the `validate_email` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct ValidateEmailReqBody { /// The session ID, generated by the `requestToken` call. pub sid: OwnedSessionId, /// The client secret that was supplied to the `requestToken` call. pub client_secret: OwnedClientSecret, /// The token generated by the `requestToken` call and emailed to the user. pub token: String, } /// Response type for the `validate_email` endpoint. #[derive(ToSchema,Serialize, Debug)] pub struct ValidateEmailResBody { /// Whether the validation was successful or not. pub success: bool, } impl ValidateEmailResBody { /// Create a new `Response` with the success status. pub fn new(success: bool) -> Self { Self { success } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identity/association/threepid.rs
crates/core/src/identity/association/threepid.rs
/// `POST /_matrix/identity/*/3pid/bind` /// /// Publish an association between a session and a Matrix user ID. /// `/v2/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/identity-service-api/#post_matrixidentityv23pidbind use crate::{third_party::Medium, UnixMillis, OwnedClientSecret, OwnedSessionId, OwnedUserId, ServerSignatures}; use crate::{third_party::Medium, OwnedClientSecret, OwnedSessionId}; use crate::{third_party::Medium, ClientSecret, OwnedSessionId, OwnedUserId}; use serde::{Deserialize, Serialize}; // const METADATA: Metadata = metadata! { // method: POST, // rate_limited: false, // authentication: AccessToken, // history: { // 1.0 => "/_matrix/identity/v2/3pid/bind", // } // }; /// Request type for the `bind_3pid` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct BindThreepidReqBody { /// The session ID generated by the `requestToken` call. pub sid: OwnedSessionId, /// The client secret passed to the `requestToken` call. pub client_secret: OwnedClientSecret, /// The Matrix user ID to associate with the 3PIDs. pub mxid: OwnedUserId, } /// Response type for the `bind_3pid` endpoint. #[derive(ToSchema,Serialize, Debug)] pub struct BindThreepidResBody { /// The 3PID address of the user being looked up. pub address: String, /// The medium type of the 3PID. pub medium: Medium, /// The Matrix user ID associated with the 3PID. pub mxid: OwnedUserId, /// A UNIX timestamp before which the association is not known to be valid. pub not_before: UnixMillis, /// A UNIX timestamp after which the association is not known to be valid. pub not_after: UnixMillis, /// The UNIX timestamp at which the association was verified. pub ts: UnixMillis, /// The signatures of the verifying identity servers which show that the /// association should be trusted, if you trust the verifying identity services. pub signatures: ServerSignatures, } impl BindThreepidResBody { /// Creates a `Response` with the given 3PID address, medium, Matrix user ID, timestamps and /// signatures. pub fn new( address: String, medium: Medium, mxid: OwnedUserId, not_before: UnixMillis, not_after: UnixMillis, ts: UnixMillis, signatures: ServerSignatures, ) -> Self { Self { address, medium, mxid, not_before, not_after, ts, signatures, } } } /// `GET /_matrix/identity/*/3pid/getValidated3pid` /// /// Determine if a given 3PID has been validated by a user. /// `/v2/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/identity-service-api/#get_matrixidentityv23pidgetvalidated3pid // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: AccessToken, // history: { // 1.0 => "/_matrix/identity/v2/3pid/getValidated3pid/", // } // }; /// Request type for the `check_3pid_validity` endpoint. // pub struct CheckThreepidValidityReqBody { // /// The Session ID generated by the `requestToken` call. // #[salvo(parameter(parameter_in = Query))] // pub sid: OwnedSessionId, // /// The client secret passed to the `requestToken` call. // #[salvo(parameter(parameter_in = Query))] // pub client_secret: OwnedClientSecret, // } /// Response type for the `check_3pid_validity` endpoint. #[derive(ToSchema,Serialize, Debug)] pub struct CheckThreepidValidityResBody { /// The medium type of the 3PID. pub medium: Medium, /// The address of the 3PID being looked up. pub address: String, /// Timestamp, in milliseconds, indicating the time that the 3PID was validated. pub validated_at: u64, } impl CheckThreepidValidityResBody { /// Creates a `Response` with the given medium, address and validation timestamp. pub fn new(medium: Medium, address: String, validated_at: u64) -> Self { Self { medium, address, validated_at, } } } /// `POST /_matrix/identity/*/3pid/unbind` /// /// Remove an association between a session and a Matrix user ID. /// `/v2/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/identity-service-api/#post_matrixidentityv23pidunbind // const METADATA: Metadata = metadata! { // method: POST, // rate_limited: false, // authentication: AccessToken, // history: { // 1.0 => "/_matrix/identity/v2/3pid/unbind", // } // }; /// Request type for the `unbind_3pid` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct UnbindThreepidReqBody { /// The proof that the client owns the 3PID. /// /// If this is not provided, the request must be signed by the homeserver which controls /// the `mxid`. #[serde(flatten, skip_serializing_if = "Option::is_none")] pub threepid_ownership_proof: Option<ThreepidOwnershipProof>, /// The Matrix user ID to remove from the 3PIDs. pub mxid: OwnedUserId, /// The 3PID to remove. /// /// Must match the 3PID used to generate the session if using `sid` and `client_secret` to /// authenticate this request. pub threepid: ThirdPartyId, } /// A 3PID to unbind. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ThirdPartyId { /// A medium matching the medium of identifier to unbind. pub medium: Medium, /// The 3PID address to remove. pub address: String, } impl ThirdPartyId { /// Creates a new `ThirdPartyId` with the given medium and address. pub fn new(medium: Medium, address: String) -> Self { Self { medium, address } } } /// A proof that the client owns the 3PID. /// /// Must be constructed using the same session ID and client secret generated and passed by the /// `requestToken` call for the given 3PID. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ThreepidOwnershipProof { /// The Session ID generated by the `requestToken` call. pub sid: OwnedSessionId, /// The client secret passed to the `requestToken` call. pub client_secret: Box<ClientSecret>, } impl ThreepidOwnershipProof { /// Creates a new `ThreepidOwnershipProof` with the given session ID and client secret. pub fn new(sid: OwnedSessionId, client_secret: Box<ClientSecret>) -> Self { Self { sid, client_secret } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/identity/association/msisdn.rs
crates/core/src/identity/association/msisdn.rs
/// `POST /_matrix/identity/*/validate/msisdn/submitToken` /// /// Validate the ownership of a phone number. use crate::{OwnedClientSecret, OwnedSessionId}; /// `/v2/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/identity-service-api/#post_matrixidentityv2validatemsisdnsubmittoken // const METADATA: Metadata = metadata! { // method: POST, // rate_limited: false, // authentication: AccessToken, // history: { // 1.0 => "/_matrix/identity/v2/validate/msisdn/submitToken", // } // }; /// Request type for the `validate_msisdn` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct ValidateMsisdnReqBody { /// The session ID, generated by the `requestToken` call. pub sid: OwnedSessionId, /// The client secret that was supplied to the `requestToken` call. pub client_secret: OwnedClientSecret, /// The token generated by the `requestToken` call and sent to the user. pub token: String, } /// Response type for the `validate_msisdn` endpoint. #[derive(ToSchema,Serialize, Debug)] pub struct ValidateMsisdnResBody { /// Whether the validation was successful or not. pub success: bool, } impl ValidateMsisdnResBody { /// Create a new `Response` with the success status. pub fn new(success: bool) -> Self { Self { success } } } /// `GET /_matrix/identity/*/validate/msisdn/submitToken` /// /// Validate the ownership of a phone number by the end user. /// `/v2/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/identity-service-api/#get_matrixidentityv2validatemsisdnsubmittoken // const METADATA: Metadata = metadata! { // method: GET, // rate_limited: false, // authentication: AccessToken, // history: { // 1.0 => "/_matrix/identity/v2/validate/msisdn/submitToken", // } // }; /// Request type for the `validate_email_by_end_user` endpoint. #[derive(ToParameters, Deserialize, Debug)] pub struct ValidateEmailByEndUserReqArgs { /// The session ID, generated by the `requestToken` call. #[salvo(parameter(parameter_in = Query))] pub sid: OwnedSessionId, /// The client secret that was supplied to the `requestToken` call. #[salvo(parameter(parameter_in = Query))] pub client_secret: OwnedClientSecret, /// The token generated by the `requestToken` call and sent to the user. #[salvo(parameter(parameter_in = Query))] pub token: String, } /// `POST /_matrix/identity/*/validate/msisdn/requestToken` /// /// Create a session for validation of a phone number. /// `/v2/` ([spec]) /// /// [spec]: https://spec.matrix.org/latest/identity-service-api/#post_matrixidentityv2validatemsisdnrequesttoken // const METADATA: Metadata = metadata! { // method: POST, // rate_limited: false, // authentication: AccessToken, // history: { // 1.0 => "/_matrix/identity/v2/validate/msisdn/requestToken", // } // }; /// Request type for the `create_msisdn_validation_session` endpoint. #[derive(ToSchema, Deserialize, Debug)] pub struct CreateMsisdnValidationSessionReqBody { /// A unique string generated by the client, and used to identify the validation attempt. pub client_secret: OwnedClientSecret, /// The two-letter uppercase ISO-3166-1 alpha-2 country code that the number in /// `phone_number` should be parsed as if it were dialled from. pub country: String, /// The phone number to validate. pub phone_number: String, /// The server will only send an SMS if the send_attempt is a number greater than the most /// recent one which it has seen, scoped to that `country` + `phone_number` + /// `client_secret` triple. pub send_attempt: u64, /// When the validation is completed, the identity server will redirect the user to this /// URL. #[serde(skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } /// Response type for the `create_msisdn_validation_session` endpoint. #[derive(ToSchema,Serialize, Debug)] pub struct CreateMsisdnValidationSessionResBody { /// The session ID. /// /// Session IDs are opaque strings generated by the identity server. pub sid: OwnedSessionId, } impl CreateMsisdnValidationSessionResBody { /// Create a new `Response` with the given session ID. pub fn new(sid: OwnedSessionId) -> Self { Self { sid } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/http_headers/rfc8187.rs
crates/core/src/http_headers/rfc8187.rs
//! Encoding and decoding functions according to [RFC 8187]. //! //! [RFC 8187]: https://datatracker.ietf.org/doc/html/rfc8187 use std::borrow::Cow; use percent_encoding::{AsciiSet, NON_ALPHANUMERIC}; /// The characters to percent-encode according to the `attr-char` set. const ATTR_CHAR: AsciiSet = NON_ALPHANUMERIC .remove(b'!') .remove(b'#') .remove(b'$') .remove(b'&') .remove(b'+') .remove(b'-') .remove(b'.') .remove(b'^') .remove(b'_') .remove(b'`') .remove(b'|') .remove(b'~'); /// Encode the given string according to [RFC 8187]. /// /// [RFC 8187]: https://datatracker.ietf.org/doc/html/rfc8187 pub(super) fn encode(s: &str) -> String { let encoded = percent_encoding::utf8_percent_encode(s, &ATTR_CHAR); format!("utf-8''{encoded}") } /// Decode the given bytes according to [RFC 8187]. /// /// Only the UTF-8 character set is supported, all other character sets return /// an error. /// /// [RFC 8187]: https://datatracker.ietf.org/doc/html/rfc8187 pub(super) fn decode(bytes: &[u8]) -> Result<Cow<'_, str>, Rfc8187DecodeError> { if bytes.is_empty() { return Err(Rfc8187DecodeError::Empty); } let mut parts = bytes.split(|b| *b == b'\''); let charset = parts.next().ok_or(Rfc8187DecodeError::WrongPartsCount)?; let _lang = parts.next().ok_or(Rfc8187DecodeError::WrongPartsCount)?; let encoded = parts.next().ok_or(Rfc8187DecodeError::WrongPartsCount)?; if parts.next().is_some() { return Err(Rfc8187DecodeError::WrongPartsCount); } if !charset.eq_ignore_ascii_case(b"utf-8") { return Err(Rfc8187DecodeError::NotUtf8); } // For maximum compatibility, do a lossy conversion. Ok(percent_encoding::percent_decode(encoded).decode_utf8_lossy()) } /// All errors encountered when trying to decode a string according to [RFC /// 8187]. /// /// [RFC 8187]: https://datatracker.ietf.org/doc/html/rfc8187 #[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] #[non_exhaustive] pub(super) enum Rfc8187DecodeError { /// The string is empty. #[error("string is empty")] Empty, /// The string does not contain the right number of parts. #[error("string does not contain the right number of parts")] WrongPartsCount, /// The character set is not UTF-8. #[error("character set is not UTF-8")] NotUtf8, }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/core/src/http_headers/content_disposition.rs
crates/core/src/http_headers/content_disposition.rs
//! Types to (de)serialize the `Content-Disposition` HTTP header. use std::{fmt, ops::Deref, str::FromStr}; use salvo::oapi::ToSchema; use serde::Serialize; use super::{ is_tchar, is_token, quote_ascii_string_if_required, rfc8187, sanitize_for_ascii_quoted_string, unescape_string, }; use crate::macros::{AsRefStr, AsStrAsRefStr, DebugAsRefStr, DisplayAsRefStr, OrdAsRefStr}; /// The value of a `Content-Disposition` HTTP header. /// /// This implementation supports the `Content-Disposition` header format as /// defined for HTTP in [RFC 6266]. /// /// The only supported parameter is `filename`. It is encoded or decoded as /// needed, using a quoted string or the `ext-token = ext-value` format, with /// the encoding defined in [RFC 8187]. /// /// This implementation does not support serializing to the format defined for /// the `multipart/form-data` content type in [RFC 7578]. It should however /// manage to parse the disposition type and filename parameter of the body /// parts. /// /// [RFC 6266]: https://datatracker.ietf.org/doc/html/rfc6266 /// [RFC 8187]: https://datatracker.ietf.org/doc/html/rfc8187 /// [RFC 7578]: https://datatracker.ietf.org/doc/html/rfc7578 #[derive(ToSchema, Serialize, Debug, Clone, PartialEq, Eq, Default)] #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] pub struct ContentDisposition { /// The disposition type. pub disposition_type: ContentDispositionType, /// The filename of the content. pub filename: Option<String>, } impl ContentDisposition { /// Creates a new `ContentDisposition` with the given disposition type. pub fn new(disposition_type: ContentDispositionType) -> Self { Self { disposition_type, filename: None, } } /// Add the given filename to this `ContentDisposition`. pub fn with_filename(mut self, filename: Option<String>) -> Self { self.filename = filename; self } } impl fmt::Display for ContentDisposition { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.disposition_type)?; if let Some(filename) = &self.filename { if filename.is_ascii() { // First, remove all non-quotable characters, that is control characters. let filename = sanitize_for_ascii_quoted_string(filename); // We can use the filename parameter. write!( f, "; filename={}", quote_ascii_string_if_required(&filename) )?; } else { // We need to use RFC 8187 encoding. write!(f, "; filename*={}", rfc8187::encode(filename))?; } } Ok(()) } } impl TryFrom<&[u8]> for ContentDisposition { type Error = ContentDispositionParseError; fn try_from(value: &[u8]) -> Result<Self, Self::Error> { let mut pos = 0; skip_ascii_whitespaces(value, &mut pos); if pos == value.len() { return Err(ContentDispositionParseError::MissingDispositionType); } let disposition_type_start = pos; // Find the next whitespace or `;`. while let Some(byte) = value.get(pos) { if byte.is_ascii_whitespace() || *byte == b';' { break; } pos += 1; } let disposition_type = ContentDispositionType::try_from(&value[disposition_type_start..pos])?; // The `filename*` parameter (`filename_ext` here) using UTF-8 encoding should // be used, but it is likely to be after the `filename` parameter // containing only ASCII characters if both are present. let mut filename_ext = None; let mut filename = None; // Parse the parameters. We ignore parameters that fail to parse for maximum // compatibility. while pos != value.len() { if let Some(param) = RawParam::parse_next(value, &mut pos) { if param.name.eq_ignore_ascii_case(b"filename*") && let Some(value) = param.decode_value() { filename_ext = Some(value); // We can stop parsing, this is the only parameter that we need. break; } else if param.name.eq_ignore_ascii_case(b"filename") && let Some(value) = param.decode_value() { filename = Some(value); } } } Ok(Self { disposition_type, filename: filename_ext.or(filename), }) } } impl FromStr for ContentDisposition { type Err = ContentDispositionParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { s.as_bytes().try_into() } } /// A raw parameter in a `Content-Disposition` HTTP header. struct RawParam<'a> { name: &'a [u8], value: &'a [u8], is_quoted_string: bool, } impl<'a> RawParam<'a> { /// Parse the next `RawParam` in the given bytes, starting at the given /// position. /// /// The position is updated during the parsing. /// /// Returns `None` if no parameter was found or if an error occurred when /// parsing the parameter. fn parse_next(bytes: &'a [u8], pos: &mut usize) -> Option<Self> { let name = parse_param_name(bytes, pos)?; skip_ascii_whitespaces(bytes, pos); if *pos == bytes.len() { // We are at the end of the bytes and only have the parameter name. return None; } if bytes[*pos] != b'=' { // We should have an equal sign, there is a problem with the bytes and we can't // recover from it. // Skip to the end to stop the parsing. *pos = bytes.len(); return None; } // Skip the equal sign. *pos += 1; skip_ascii_whitespaces(bytes, pos); let (value, is_quoted_string) = parse_param_value(bytes, pos)?; Some(Self { name, value, is_quoted_string, }) } /// Decode the value of this `RawParam`. /// /// Returns `None` if decoding the param failed. fn decode_value(&self) -> Option<String> { if self.name.ends_with(b"*") { rfc8187::decode(self.value).ok().map(|s| s.into_owned()) } else { let s = String::from_utf8_lossy(self.value); if self.is_quoted_string { Some(unescape_string(&s)) } else { Some(s.into_owned()) } } } } /// Skip ASCII whitespaces in the given bytes, starting at the given position. /// /// The position is updated to after the whitespaces. fn skip_ascii_whitespaces(bytes: &[u8], pos: &mut usize) { while let Some(byte) = bytes.get(*pos) { if !byte.is_ascii_whitespace() { break; } *pos += 1; } } /// Parse a parameter name in the given bytes, starting at the given position. /// /// The position is updated while parsing. /// /// Returns `None` if the end of the bytes was reached, or if an error was /// encountered. fn parse_param_name<'a>(bytes: &'a [u8], pos: &mut usize) -> Option<&'a [u8]> { skip_ascii_whitespaces(bytes, pos); if *pos == bytes.len() { // We are at the end of the bytes and didn't find anything. return None; } let name_start = *pos; // Find the end of the parameter name. The name can only contain token chars. while let Some(byte) = bytes.get(*pos) { if !is_tchar(*byte) { break; } *pos += 1; } if *pos == bytes.len() { // We are at the end of the bytes and only have the parameter name. return None; } if bytes[*pos] == b';' { // We are at the end of the parameter and only have the parameter name, skip the // `;` and parse the next parameter. *pos += 1; return None; } let name = &bytes[name_start..*pos]; if name.is_empty() { // It's probably a syntax error, we cannot recover from it. *pos = bytes.len(); return None; } Some(name) } /// Parse a parameter value in the given bytes, starting at the given position. /// /// The position is updated while parsing. /// /// Returns a `(value, is_quoted_string)` tuple if parsing succeeded. /// Returns `None` if the end of the bytes was reached, or if an error was /// encountered. fn parse_param_value<'a>(bytes: &'a [u8], pos: &mut usize) -> Option<(&'a [u8], bool)> { skip_ascii_whitespaces(bytes, pos); if *pos == bytes.len() { // We are at the end of the bytes and didn't find anything. return None; } let is_quoted_string = bytes[*pos] == b'"'; if is_quoted_string { // Skip the start double quote. *pos += 1; } let value_start = *pos; // Keep track of whether the next byte is escaped with a backslash. let mut escape_next = false; // Find the end of the value, it's a whitespace or a semi-colon, or a double // quote if the string is quoted. while let Some(byte) = bytes.get(*pos) { if !is_quoted_string && (byte.is_ascii_whitespace() || *byte == b';') { break; } if is_quoted_string && *byte == b'"' && !escape_next { break; } escape_next = *byte == b'\\' && !escape_next; *pos += 1; } let value = &bytes[value_start..*pos]; if is_quoted_string && *pos != bytes.len() { // Skip the end double quote. *pos += 1; } skip_ascii_whitespaces(bytes, pos); // Check for parameters separator if we are not at the end of the string. if *pos != bytes.len() { if bytes[*pos] == b';' { // Skip the `;` at the end of the parameter. *pos += 1; } else { // We should have a `;`, there is a problem with the bytes and we can't recover // from it. // Skip to the end to stop the parsing. *pos = bytes.len(); return None; } } Some((value, is_quoted_string)) } /// An error encountered when trying to parse an invalid [`ContentDisposition`]. #[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] #[non_exhaustive] pub enum ContentDispositionParseError { /// The disposition type is missing. #[error("disposition type is missing")] MissingDispositionType, /// The disposition type is invalid. #[error("invalid disposition type: {0}")] InvalidDispositionType(#[from] TokenStringParseError), } /// A disposition type in the `Content-Disposition` HTTP header as defined in /// [Section 4.2 of RFC 6266]. /// /// This type can hold an arbitrary [`TokenString`]. To build this with a custom /// value, convert it from a `TokenString` with `::from()` / `.into()`. To check /// for values that are not available as a documented variant here, use its /// string representation, obtained through [`.as_str()`](Self::as_str()). /// /// Comparisons with other string types are done case-insensitively. /// /// [Section 4.2 of RFC 6266]: https://datatracker.ietf.org/doc/html/rfc6266#section-4.2 #[derive( ToSchema, Serialize, Clone, Default, AsRefStr, DebugAsRefStr, AsStrAsRefStr, DisplayAsRefStr, OrdAsRefStr, )] #[palpo_enum(rename_all = "lowercase")] #[non_exhaustive] pub enum ContentDispositionType { /// The content can be displayed. /// /// This is the default. #[default] Inline, /// The content should be downloaded instead of displayed. Attachment, #[doc(hidden)] #[salvo(schema(value_type = String))] _Custom(TokenString), } impl ContentDispositionType { /// Try parsing a `&str` into a `ContentDispositionType`. pub fn parse(s: &str) -> Result<Self, TokenStringParseError> { Self::from_str(s) } } impl From<TokenString> for ContentDispositionType { fn from(value: TokenString) -> Self { if value.eq_ignore_ascii_case("inline") { Self::Inline } else if value.eq_ignore_ascii_case("attachment") { Self::Attachment } else { Self::_Custom(value) } } } impl<'a> TryFrom<&'a [u8]> for ContentDispositionType { type Error = TokenStringParseError; fn try_from(value: &'a [u8]) -> Result<Self, Self::Error> { if value.eq_ignore_ascii_case(b"inline") { Ok(Self::Inline) } else if value.eq_ignore_ascii_case(b"attachment") { Ok(Self::Attachment) } else { TokenString::try_from(value).map(Self::_Custom) } } } impl FromStr for ContentDispositionType { type Err = TokenStringParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { s.as_bytes().try_into() } } impl PartialEq<ContentDispositionType> for ContentDispositionType { fn eq(&self, other: &ContentDispositionType) -> bool { self.as_str().eq_ignore_ascii_case(other.as_str()) } } impl Eq for ContentDispositionType {} impl PartialEq<TokenString> for ContentDispositionType { fn eq(&self, other: &TokenString) -> bool { self.as_str().eq_ignore_ascii_case(other.as_str()) } } impl<'a> PartialEq<&'a str> for ContentDispositionType { fn eq(&self, other: &&'a str) -> bool { self.as_str().eq_ignore_ascii_case(other) } } /// A non-empty string consisting only of `token`s as defined in [RFC 9110 /// Section 3.2.6]. /// /// This is a string that can only contain a limited character set. /// /// [RFC 7230 Section 3.2.6]: https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.6 #[derive( Clone, Serialize, PartialEq, Eq, DebugAsRefStr, AsStrAsRefStr, DisplayAsRefStr, OrdAsRefStr, )] pub struct TokenString(Box<str>); impl TokenString { /// Try parsing a `&str` into a `TokenString`. pub fn parse(s: &str) -> Result<Self, TokenStringParseError> { Self::from_str(s) } } impl Deref for TokenString { type Target = str; fn deref(&self) -> &Self::Target { self.as_ref() } } impl AsRef<str> for TokenString { fn as_ref(&self) -> &str { &self.0 } } impl<'a> PartialEq<&'a str> for TokenString { fn eq(&self, other: &&'a str) -> bool { self.as_str().eq(*other) } } impl<'a> TryFrom<&'a [u8]> for TokenString { type Error = TokenStringParseError; fn try_from(value: &'a [u8]) -> Result<Self, Self::Error> { if value.is_empty() { Err(TokenStringParseError::Empty) } else if is_token(value) { let s = std::str::from_utf8(value).expect("ASCII bytes are valid UTF-8"); Ok(Self(s.into())) } else { Err(TokenStringParseError::InvalidCharacter) } } } impl FromStr for TokenString { type Err = TokenStringParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { s.as_bytes().try_into() } } /// The parsed string contains a character not allowed for a [`TokenString`]. #[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] #[non_exhaustive] pub enum TokenStringParseError { /// The string is empty. #[error("string is empty")] Empty, /// The string contains an invalid character for a token string. #[error("string contains invalid character")] InvalidCharacter, } #[cfg(test)] mod tests { use std::str::FromStr; use super::{ContentDisposition, ContentDispositionType}; #[test] fn parse_content_disposition_valid() { // Only disposition type. let content_disposition = ContentDisposition::from_str("inline").unwrap(); assert_eq!( content_disposition.disposition_type, ContentDispositionType::Inline ); assert_eq!(content_disposition.filename, None); // Only disposition type with separator. let content_disposition = ContentDisposition::from_str("attachment;").unwrap(); assert_eq!( content_disposition.disposition_type, ContentDispositionType::Attachment ); assert_eq!(content_disposition.filename, None); // Unknown disposition type and parameters. let content_disposition = ContentDisposition::from_str("custom; foo=bar; foo*=utf-8''b%C3%A0r'").unwrap(); assert_eq!(content_disposition.disposition_type.as_str(), "custom"); assert_eq!(content_disposition.filename, None); // Disposition type and filename. let content_disposition = ContentDisposition::from_str("inline; filename=my_file").unwrap(); assert_eq!( content_disposition.disposition_type, ContentDispositionType::Inline ); assert_eq!(content_disposition.filename.unwrap(), "my_file"); // Case insensitive. let content_disposition = ContentDisposition::from_str("INLINE; FILENAME=my_file").unwrap(); assert_eq!( content_disposition.disposition_type, ContentDispositionType::Inline ); assert_eq!(content_disposition.filename.unwrap(), "my_file"); // Extra spaces. let content_disposition = ContentDisposition::from_str(" INLINE ;FILENAME = my_file ").unwrap(); assert_eq!( content_disposition.disposition_type, ContentDispositionType::Inline ); assert_eq!(content_disposition.filename.unwrap(), "my_file"); // Unsupported filename* is skipped and falls back to ASCII filename. let content_disposition = ContentDisposition::from_str( r#"attachment; filename*=iso-8859-1''foo-%E4.html; filename="foo-a.html"#, ) .unwrap(); assert_eq!( content_disposition.disposition_type, ContentDispositionType::Attachment ); assert_eq!(content_disposition.filename.unwrap(), "foo-a.html"); // filename could be UTF-8 for extra compatibility (with `form-data` for // example). let content_disposition = ContentDisposition::from_str(r#"form-data; name=upload; filename="文件.webp""#) .unwrap(); assert_eq!(content_disposition.disposition_type.as_str(), "form-data"); assert_eq!(content_disposition.filename.unwrap(), "文件.webp"); } #[test] fn parse_content_disposition_invalid_type() { // Empty. ContentDisposition::from_str("").unwrap_err(); // Missing disposition type. ContentDisposition::from_str("; foo=bar").unwrap_err(); } #[test] fn parse_content_disposition_invalid_parameters() { // Unexpected `:` after parameter name, filename parameter is not reached. let content_disposition = ContentDisposition::from_str("inline; foo:bar; filename=my_file").unwrap(); assert_eq!( content_disposition.disposition_type, ContentDispositionType::Inline ); assert_eq!(content_disposition.filename, None); // Same error, but after filename, so filename was parser. let content_disposition = ContentDisposition::from_str("inline; filename=my_file; foo:bar").unwrap(); assert_eq!( content_disposition.disposition_type, ContentDispositionType::Inline ); assert_eq!(content_disposition.filename.unwrap(), "my_file"); // Missing `;` between parameters, filename parameter is not parsed // successfully. let content_disposition = ContentDisposition::from_str("inline; filename=my_file foo=bar").unwrap(); assert_eq!( content_disposition.disposition_type, ContentDispositionType::Inline ); assert_eq!(content_disposition.filename, None); } #[test] fn content_disposition_serialize() { // Only disposition type. let content_disposition = ContentDisposition::new(ContentDispositionType::Inline); let serialized = content_disposition.to_string(); assert_eq!(serialized, "inline"); // Disposition type and ASCII filename without space. let content_disposition = ContentDisposition::new(ContentDispositionType::Attachment) .with_filename(Some("my_file".to_owned())); let serialized = content_disposition.to_string(); assert_eq!(serialized, "attachment; filename=my_file"); // Disposition type and ASCII filename with space. let content_disposition = ContentDisposition::new(ContentDispositionType::Attachment) .with_filename(Some("my file".to_owned())); let serialized = content_disposition.to_string(); assert_eq!(serialized, r#"attachment; filename="my file""#); // Disposition type and ASCII filename with double quote and backslash. let content_disposition = ContentDisposition::new(ContentDispositionType::Attachment) .with_filename(Some(r#""my"\file"#.to_owned())); let serialized = content_disposition.to_string(); assert_eq!(serialized, r#"attachment; filename="\"my\"\\file""#); // Disposition type and UTF-8 filename. let content_disposition = ContentDisposition::new(ContentDispositionType::Attachment) .with_filename(Some("Mi Corazón".to_owned())); let serialized = content_disposition.to_string(); assert_eq!(serialized, "attachment; filename*=utf-8''Mi%20Coraz%C3%B3n"); // Sanitized filename. let content_disposition = ContentDisposition::new(ContentDispositionType::Attachment) .with_filename(Some("my\r\nfile".to_owned())); let serialized = content_disposition.to_string(); assert_eq!(serialized, "attachment; filename=myfile"); } #[test] fn rfc6266_examples() { // Basic syntax with unquoted filename. let unquoted = "Attachment; filename=example.html"; let content_disposition = ContentDisposition::from_str(unquoted).unwrap(); assert_eq!( content_disposition.disposition_type, ContentDispositionType::Attachment ); assert_eq!( content_disposition.filename.as_deref().unwrap(), "example.html" ); let reserialized = content_disposition.to_string(); assert_eq!(reserialized, "attachment; filename=example.html"); // With quoted filename, case insensitivity and extra whitespaces. let quoted = r#"INLINE; FILENAME= "an example.html""#; let content_disposition = ContentDisposition::from_str(quoted).unwrap(); assert_eq!( content_disposition.disposition_type, ContentDispositionType::Inline ); assert_eq!( content_disposition.filename.as_deref().unwrap(), "an example.html" ); let reserialized = content_disposition.to_string(); assert_eq!(reserialized, r#"inline; filename="an example.html""#); // With RFC 8187-encoded UTF-8 filename. let rfc8187 = "attachment; filename*= UTF-8''%e2%82%ac%20rates"; let content_disposition = ContentDisposition::from_str(rfc8187).unwrap(); assert_eq!( content_disposition.disposition_type, ContentDispositionType::Attachment ); assert_eq!(content_disposition.filename.as_deref().unwrap(), "€ rates"); let reserialized = content_disposition.to_string(); assert_eq!( reserialized, r#"attachment; filename*=utf-8''%E2%82%AC%20rates"# ); // With RFC 8187-encoded UTF-8 filename with fallback ASCII filename. let rfc8187_with_fallback = r#"attachment; filename="EURO rates"; filename*=utf-8''%e2%82%ac%20rates"#; let content_disposition = ContentDisposition::from_str(rfc8187_with_fallback).unwrap(); assert_eq!( content_disposition.disposition_type, ContentDispositionType::Attachment ); assert_eq!(content_disposition.filename.as_deref().unwrap(), "€ rates"); } #[test] fn rfc8187_examples() { // Those examples originate from RFC 8187, but are changed to fit the // expectations here: // // - A disposition type is added // - The title parameter is renamed to filename // Basic syntax with unquoted filename. let unquoted = "attachment; foo= bar; filename=Economy"; let content_disposition = ContentDisposition::from_str(unquoted).unwrap(); assert_eq!( content_disposition.disposition_type, ContentDispositionType::Attachment ); assert_eq!(content_disposition.filename.as_deref().unwrap(), "Economy"); let reserialized = content_disposition.to_string(); assert_eq!(reserialized, "attachment; filename=Economy"); // With quoted filename. let quoted = r#"attachment; foo=bar; filename="US-$ rates""#; let content_disposition = ContentDisposition::from_str(quoted).unwrap(); assert_eq!( content_disposition.disposition_type, ContentDispositionType::Attachment ); assert_eq!( content_disposition.filename.as_deref().unwrap(), "US-$ rates" ); let reserialized = content_disposition.to_string(); assert_eq!(reserialized, r#"attachment; filename="US-$ rates""#); // With RFC 8187-encoded UTF-8 filename. let rfc8187 = "attachment; foo=bar; filename*=utf-8'en'%C2%A3%20rates"; let content_disposition = ContentDisposition::from_str(rfc8187).unwrap(); assert_eq!( content_disposition.disposition_type, ContentDispositionType::Attachment ); assert_eq!(content_disposition.filename.as_deref().unwrap(), "£ rates"); let reserialized = content_disposition.to_string(); assert_eq!( reserialized, r#"attachment; filename*=utf-8''%C2%A3%20rates"# ); // With RFC 8187-encoded UTF-8 filename again. let rfc8187_other = r#"attachment; foo=bar; filename*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates"#; let content_disposition = ContentDisposition::from_str(rfc8187_other).unwrap(); assert_eq!( content_disposition.disposition_type, ContentDispositionType::Attachment ); assert_eq!( content_disposition.filename.as_deref().unwrap(), "£ and € rates" ); let reserialized = content_disposition.to_string(); assert_eq!( reserialized, r#"attachment; filename*=utf-8''%C2%A3%20and%20%E2%82%AC%20rates"# ); // With RFC 8187-encoded UTF-8 filename with fallback ASCII filename. let rfc8187_with_fallback = r#"attachment; foo=bar; filename="EURO exchange rates"; filename*=utf-8''%e2%82%ac%20exchange%20rates"#; let content_disposition = ContentDisposition::from_str(rfc8187_with_fallback).unwrap(); assert_eq!( content_disposition.disposition_type, ContentDispositionType::Attachment ); assert_eq!( content_disposition.filename.as_deref().unwrap(), "€ exchange rates" ); let reserialized = content_disposition.to_string(); assert_eq!( reserialized, r#"attachment; filename*=utf-8''%E2%82%AC%20exchange%20rates"# ); } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/config.rs
crates/server/src/config.rs
use std::iter::once; use std::ops::Deref; use std::path::Path; use std::sync::{LazyLock, OnceLock}; use base64::{Engine as _, engine::general_purpose::STANDARD}; use figment::Figment; use figment::providers::{Env, Format, Json, Toml, Yaml}; use ipaddress::IPAddress; mod server; pub use server::*; mod admin; pub use admin::*; // mod appservice; // pub use appservice::*; mod jwt; pub use jwt::*; mod blurhash; pub use blurhash::*; // mod cache; // pub use cache::*; mod compression; pub use compression::*; mod db; pub use db::*; // mod dns; // pub use dns::*; mod federation; pub use federation::*; mod http_client; pub use http_client::*; // mod ldap; // pub use ldap::*; mod logger; pub use logger::*; mod media; pub use media::*; mod presence; pub use presence::*; mod proxy; pub use proxy::*; mod read_receipt; pub use read_receipt::*; mod turn; pub use turn::*; mod typing; pub use typing::*; mod url_preview; pub use url_preview::*; mod oidc; pub use oidc::*; use crate::AppResult; use crate::core::client::discovery::capabilities::RoomVersionStability; use crate::core::identifiers::*; use crate::core::signatures::Ed25519KeyPair; pub static CONFIG: OnceLock<ServerConfig> = OnceLock::new(); pub static STABLE_ROOM_VERSIONS: LazyLock<Vec<RoomVersionId>> = LazyLock::new(|| { vec![ RoomVersionId::V6, RoomVersionId::V7, RoomVersionId::V8, RoomVersionId::V9, RoomVersionId::V10, RoomVersionId::V11, RoomVersionId::V12, ] }); pub static UNSTABLE_ROOM_VERSIONS: LazyLock<Vec<RoomVersionId>> = LazyLock::new(|| { vec![ RoomVersionId::V2, RoomVersionId::V3, RoomVersionId::V4, RoomVersionId::V5, ] }); fn figment_from_path<P: AsRef<Path>>(path: P) -> Figment { let ext = path .as_ref() .extension() .and_then(|s| s.to_str()) .unwrap_or_default(); match ext { "yaml" | "yml" => Figment::new().merge(Yaml::file(path)), "json" => Figment::new().merge(Json::file(path)), "toml" => Figment::new().merge(Toml::file(path)), _ => panic!("unsupported config file format: {ext}"), } } pub fn init(config_path: impl AsRef<Path>) { let config_path = config_path.as_ref(); if !config_path.exists() { panic!("config file not found: `{}`", config_path.display()); } let raw_conf = figment_from_path(config_path).merge(Env::prefixed("PALPO_").global()); let conf = match raw_conf.extract::<ServerConfig>() { Ok(s) => s, Err(e) => { eprintln!("it looks like your config is invalid. The following error occurred: {e}"); std::process::exit(1); } }; CONFIG.set(conf).expect("config should be set once"); } pub fn reload(path: impl AsRef<Path>) -> AppResult<()> { // TODO: reload config Ok(()) } pub fn get() -> &'static ServerConfig { CONFIG.get().unwrap() } pub static SERVER_USER_ID: OnceLock<OwnedUserId> = OnceLock::new(); pub fn server_user_id() -> &'static UserId { SERVER_USER_ID.get_or_init(|| { format!("@palpo:{}", get().server_name) .try_into() .expect("invalid server user ID") }) } pub fn server_user() -> crate::data::user::DbUser { crate::data::user::get_user(server_user_id()).expect("server user should exist in the database") } pub fn space_path() -> &'static str { get().space_path.deref() } pub fn server_name() -> &'static ServerName { get().server_name.deref() } static ADMIN_ALIAS: OnceLock<OwnedRoomAliasId> = OnceLock::new(); pub fn admin_alias() -> &'static RoomAliasId { ADMIN_ALIAS.get_or_init(|| { let alias = format!("#admins:{}", get().server_name); alias .try_into() .expect("admin alias should be a valid room alias") }) } pub fn appservice_registration_dir() -> Option<&'static str> { get().appservice_registration_dir.as_deref() } /// Returns this server's keypair. pub fn keypair() -> &'static Ed25519KeyPair { static KEYPAIR: OnceLock<Ed25519KeyPair> = OnceLock::new(); KEYPAIR.get_or_init(|| { if let Some(keypair) = &get().keypair { let bytes = STANDARD .decode(&keypair.document) .expect("server keypair is invalid base64 string"); Ed25519KeyPair::from_der(&bytes, keypair.version.clone()) .expect("invalid server Ed25519KeyPair") } else { crate::utils::generate_keypair() } }) } pub fn valid_cidr_range(ip: &IPAddress) -> bool { cidr_range_denylist().iter().all(|cidr| !cidr.includes(ip)) } pub fn cidr_range_denylist() -> &'static [IPAddress] { static CIDR_RANGE_DENYLIST: OnceLock<Vec<IPAddress>> = OnceLock::new(); CIDR_RANGE_DENYLIST.get_or_init(|| { let conf = get(); conf.ip_range_denylist .iter() .map(IPAddress::parse) .inspect(|cidr| trace!("Denied CIDR range: {cidr:?}")) .collect::<Result<_, String>>() .expect("invalid CIDR range in config") }) } pub fn jwt_decoding_key() -> Option<&'static jsonwebtoken::DecodingKey> { static JWT_DECODING_KEY: OnceLock<Option<jsonwebtoken::DecodingKey>> = OnceLock::new(); JWT_DECODING_KEY .get_or_init(|| { get() .jwt .as_ref() .map(|jwt| jsonwebtoken::DecodingKey::from_secret(jwt.secret.as_bytes())) }) .as_ref() } pub fn supported_room_versions() -> Vec<RoomVersionId> { let mut room_versions: Vec<RoomVersionId> = vec![]; room_versions.extend(STABLE_ROOM_VERSIONS.clone()); if get().allow_unstable_room_versions { room_versions.extend(UNSTABLE_ROOM_VERSIONS.clone()); }; room_versions } pub fn supports_room_version(room_version: &RoomVersionId) -> bool { supported_room_versions().contains(room_version) } pub type RoomVersion = (RoomVersionId, RoomVersionStability); pub fn available_room_versions() -> impl Iterator<Item = RoomVersion> { let unstable_room_versions = UNSTABLE_ROOM_VERSIONS .iter() .cloned() .zip(once(RoomVersionStability::Unstable).cycle()); STABLE_ROOM_VERSIONS .iter() .cloned() .zip(once(RoomVersionStability::Stable).cycle()) .chain(unstable_room_versions) } #[inline] fn supported_stability(stability: &RoomVersionStability) -> bool { get().allow_unstable_room_versions || *stability == RoomVersionStability::Stable }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/exts.rs
crates/server/src/exts.rs
use salvo::prelude::*; use crate::core::identifiers::*; use crate::{AppResult, AuthedInfo, config}; mod url; pub use url::*; pub trait DepotExt { fn authed_info(&self) -> AppResult<&AuthedInfo>; fn set_origin(&mut self, origin: OwnedServerName); fn origin(&mut self) -> AppResult<&OwnedServerName>; fn take_authed_info(&mut self) -> AppResult<AuthedInfo>; } impl DepotExt for Depot { fn authed_info(&self) -> AppResult<&AuthedInfo> { self.obtain::<AuthedInfo>() .map_err(|_| StatusError::unauthorized().into()) } fn set_origin(&mut self, origin: OwnedServerName) { self.insert("origin", origin); } fn origin(&mut self) -> AppResult<&OwnedServerName> { self.get::<OwnedServerName>("origin") .map_err(|_| StatusError::unauthorized().into()) } fn take_authed_info(&mut self) -> AppResult<AuthedInfo> { self.scrape::<AuthedInfo>() .map_err(|_| StatusError::unauthorized().into()) } } pub trait IsRemoteOrLocal { fn is_remote(&self) -> bool; fn is_local(&self) -> bool; } impl IsRemoteOrLocal for UserId { fn is_remote(&self) -> bool { self.server_name() != config::get().server_name } fn is_local(&self) -> bool { self.server_name() == config::get().server_name } } impl IsRemoteOrLocal for OwnedUserId { fn is_remote(&self) -> bool { self.server_name() != config::get().server_name } fn is_local(&self) -> bool { self.server_name() == config::get().server_name } } impl IsRemoteOrLocal for RoomId { fn is_remote(&self) -> bool { self.server_name() .map(|s| s != config::get().server_name) .unwrap_or(false) } fn is_local(&self) -> bool { self.server_name() .map(|s| s == config::get().server_name) .unwrap_or(false) } } impl IsRemoteOrLocal for OwnedRoomId { fn is_remote(&self) -> bool { self.server_name() .map(|s| s != config::get().server_name) .unwrap_or(false) } fn is_local(&self) -> bool { self.server_name() .map(|s| s == config::get().server_name) .unwrap_or(false) } } impl IsRemoteOrLocal for RoomAliasId { fn is_remote(&self) -> bool { self.server_name() != config::get().server_name } fn is_local(&self) -> bool { self.server_name() == config::get().server_name } } impl IsRemoteOrLocal for OwnedRoomAliasId { fn is_remote(&self) -> bool { self.server_name() != config::get().server_name } fn is_local(&self) -> bool { self.server_name() == config::get().server_name } } impl IsRemoteOrLocal for ServerName { fn is_remote(&self) -> bool { self != config::get().server_name } fn is_local(&self) -> bool { self == config::get().server_name } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/user.rs
crates/server/src/user.rs
mod password; use palpo_data::user::set_display_name; pub use password::*; pub mod key; pub mod pusher; pub use key::*; pub mod presence; // mod ldap; // pub use ldap::*; pub mod session; pub use presence::*; use std::mem; use diesel::prelude::*; use serde::de::DeserializeOwned; use crate::core::UnixMillis; use crate::core::events::GlobalAccountDataEventType; use crate::core::events::ignored_user_list::IgnoredUserListEvent; use crate::core::events::room::power_levels::RoomPowerLevelsEventContent; use crate::core::identifiers::*; use crate::core::serde::JsonValue; use crate::data::schema::*; use crate::data::user::{DbUser, DbUserData, NewDbPassword, NewDbUser}; use crate::data::{DataResult, connect}; use crate::room::timeline; use crate::{AppError, AppResult, IsRemoteOrLocal, MatrixError, PduBuilder, config, data, room}; pub fn is_username_available(username: &str) -> AppResult<bool> { let user_id = UserId::parse(format!("@{}:{}", username, config::server_name())) .map_err(|_| AppError::internal("invalid username format"))?; user_id.validate_strict()?; let available = !data::user::user_exists(&user_id)?; Ok(available) } pub fn create_user(user_id: impl Into<OwnedUserId>, password: Option<&str>) -> AppResult<DbUser> { let user_id = user_id.into(); let new_user = NewDbUser { id: user_id.clone(), ty: None, is_admin: false, is_guest: password.is_none(), is_local: user_id.is_local(), localpart: user_id.localpart().to_owned(), server_name: user_id.server_name().to_owned(), appservice_id: None, created_at: UnixMillis::now(), }; let user = diesel::insert_into(users::table) .values(&new_user) .on_conflict(users::id) .do_update() .set(&new_user) .get_result::<DbUser>(&mut connect()?)?; let display_name = user_id.localpart().to_owned(); if let Some(password) = password { crate::user::set_password(&user.id, password)?; } if let Err(e) = set_display_name(&user.id, &display_name) { tracing::warn!("failed to set profile for new user (non-fatal): {}", e); } Ok(user) } pub fn list_local_users() -> AppResult<Vec<OwnedUserId>> { let users = user_passwords::table .select(user_passwords::user_id) .load::<OwnedUserId>(&mut connect()?)?; Ok(users) } /// Ensure that a user only sees signatures from themselves and the target user pub fn clean_signatures<F: Fn(&UserId) -> bool>( cross_signing_key: &mut serde_json::Value, sender_id: Option<&UserId>, user_id: &UserId, allowed_signatures: F, ) -> AppResult<()> { if let Some(signatures) = cross_signing_key .get_mut("signatures") .and_then(|v| v.as_object_mut()) { // Don't allocate for the full size of the current signatures, but require // at most one resize if nothing is dropped let new_capacity = signatures.len() / 2; for (user, signature) in mem::replace(signatures, serde_json::Map::with_capacity(new_capacity)) { let sid = <&UserId>::try_from(user.as_str()) .map_err(|_| AppError::internal("Invalid user ID in database."))?; if sender_id == Some(user_id) || sid == user_id || allowed_signatures(sid) { signatures.insert(user, signature); } } } Ok(()) } /// Returns true/false based on whether the recipient/receiving user has /// blocked the sender pub fn user_is_ignored(sender_id: &UserId, recipient_id: &UserId) -> bool { if let Ok(Some(ignored)) = data::user::get_global_data::<IgnoredUserListEvent>( recipient_id, &GlobalAccountDataEventType::IgnoredUserList.to_string(), ) { ignored .content .ignored_users .keys() .any(|blocked_user| blocked_user == sender_id) } else { false } } /// Runs through all the deactivation steps: /// /// - Mark as deactivated /// - Removing display name /// - Removing avatar URL and blurhash /// - Removing all profile data /// - Leaving all rooms (and forgets all of them) pub async fn full_user_deactivate( user_id: &UserId, all_joined_rooms: &[OwnedRoomId], ) -> AppResult<()> { data::user::deactivate(user_id).ok(); data::user::delete_profile(user_id).ok(); // TODO: remove all user data // for profile_key in data::user::all_profile_keys(user_id) { // data::user::set_profile_key(user_id, &profile_key, None); // } for room_id in all_joined_rooms { let state_lock = room::lock_state(room_id).await; let room_version = room::get_version(room_id)?; let version_rules = room::get_version_rules(&room_version)?; let room_power_levels = room::get_power_levels(room_id).await.ok(); let user_can_change_self = room_power_levels.as_ref().is_some_and(|power_levels| { power_levels.user_can_change_user_power_level(user_id, user_id) }); let user_can_demote_self = user_can_change_self || room::get_create(room_id).is_ok_and(|event| event.sender == user_id); if user_can_demote_self { let mut power_levels_content: RoomPowerLevelsEventContent = room_power_levels .map(TryInto::try_into) .transpose()? .unwrap_or_else(|| RoomPowerLevelsEventContent::new(&version_rules.authorization)); power_levels_content.users.remove(user_id); // ignore errors so deactivation doesn't fail match timeline::build_and_append_pdu( PduBuilder::state(String::new(), &power_levels_content), user_id, room_id, &room_version, &state_lock, ) .await { Err(e) => { warn!(%room_id, %user_id, "Failed to demote user's own power level: {e}"); } _ => { info!("Demoted {user_id} in {room_id} as part of account deactivation"); } } } } if let Err(e) = crate::membership::leave_all_rooms(user_id).await { tracing::warn!(%user_id, "failed to leave all rooms during deactivation: {e}"); } Ok(()) } /// Find out which user an OpenID access token belongs to. pub async fn find_from_openid_token(token: &str) -> AppResult<OwnedUserId> { let Ok((user_id, expires_at)) = user_openid_tokens::table .filter(user_openid_tokens::token.eq(token)) .select((user_openid_tokens::user_id, user_openid_tokens::expires_at)) .first::<(OwnedUserId, UnixMillis)>(&mut connect()?) else { return Err(MatrixError::unauthorized("OpenID token is unrecognised").into()); }; if expires_at < UnixMillis::now() { tracing::warn!("OpenID token is expired, removing"); diesel::delete(user_openid_tokens::table.filter(user_openid_tokens::token.eq(token))) .execute(&mut connect()?)?; return Err(MatrixError::unauthorized("OpenID token is expired").into()); } Ok(user_id) } /// Creates a short-lived login token, which can be used to log in using the /// `m.login.token` mechanism. pub fn create_login_token(user_id: &UserId, token: &str) -> AppResult<u64> { use std::num::Saturating as Sat; let expires_in = crate::config::get().login_token_ttl; let expires_at = (Sat(UnixMillis::now().get()) + Sat(expires_in)).0 as i64; diesel::insert_into(user_login_tokens::table) .values(( user_login_tokens::user_id.eq(user_id), user_login_tokens::token.eq(token), user_login_tokens::expires_at.eq(expires_at), )) .on_conflict(user_login_tokens::token) .do_update() .set(user_login_tokens::expires_at.eq(expires_at)) .execute(&mut connect()?)?; Ok(expires_in) } /// Find out which user a login token belongs to. /// Removes the token to prevent double-use attacks. pub fn take_login_token(token: &str) -> AppResult<OwnedUserId> { let Ok((user_id, expires_at)) = user_login_tokens::table .filter(user_login_tokens::token.eq(token)) .select((user_login_tokens::user_id, user_login_tokens::expires_at)) .first::<(OwnedUserId, UnixMillis)>(&mut connect()?) else { return Err(MatrixError::forbidden("Login token is unrecognised.", None).into()); }; if expires_at < UnixMillis::now() { trace!(?user_id, ?token, "Removing expired login token"); diesel::delete(user_login_tokens::table.filter(user_login_tokens::token.eq(token))) .execute(&mut connect()?)?; return Err(MatrixError::forbidden("Login token is expired.", None).into()); } diesel::delete(user_login_tokens::table.filter(user_login_tokens::token.eq(token))) .execute(&mut connect()?)?; Ok(user_id) } pub fn valid_refresh_token(user_id: &UserId, device_id: &DeviceId, token: &str) -> AppResult<()> { let Ok(expires_at) = user_refresh_tokens::table .filter(user_refresh_tokens::user_id.eq(user_id)) .filter(user_refresh_tokens::device_id.eq(device_id)) .filter(user_refresh_tokens::token.eq(token)) .select(user_refresh_tokens::expires_at) .first::<i64>(&mut connect()?) else { return Err(MatrixError::unauthorized("Invalid refresh token.").into()); }; if expires_at < UnixMillis::now().get() as i64 { return Err(MatrixError::unauthorized("Refresh token expired.").into()); } Ok(()) } pub fn make_user_admin(user_id: &UserId) -> AppResult<()> { let user_id = user_id.to_owned(); diesel::update(users::table.filter(users::id.eq(&user_id))) .set(users::is_admin.eq(true)) .execute(&mut connect()?)?; Ok(()) } /// Places one event in the account data of the user and removes the previous entry. #[tracing::instrument(skip(room_id, user_id, event_type, json_data))] pub fn set_data( user_id: &UserId, room_id: Option<OwnedRoomId>, event_type: &str, json_data: JsonValue, ) -> DataResult<DbUserData> { let user_data = data::user::set_data(user_id, room_id, event_type, json_data)?; Ok(user_data) } pub fn get_data<E: DeserializeOwned>( user_id: &UserId, room_id: Option<&RoomId>, kind: &str, ) -> DataResult<E> { let data = data::user::get_data::<E>(user_id, room_id, kind)?; Ok(data) } pub fn get_global_datas(user_id: &UserId) -> DataResult<Vec<DbUserData>> { let datas = user_datas::table .filter(user_datas::user_id.eq(user_id)) .filter(user_datas::room_id.is_null()) .load::<DbUserData>(&mut connect()?)?; Ok(datas) } pub async fn delete_all_media(user_id: &UserId) -> AppResult<i64> { let medias = media_metadatas::table .filter(media_metadatas::created_by.eq(user_id)) .select((media_metadatas::origin_server, media_metadatas::media_id)) .load::<(OwnedServerName, String)>(&mut connect()?)?; for (origin_server, media_id) in &medias { if let Err(e) = crate::media::delete_media(origin_server, media_id).await { tracing::error!("failed to delete media file: {e}"); } } Ok(0) } pub async fn deactivate_account(user_id: &UserId) -> AppResult<()> { diesel::update(users::table.find(user_id)) .set(users::deactivated_at.eq(UnixMillis::now())) .execute(&mut connect()?)?; Ok(()) }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/event.rs
crates/server/src/event.rs
mod batch_token; pub mod fetching; pub mod handler; mod pdu; pub mod resolver; pub use batch_token::*; pub use pdu::*; mod outlier; pub mod search; pub use outlier::*; use diesel::prelude::*; use crate::core::identifiers::*; use crate::core::serde::{CanonicalJsonObject, RawJsonValue}; use crate::core::{Direction, Seqnum, UnixMillis, signatures}; use crate::data::connect; use crate::data::room::DbEvent; use crate::data::schema::*; use crate::utils::SeqnumQueueGuard; use crate::{AppError, AppResult, MatrixError}; /// Generates a correct eventId for the incoming pdu. /// /// Returns a tuple of the new `EventId` and the PDU as a `BTreeMap<String, CanonicalJsonValue>`. pub fn gen_event_id_canonical_json( pdu: &RawJsonValue, room_version_id: &RoomVersionId, ) -> AppResult<(OwnedEventId, CanonicalJsonObject)> { let value: CanonicalJsonObject = serde_json::from_str(pdu.get()).map_err(|e| { warn!("error parsing event {:?}: {:?}", pdu, e); AppError::public("invalid pdu in server response") })?; let event_id = gen_event_id(&value, room_version_id)?; Ok((event_id, value)) } /// Generates a correct eventId for the incoming pdu. pub fn gen_event_id( value: &CanonicalJsonObject, room_version_id: &RoomVersionId, ) -> AppResult<OwnedEventId> { let version_rules = crate::room::get_version_rules(room_version_id)?; let reference_hash = signatures::reference_hash(value, &version_rules)?; let event_id: OwnedEventId = format!("${reference_hash}").try_into()?; Ok(event_id) } pub fn ensure_event_sn( room_id: &RoomId, event_id: &EventId, ) -> AppResult<(Seqnum, Option<SeqnumQueueGuard>)> { if let Some(sn) = event_points::table .find(event_id) .select(event_points::event_sn) .first::<Seqnum>(&mut connect()?) .optional()? { Ok((sn, None)) } else { let sn = diesel::insert_into(event_points::table) .values(( event_points::event_id.eq(event_id), event_points::room_id.eq(room_id), )) .on_conflict_do_nothing() .returning(event_points::event_sn) .get_result::<Seqnum>(&mut connect()?)?; diesel::update(events::table.find(event_id)) .set(events::sn.eq(sn)) .execute(&mut connect()?)?; diesel::update(event_datas::table.find(event_id)) .set(event_datas::event_sn.eq(sn)) .execute(&mut connect()?)?; Ok((sn, Some(crate::queue_seqnum(sn)))) } } /// Returns the `count` of this pdu's id. pub fn get_event_sn(event_id: &EventId) -> AppResult<Seqnum> { event_points::table .find(event_id) .select(event_points::event_sn) .first::<Seqnum>(&mut connect()?) .map_err(Into::into) } pub fn get_live_token(event_id: &EventId) -> AppResult<BatchToken> { events::table .find(event_id) .select((events::sn, events::depth)) .first::<(Seqnum, i64)>(&mut connect()?) .map(|(sn, _depth)| BatchToken::new_live(sn)) .map_err(Into::into) } pub fn get_historic_token(event_id: &EventId) -> AppResult<BatchToken> { events::table .find(event_id) .select((events::sn, events::depth)) .first::<(Seqnum, i64)>(&mut connect()?) .map(|(sn, depth)| BatchToken::new_historic(sn, depth)) .map_err(Into::into) } pub fn get_historic_token_by_sn(event_sn: Seqnum) -> AppResult<BatchToken> { events::table .filter(events::sn.eq(event_sn)) .select((events::sn, events::depth)) .first::<(Seqnum, i64)>(&mut connect()?) .map(|(sn, depth)| BatchToken::new_historic(sn, depth)) .map_err(Into::into) } pub fn get_event_id_by_sn(event_sn: Seqnum) -> AppResult<OwnedEventId> { event_points::table .filter(event_points::event_sn.eq(event_sn)) .select(event_points::event_id) .first::<OwnedEventId>(&mut connect()?) .map_err(Into::into) } pub fn get_event_for_timestamp( room_id: &RoomId, timestamp: UnixMillis, dir: Direction, ) -> AppResult<(OwnedEventId, UnixMillis)> { match dir { Direction::Forward => { let (local_event_id, origin_server_ts) = events::table .filter(events::room_id.eq(room_id)) .filter(events::origin_server_ts.ge(timestamp)) .filter(events::is_outlier.eq(false)) .filter(events::is_redacted.eq(false)) .order_by(( events::origin_server_ts.asc(), events::depth.asc(), events::stream_ordering.asc(), )) .select((events::id, events::origin_server_ts)) .first::<(OwnedEventId, UnixMillis)>(&mut connect()?)?; Ok((local_event_id, origin_server_ts)) } Direction::Backward => { let (local_event_id, origin_server_ts) = events::table .filter(events::room_id.eq(room_id)) .filter(events::origin_server_ts.le(timestamp)) .filter(events::is_outlier.eq(false)) .filter(events::is_redacted.eq(false)) .order_by(( events::origin_server_ts.desc(), events::depth.desc(), events::stream_ordering.desc(), )) .select((events::id, events::origin_server_ts)) .first::<(OwnedEventId, UnixMillis)>(&mut connect()?)?; Ok((local_event_id, origin_server_ts)) } } // TODO: implement this function to find the event for a given timestamp // Check for gaps in the history where events could be hiding in between // the timestamp given and the event we were able to find locally // let is_event_next_to_backward_gap = false; // let is_event_next_to_forward_gap = false; // let local_event = None; } pub fn get_event_sn_and_ty(event_id: &EventId) -> AppResult<(Seqnum, String)> { let (sn, ty) = events::table .find(event_id) .select((events::sn, events::ty)) .first::<(Seqnum, String)>(&mut connect()?)?; Ok((sn, ty)) } pub fn get_db_event(event_id: &EventId) -> AppResult<DbEvent> { events::table .find(event_id) .first::<DbEvent>(&mut connect()?) .map_err(Into::into) } pub fn get_frame_id(room_id: &RoomId, event_sn: Seqnum) -> AppResult<i64> { event_points::table .filter(event_points::room_id.eq(room_id)) .filter(event_points::event_sn.eq(event_sn)) .select(event_points::frame_id) .first::<Option<i64>>(&mut connect()?)? .ok_or(MatrixError::not_found("room frame id is not found").into()) } pub fn get_last_frame_id(room_id: &RoomId, before_sn: Option<Seqnum>) -> AppResult<i64> { if let Some(before_sn) = before_sn { event_points::table .filter(event_points::room_id.eq(room_id)) .filter(event_points::event_sn.le(before_sn)) .filter(event_points::frame_id.is_not_null()) .select(event_points::frame_id) .order_by(event_points::event_sn.desc()) .first::<Option<i64>>(&mut connect()?)? .ok_or(MatrixError::not_found("room last frame id is not found").into()) } else { event_points::table .filter(event_points::room_id.eq(room_id)) .filter(event_points::frame_id.is_not_null()) .select(event_points::frame_id) .order_by(event_points::event_sn.desc()) .first::<Option<i64>>(&mut connect()?)? .ok_or(MatrixError::not_found("room last frame id is not found").into()) } } pub fn update_frame_id(event_id: &EventId, frame_id: i64) -> AppResult<()> { diesel::update(event_points::table.find(event_id)) .set(event_points::frame_id.eq(frame_id)) .execute(&mut connect()?)?; // diesel::update(events::table.find(event_id)) // .set(events::stream_ordering.eq(frame_id)) // .execute(&mut connect()?)?; Ok(()) } pub fn update_frame_id_by_sn(event_sn: Seqnum, frame_id: i64) -> AppResult<()> { diesel::update(event_points::table.filter(event_points::event_sn.eq(event_sn))) .set(event_points::frame_id.eq(frame_id)) .execute(&mut connect()?)?; // diesel::update(events::table.filter(events::sn.eq(event_sn))) // .set(events::stream_ordering.eq(frame_id)) // .execute(&mut connect()?)?; Ok(()) } pub type PdusIterItem<'a> = (&'a Seqnum, &'a SnPduEvent); pub fn parse_fetched_pdu( room_id: &RoomId, room_version: &RoomVersionId, raw_value: &RawJsonValue, ) -> AppResult<(OwnedEventId, CanonicalJsonObject)> { let value: CanonicalJsonObject = serde_json::from_str(raw_value.get()).map_err(|e| { warn!("error parsing fetched event {:?}: {:?}", raw_value, e); MatrixError::bad_json("invalid pdu in server response") })?; let parsed_room_id = value .get("room_id") .and_then(|id| RoomId::parse(id.as_str()?).ok()); if let Some(parsed_room_id) = parsed_room_id && parsed_room_id != room_id { return Err(MatrixError::invalid_param("mismatched room_id in fetched pdu").into()); } let event_id = match crate::event::gen_event_id(&value, room_version) { Ok(t) => t, Err(e) => { // Event could not be converted to canonical json error!(value = ?value, "error generating event id for fetched pdu: {:?}", e); return Err( MatrixError::invalid_param("could not convert event to canonical json").into(), ); } }; Ok((event_id, value)) } pub fn parse_incoming_pdu( raw_value: &RawJsonValue, ) -> AppResult<( OwnedEventId, CanonicalJsonObject, OwnedRoomId, RoomVersionId, )> { let value: CanonicalJsonObject = serde_json::from_str(raw_value.get()).map_err(|e| { warn!("error parsing incoming event {:?}: {:?}", raw_value, e); MatrixError::bad_json("invalid pdu in server response") })?; let room_id = value .get("room_id") .and_then(|id| RoomId::parse(id.as_str()?).ok()) .ok_or(MatrixError::invalid_param("invalid room id in pdu"))?; let room_version_id = crate::room::get_version(&room_id).map_err(|_| { MatrixError::invalid_param(format!( "server is not in room `{room_id}` when parse incoming event" )) })?; let event_id = match crate::event::gen_event_id(&value, &room_version_id) { Ok(t) => t, Err(_) => { // Event could not be converted to canonical json return Err( MatrixError::invalid_param("could not convert event to canonical json").into(), ); } }; Ok((event_id, value, room_id, room_version_id)) } pub fn seen_event_ids( room_id: &RoomId, event_ids: &[OwnedEventId], ) -> AppResult<Vec<OwnedEventId>> { let seen_events = events::table .filter(events::room_id.eq(room_id)) .filter(events::id.eq_any(event_ids)) .select(events::id) .load::<OwnedEventId>(&mut connect()?)?; Ok(seen_events) } #[inline] pub fn ignored_filter(item: PdusIterItem, user_id: &UserId) -> bool { let (_, pdu) = item; !is_ignored_pdu(pdu, user_id) } pub fn is_ignored_pdu(pdu: &SnPduEvent, _user_id: &UserId) -> bool { // exclude Synapse's dummy events from bloating up response bodies. clients // don't need to see this. if pdu.event_ty.to_string() == "org.matrix.dummy_event" { return true; } // TODO: fixme // let ignored_type = IGNORED_MESSAGE_TYPES.binary_search(&pdu.kind).is_ok(); // let ignored_server = crate::config::get() // .forbidden_remote_server_names // .contains(pdu.sender().server_name()); // if ignored_type && (crate::user::user_is_ignored(&pdu.sender, user_id).await) { // return true; // } false }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/sync_v3.rs
crates/server/src/sync_v3.rs
use std::collections::{BTreeMap, HashMap, HashSet, hash_map::Entry}; use indexmap::IndexMap; use state::DbRoomStateField; use crate::core::client::filter::{FilterDefinition, LazyLoadOptions, RoomEventFilter}; use crate::core::client::sync_events::UnreadNotificationsCount; use crate::core::client::sync_events::v3::{ Ephemeral, Filter, GlobalAccountData, InviteState, InvitedRoom, JoinedRoom, KnockState, KnockedRoom, LeftRoom, Presence, RoomAccountData, RoomSummary, Rooms, State, SyncEventsReqArgs, SyncEventsResBody, Timeline, ToDevice, }; use crate::core::device::DeviceLists; use crate::core::events::receipt::SyncReceiptEvent; use crate::core::events::room::member::{MembershipState, RoomMemberEventContent}; use crate::core::events::{ AnyRawAccountDataEvent, AnySyncEphemeralRoomEvent, StateEventType, TimelineEventType, }; use crate::core::identifiers::*; use crate::core::serde::RawJson; use crate::core::{Seqnum, UnixMillis}; use crate::data::{connect, schema::*}; use crate::event::BatchToken; use crate::event::{EventHash, PduEvent, SnPduEvent}; use crate::room::{state, timeline}; use crate::{AppError, AppResult, config, data, extract_variant, room}; pub const DEFAULT_BUMP_TYPES: &[TimelineEventType; 6] = &[ TimelineEventType::CallInvite, TimelineEventType::PollStart, TimelineEventType::Beacon, TimelineEventType::RoomEncrypted, TimelineEventType::RoomMessage, TimelineEventType::Sticker, ]; #[tracing::instrument(skip_all)] pub async fn sync_events( sender_id: &UserId, device_id: &DeviceId, args: &SyncEventsReqArgs, ) -> AppResult<SyncEventsResBody> { let curr_sn = data::curr_sn()?; crate::seqnum_reach(curr_sn).await; let since_tk = if let Some(since_str) = args.since.as_ref() { let since_tk: BatchToken = since_str.parse()?; if since_tk.stream_ordering() > curr_sn { return Ok(SyncEventsResBody::new(since_str.to_owned())); } Some(since_tk) } else { None }; let mut next_batch = BatchToken::new_live(curr_sn + 1); // Load filter let filter = match &args.filter { None => FilterDefinition::default(), Some(Filter::FilterDefinition(filter)) => filter.to_owned(), Some(Filter::FilterId(filter_id)) => { data::user::get_filter(sender_id, filter_id.parse::<i64>().unwrap_or_default())? } }; let _lazy_load_enabled = filter.room.state.lazy_load_options.is_enabled() || filter.room.timeline.lazy_load_options.is_enabled(); let full_state = args.full_state; let mut joined_rooms = BTreeMap::new(); let mut presence_updates = HashMap::new(); // Users that have joined any encrypted rooms the sender was in let mut joined_users = HashSet::new(); // Users that have left any encrypted rooms the sender was in let mut left_users = HashSet::new(); let mut device_list_updates = HashSet::new(); let mut device_list_left = HashSet::new(); // Look for device list updates of this account device_list_updates.extend(data::user::keys_changed_users( sender_id, since_tk.unwrap_or(BatchToken::LIVE_MIN).event_sn(), None, )?); let all_joined_rooms = data::user::joined_rooms(sender_id)?; for room_id in &all_joined_rooms { let joined_room = match load_joined_room( sender_id, device_id, room_id, since_tk, Some(BatchToken::new_live(curr_sn)), next_batch, full_state, &filter, args.use_state_after, &mut device_list_updates, &mut joined_users, &mut left_users, ) .await { Ok((joined_room, nb)) => { if let Some(nb) = nb && nb.stream_ordering() < next_batch.stream_ordering() { next_batch = nb; } joined_room } Err(e) => { tracing::error!(error = ?e, "load joined room failed"); continue; } }; if !joined_room.is_empty() { joined_rooms.insert(room_id.to_owned(), joined_room); } } let mut left_rooms = BTreeMap::new(); let all_left_rooms = room::user::left_rooms(sender_id, since_tk)?; for room_id in all_left_rooms.keys() { let Ok(left_sn) = room::user::left_sn(room_id, sender_id) else { tracing::warn!("left room {} without a left_sn, skipping", room_id); continue; }; // Left before last sync if since_tk.map(|t| t.stream_ordering()) > Some(left_sn) { continue; } let left_room = match load_left_room( sender_id, device_id, room_id, since_tk, Some(BatchToken::new_live(curr_sn)), left_sn, next_batch, full_state, &filter, &mut device_list_updates, &mut joined_users, &mut left_users, ) .await { Ok(left_room) => left_room, Err(e) => { tracing::error!(error = ?e, "load left room failed"); continue; } }; left_rooms.insert(room_id.to_owned(), left_room); } let invited_rooms: BTreeMap<_, _> = data::user::invited_rooms( sender_id, since_tk.unwrap_or(BatchToken::LIVE_MIN).stream_ordering(), )? .into_iter() .map(|(room_id, invite_state_events)| { ( room_id, InvitedRoom::new(InviteState::new(invite_state_events)), ) }) .collect(); for left_room in left_rooms.keys() { for user_id in room::joined_users(left_room, None)? { let dont_share_encrypted_room = room::user::shared_rooms(vec![sender_id.to_owned(), user_id.clone()])? .into_iter() .map(|other_room_id| { room::get_state(&other_room_id, &StateEventType::RoomEncryption, "", None) .is_ok() }) .all(|encrypted| !encrypted); // If the user doesn't share an encrypted room with the target anymore, we need to tell them. if dont_share_encrypted_room { device_list_left.insert(user_id); } } } for user_id in left_users { let dont_share_encrypted_room = room::user::shared_rooms(vec![sender_id.to_owned(), user_id.clone()])? .into_iter() .map(|other_room_id| { room::get_state(&other_room_id, &StateEventType::RoomEncryption, "", None) .is_ok() }) .all(|encrypted| !encrypted); // If the user doesn't share an encrypted room with the target anymore, we need to tell them. if dont_share_encrypted_room { device_list_left.insert(user_id); } } let knocked_rooms = data::user::knocked_rooms(sender_id, 0)?.into_iter().fold( BTreeMap::default(), |mut knocked_rooms: BTreeMap<_, _>, (room_id, knock_state)| { let knock_sn = room::user::knock_sn(sender_id, &room_id).ok(); // Knocked before last sync if since_tk.map(|t| t.event_sn()) > knock_sn { return knocked_rooms; } let knocked_room = KnockedRoom { knock_state: KnockState { events: knock_state, }, }; knocked_rooms.insert(room_id, knocked_room); knocked_rooms }, ); if config::get().presence.allow_local { // Take presence updates from this room for (user_id, presence_event) in crate::data::user::presences_since(since_tk.unwrap_or(BatchToken::LIVE_MIN).event_sn())? { if user_id == sender_id || !state::user_can_see_user(sender_id, &user_id)? { continue; } match presence_updates.entry(user_id) { Entry::Vacant(slot) => { slot.insert(presence_event); } Entry::Occupied(mut slot) => { let curr_event = slot.get_mut(); let curr_content = &mut curr_event.content; let new_content = presence_event.content; // Update existing presence event with more info curr_content.presence = new_content.presence; curr_content.status_msg = new_content.status_msg.or(curr_content.status_msg.take()); curr_content.last_active_ago = new_content.last_active_ago.or(curr_content.last_active_ago); curr_content.display_name = new_content .display_name .or(curr_content.display_name.take()); curr_content.avatar_url = new_content.avatar_url.or(curr_content.avatar_url.take()); curr_content.currently_active = new_content .currently_active .or(curr_content.currently_active); } } } for joined_user in &joined_users { if !presence_updates.contains_key(joined_user) && let Ok(presence) = data::user::last_presence(joined_user) { presence_updates.insert(joined_user.to_owned(), presence); } } } // Remove all to-device events the device received *last time* data::user::device::remove_to_device_events( sender_id, device_id, since_tk.unwrap_or(BatchToken::LIVE_MIN).event_sn() - 1, )?; let account_data = GlobalAccountData { events: data::user::data_changes( None, sender_id, since_tk.unwrap_or(BatchToken::LIVE_MIN).event_sn(), None, )? .into_iter() .filter_map(|e| extract_variant!(e, AnyRawAccountDataEvent::Global)) .collect(), }; let rooms = Rooms { leave: left_rooms, join: joined_rooms, invite: invited_rooms, knock: knocked_rooms, }; let presence = Presence { events: presence_updates .into_values() .map(|v| RawJson::new(&v).expect("PresenceEvent always serializes successfully")) .collect(), }; let device_lists = DeviceLists { changed: device_list_updates.into_iter().collect(), left: device_list_left.into_iter().collect(), }; let to_device = ToDevice { events: data::user::device::get_to_device_events( sender_id, device_id, since_tk.map(|s| s.event_sn()), Some(next_batch.event_sn()), )?, }; let res_body = SyncEventsResBody { next_batch: next_batch.to_string(), rooms, presence, account_data, device_lists, device_one_time_keys_count: { data::user::count_one_time_keys(sender_id, device_id).unwrap_or_default() }, to_device, // Fallback keys are not yet supported device_unused_fallback_key_types: None, }; Ok(res_body) } #[tracing::instrument(skip_all)] async fn load_joined_room( sender_id: &UserId, device_id: &DeviceId, room_id: &RoomId, since_tk: Option<BatchToken>, until_tk: Option<BatchToken>, next_batch: BatchToken, full_state: bool, filter: &FilterDefinition, _use_state_after: bool, // TODO device_list_updates: &mut HashSet<OwnedUserId>, joined_users: &mut HashSet<OwnedUserId>, left_users: &mut HashSet<OwnedUserId>, ) -> AppResult<(JoinedRoom, Option<BatchToken>)> { if since_tk.map(|s| s.event_sn()) > Some(data::curr_sn()?) { return Ok((JoinedRoom::default(), None)); } let lazy_load_enabled = filter.room.state.lazy_load_options.is_enabled() || filter.room.timeline.lazy_load_options.is_enabled(); let lazy_load_send_redundant = match filter.room.state.lazy_load_options { LazyLoadOptions::Enabled { include_redundant_members: redundant, } => redundant, _ => false, }; let Ok(current_frame_id) = room::get_frame_id(room_id, None) else { return Ok((JoinedRoom::default(), None)); }; let since_frame_id = crate::event::get_last_frame_id(room_id, since_tk.map(|t| t.event_sn())).ok(); let timeline = load_timeline( sender_id, room_id, since_tk, Some(next_batch), Some(&filter.room.timeline), )?; let since_tk = if let Some(since_tk) = since_tk { since_tk } else { BatchToken::new_live(crate::room::user::join_sn(sender_id, room_id).unwrap_or_default()) }; let send_notification_counts = !timeline.events.is_empty() || room::user::last_read_notification(sender_id, room_id)? >= since_tk.event_sn(); let mut timeline_users = HashSet::new(); let mut timeline_pdu_ids = HashSet::new(); for (_, event) in &timeline.events { timeline_users.insert(event.sender.as_str().to_owned()); timeline_pdu_ids.insert(event.event_id.clone()); } room::lazy_loading::lazy_load_confirm_delivery( sender_id, device_id, room_id, since_tk.event_sn(), )?; let (heroes, joined_member_count, invited_member_count, joined_since_last_sync, state_events) = if timeline.events.is_empty() && (since_frame_id == Some(current_frame_id) || since_frame_id.is_none()) { // No state changes (Vec::new(), None, None, false, Vec::new()) } else { // Calculates joined_member_count, invited_member_count and heroes let calculate_counts = || { let joined_member_count = room::joined_member_count(room_id).unwrap_or(0); let invited_member_count = room::invited_member_count(room_id).unwrap_or(0); // Recalculate heroes (first 5 members) let mut heroes = Vec::new(); if joined_member_count + invited_member_count <= 5 { // Go through all PDUs and for each member event, check if the user is still joined or // invited until we have 5 or we reach the end for hero in timeline::stream::load_all_pdus(Some(sender_id), room_id, until_tk)? .into_iter() // Ignore all broken pdus .filter(|(_, pdu)| pdu.event_ty == TimelineEventType::RoomMember) .map(|(_, pdu)| { let content = pdu.get_content::<RoomMemberEventContent>()?; if let Some(state_key) = &pdu.state_key { let user_id = UserId::parse(state_key.clone()).map_err(|_| { AppError::public("invalid UserId in member PDU.") })?; // The membership was and still is invite or join if matches!( content.membership, MembershipState::Join | MembershipState::Invite ) && (room::user::is_joined(&user_id, room_id)? || room::user::is_invited(&user_id, room_id)?) { Ok::<_, AppError>(Some(state_key.clone())) } else { Ok(None) } } else { Ok(None) } }) // Filter out buggy users .filter_map(|u| u.ok()) // Filter for possible heroes .flatten() { if heroes.contains(&hero) || hero == sender_id.as_str() { continue; } heroes.push(hero); } } Ok::<_, AppError>(( Some(joined_member_count), Some(invited_member_count), heroes, )) }; let joined_since_last_sync = room::user::join_sn(sender_id, room_id)? >= since_tk.event_sn(); if since_tk.event_sn() == 0 || joined_since_last_sync { // Probably since = 0, we will do an initial sync let (joined_member_count, invited_member_count, heroes) = calculate_counts()?; let current_state_ids = state::get_full_state_ids(since_frame_id.unwrap_or(current_frame_id))?; let mut state_events = Vec::new(); let mut lazy_loaded = HashSet::new(); for (state_key_id, event_id) in current_state_ids { if let Some(state_limit) = filter.room.state.limit && state_events.len() >= state_limit { break; } let DbRoomStateField { event_ty, state_key, .. } = state::get_field(state_key_id)?; // skip room name type is just for pass TestSyncOmitsStateChangeOnFilteredEvents test if timeline_pdu_ids.contains(&event_id) && event_ty != StateEventType::RoomName { continue; } if event_ty != StateEventType::RoomMember { let Ok(pdu) = timeline::get_pdu(&event_id) else { warn!( "pdu in state not found: {} event_type: {}", event_id, event_ty ); continue; }; if pdu.can_pass_filter(&filter.room.state) { state_events.push(pdu); } } else if !lazy_load_enabled || full_state || timeline_users.contains(&state_key) // TODO: Delete the following line when this is resolved: https://github.com/vector-im/element-web/issues/22565 || *sender_id == state_key { let Ok(pdu) = timeline::get_pdu(&event_id) else { warn!( "pdu in state not found: {} state_key: {}", event_id, state_key ); continue; }; // This check is in case a bad user ID made it into the database if let Ok(uid) = UserId::parse(&state_key) { lazy_loaded.insert(uid); } if pdu.can_pass_filter(&filter.room.state) { state_events.push(pdu); } } } // Reset lazy loading because this is an initial sync room::lazy_loading::lazy_load_reset(sender_id, device_id, room_id)?; // The state_events above should contain all timeline_users, let's mark them as lazy loaded. room::lazy_loading::lazy_load_mark_sent( sender_id, device_id, room_id, lazy_loaded, next_batch.event_sn(), ); // && encrypted_room || new_encrypted_room { // If the user is in a new encrypted room, give them all joined users *joined_users = room::joined_users(room_id, None)?.into_iter().collect(); // .into_iter() // .filter(|user_id| { // // Don't send key updates from the sender to the sender // sender_id != user_id // }) // .collect(); device_list_updates.extend( joined_users.clone().into_iter(), // .filter(|user_id| { // Only send keys if the sender doesn't share an encrypted room with the target already // !share_encrypted_room(sender_id, user_id, &room_id).unwrap_or(false) // }), ); ( heroes, joined_member_count, invited_member_count, true, state_events, ) } else if let Some(since_frame_id) = since_frame_id { // Incremental /sync let mut state_events = Vec::new(); let mut lazy_loaded = HashSet::new(); if since_frame_id != current_frame_id { let current_state_ids = state::get_full_state_ids(current_frame_id)?; let since_state_ids = state::get_full_state_ids(since_frame_id)?; for (key, id) in current_state_ids { if let Some(state_limit) = filter.room.state.limit && state_events.len() >= state_limit { break; } if full_state || since_state_ids.get(&key) != Some(&id) { let pdu = match timeline::get_pdu(&id) { Ok(pdu) => pdu, Err(_) => { warn!("pdu in state not found: {}", id); continue; } }; if pdu.event_ty == TimelineEventType::RoomMember { match UserId::parse( pdu.state_key .as_ref() .expect("state event has state key") .clone(), ) { Ok(state_key_user_id) => { lazy_loaded.insert(state_key_user_id); } Err(e) => error!("invalid state key for member event: {}", e), } } if pdu.can_pass_filter(&filter.room.state) { state_events.push(pdu); } } } } for (_, event) in &timeline.events { if let Some(state_limit) = filter.room.state.limit && state_events.len() >= state_limit { break; } if lazy_loaded.contains(&event.sender) { continue; } if (!room::lazy_loading::lazy_load_was_sent_before( sender_id, device_id, room_id, &event.sender, )? || lazy_load_send_redundant) && let Ok(member_event) = room::get_state( room_id, &StateEventType::RoomMember, event.sender.as_str(), None, ) { lazy_loaded.insert(event.sender.clone()); if member_event.can_pass_filter(&filter.room.state) { state_events.push(member_event); } } } room::lazy_loading::lazy_load_mark_sent( sender_id, device_id, room_id, lazy_loaded, next_batch.event_sn(), ); let encrypted_room = state::get_state(current_frame_id, &StateEventType::RoomEncryption, "").is_ok(); let since_encryption = state::get_state(since_frame_id, &StateEventType::RoomEncryption, "").ok(); // Calculations: let _new_encrypted_room = encrypted_room && since_encryption.is_none(); let send_member_count = state_events .iter() .any(|event| event.event_ty == TimelineEventType::RoomMember); // if encrypted_room { for state_event in &state_events { if state_event.event_ty != TimelineEventType::RoomMember { continue; } if let Some(state_key) = &state_event.state_key { let user_id = UserId::parse(state_key.clone()) .map_err(|_| AppError::public("invalid UserId in member pdu"))?; if user_id == sender_id { continue; } let new_membership = state_event .get_content::<RoomMemberEventContent>() .map_err(|_| AppError::public("invalid pdu in database"))? .membership; match new_membership { MembershipState::Join => { // A new user joined an encrypted room // if !share_encrypted_room(sender_id, &user_id, &room_id)? { if since_tk.event_sn() <= state_event.event_sn && !room::user::shared_rooms(vec![ sender_id.to_owned(), user_id.to_owned(), ])? .is_empty() { // if user_id.is_local() { // check for test TestDeviceListsUpdateOverFederation // device_list_updates.insert(user_id.clone()); // } joined_users.insert(user_id); } } MembershipState::Leave => { // Write down users that have left encrypted rooms we are in left_users.insert(user_id); } _ => {} } } } // } if joined_since_last_sync { // && encrypted_room || new_encrypted_room { // If the user is in a new encrypted room, give them all joined users device_list_updates.extend( room::joined_users(room_id, None)? .into_iter() .filter(|user_id| { // Don't send key updates from the sender to the sender sender_id != user_id }), // .filter(|user_id| { // Only send keys if the sender doesn't share an encrypted room with the target already // !share_encrypted_room(sender_id, user_id, &room_id).unwrap_or(false) // }), ); } let (joined_member_count, invited_member_count, heroes) = if send_member_count { calculate_counts()? } else { (None, None, Vec::new()) }; ( heroes, joined_member_count, invited_member_count, joined_since_last_sync, state_events, ) } else { (Vec::new(), None, None, false, Vec::new()) } }; // Look for device list updates in this room device_list_updates.extend(room::keys_changed_users( room_id, since_tk.event_sn(), None, )?); let mut limited = timeline.limited || joined_since_last_sync; if let Some((_, first_event)) = timeline.events.first() && first_event.event_ty == TimelineEventType::RoomCreate { limited = false; } let mut edus: Vec<RawJson<AnySyncEphemeralRoomEvent>> = Vec::new(); for (_, content) in data::room::receipt::read_receipts(room_id, since_tk.event_sn())? { let receipt = SyncReceiptEvent { content }; edus.push(RawJson::new(&receipt)?.cast()); } if room::typing::last_typing_update(room_id).await? >= since_tk.event_sn() { edus.push( serde_json::from_str(&serde_json::to_string( &room::typing::all_typings(room_id).await?, )?) .expect("event is valid, we just created it"), ); } let account_events = data::user::data_changes(Some(room_id), sender_id, since_tk.event_sn(), None)? .into_iter() .filter_map(|e| extract_variant!(e, AnyRawAccountDataEvent::Room)) .collect(); let notify_summary = room::user::notify_summary(sender_id, room_id)?; let mut notification_count = None; let mut highlight_count = None; let mut unread_count = None; if send_notification_counts { if filter.room.timeline.unread_thread_notifications { notification_count = Some(notify_summary.notification_count); highlight_count = Some(notify_summary.highlight_count); } else { notification_count = Some(notify_summary.all_notification_count()); highlight_count = Some(notify_summary.all_highlight_count()); } unread_count = Some(notify_summary.all_unread_count()) } let joined_room = JoinedRoom { account_data: RoomAccountData { events: account_events, }, summary: RoomSummary { heroes, joined_member_count: joined_member_count.map(|n| (n as u32).into()), invited_member_count: invited_member_count.map(|n| (n as u32).into()), }, unread_notifications: UnreadNotificationsCount { highlight_count, notification_count, }, timeline: Timeline { limited, prev_batch: timeline.prev_batch.map(|sn| sn.to_string()), events: timeline .events .iter() .map(|(_, pdu)| pdu.to_sync_room_event()) .collect(), }, state: State::Before( state_events .iter() .map(|pdu| pdu.to_sync_state_event()) .collect::<Vec<_>>() .into(), ), ephemeral: Ephemeral { events: edus }, unread_thread_notifications: if filter.room.timeline.unread_thread_notifications { notify_summary .threads .iter() .map(|(thread_id, summary)| { ( thread_id.to_owned(), UnreadNotificationsCount { notification_count: Some(summary.notification_count), highlight_count: Some(summary.highlight_count), }, ) })
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
true
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/global.rs
crates/server/src/global.rs
use std::collections::{BTreeMap, HashMap, HashSet}; use std::future::Future; use std::net::IpAddr; use std::sync::atomic::AtomicBool; use std::sync::{Arc, LazyLock, OnceLock, RwLock}; use std::time::Instant; use diesel::prelude::*; use hickory_resolver::Resolver as HickoryResolver; use hickory_resolver::config::*; use hickory_resolver::name_server::TokioConnectionProvider; use salvo::oapi::ToSchema; use serde::Serialize; use tokio::sync::{Semaphore, broadcast}; use crate::core::appservice::Registration; use crate::core::federation::discovery::{OldVerifyKey, ServerSigningKeys}; use crate::core::identifiers::*; use crate::core::serde::{Base64, JsonValue}; use crate::core::{Seqnum, UnixMillis}; use crate::data::misc::DbServerSigningKeys; use crate::data::schema::*; use crate::data::user::{NewDbUser, NewDbUserDevice}; use crate::data::{connect, diesel_exists}; use crate::utils::{MutexMap, MutexMapGuard, SeqnumQueue, SeqnumQueueFuture, SeqnumQueueGuard}; use crate::{AppResult, SigningKeys}; pub const MXC_LENGTH: usize = 32; pub const DEVICE_ID_LENGTH: usize = 10; pub const TOKEN_LENGTH: usize = 32; pub const SESSION_ID_LENGTH: usize = 32; pub const AUTO_GEN_PASSWORD_LENGTH: usize = 15; pub const RANDOM_USER_ID_LENGTH: usize = 10; pub type TlsNameMap = HashMap<String, (Vec<IpAddr>, u16)>; type RateLimitState = (Instant, u32); // Time if last failed try, number of failed tries pub type RoomMutexMap = MutexMap<OwnedRoomId, ()>; pub type RoomMutexGuard = MutexMapGuard<OwnedRoomId, ()>; pub type LazyRwLock<T> = LazyLock<RwLock<T>>; pub static TLS_NAME_OVERRIDE: LazyRwLock<TlsNameMap> = LazyLock::new(Default::default); pub static BAD_EVENT_RATE_LIMITER: LazyRwLock<HashMap<OwnedEventId, RateLimitState>> = LazyLock::new(Default::default); pub static BAD_SIGNATURE_RATE_LIMITER: LazyRwLock<HashMap<Vec<String>, RateLimitState>> = LazyLock::new(Default::default); pub static BAD_QUERY_RATE_LIMITER: LazyRwLock<HashMap<OwnedServerName, RateLimitState>> = LazyLock::new(Default::default); pub static SERVER_NAME_RATE_LIMITER: LazyRwLock<HashMap<OwnedServerName, Arc<Semaphore>>> = LazyLock::new(Default::default); pub static ROOM_ID_FEDERATION_HANDLE_TIME: LazyRwLock< HashMap<OwnedRoomId, (OwnedEventId, Instant)>, > = LazyLock::new(Default::default); pub static APPSERVICE_IN_ROOM_CACHE: LazyRwLock<HashMap<OwnedRoomId, HashMap<String, bool>>> = LazyRwLock::new(Default::default); pub static ROTATE: LazyLock<RotationHandler> = LazyLock::new(Default::default); pub static SHUTDOWN: AtomicBool = AtomicBool::new(false); pub static SEQNUM_QUEUE: LazyLock<SeqnumQueue> = LazyLock::new(Default::default); /// Handles "rotation" of long-polling requests. "Rotation" in this context is similar to "rotation" of log files and the like. /// /// This is utilized to have sync workers return early and release read locks on the database. pub struct RotationHandler(broadcast::Sender<()>, broadcast::Receiver<()>); #[derive(Serialize, ToSchema, Clone, Copy, Debug)] pub struct EmptyObject {} impl RotationHandler { pub fn new() -> Self { let (s, r) = broadcast::channel(1); Self(s, r) } pub fn watch(&self) -> impl Future<Output = ()> { let mut r = self.0.subscribe(); async move { let _ = r.recv().await; } } pub fn fire(&self) { let _ = self.0.send(()); } } impl Default for RotationHandler { fn default() -> Self { Self::new() } } pub fn queue_seqnum(sn: Seqnum) -> SeqnumQueueGuard { SEQNUM_QUEUE.push(sn) } pub fn seqnum_reach(sn: Seqnum) -> SeqnumQueueFuture { SEQNUM_QUEUE.reach(sn) } pub fn dns_resolver() -> &'static HickoryResolver<TokioConnectionProvider> { static DNS_RESOLVER: OnceLock<HickoryResolver<TokioConnectionProvider>> = OnceLock::new(); DNS_RESOLVER.get_or_init(|| { HickoryResolver::builder_with_config( ResolverConfig::default(), TokioConnectionProvider::default(), ) .build() }) } pub fn appservices() -> &'static Vec<Registration> { use figment::{ Figment, providers::{Format, Toml, Yaml}, }; static APPSERVICES: OnceLock<Vec<Registration>> = OnceLock::new(); APPSERVICES.get_or_init(|| { let mut appservices = vec![]; let Some(registration_dir) = crate::config::appservice_registration_dir() else { return appservices; }; tracing::info!("Appservice registration dir: {}", registration_dir); let mut exist_ids = HashSet::new(); let Ok(entries) = std::fs::read_dir(registration_dir) else { return appservices; }; for entry in entries { let Ok(entry) = entry else { continue; }; let path = entry.path(); if path.is_dir() { continue; } let Some(ext) = path.extension() else { continue; }; let registration = match ext.to_str() { Some("yaml") | Some("yml") => match Figment::new() .merge(Yaml::file(&path)) .extract::<Registration>() { Ok(registration) => registration, Err(e) => { tracing::error!( "It looks like your config `{}` is invalid. Error occurred: {e}", path.display() ); continue; } }, Some("toml") => match Figment::new() .merge(Toml::file(&path)) .extract::<Registration>() { Ok(registration) => registration, Err(e) => { tracing::error!( "It looks like your config `{}` is invalid. Error occurred: {e}", path.display() ); continue; } }, _ => { continue; } }; if exist_ids.contains(&registration.id) { tracing::error!("Duplicate appservice registration id: {}", registration.id); continue; } exist_ids.insert(registration.id.clone()); appservices.push(registration.clone()); let user_id = OwnedUserId::try_from(format!( "@{}:{}", registration.sender_localpart, crate::config::get().server_name )) .unwrap(); let mut conn = connect().expect("db connect failed"); if !diesel_exists!(users::table.filter(users::id.eq(&user_id)), &mut conn) .expect("db query failed") { diesel::insert_into(users::table) .values(NewDbUser { id: user_id.to_owned(), ty: None, is_admin: false, is_guest: false, is_local: true, localpart: user_id.localpart().to_owned(), server_name: user_id.server_name().to_owned(), appservice_id: Some(registration.id.clone()), created_at: UnixMillis::now(), }) .execute(&mut conn) .expect("db query failed"); } if !diesel_exists!( user_devices::table.filter(user_devices::user_id.eq(&user_id)), &mut conn ) .expect("db query failed") { diesel::insert_into(user_devices::table) .values(NewDbUserDevice { user_id, device_id: OwnedDeviceId::from("_"), display_name: Some("[Default]".to_string()), user_agent: None, is_hidden: true, last_seen_ip: None, last_seen_at: None, created_at: UnixMillis::now(), }) .execute(&mut conn) .expect("db query failed"); } } appservices }) } pub fn add_signing_key_from_trusted_server( from_server: &ServerName, new_keys: ServerSigningKeys, ) -> AppResult<SigningKeys> { let key_data = server_signing_keys::table .filter(server_signing_keys::server_id.eq(from_server)) .select(server_signing_keys::key_data) .first::<JsonValue>(&mut connect()?) .optional()?; let prev_keys: Option<ServerSigningKeys> = key_data.map(serde_json::from_value).transpose()?; if let Some(mut prev_keys) = prev_keys { let ServerSigningKeys { verify_keys, old_verify_keys, .. } = new_keys; prev_keys.verify_keys.extend(verify_keys); prev_keys.old_verify_keys.extend(old_verify_keys); prev_keys.valid_until_ts = new_keys.valid_until_ts; diesel::insert_into(server_signing_keys::table) .values(DbServerSigningKeys { server_id: from_server.to_owned(), key_data: serde_json::to_value(&prev_keys)?, updated_at: UnixMillis::now(), created_at: UnixMillis::now(), }) .on_conflict(server_signing_keys::server_id) .do_update() .set(( server_signing_keys::key_data.eq(serde_json::to_value(&prev_keys)?), server_signing_keys::updated_at.eq(UnixMillis::now()), )) .execute(&mut connect()?)?; Ok(prev_keys.into()) } else { diesel::insert_into(server_signing_keys::table) .values(DbServerSigningKeys { server_id: from_server.to_owned(), key_data: serde_json::to_value(&new_keys)?, updated_at: UnixMillis::now(), created_at: UnixMillis::now(), }) .on_conflict(server_signing_keys::server_id) .do_update() .set(( server_signing_keys::key_data.eq(serde_json::to_value(&new_keys)?), server_signing_keys::updated_at.eq(UnixMillis::now()), )) .execute(&mut connect()?)?; Ok(new_keys.into()) } } pub fn add_signing_key_from_origin( origin: &ServerName, new_keys: ServerSigningKeys, ) -> AppResult<SigningKeys> { let key_data = server_signing_keys::table .filter(server_signing_keys::server_id.eq(origin)) .select(server_signing_keys::key_data) .first::<JsonValue>(&mut connect()?) .optional()?; let prev_keys: Option<ServerSigningKeys> = key_data.map(serde_json::from_value).transpose()?; if let Some(mut prev_keys) = prev_keys { let ServerSigningKeys { verify_keys, old_verify_keys, .. } = new_keys; // Moving `verify_keys` no longer present to `old_verify_keys` for (key_id, key) in prev_keys.verify_keys { if !verify_keys.contains_key(&key_id) { prev_keys .old_verify_keys .insert(key_id, OldVerifyKey::new(prev_keys.valid_until_ts, key.key)); } } prev_keys.verify_keys = verify_keys; prev_keys.old_verify_keys.extend(old_verify_keys); prev_keys.valid_until_ts = new_keys.valid_until_ts; diesel::insert_into(server_signing_keys::table) .values(DbServerSigningKeys { server_id: origin.to_owned(), key_data: serde_json::to_value(&prev_keys)?, updated_at: UnixMillis::now(), created_at: UnixMillis::now(), }) .on_conflict(server_signing_keys::server_id) .do_update() .set(( server_signing_keys::key_data.eq(serde_json::to_value(&prev_keys)?), server_signing_keys::updated_at.eq(UnixMillis::now()), )) .execute(&mut connect()?)?; Ok(prev_keys.into()) } else { diesel::insert_into(server_signing_keys::table) .values(DbServerSigningKeys { server_id: origin.to_owned(), key_data: serde_json::to_value(&new_keys)?, updated_at: UnixMillis::now(), created_at: UnixMillis::now(), }) .on_conflict(server_signing_keys::server_id) .do_update() .set(( server_signing_keys::key_data.eq(serde_json::to_value(&new_keys)?), server_signing_keys::updated_at.eq(UnixMillis::now()), )) .execute(&mut connect()?)?; Ok(new_keys.into()) } } // /// This returns an empty `Ok(None)` when there are no keys found for the server. // pub fn signing_keys_for(origin: &ServerName) -> AppResult<Option<SigningKeys>> { // let key_data = server_signing_keys::table // .filter(server_signing_keys::server_id.eq(origin)) // .select(server_signing_keys::key_data) // .first::<JsonValue>(&mut connect()?) // .optional()?; // if let Some(key_data) = key_data { // Ok(serde_json::from_value(key_data).map(Option::Some)?) // } else { // Ok(None) // } // } /// Filters the key map of multiple servers down to keys that should be accepted given the expiry time, /// room version, and timestamp of the paramters pub fn filter_keys_server_map( keys: BTreeMap<String, SigningKeys>, timestamp: UnixMillis, room_version: &RoomVersionId, ) -> BTreeMap<String, BTreeMap<String, Base64>> { keys.into_iter() .filter_map(|(server, keys)| { filter_keys_single_server(keys, timestamp, room_version).map(|keys| (server, keys)) }) .collect() } /// Filters the keys of a single server down to keys that should be accepted given the expiry time, /// room version, and timestamp of the paramters pub fn filter_keys_single_server( keys: SigningKeys, timestamp: UnixMillis, room_version: &RoomVersionId, ) -> Option<BTreeMap<String, Base64>> { if keys.valid_until_ts > timestamp // valid_until_ts MUST be ignored in room versions 1, 2, 3, and 4. // https://spec.matrix.org/v1.10/server-server-api/#get_matrixkeyv2server || matches!(room_version, RoomVersionId::V1 | RoomVersionId::V2 | RoomVersionId::V4 | RoomVersionId::V3) { // Given that either the room version allows stale keys, or the valid_until_ts is // in the future, all verify_keys are valid let mut map: BTreeMap<_, _> = keys .verify_keys .into_iter() .map(|(id, key)| (id, key.key)) .collect(); map.extend(keys.old_verify_keys.into_iter().filter_map(|(id, key)| { // Even on old room versions, we don't allow old keys if they are expired if key.expired_ts > timestamp { Some((id, key.key)) } else { None } })); Some(map) } else { None } } pub fn shutdown() { SHUTDOWN.store(true, std::sync::atomic::Ordering::Relaxed); // On shutdown info!(target: "shutdown-sync", "received shutdown notification, notifying sync helpers..."); ROTATE.fire(); } pub fn get_servers_from_users(users: &[OwnedUserId]) -> Vec<OwnedServerName> { let mut servers = HashSet::new(); for user in users { let server_name = user.server_name().to_owned(); servers.insert(server_name); } servers.into_iter().collect() } pub fn palpo_user(server_name: &ServerName) -> OwnedUserId { UserId::parse_with_server_name("palpo", server_name).expect("@palpo:server_name is valid") }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/sending.rs
crates/server/src/sending.rs
use std::fmt::Debug; use std::sync::{Arc, OnceLock, RwLock}; use std::time::{Duration, Instant}; use base64::{Engine as _, engine::general_purpose}; use diesel::prelude::*; use reqwest_middleware::{ClientBuilder, ClientWithMiddleware}; use reqwest_retry::{RetryTransientMiddleware, policies::ExponentialBackoff}; use serde::Deserialize; use serde_json::value::to_raw_value; use tokio::sync::{Mutex, Semaphore, mpsc}; use crate::core::appservice::Registration; use crate::core::appservice::event::{PushEventsReqBody, push_events_request}; use crate::core::events::GlobalAccountDataEventType; use crate::core::events::push_rules::PushRulesEventContent; use crate::core::federation::transaction::{ Edu, SendMessageReqBody, SendMessageResBody, send_message_request, }; use crate::core::identifiers::*; pub use crate::core::sending::*; use crate::core::serde::{CanonicalJsonObject, RawJsonValue}; use crate::core::{UnixMillis, push}; use crate::data::connect; use crate::data::schema::*; use crate::data::sending::{DbOutgoingRequest, NewDbOutgoingRequest}; use crate::room::timeline; use crate::{AppError, AppResult, GetUrlOrigin, ServerConfig, TlsNameMap, config, data, utils}; mod dest; pub use dest::*; pub mod guard; pub mod resolver; const SELECT_PRESENCE_LIMIT: usize = 256; const SELECT_RECEIPT_LIMIT: usize = 256; const SELECT_EDU_LIMIT: usize = EDU_LIMIT - 2; const DEQUEUE_LIMIT: usize = 48; const EDU_BUF_CAP: usize = 128; const EDU_VEC_CAP: usize = 1; pub type EduBuf = Vec<u8>; pub type EduVec = Vec<EduBuf>; pub const PDU_LIMIT: usize = 50; pub const EDU_LIMIT: usize = 100; // pub(super) type OutgoingItem = (Key, SendingEvent, Destination); // pub(super) type SendingItem = (Key, SendingEvent); // pub(super) type QueueItem = (Key, SendingEvent); // pub(super) type Key = Vec<u8>; pub static MPSC_SENDER: OnceLock<mpsc::UnboundedSender<(OutgoingKind, SendingEventType, i64)>> = OnceLock::new(); pub static MPSC_RECEIVER: OnceLock< Mutex<mpsc::UnboundedReceiver<(OutgoingKind, SendingEventType, i64)>>, > = OnceLock::new(); pub fn sender() -> mpsc::UnboundedSender<(OutgoingKind, SendingEventType, i64)> { MPSC_SENDER.get().expect("sender should set").clone() } #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum OutgoingKind { Appservice(String), Push(OwnedUserId, String), // user and pushkey Normal(OwnedServerName), } impl OutgoingKind { pub fn name(&self) -> &'static str { match self { OutgoingKind::Appservice(_) => "appservice", OutgoingKind::Push(_, _) => "push", OutgoingKind::Normal(_) => "normal", } } } #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum SendingEventType { Pdu(OwnedEventId), // pduid Edu(EduBuf), // pdu json Flush, // none } /// The state for a given state hash. pub fn max_request() -> Arc<Semaphore> { static MAX_REQUESTS: OnceLock<Arc<Semaphore>> = OnceLock::new(); MAX_REQUESTS .get_or_init(|| { Arc::new(Semaphore::new( crate::config::get().max_concurrent_requests as usize, )) }) .clone() } enum TransactionStatus { Running, Failed(u32, Instant), // number of times failed, time of last failure Retrying(u32), // number of times failed } /// Returns a reqwest client which can be used to send requests pub fn default_client() -> reqwest::Client { // Client is cheap to clone (Arc wrapper) and avoids lifetime issues static DEFAULT_CLIENT: OnceLock<reqwest::Client> = OnceLock::new(); DEFAULT_CLIENT .get_or_init(|| { reqwest_client_builder(crate::config::get()) .expect("failed to build request clinet") .build() .expect("failed to build request clinet") }) .clone() } /// Returns a client used for resolving .well-knowns pub fn federation_client() -> ClientWithMiddleware { static FEDERATION_CLIENT: OnceLock<ClientWithMiddleware> = OnceLock::new(); FEDERATION_CLIENT .get_or_init(|| { let conf = crate::config::get(); // Client is cheap to clone (Arc wrapper) and avoids lifetime issues let tls_name_override = Arc::new(RwLock::new(TlsNameMap::new())); // let jwt_decoding_key = conf // .jwt_secret // .as_ref() // .map(|secret| jsonwebtoken::DecodingKey::from_secret(secret.as_bytes())); let retry_policy = ExponentialBackoff::builder() .retry_bounds( Duration::from_secs(5), Duration::from_millis(conf.http_client.federation_timeout), ) .build_with_max_retries(conf.http_client.federation_retries); let client = reqwest_client_builder(conf) .expect("build reqwest client failed") // .dns_resolver(Arc::new(Resolver::new(tls_name_override.clone()))) .timeout(Duration::from_secs(2 * 60)) .build() .expect("build reqwest client failed"); ClientBuilder::new(client) .with(RetryTransientMiddleware::new_with_policy(retry_policy)) .build() }) .clone() } #[tracing::instrument(skip(pdu_id, user, pushkey))] pub fn send_push_pdu(pdu_id: &EventId, user: &UserId, pushkey: String) -> AppResult<()> { let outgoing_kind = OutgoingKind::Push(user.to_owned(), pushkey); let event = SendingEventType::Pdu(pdu_id.to_owned()); let keys = queue_requests(&[(&outgoing_kind, event.clone())])?; sender() .send((outgoing_kind, event, keys.into_iter().next().unwrap())) .unwrap(); Ok(()) } #[tracing::instrument(level = "debug")] pub fn send_pdu_room( room_id: &RoomId, pdu_id: &EventId, extra_servers: &[OwnedServerName], ignore_servers: &[OwnedServerName], ) -> AppResult<()> { let servers = room_joined_servers::table .filter(room_joined_servers::room_id.eq(room_id)) .filter(room_joined_servers::server_id.ne(&config::get().server_name)) // .filter(room_joined_servers::server_id.ne_all(skip_servers)) .select(room_joined_servers::server_id) .load::<OwnedServerName>(&mut connect()?)?; let mut servers = servers .into_iter() .chain(extra_servers.iter().cloned()) .collect::<Vec<_>>(); servers.sort_unstable(); servers.dedup(); let servers = servers.into_iter().filter(|s| !ignore_servers.contains(s)); send_pdu_servers(servers, pdu_id) } #[tracing::instrument(skip(servers, pdu_id), level = "debug")] pub fn send_pdu_servers<S: Iterator<Item = OwnedServerName>>( servers: S, pdu_id: &EventId, ) -> AppResult<()> { let requests = servers .into_iter() .filter_map(|server| { if server == config::get().server_name { warn!("not sending pdu to ourself: {server}"); None } else { Some(( OutgoingKind::Normal(server), SendingEventType::Pdu(pdu_id.to_owned()), )) } }) .collect::<Vec<_>>(); let keys = queue_requests( &requests .iter() .map(|(o, e)| (o, e.clone())) .collect::<Vec<_>>(), )?; for ((outgoing_kind, event_type), key) in requests.into_iter().zip(keys) { if let Err(e) = sender().send((outgoing_kind.to_owned(), event_type, key)) { error!("failed to send pdu: {}", e); } } Ok(()) } #[tracing::instrument(skip(room_id, edu), level = "debug")] pub fn send_edu_room(room_id: &RoomId, edu: &Edu) -> AppResult<()> { let servers = room_joined_servers::table .filter(room_joined_servers::room_id.eq(room_id)) .filter(room_joined_servers::server_id.ne(&config::get().server_name)) .select(room_joined_servers::server_id) .load::<OwnedServerName>(&mut connect()?)?; send_edu_servers(servers.into_iter(), edu) } #[tracing::instrument(skip(servers, edu), level = "debug")] pub fn send_edu_servers<S: Iterator<Item = OwnedServerName>>( servers: S, edu: &Edu, ) -> AppResult<()> { let mut serialized = EduBuf::new(); serde_json::to_writer(&mut serialized, &edu).expect("serialized edu"); let requests = servers .into_iter() .map(|server| { ( OutgoingKind::Normal(server), SendingEventType::Edu(serialized.to_owned()), ) }) .collect::<Vec<_>>(); let keys = queue_requests( &requests .iter() .map(|(o, e)| (o, e.clone())) .collect::<Vec<_>>(), )?; for ((outgoing_kind, event), key) in requests.into_iter().zip(keys) { sender() .send((outgoing_kind.to_owned(), event, key)) .map_err(|e| AppError::internal(e.to_string()))?; } Ok(()) } #[tracing::instrument(skip(server, edu), level = "debug")] pub fn send_edu_server(server: &ServerName, edu: &Edu) -> AppResult<()> { let mut serialized = EduBuf::new(); serde_json::to_writer(&mut serialized, &edu).expect("serialized edu"); let outgoing_kind = OutgoingKind::Normal(server.to_owned()); let event = SendingEventType::Edu(serialized.to_owned()); let key = queue_request(&outgoing_kind, &event)?; sender() .send((outgoing_kind, event, key)) .map_err(|e| AppError::internal(e.to_string()))?; Ok(()) } #[tracing::instrument(skip(server, edu))] pub fn send_reliable_edu(server: &ServerName, edu: &Edu, id: &str) -> AppResult<()> { let mut serialized = EduBuf::new(); serde_json::to_writer(&mut serialized, &edu).expect("serialized edu"); let outgoing_kind = OutgoingKind::Normal(server.to_owned()); let event = SendingEventType::Edu(serialized); let keys = queue_requests(&[(&outgoing_kind, event.clone())])?; sender() .send((outgoing_kind, event, keys.into_iter().next().unwrap())) .unwrap(); Ok(()) } #[tracing::instrument] pub fn send_pdu_appservice(appservice_id: String, pdu_id: &EventId) -> AppResult<()> { let outgoing_kind = OutgoingKind::Appservice(appservice_id); let event = SendingEventType::Pdu(pdu_id.to_owned()); let keys = queue_requests(&[(&outgoing_kind, event.clone())])?; sender() .send((outgoing_kind, event, keys.into_iter().next().unwrap())) .unwrap(); Ok(()) } #[tracing::instrument(skip(events, kind))] async fn send_events( kind: OutgoingKind, events: Vec<SendingEventType>, ) -> Result<OutgoingKind, (OutgoingKind, AppError)> { match &kind { OutgoingKind::Appservice(id) => { let mut pdu_jsons = Vec::new(); for event in &events { match event { SendingEventType::Pdu(event_id) => pdu_jsons.push( timeline::get_pdu(event_id) .map_err(|e| (kind.clone(), e))? .to_room_event(), ), SendingEventType::Edu(_) => { // Appservices don't need EDUs (?) } SendingEventType::Flush => {} } } let max_request = crate::sending::max_request(); let permit = max_request.acquire().await; let registration = crate::appservice::get_registration(id) .map_err(|e| (kind.clone(), e))? .ok_or_else(|| { ( kind.clone(), AppError::internal( "[Appservice] Could not load registration from database", ), ) })?; let req_body = PushEventsReqBody { events: pdu_jsons, to_device: vec![] }; let txn_id = &*general_purpose::URL_SAFE_NO_PAD.encode(utils::hash_keys( events.iter().filter_map(|e| match e { SendingEventType::Edu(b) => Some(&**b), SendingEventType::Pdu(b) => Some(b.as_bytes()), SendingEventType::Flush => None, }), )); let request = push_events_request( registration.url.as_deref().unwrap_or_default(), txn_id, req_body, ) .map_err(|e| (kind.clone(), e.into()))? .into_inner(); let response = crate::appservice::send_request(registration, request) .await .map_err(|e| (kind.clone(), e)) .map(|_response| kind.clone()); drop(permit); response } OutgoingKind::Push(user_id, pushkey) => { let mut pdus = Vec::new(); for event in &events { match event { SendingEventType::Pdu(event_id) => { pdus.push(timeline::get_pdu(event_id).map_err(|e| (kind.clone(), e))?); } SendingEventType::Edu(_) => { // Push gateways don't need EDUs (?) } SendingEventType::Flush => {} } } for pdu in pdus { // Redacted events are not notification targets (we don't send push for them) if pdu.unsigned.contains_key("redacted_because") { continue; } let pusher = match data::user::pusher::get_pusher(user_id, pushkey).map_err(|e| { ( OutgoingKind::Push(user_id.clone(), pushkey.clone()), e.into(), ) })? { Some(pusher) => pusher, None => continue, }; let rules_for_user = data::user::get_global_data::<PushRulesEventContent>( user_id, &GlobalAccountDataEventType::PushRules.to_string(), ) .unwrap_or_default() .map(|content: PushRulesEventContent| content.global) .unwrap_or_else(|| push::Ruleset::server_default(user_id)); let notify_summary = crate::room::user::notify_summary(user_id, &pdu.room_id) .map_err(|e| (kind.clone(), e))?; let max_request = crate::sending::max_request(); let permit = max_request.acquire().await; let _response = crate::user::pusher::send_push_notice( user_id, notify_summary.all_unread_count(), &pusher, rules_for_user, &pdu, ) .await .map(|_response| kind.clone()) .map_err(|e| (kind.clone(), e)); drop(permit); } Ok(OutgoingKind::Push(user_id.clone(), pushkey.clone())) } OutgoingKind::Normal(server) => { let mut edu_jsons = Vec::new(); let mut pdu_jsons = Vec::new(); for event in &events { match event { SendingEventType::Pdu(pdu_id) => { // TODO: check room version and remove event_id if needed let raw = crate::sending::convert_to_outgoing_federation_event( timeline::get_pdu_json(pdu_id) .map_err(|e| (OutgoingKind::Normal(server.clone()), e))? .ok_or_else(|| { error!("event not found: {server} {pdu_id:?}"); ( OutgoingKind::Normal(server.clone()), AppError::internal(format!( "event not found: {server} {pdu_id}" )), ) })?, ); pdu_jsons.push(raw); } SendingEventType::Edu(edu) => { if let Ok(raw) = serde_json::from_slice(edu) { edu_jsons.push(raw); } } SendingEventType::Flush => {} // flush only; no new content } } let max_request = crate::sending::max_request(); let permit = max_request.acquire().await; let txn_id = &*general_purpose::URL_SAFE_NO_PAD.encode(utils::hash_keys( events.iter().filter_map(|e| match e { SendingEventType::Edu(b) => Some(&**b), SendingEventType::Pdu(b) => Some(b.as_bytes()), SendingEventType::Flush => None, }), )); let request = send_message_request( &server.origin().await, txn_id, SendMessageReqBody { origin: config::get().server_name.to_owned(), pdus: pdu_jsons, edus: edu_jsons, origin_server_ts: UnixMillis::now(), }, ) .map_err(|e| (kind.clone(), e.into()))? .into_inner(); let response = crate::sending::send_federation_request(server, request, None) .await .map_err(|e| (kind.clone(), e))? .json::<SendMessageResBody>() .await .map(|response| { for pdu in response.pdus { if pdu.1.is_err() { warn!("failed to send to {}: {:?}", server, pdu); } } kind.clone() }) .map_err(|e| (kind, e.into())); drop(permit); response } } } #[tracing::instrument(skip(request))] pub async fn send_federation_request( destination: &ServerName, request: reqwest::Request, timeout_secs: Option<u64>, ) -> AppResult<reqwest::Response> { debug!("waiting for permit"); let max_request = max_request(); let permit = max_request.acquire().await; debug!("Got permit"); let url = request.url().clone(); let response = tokio::time::timeout( Duration::from_secs(timeout_secs.unwrap_or(2 * 60)), crate::federation::send_request(destination, request), ) .await .map_err(|_| { warn!("timeout waiting for server response of {}", url); AppError::public("timeout waiting for server response") })?; drop(permit); response } #[tracing::instrument(skip_all)] pub async fn send_appservice_request<T>( registration: Registration, request: reqwest::Request, ) -> AppResult<T> where T: for<'de> Deserialize<'de> + Debug, { // let permit = acquire_request().await; let response = crate::appservice::send_request(registration, request).await?; // drop(permit); Ok(response.json().await?) } fn active_requests() -> AppResult<Vec<(i64, OutgoingKind, SendingEventType)>> { let outgoing_requests = outgoing_requests::table .filter(outgoing_requests::state.eq("pending")) .load::<DbOutgoingRequest>(&mut connect()?)?; Ok(outgoing_requests .into_iter() .filter_map(|item| { let kind = match item.kind.as_str() { "appservice" => { if let Some(appservice_id) = &item.appservice_id { OutgoingKind::Appservice(appservice_id.clone()) } else { return None; } } "push" => { if let (Some(user_id), Some(pushkey)) = (item.user_id.clone(), item.pushkey.clone()) { OutgoingKind::Push(user_id, pushkey) } else { return None; } } "normal" => { if let Some(server_id) = &item.server_id { OutgoingKind::Normal(server_id.to_owned()) } else { return None; } } _ => return None, }; let event = if let Some(value) = item.edu_json { SendingEventType::Edu(value) } else if let Some(pdu_id) = item.pdu_id { SendingEventType::Pdu(pdu_id) } else { return None; }; Some((item.id, kind, event)) }) .collect()) } fn delete_request(id: i64) -> AppResult<()> { diesel::delete(outgoing_requests::table.find(id)).execute(&mut connect()?)?; Ok(()) } fn delete_all_active_requests_for(outgoing_kind: &OutgoingKind) -> AppResult<()> { diesel::delete( outgoing_requests::table .filter(outgoing_requests::kind.eq(outgoing_kind.name())) .filter(outgoing_requests::state.eq("pending")), ) .execute(&mut connect()?)?; Ok(()) } fn delete_all_requests_for(outgoing_kind: &OutgoingKind) -> AppResult<()> { diesel::delete( outgoing_requests::table.filter(outgoing_requests::kind.eq(outgoing_kind.name())), ) .execute(&mut connect()?)?; Ok(()) } fn queue_requests(requests: &[(&OutgoingKind, SendingEventType)]) -> AppResult<Vec<i64>> { let mut ids = Vec::new(); for (outgoing_kind, event) in requests { ids.push(queue_request(outgoing_kind, event)?); } Ok(ids) } fn queue_request(outgoing_kind: &OutgoingKind, event: &SendingEventType) -> AppResult<i64> { let appservice_id = if let OutgoingKind::Appservice(service_id) = outgoing_kind { Some(service_id.clone()) } else { None }; let (user_id, pushkey) = if let OutgoingKind::Push(user_id, pushkey) = outgoing_kind { (Some(user_id.clone()), Some(pushkey.clone())) } else { (None, None) }; let server_id = if let OutgoingKind::Normal(server_id) = outgoing_kind { Some(server_id.clone()) } else { None }; let (pdu_id, edu_json) = match event { SendingEventType::Pdu(pdu_id) => (Some(pdu_id.to_owned()), None), SendingEventType::Edu(edu_json) => (None, Some(edu_json.clone())), SendingEventType::Flush => (None, None), }; let id = diesel::insert_into(outgoing_requests::table) .values(&NewDbOutgoingRequest { kind: outgoing_kind.name().to_owned(), appservice_id, user_id, pushkey, server_id, pdu_id, edu_json, }) .returning(outgoing_requests::id) .get_result::<i64>(&mut connect()?)?; Ok(id) } fn active_requests_for(outgoing_kind: &OutgoingKind) -> AppResult<Vec<(i64, SendingEventType)>> { let list = outgoing_requests::table .filter(outgoing_requests::kind.eq(outgoing_kind.name())) .load::<DbOutgoingRequest>(&mut connect()?)? .into_iter() .filter_map(|r| { if let Some(value) = r.edu_json { Some((r.id, SendingEventType::Edu(value))) } else if let Some(pdu_id) = r.pdu_id { Some((r.id, SendingEventType::Pdu(pdu_id))) } else { None } }) .collect(); Ok(list) } fn queued_requests(outgoing_kind: &OutgoingKind) -> AppResult<Vec<(i64, SendingEventType)>> { Ok(outgoing_requests::table .filter(outgoing_requests::kind.eq(outgoing_kind.name())) .load::<DbOutgoingRequest>(&mut connect()?)? .into_iter() .filter_map(|r| { if let Some(value) = r.edu_json { Some((r.id, SendingEventType::Edu(value))) } else if let Some(pdu_id) = r.pdu_id { Some((r.id, SendingEventType::Pdu(pdu_id))) } else { None } }) .collect()) } fn mark_as_active(events: &[(i64, SendingEventType)]) -> AppResult<()> { for (id, e) in events { let value = if let SendingEventType::Edu(value) = &e { &**value } else { &[] }; diesel::update(outgoing_requests::table.find(id)) .set(( outgoing_requests::data.eq(value), outgoing_requests::state.eq("pending"), )) .execute(&mut connect()?)?; } Ok(()) } /// This does not return a full `Pdu` it is only to satisfy palpo's types. #[tracing::instrument] pub fn convert_to_outgoing_federation_event( mut pdu_json: CanonicalJsonObject, ) -> Box<RawJsonValue> { if let Some(unsigned) = pdu_json .get_mut("unsigned") .and_then(|val| val.as_object_mut()) { unsigned.remove("transaction_id"); } pdu_json.remove("event_id"); pdu_json.remove("event_sn"); // TODO: another option would be to convert it to a canonical string to validate size // and return a Result<RawJson<...>> // serde_json::from_str::<RawJson<_>>( // crate::core::serde::to_canonical_json_string(pdu_json).expect("CanonicalJson is valid serde_json::Value"), // ) // .expect("RawJson::from_value always works") to_raw_value(&pdu_json).expect("CanonicalJson is valid serde_json::Value") } fn reqwest_client_builder(_config: &ServerConfig) -> AppResult<reqwest::ClientBuilder> { let reqwest_client_builder = reqwest::Client::builder() .pool_max_idle_per_host(0) .connect_timeout(Duration::from_secs(30)) .timeout(Duration::from_secs(60 * 3)); // TODO: add proxy support // if let Some(proxy) = config.to_proxy()? { // reqwest_client_builder = reqwest_client_builder.proxy(proxy); // } Ok(reqwest_client_builder) }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/routing.rs
crates/server/src/routing.rs
mod admin; mod appservice; mod client; mod federation; mod media; use salvo::prelude::*; use salvo::serve_static::StaticDir; use url::Url; use crate::core::MatrixError; use crate::core::client::discovery::{ client::{ClientResBody, HomeServerInfo}, support::{Contact, SupportResBody}, }; use crate::core::federation::directory::ServerResBody; use crate::{AppResult, JsonResult, config, hoops, json_ok}; pub mod prelude { pub use crate::core::MatrixError; pub use crate::core::identifiers::*; pub use crate::core::serde::{JsonValue, RawJson}; pub use crate::{ AppError, AppResult, AuthArgs, DepotExt, EmptyResult, JsonResult, OptionalExtension, config, empty_ok, exts::*, hoops, json_ok, }; pub use salvo::prelude::*; } pub fn root() -> Router { Router::new() .hoop(hoops::ensure_accept) .hoop(hoops::limit_size) .get(home) .push( Router::with_path("_matrix") .push(client::router()) .push(media::router()) .push(federation::router()) .push(federation::key::router()) .push(appservice::router()), ) .push(admin::router()) .push( Router::with_path(".well-known/matrix") .push(Router::with_path("client").get(well_known_client)) .push(Router::with_path("support").get(well_known_support)) .push(Router::with_path("server").get(well_known_server)), ) .push(Router::with_path("{*path}").get(StaticDir::new("./static"))) } #[handler] async fn home(req: &mut Request, res: &mut Response) { if let Some(home_page) = &config::get().home_page { res.send_file(home_page, req.headers()).await; } res.render("Hello Palpo"); } #[handler] pub async fn limit_rate() -> AppResult<()> { Ok(()) } #[endpoint] fn well_known_client() -> JsonResult<ClientResBody> { let conf = config::get(); let client_url = conf.well_known_client(); json_ok(ClientResBody::new(HomeServerInfo { base_url: client_url.clone(), })) } #[endpoint] fn well_known_support() -> JsonResult<SupportResBody> { let conf = config::get(); let support_page = conf .well_known .support_page .as_ref() .map(ToString::to_string); let role = conf.well_known.support_role.clone(); // support page or role must be either defined for this to be valid if support_page.is_none() && role.is_none() { return Err(MatrixError::not_found("Not found.").into()); } let email_address = conf.well_known.support_email.clone(); let matrix_id = conf.well_known.support_mxid.clone(); // if a role is specified, an email address or matrix id is required if role.is_some() && (email_address.is_none() && matrix_id.is_none()) { return Err(MatrixError::not_found("Not found.").into()); } // TODO: support defining multiple contacts in the config let mut contacts: Vec<Contact> = vec![]; if let Some(role) = role { let contact = Contact { role, email_address, matrix_id, }; contacts.push(contact); } // support page or role+contacts must be either defined for this to be valid if contacts.is_empty() && support_page.is_none() { return Err(MatrixError::not_found("Not found.").into()); } json_ok(SupportResBody { contacts, support_page, }) } #[endpoint] fn well_known_server() -> JsonResult<ServerResBody> { json_ok(ServerResBody { server: config::get().well_known_server(), }) }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/signing_keys.rs
crates/server/src/signing_keys.rs
use std::collections::BTreeMap; use std::time::{Duration, SystemTime}; use serde::Deserialize; use crate::config; use crate::core::UnixMillis; use crate::core::federation::discovery::{OldVerifyKey, ServerSigningKeys, VerifyKey}; use crate::core::serde::Base64; /// Similar to ServerSigningKeys, but drops a few unnecessary fields we don't require post-validation #[derive(Deserialize, Debug, Clone)] pub struct SigningKeys { pub verify_keys: BTreeMap<String, VerifyKey>, pub old_verify_keys: BTreeMap<String, OldVerifyKey>, pub valid_until_ts: UnixMillis, } impl SigningKeys { /// Creates the SigningKeys struct, using the keys of the current server pub fn load_own_keys() -> Self { let mut keys = Self { verify_keys: BTreeMap::new(), old_verify_keys: BTreeMap::new(), valid_until_ts: UnixMillis::from_system_time( SystemTime::now() + Duration::from_secs(7 * 86400), ) .expect("Should be valid until year 500,000,000"), }; keys.verify_keys.insert( format!("ed25519:{}", config::keypair().version()), VerifyKey { key: Base64::new(config::keypair().public_key().to_vec()), }, ); keys } } impl From<ServerSigningKeys> for SigningKeys { fn from(value: ServerSigningKeys) -> Self { let ServerSigningKeys { verify_keys, old_verify_keys, valid_until_ts, .. } = value; Self { verify_keys: verify_keys .into_iter() .map(|(id, key)| (id.to_string(), key)) .collect(), old_verify_keys: old_verify_keys .into_iter() .map(|(id, key)| (id.to_string(), key)) .collect(), valid_until_ts, } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/signal.rs
crates/server/src/signal.rs
use std::sync::Arc; use tokio::signal; #[cfg(unix)] #[tracing::instrument(skip_all)] pub(super) async fn signal() { use signal::unix; use unix::SignalKind; const CONSOLE: bool = cfg!(feature = "console"); const RELOADING: bool = cfg!(all(palpo_mods, feature = "palpo_mods", not(CONSOLE))); let mut quit = unix::signal(SignalKind::quit()).expect("SIGQUIT handler"); let mut term = unix::signal(SignalKind::terminate()).expect("SIGTERM handler"); let mut usr1 = unix::signal(SignalKind::user_defined1()).expect("SIGUSR1 handler"); let mut usr2 = unix::signal(SignalKind::user_defined2()).expect("SIGUSR2 handler"); loop { trace!("Installed signal handlers"); let sig: &'static str; tokio::select! { _ = signal::ctrl_c() => { sig = "SIGINT"; }, _ = quit.recv() => { sig = "SIGQUIT"; }, _ = term.recv() => { sig = "SIGTERM"; }, _ = usr1.recv() => { sig = "SIGUSR1"; }, _ = usr2.recv() => { sig = "SIGUSR2"; }, } warn!("Received {sig}"); let result = if RELOADING && sig == "SIGINT" { crate::reload() } else if matches!(sig, "SIGQUIT" | "SIGTERM") || (!CONSOLE && sig == "SIGINT") { crate::shutdown() } else { server.server.signal(sig) }; if let Err(e) = result { debug_error!(?sig, "signal: {e}"); } } } #[cfg(not(unix))] #[tracing::instrument(skip_all)] pub(super) async fn signal(server: Arc<Server>) { loop { tokio::select! { _ = signal::ctrl_c() => { warn!("Received Ctrl+C"); if let Err(e) = server.server.signal.send("SIGINT") { debug_error!("signal channel: {e}"); } }, } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/hoops.rs
crates/server/src/hoops.rs
use salvo::http::{ParseError, ResBody}; use salvo::prelude::*; use salvo::size_limiter; use url::Url; use crate::AppResult; use crate::core::MatrixError; mod auth; pub use auth::*; #[handler] pub async fn ensure_accept(req: &mut Request) { if req.accept().is_empty() { req.headers_mut().insert( "Accept", "application/json".parse().expect("should not fail"), ); } } #[handler] pub async fn limit_size( req: &mut Request, depot: &mut Depot, res: &mut Response, ctrl: &mut FlowCtrl, ) { let mut max_size = 1024 * 1024 * 16; if let Some(ctype) = req.content_type() && ctype.type_() == mime::MULTIPART { max_size = 1024 * 1024 * 1024; } let limiter = size_limiter::max_size(max_size); limiter.handle(req, depot, res, ctrl).await; } #[handler] async fn access_control( req: &mut Request, depot: &mut Depot, res: &mut Response, ctrl: &mut FlowCtrl, ) { let headers = res.headers_mut(); headers.insert("Access-Control-Allow-Origin", "*".parse().unwrap()); headers.insert( "Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,PATCH,OPTIONS".parse().unwrap(), ); headers.insert( "Access-Control-Allow-Headers", "Accept,Content-Type,Authorization,Range".parse().unwrap(), ); headers.insert( "Access-Control-Expose-Headers", "Access-Token,Response-Status,Content-Length,Content-Range" .parse() .unwrap(), ); headers.insert("Access-Control-Allow-Credentials", "true".parse().unwrap()); headers.insert( "Content-Security-Policy", "frame-ancestors 'self'".parse().unwrap(), ); ctrl.call_next(req, depot, res).await; // headers.insert("Cross-Origin-Embedder-Policy", "require-corp".parse().unwrap()); // headers.insert("Cross-Origin-Opener-Policy", "same-origin".parse().unwrap()); } #[handler] pub async fn limit_rate() -> AppResult<()> { Ok(()) } // utf8 will cause complement testing fail. #[handler] pub async fn remove_json_utf8( req: &mut Request, depot: &mut Depot, res: &mut Response, ctrl: &mut FlowCtrl, ) { ctrl.call_next(req, depot, res).await; if let Some(true) = res.headers().get("content-type").map(|h| { let h = h.to_str().unwrap_or_default(); h.contains("application/json") && h.contains(";") }) { res.add_header("content-type", "application/json", true) .expect("should not fail"); } } #[handler] pub async fn default_accept_json( req: &mut Request, depot: &mut Depot, res: &mut Response, ctrl: &mut FlowCtrl, ) { if !req.headers().contains_key("accept") { req.add_header("accept", "application/json", true) .expect("should not fail"); } ctrl.call_next(req, depot, res).await; } #[handler] pub async fn catch_status_error( req: &mut Request, depot: &mut Depot, res: &mut Response, ctrl: &mut FlowCtrl, ) { if let ResBody::Error(e) = &res.body { if let Some(e) = &e.cause { if let Some(e) = e.downcast_ref::<ParseError>() { #[cfg(debug_assertions)] let matrix = MatrixError::bad_json(e.to_string()); #[cfg(not(debug_assertions))] let matrix = MatrixError::bad_json("bad json"); matrix.write(req, depot, res).await; ctrl.skip_rest(); } } else { let matrix = MatrixError::unrecognized(e.brief.clone()); matrix.write(req, depot, res).await; ctrl.skip_rest(); } } else if res.status_code == Some(StatusCode::METHOD_NOT_ALLOWED) { let matrix = MatrixError::unrecognized("method not allowed"); matrix.write(req, depot, res).await; ctrl.skip_rest(); } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/appservice.rs
crates/server/src/appservice.rs
use std::collections::BTreeMap; use std::time::Duration; use diesel::prelude::*; use regex::RegexSet; use serde::{Deserialize, Serialize}; use crate::core::appservice::{Namespace, Registration}; use crate::core::identifiers::*; use crate::core::serde::JsonValue; use crate::data::connect; use crate::data::schema::*; use crate::{AppError, AppResult, sending}; /// Compiled regular expressions for a namespace. #[derive(Clone, Debug)] pub struct NamespaceRegex { pub exclusive: Option<RegexSet>, pub non_exclusive: Option<RegexSet>, } impl NamespaceRegex { /// Checks if this namespace has rights to a namespace pub fn is_match(&self, heystack: &str) -> bool { if self.is_exclusive_match(heystack) { return true; } if let Some(non_exclusive) = &self.non_exclusive && non_exclusive.is_match(heystack) { return true; } false } /// Checks if this namespace has exlusive rights to a namespace pub fn is_exclusive_match(&self, heystack: &str) -> bool { if let Some(exclusive) = &self.exclusive && exclusive.is_match(heystack) { return true; } false } } impl TryFrom<Vec<Namespace>> for NamespaceRegex { fn try_from(value: Vec<Namespace>) -> Result<Self, regex::Error> { let mut exclusive = vec![]; let mut non_exclusive = vec![]; for namespace in value { if namespace.exclusive { exclusive.push(namespace.regex); } else { non_exclusive.push(namespace.regex); } } Ok(NamespaceRegex { exclusive: if exclusive.is_empty() { None } else { Some(RegexSet::new(exclusive)?) }, non_exclusive: if non_exclusive.is_empty() { None } else { Some(RegexSet::new(non_exclusive)?) }, }) } type Error = regex::Error; } /// Appservice registration combined with its compiled regular expressions. #[derive(Clone, Debug)] pub struct RegistrationInfo { pub registration: Registration, pub users: NamespaceRegex, pub aliases: NamespaceRegex, pub rooms: NamespaceRegex, } impl RegistrationInfo { /// Checks if a given user ID matches either the users namespace or the localpart specified in the appservice registration pub fn is_user_match(&self, user_id: &UserId) -> bool { self.users.is_match(user_id.as_str()) || self.registration.sender_localpart == user_id.localpart() } /// Checks if a given user ID exclusively matches either the users namespace or the localpart specified in the appservice registration pub fn is_exclusive_user_match(&self, user_id: &UserId) -> bool { self.users.is_exclusive_match(user_id.as_str()) || self.registration.sender_localpart == user_id.localpart() } } impl AsRef<Registration> for RegistrationInfo { fn as_ref(&self) -> &Registration { &self.registration } } impl TryFrom<Registration> for RegistrationInfo { type Error = regex::Error; fn try_from(value: Registration) -> Result<RegistrationInfo, Self::Error> { Ok(RegistrationInfo { users: value.namespaces.users.clone().try_into()?, aliases: value.namespaces.aliases.clone().try_into()?, rooms: value.namespaces.rooms.clone().try_into()?, registration: value, }) } } impl TryFrom<DbRegistration> for RegistrationInfo { type Error = AppError; fn try_from(value: DbRegistration) -> Result<RegistrationInfo, Self::Error> { let value: Registration = value.try_into()?; Ok(RegistrationInfo { users: value.namespaces.users.clone().try_into()?, aliases: value.namespaces.aliases.clone().try_into()?, rooms: value.namespaces.rooms.clone().try_into()?, registration: value, }) } } #[derive(Identifiable, Queryable, Insertable, Serialize, Deserialize, Clone, Debug)] #[diesel(table_name = appservice_registrations)] pub struct DbRegistration { /// A unique, user - defined ID of the application service which will never change. pub id: String, /// The URL for the application service. /// /// Optionally set to `null` if no traffic is required. pub url: Option<String>, /// A unique token for application services to use to authenticate requests to HomeServers. pub as_token: String, /// A unique token for HomeServers to use to authenticate requests to application services. pub hs_token: String, /// The localpart of the user associated with the application service. pub sender_localpart: String, /// A list of users, aliases and rooms namespaces that the application service controls. pub namespaces: JsonValue, /// Whether requests from masqueraded users are rate-limited. /// /// The sender is excluded. #[serde(skip_serializing_if = "Option::is_none")] pub rate_limited: Option<bool>, /// The external protocols which the application service provides (e.g. IRC). #[serde(skip_serializing_if = "Option::is_none")] pub protocols: Option<JsonValue>, /// Whether the application service wants to receive ephemeral data. /// /// Defaults to `false`. pub receive_ephemeral: bool, /// Whether the application service wants to do device management, as part of MSC4190. /// /// Defaults to `false` #[serde(default, rename = "io.element.msc4190")] pub device_management: bool, } impl From<Registration> for DbRegistration { fn from(value: Registration) -> Self { let Registration { id, url, as_token, hs_token, sender_localpart, namespaces, rate_limited, protocols, receive_ephemeral, device_management, } = value; Self { id, url, as_token, hs_token, sender_localpart, namespaces: serde_json::to_value(namespaces).unwrap_or_default(), rate_limited, protocols: protocols .map(|protocols| serde_json::to_value(protocols).unwrap_or_default()), receive_ephemeral, device_management, } } } impl TryFrom<DbRegistration> for Registration { type Error = serde_json::Error; fn try_from(value: DbRegistration) -> Result<Self, Self::Error> { let DbRegistration { id, url, as_token, hs_token, sender_localpart, namespaces, rate_limited, protocols, receive_ephemeral, device_management, } = value; let protocols = if let Some(protocols) = protocols { serde_json::from_value(protocols)? } else { None }; Ok(Self { id, url, as_token, hs_token, sender_localpart, namespaces: serde_json::from_value(namespaces)?, rate_limited, protocols, receive_ephemeral, device_management, }) } } /// Registers an appservice and returns the ID to the caller pub fn register_appservice(registration: Registration) -> AppResult<String> { let db_registration: DbRegistration = registration.into(); diesel::insert_into(appservice_registrations::table) .values(&db_registration) .execute(&mut connect()?)?; Ok(db_registration.id) } /// Remove an appservice registration /// /// # Arguments /// /// * `service_name` - the name you send to register the service previously pub fn unregister_appservice(id: &str) -> AppResult<()> { diesel::delete(appservice_registrations::table.find(id)).execute(&mut connect()?)?; Ok(()) } pub fn get_registration(id: &str) -> AppResult<Option<Registration>> { if let Some(registration) = appservice_registrations::table .find(id) .first::<DbRegistration>(&mut connect()?) .optional()? { Ok(Some(registration.try_into()?)) } else { Ok(None) } } pub async fn find_from_token(token: &str) -> AppResult<Option<RegistrationInfo>> { Ok(all()? .values() .find(|info| info.registration.as_token == token) .cloned()) } // Checks if a given user id matches any exclusive appservice regex pub fn is_exclusive_user_id(user_id: &UserId) -> AppResult<bool> { for info in all()?.values() { if info.is_exclusive_user_match(user_id) { return Ok(true); } } Ok(false) } // Checks if a given room alias matches any exclusive appservice regex pub async fn is_exclusive_alias(alias: &RoomAliasId) -> AppResult<bool> { for info in all()?.values() { if info.aliases.is_exclusive_match(alias.as_str()) { return Ok(true); } } Ok(false) } // Checks if a given room id matches any exclusive appservice regex pub async fn is_exclusive_room_id(room_id: &RoomId) -> AppResult<bool> { for info in all()?.values() { if info.rooms.is_exclusive_match(room_id.as_str()) { return Ok(true); } } Ok(false) } pub fn all() -> AppResult<BTreeMap<String, RegistrationInfo>> { let registrations = appservice_registrations::table.load::<DbRegistration>(&mut connect()?)?; Ok(registrations .into_iter() .filter_map(|db_registration| { let info: RegistrationInfo = match db_registration.try_into() { Ok(registration) => registration, Err(e) => { warn!("Failed to parse appservice registration: {}", e); return None; } }; Some((info.registration.id.clone(), info)) }) .collect()) } /// Sends a request to an appservice /// /// Only returns None if there is no url specified in the appservice registration file #[tracing::instrument(skip(request))] pub(crate) async fn send_request( registration: Registration, mut request: reqwest::Request, ) -> AppResult<reqwest::Response> { let destination = match registration.url { Some(url) => url, None => { return Err(AppError::public("destination is none")); } }; let hs_token = registration.hs_token.as_str(); // let mut http_request = request // .try_into_http_request::<BytesMut>( // &destination, // SendAccessToken::IfRequired(hs_token), // &[MatrixVersion::V1_0], // ) // .unwrap() // .map(|body| body.freeze()); request .url_mut() .query_pairs_mut() .append_pair("access_token", hs_token); // let mut reqwest_request = reqwest::Request::try_from(http_request)?; *request.timeout_mut() = Some(Duration::from_secs(30)); let url = request.url().clone(); let response = match sending::default_client().execute(request).await { Ok(r) => r, Err(e) => { warn!( "Could not send request to appservice {:?} at {}: {}", registration.id, destination, e ); return Err(e.into()); } }; // reqwest::Response -> http::Response conversion let status = response.status(); // std::mem::swap( // response.headers_mut(), // http_response_builder // .headers_mut() // .expect("http::response::Builder is usable"), // ); // let body = response.bytes().await.unwrap_or_else(|e| { // warn!("server error: {}", e); // Vec::new().into() // }); // TODO: handle timeout if status != 200 { warn!( "Appservice returned bad response {} {}\n{}", destination, status, url, ); } // let response = T::IncomingResponse::try_from_http_response( // http_response_builder // .body(body) // .expect("reqwest body is valid http body"), // ); Ok(response) }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/state.rs
crates/server/src/state.rs
use crate::core::events::room::canonical_alias::RoomCanonicalAliasEventContent; use crate::core::events::room::history_visibility::{ HistoryVisibility, RoomHistoryVisibilityEventContent, }; use crate::core::events::room::join_rule::RoomJoinRulesEventContent; use crate::core::events::room::member::{MembershipState, RoomMemberEventContent}; use crate::core::events::room::power_levels::RoomPowerLevelsEventContent; use crate::core::events::{AnyStateEventContent, StateEventType}; use crate::core::identifiers::*; use crate::core::room::JoinRule; use crate::core::serde::RawJson; use crate::event::PduBuilder; use crate::room::timeline; use crate::{AppResult, IsRemoteOrLocal, MatrixError, config, room}; pub async fn send_state_event_for_key( user_id: &UserId, room_id: &RoomId, room_version: &RoomVersionId, event_type: &StateEventType, json: RawJson<AnyStateEventContent>, state_key: String, ) -> AppResult<OwnedEventId> { allowed_to_send_state_event(room_id, event_type, &state_key, &json)?; let pdu = timeline::build_and_append_pdu( PduBuilder { event_type: event_type.to_string().into(), content: serde_json::from_value(serde_json::to_value(json)?)?, state_key: Some(state_key), ..Default::default() }, user_id, room_id, room_version, &room::lock_state(room_id).await, ) .await? .pdu; Ok(pdu.event_id) } fn allowed_to_send_state_event( room_id: &RoomId, event_type: &StateEventType, state_key: &str, json: &RawJson<AnyStateEventContent>, ) -> AppResult<()> { let conf = config::get(); match event_type { StateEventType::RoomCreate => { return Err(MatrixError::bad_json( "You cannot update m.room.create after a room has been created.", ) .into()); } // Forbid m.room.encryption if encryption is disabled StateEventType::RoomEncryption => { if !conf.allow_encryption { return Err(MatrixError::forbidden( "Encryption is disabled on this homeserver.", None, ) .into()); } } // admin room is a sensitive room, it should not ever be made public StateEventType::RoomJoinRules => { if crate::room::is_admin_room(room_id)? && let Ok(join_rule) = serde_json::from_str::<RoomJoinRulesEventContent>(json.inner().get()) && join_rule.join_rule == JoinRule::Public { return Err(MatrixError::forbidden( "Admin room is a sensitive room, it cannot be made public", None, ) .into()); } } // admin room is a sensitive room, it should not ever be made world readable StateEventType::RoomHistoryVisibility => { if let Ok(visibility_content) = serde_json::from_str::<RoomHistoryVisibilityEventContent>(json.inner().get()) && crate::room::is_admin_room(room_id)? && visibility_content.history_visibility == HistoryVisibility::WorldReadable { return Err(MatrixError::forbidden( "Admin room is a sensitive room, it cannot be made world readable \ (public room history).", None, ) .into()); } } StateEventType::RoomCanonicalAlias => { if let Ok(canonical_alias) = serde_json::from_str::<RoomCanonicalAliasEventContent>(json.inner().get()) { let mut aliases = canonical_alias.alt_aliases.clone(); if let Some(alias) = canonical_alias.alias { aliases.push(alias); } for alias in aliases { if !alias.server_name().is_local() { return Err(MatrixError::forbidden( "Canonical_alias must be for this server.", None, ) .into()); } if !crate::room::resolve_local_alias(&alias).is_ok_and(|room| room == room_id) // Make sure it's the right room { return Err(MatrixError::bad_alias( "You are only allowed to send canonical_alias events when its \ aliases already exist", ) .into()); } } } else { return Err(MatrixError::invalid_param("Invalid aliases or alt_aliases").into()); } } StateEventType::RoomMember => { let Ok(membership_content) = serde_json::from_str::<RoomMemberEventContent>(json.inner().get()) else { return Err(MatrixError::bad_json( "Membership content must have a valid JSON body with at least a valid \ membership state.", ) .into()); }; let Ok(state_key) = UserId::parse(state_key) else { return Err(MatrixError::bad_json( "Membership event has invalid or non-existent state key", ) .into()); }; if let Some(authorising_user) = membership_content.join_authorized_via_users_server { if membership_content.membership != MembershipState::Join { return Err(MatrixError::bad_json( "join_authorised_via_users_server is only for member joins", ) .into()); } if crate::room::user::is_joined(&state_key, room_id)? { return Err(MatrixError::invalid_param( "{state_key} is already joined, an authorising user is not required.", ) .into()); } if !&authorising_user.is_local() { return Err(MatrixError::invalid_param( "Authorising user {authorising_user} does not belong to this homeserver", ) .into()); } if !crate::room::user::is_joined(&authorising_user, room_id)? { return Err(MatrixError::invalid_param( "Authorising user {authorising_user} is not in the room, they cannot \ authorise the join.", ) .into()); } } } StateEventType::RoomPowerLevels => { let room_version = room::get_version(room_id)?; let version_rules = crate::room::get_version_rules(&room_version)?; if version_rules .authorization .explicitly_privilege_room_creators { let Ok(power_level_content) = serde_json::from_str::<RoomPowerLevelsEventContent>(json.inner().get()) else { return Err(MatrixError::bad_json( "Power level content must have a valid JSON body with at least a valid \ power level state.", ) .into()); }; let create_event = crate::room::get_create(room_id)?; for crator in create_event.creators()? { if power_level_content.users.contains_key(&crator) { return Err(MatrixError::bad_json( "room creators can not be added to power level", ) .into()); } } } } _ => (), } Ok(()) }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/media.rs
crates/server/src/media.rs
mod preview; mod remote; pub use preview::*; pub use remote::*; use std::cmp; use std::num::Saturating; use std::path::PathBuf; use diesel::prelude::*; use tokio::io::AsyncWriteExt; use crate::core::http_headers::ContentDisposition; use crate::core::media::ResizeMethod; use crate::core::{Mxc, OwnedMxcUri, ServerName, UnixMillis, UserId}; use crate::data::connect; use crate::data::media::NewDbThumbnail; use crate::data::schema::*; use crate::{AppResult, config, data}; #[derive(Debug)] pub struct FileMeta { pub content: Option<Vec<u8>>, pub content_type: Option<String>, pub content_disposition: Option<ContentDisposition>, } /// Dimension specification for a thumbnail. #[derive(Debug)] pub struct Dimension { pub width: u32, pub height: u32, pub method: ResizeMethod, } impl Dimension { /// Instantiate a Dim with optional method #[inline] #[must_use] pub fn new(width: u32, height: u32, method: Option<ResizeMethod>) -> Self { Self { width, height, method: method.unwrap_or(ResizeMethod::Scale), } } pub fn scaled(&self, image: &Self) -> AppResult<Self> { let image_width = image.width; let image_height = image.height; let width = cmp::min(self.width, image_width); let height = cmp::min(self.height, image_height); let use_width = Saturating(width) * Saturating(image_height) < Saturating(height) * Saturating(image_width); let x = if use_width { let dividend = (Saturating(height) * Saturating(image_width)).0; dividend / image_height } else { width }; let y = if !use_width { let dividend = (Saturating(width) * Saturating(image_height)).0; dividend / image_width } else { height }; Ok(Self { width: x, height: y, method: ResizeMethod::Scale, }) } /// Returns width, height of the thumbnail and whether it should be cropped. /// Returns None when the server should send the original file. /// Ignores the input Method. #[must_use] pub fn normalized(&self) -> Self { match (self.width, self.height) { (0..=32, 0..=32) => Self::new(32, 32, Some(ResizeMethod::Crop)), (0..=96, 0..=96) => Self::new(96, 96, Some(ResizeMethod::Crop)), (0..=320, 0..=240) => Self::new(320, 240, Some(ResizeMethod::Scale)), (0..=640, 0..=480) => Self::new(640, 480, Some(ResizeMethod::Scale)), (0..=800, 0..=600) => Self::new(800, 600, Some(ResizeMethod::Scale)), _ => Self::default(), } } /// Returns true if the method is Crop. #[inline] #[must_use] pub fn crop(&self) -> bool { self.method == ResizeMethod::Crop } } impl Default for Dimension { #[inline] fn default() -> Self { Self { width: 0, height: 0, method: ResizeMethod::Scale, } } } pub fn get_media_path(server_name: &ServerName, media_id: &str) -> PathBuf { let server_name = if server_name == config::server_name() { "_" } else { server_name.as_str() }; let mut r = PathBuf::new(); r.push(config::space_path()); r.push("media"); r.push(server_name); // let extension = extension.unwrap_or_default(); // if !extension.is_empty() { // r.push(format!("{media_id}.{extension}")); // } else { r.push(media_id); // } r } pub async fn delete_media(server_name: &ServerName, media_id: &str) -> AppResult<()> { data::media::delete_media(server_name, media_id)?; let path = get_media_path(server_name, media_id); if path.exists() && let Err(e) = tokio::fs::remove_file(path).await { tracing::error!("failed to delete media file: {e}"); } Ok(()) } /// Returns width, height of the thumbnail and whether it should be cropped. Returns None when /// the server should send the original file. pub fn thumbnail_properties(width: u32, height: u32) -> Option<(u32, u32, bool)> { match (width, height) { (0..=32, 0..=32) => Some((32, 32, true)), (0..=96, 0..=96) => Some((96, 96, true)), (0..=320, 0..=240) => Some((320, 240, false)), (0..=640, 0..=480) => Some((640, 480, false)), (0..=800, 0..=600) => Some((800, 600, false)), _ => None, } } pub fn get_all_mxcs() -> AppResult<Vec<OwnedMxcUri>> { let mxcs = media_metadatas::table .select((media_metadatas::origin_server, media_metadatas::media_id)) .load::<(String, String)>(&mut connect()?)? .into_iter() .map(|(origin_server, media_id)| { OwnedMxcUri::from(format!("mxc://{origin_server}/{media_id}")) }) .collect(); Ok(mxcs) } /// Save or replaces a file thumbnail. #[allow(clippy::too_many_arguments)] pub async fn save_thumbnail( mxc: &Mxc<'_>, user: Option<&UserId>, content_type: Option<&str>, content_disposition: Option<&ContentDisposition>, dim: &Dimension, file: &[u8], ) -> AppResult<()> { let db_thumbnail = NewDbThumbnail { media_id: mxc.media_id.to_owned(), origin_server: mxc.server_name.to_owned(), content_type: content_type.map(|c| c.to_owned()), disposition_type: content_disposition.map(|d| d.to_string()), file_size: file.len() as i64, width: dim.width as i32, height: dim.height as i32, resize_method: dim.method.to_string(), created_at: UnixMillis::now(), }; let id = diesel::insert_into(media_thumbnails::table) .values(&db_thumbnail) .on_conflict_do_nothing() .returning(media_thumbnails::id) .get_result::<i64>(&mut connect()?) .optional()?; if let Some(id) = id { save_thumbnail_file(mxc.server_name, mxc.media_id, id, file).await?; } Ok(()) } pub async fn save_thumbnail_file( server_name: &ServerName, media_id: &str, thumbnail_id: i64, file: &[u8], ) -> AppResult<PathBuf> { let thumb_path = get_thumbnail_path(server_name, media_id, thumbnail_id); let mut f = tokio::fs::File::create(&thumb_path).await?; f.write_all(file).await?; Ok(thumb_path) } pub fn get_thumbnail_path(server_name: &ServerName, media_id: &str, thumbnail_id: i64) -> PathBuf { get_media_path( server_name, &format!("{media_id}.thumbnails/{thumbnail_id}"), ) }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/watcher.rs
crates/server/src/watcher.rs
use std::future::Future; use std::pin::Pin; use std::time::Duration; use diesel::prelude::*; use futures_util::{StreamExt, stream::FuturesUnordered}; use crate::AppResult; use crate::core::Seqnum; use crate::core::identifiers::*; use crate::data::schema::*; use crate::data::{self, connect}; pub async fn watch(user_id: &UserId, device_id: &DeviceId) -> AppResult<()> { let inbox_id = device_inboxes::table .filter(device_inboxes::user_id.eq(user_id)) .filter(device_inboxes::device_id.eq(device_id)) .order_by(device_inboxes::id.desc()) .select(device_inboxes::id) .first::<i64>(&mut connect()?) .unwrap_or_default(); let key_change_id = e2e_key_changes::table .filter(e2e_key_changes::user_id.eq(user_id)) .order_by(e2e_key_changes::id.desc()) .select(e2e_key_changes::id) .first::<i64>(&mut connect()?) .unwrap_or_default(); let room_user_id = room_users::table .filter(room_users::user_id.eq(user_id)) .order_by(room_users::id.desc()) .select(room_users::id) .first::<i64>(&mut connect()?) .unwrap_or_default(); let room_ids = data::user::joined_rooms(user_id)?; let last_event_sn = event_points::table .filter(event_points::room_id.eq_any(&room_ids)) .filter(event_points::frame_id.is_not_null()) .order_by(event_points::event_sn.desc()) .select(event_points::event_sn) .first::<Seqnum>(&mut connect()?) .unwrap_or_default(); let push_rule_sn = user_datas::table .filter(user_datas::user_id.eq(user_id)) .order_by(user_datas::occur_sn.desc()) .select(user_datas::occur_sn) .first::<i64>(&mut connect()?) .unwrap_or_default(); let mut futures: FuturesUnordered<Pin<Box<dyn Future<Output = AppResult<()>> + Send>>> = FuturesUnordered::new(); for room_id in room_ids.clone() { futures.push(Box::into_pin(Box::new(async move { crate::room::typing::wait_for_update(&room_id).await }))); } futures.push(Box::into_pin(Box::new(async move { loop { if inbox_id < device_inboxes::table .filter(device_inboxes::user_id.eq(user_id)) .filter(device_inboxes::device_id.eq(device_id)) .order_by(device_inboxes::id.desc()) .select(device_inboxes::id) .first::<i64>(&mut connect()?) .unwrap_or_default() { return Ok(()); } if key_change_id < e2e_key_changes::table .filter(e2e_key_changes::user_id.eq(user_id)) .order_by(e2e_key_changes::id.desc()) .select(e2e_key_changes::id) .first::<i64>(&mut connect()?) .unwrap_or_default() { return Ok(()); } if room_user_id < room_users::table .filter(room_users::user_id.eq(user_id)) .order_by(room_users::id.desc()) .select(room_users::id) .first::<i64>(&mut connect()?) .unwrap_or_default() { return Ok(()); } if last_event_sn < event_points::table .filter(event_points::room_id.eq_any(&room_ids)) .filter(event_points::frame_id.is_not_null()) .order_by(event_points::event_sn.desc()) .select(event_points::event_sn) .first::<Seqnum>(&mut connect()?) .unwrap_or_default() { return Ok(()); } if push_rule_sn < user_datas::table .filter(user_datas::user_id.eq(user_id)) .order_by(user_datas::occur_sn.desc()) .select(user_datas::occur_sn) .first::<i64>(&mut connect()?) .unwrap_or_default() { return Ok(()); } tokio::time::sleep(Duration::from_secs(1)).await; } }))); // Wait until one of them finds something futures.next().await; Ok(()) }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/info.rs
crates/server/src/info.rs
//! Information about the project. This module contains version, build, system, //! etc information which can be queried by admins or used by developers. pub mod cargo; pub mod rustc; pub mod version; pub use version::version;
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/transaction_id.rs
crates/server/src/transaction_id.rs
use diesel::prelude::*; use palpo_core::UnixMillis; use crate::AppResult; use crate::core::identifiers::*; use crate::core::{DeviceId, TransactionId, UserId}; use crate::data::room::NewDbEventIdempotent; use crate::data::schema::*; use crate::data::{connect, diesel_exists}; pub fn add_txn_id( txn_id: &TransactionId, user_id: &UserId, device_id: Option<&DeviceId>, room_id: Option<&RoomId>, event_id: Option<&EventId>, ) -> AppResult<()> { diesel::insert_into(event_idempotents::table) .values(&NewDbEventIdempotent { txn_id: txn_id.to_owned(), user_id: user_id.to_owned(), device_id: device_id.map(|d| d.to_owned()), room_id: room_id.map(|r| r.to_owned()), event_id: event_id.map(|e| e.to_owned()), created_at: UnixMillis::now(), }) .execute(&mut connect()?)?; Ok(()) } pub fn txn_id_exists( txn_id: &TransactionId, user_id: &UserId, device_id: Option<&DeviceId>, ) -> AppResult<bool> { if let Some(device_id) = device_id { let query = event_idempotents::table .filter(event_idempotents::user_id.eq(user_id)) .filter(event_idempotents::device_id.eq(device_id)) .filter(event_idempotents::txn_id.eq(txn_id)) .select(event_idempotents::event_id); diesel_exists!(query, &mut connect()?).map_err(Into::into) } else { let query = event_idempotents::table .filter(event_idempotents::user_id.eq(user_id)) .filter(event_idempotents::device_id.is_null()) .filter(event_idempotents::txn_id.eq(txn_id)) .select(event_idempotents::event_id); diesel_exists!(query, &mut connect()?).map_err(Into::into) } } pub fn get_event_id( txn_id: &TransactionId, user_id: &UserId, device_id: Option<&DeviceId>, room_id: Option<&RoomId>, ) -> AppResult<Option<OwnedEventId>> { let mut query = event_idempotents::table .filter(event_idempotents::user_id.eq(user_id)) .filter(event_idempotents::txn_id.eq(txn_id)) .into_boxed(); if let Some(device_id) = device_id { query = query.filter(event_idempotents::device_id.eq(device_id)); } else { query = query.filter(event_idempotents::device_id.is_null()); } if let Some(room_id) = room_id { query = query.filter(event_idempotents::room_id.eq(room_id)); } else { query = query.filter(event_idempotents::room_id.is_null()); } query .select(event_idempotents::event_id) .first::<Option<OwnedEventId>>(&mut connect()?) .optional() .map(|v| v.flatten()) .map_err(Into::into) }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/federation.rs
crates/server/src/federation.rs
use salvo::http::header::AUTHORIZATION; use salvo::http::headers::authorization::Credentials; use crate::core::federation::authentication::XMatrix; use crate::core::error::AuthenticateError; use crate::core::error::ErrorKind; use crate::core::identifiers::*; use crate::core::room::{AllowRule, JoinRule}; use crate::core::serde::CanonicalJsonObject; use crate::core::serde::JsonValue; use crate::core::{MatrixError, signatures}; use crate::{AppError, AppResult, config, room, sending}; mod access_check; pub mod membership; pub use access_check::access_check; #[tracing::instrument(skip(request))] pub(crate) async fn send_request( destination: &ServerName, mut request: reqwest::Request, ) -> AppResult<reqwest::Response> { if crate::config::get().enabled_federation().is_none() { return Err(AppError::public("Federation is disabled.")); } if destination == config::get().server_name { return Err(AppError::public( "won't send federation request to ourselves", )); } debug!("preparing to send request to {destination}"); let mut request_map = serde_json::Map::new(); if let Some(body) = request.body() { request_map.insert( "content".to_owned(), serde_json::from_slice(body.as_bytes().unwrap_or_default()) .expect("body is valid json, we just created it"), ); }; request_map.insert("method".to_owned(), request.method().to_string().into()); request_map.insert( "uri".to_owned(), format!( "{}{}", request.url().path(), request .url() .query() .map(|q| format!("?{q}")) .unwrap_or_default() ) .into(), ); request_map.insert( "origin".to_owned(), config::get().server_name.as_str().into(), ); request_map.insert("destination".to_owned(), destination.as_str().into()); let mut request_json = serde_json::from_value(request_map.into()).expect("valid JSON is valid BTreeMap"); signatures::sign_json( config::get().server_name.as_str(), config::keypair(), &mut request_json, ) .expect("our request json is what palpo expects"); let request_json: serde_json::Map<String, serde_json::Value> = serde_json::from_slice(&serde_json::to_vec(&request_json).unwrap()).unwrap(); let signatures = request_json["signatures"] .as_object() .unwrap() .values() .map(|v| { v.as_object() .unwrap() .iter() .map(|(k, v)| (k, v.as_str().unwrap())) }); for signature_server in signatures { for s in signature_server { request.headers_mut().insert( AUTHORIZATION, XMatrix::parse(format!( "X-Matrix origin=\"{}\",destination=\"{}\",key=\"{}\",sig=\"{}\"", config::get().server_name, destination, s.0, s.1 )) .expect("When signs JSON, it produces a valid base64 signature. All other types are valid ServerNames or OwnedKeyId") .encode(), ); } } let url = request.url().clone(); debug!("sending request to {destination} at {url}"); let response = sending::federation_client().execute(request).await; match response { Ok(response) => { let status = response.status(); if status == 200 { Ok(response) } else { let authenticate = if let Some(header) = response.headers().get("WWW-Authenticate") { if let Ok(header) = header.to_str() { AuthenticateError::from_str(header) } else { None } } else { None }; let body = response.text().await.unwrap_or_default(); warn!("answer from {destination}({url}) {status}: {body}"); let mut extra = serde_json::from_str::<serde_json::Map<String, JsonValue>>(&body) .unwrap_or_default(); let msg = extra .remove("error") .map(|v| v.as_str().unwrap_or_default().to_owned()) .unwrap_or("parse remote response data failed".to_owned()); Err(MatrixError { status_code: Some(status), authenticate, kind: serde_json::from_value(JsonValue::Object(extra)) .unwrap_or(ErrorKind::Unknown), body: msg.into(), } .into()) } } Err(e) => { warn!( "could not send request to {} at {}: {}", destination, url, e ); Err(e.into()) } } } /// Checks whether the given user can join the given room via a restricted join. pub(crate) async fn user_can_perform_restricted_join( user_id: &UserId, room_id: &RoomId, room_version_id: &RoomVersionId, join_rule: Option<&JoinRule>, ) -> AppResult<bool> { use RoomVersionId::*; // restricted rooms are not supported on <=v7 if matches!(room_version_id, V1 | V2 | V3 | V4 | V5 | V6 | V7) { return Ok(false); } if room::user::is_joined(user_id, room_id).unwrap_or(false) { // joining user is already joined, there is nothing we need to do return Ok(false); } if room::user::is_invited(user_id, room_id).unwrap_or(false) { return Ok(true); } let join_rule = match join_rule { Some(rule) => rule.to_owned(), None => { // If no join rule is provided, we need to fetch it from the room state let Ok(join_rule) = room::get_join_rule(room_id) else { return Ok(false); }; join_rule } }; let (JoinRule::Restricted(r) | JoinRule::KnockRestricted(r)) = join_rule else { return Ok(false); }; if r.allow.is_empty() { tracing::info!("`{room_id}` is restricted but the allow key is empty"); return Ok(false); } if r.allow .iter() .filter_map(|rule| { if let AllowRule::RoomMembership(membership) = rule { Some(membership) } else { None } }) .any(|m| { room::is_server_joined(&config::get().server_name, &m.room_id).unwrap_or(false) && room::user::is_joined(user_id, &m.room_id).unwrap_or(false) }) { Ok(true) } else { Err(MatrixError::unable_to_authorize_join( "joining user is not known to be in any required room", ) .into()) } } pub(crate) fn maybe_strip_event_id( pdu_json: &mut CanonicalJsonObject, room_version_id: &RoomVersionId, ) -> bool { match room_version_id { RoomVersionId::V1 | RoomVersionId::V2 => false, _ => { pdu_json.remove("event_id"); true } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/error.rs
crates/server/src/error.rs
use std::borrow::Cow; use std::io; use std::string::FromUtf8Error; use async_trait::async_trait; use salvo::http::{StatusCode, StatusError}; use salvo::oapi::{self, EndpointOutRegister, ToSchema}; use salvo::prelude::{Depot, Request, Response, Writer}; use thiserror::Error; // use crate::User; // use crate::DepotExt; use crate::core::MatrixError; use crate::core::events::room::power_levels::PowerLevelsError; use crate::core::state::StateError; #[derive(Error, Debug)] pub enum AppError { #[error("public: `{0}`")] Public(String), #[error("internal: `{0}`")] Internal(String), #[error("state: `{0}`")] State(#[from] StateError), #[error("power levels: `{0}`")] PowerLevels(#[from] PowerLevelsError), // #[error("local unable process: `{0}`")] // LocalUnableProcess(String), #[error("salvo internal error: `{0}`")] Salvo(#[from] ::salvo::Error), #[error("parse int error: `{0}`")] ParseIntError(#[from] std::num::ParseIntError), #[error("frequently request resource")] FrequentlyRequest, #[error("io: `{0}`")] Io(#[from] io::Error), #[error("utf8: `{0}`")] FromUtf8(#[from] FromUtf8Error), #[error("decoding: `{0}`")] Decoding(Cow<'static, str>), #[error("url parse: `{0}`")] UrlParse(#[from] url::ParseError), #[error("serde json: `{0}`")] SerdeJson(#[from] serde_json::error::Error), #[error("diesel: `{0}`")] Diesel(#[from] diesel::result::Error), #[error("regex: `{0}`")] Regex(#[from] regex::Error), #[error("http: `{0}`")] HttpStatus(#[from] salvo::http::StatusError), #[error("http parse: `{0}`")] HttpParse(#[from] salvo::http::ParseError), #[error("reqwest: `{0}`")] Reqwest(#[from] reqwest::Error), #[error("data: `{0}`")] Data(#[from] crate::data::DataError), #[error("pool: `{0}`")] Pool(#[from] crate::data::PoolError), #[error("utf8: `{0}`")] Utf8Error(#[from] std::str::Utf8Error), // #[error("redis: `{0}`")] // Redis(#[from] redis::RedisError), #[error("GlobError error: `{0}`")] Glob(#[from] globwalk::GlobError), #[error("Matrix error: `{0}`")] Matrix(#[from] palpo_core::MatrixError), #[error("argon2 error: `{0}`")] Argon2(#[from] argon2::Error), #[error("Uiaa error: `{0}`")] Uiaa(#[from] palpo_core::client::uiaa::UiaaInfo), #[error("Send error: `{0}`")] Send(#[from] palpo_core::sending::SendError), #[error("ID parse error: `{0}`")] IdParse(#[from] palpo_core::identifiers::IdParseError), #[error("CanonicalJson error: `{0}`")] CanonicalJson(#[from] palpo_core::serde::CanonicalJsonError), #[error("MxcUriError: `{0}`")] MxcUri(#[from] palpo_core::identifiers::MxcUriError), #[error("ImageError: `{0}`")] Image(#[from] image::ImageError), #[error("Signatures: `{0}`")] Signatures(#[from] palpo_core::signatures::Error), #[error("FmtError: `{0}`")] Fmt(#[from] std::fmt::Error), #[error("CargoTomlError: `{0}`")] CargoToml(#[from] cargo_toml::Error), #[error("YamlError: `{0}`")] Yaml(#[from] serde_saphyr::ser_error::Error), #[error("Command error: `{0}`")] Clap(#[from] clap::Error), #[error("SystemTimeError: `{0}`")] SystemTime(#[from] std::time::SystemTimeError), #[error("ReqwestMiddlewareError: `{0}`")] ReqwestMiddleware(#[from] reqwest_middleware::Error), } impl AppError { pub fn public<S: Into<String>>(msg: S) -> Self { Self::Public(msg.into()) } pub fn internal<S: Into<String>>(msg: S) -> Self { Self::Internal(msg.into()) } // pub fn local_unable_process<S: Into<String>>(msg: S) -> Self { // Self::LocalUnableProcess(msg.into()) // } pub fn is_not_found(&self) -> bool { match self { Self::Diesel(diesel::result::Error::NotFound) => true, Self::Matrix(e) => e.is_not_found(), _ => false, } } } #[async_trait] impl Writer for AppError { async fn write(mut self, req: &mut Request, depot: &mut Depot, res: &mut Response) { let matrix = match self { Self::Salvo(_e) => MatrixError::unknown("unknown error in salvo"), Self::FrequentlyRequest => MatrixError::unknown("frequently request resource"), Self::Public(msg) => MatrixError::unknown(msg), Self::Internal(msg) => { error!(error = ?msg, "internal error"); MatrixError::unknown("unknown error") } // Self::LocalUnableProcess(msg) => MatrixError::unrecognized(msg), Self::Matrix(e) => e, Self::State(e) => { if let StateError::Forbidden(msg) = e { tracing::error!(error = ?msg, "forbidden error"); MatrixError::forbidden(msg, None) } else if let StateError::AuthEvent(msg) = e { tracing::error!(error = ?msg, "forbidden error"); MatrixError::forbidden(msg, None) } else { MatrixError::unknown(e.to_string()) } } Self::Uiaa(uiaa) => { use crate::core::client::uiaa::ErrorKind; if res.status_code.map(|c| c.is_success()).unwrap_or(true) { let code = if let Some(error) = &uiaa.auth_error { match &error.kind { ErrorKind::Forbidden { .. } | ErrorKind::UserDeactivated => { StatusCode::FORBIDDEN } ErrorKind::NotFound => StatusCode::NOT_FOUND, ErrorKind::BadStatus { status, .. } => { status.unwrap_or(StatusCode::BAD_REQUEST) } ErrorKind::BadState | ErrorKind::BadJson | ErrorKind::BadAlias => { StatusCode::BAD_REQUEST } ErrorKind::Unauthorized => StatusCode::UNAUTHORIZED, ErrorKind::CannotOverwriteMedia => StatusCode::CONFLICT, ErrorKind::NotYetUploaded => StatusCode::GATEWAY_TIMEOUT, _ => StatusCode::INTERNAL_SERVER_ERROR, } } else { StatusCode::UNAUTHORIZED }; res.status_code(code); } res.add_header(salvo::http::header::CONTENT_TYPE, "application/json", true) .ok(); let body: Vec<u8> = crate::core::serde::json_to_buf(&uiaa).unwrap(); res.write_body(body).ok(); return; } Self::Diesel(e) => { tracing::error!(error = ?e, "diesel db error"); if let diesel::result::Error::NotFound = e { MatrixError::not_found("resource not found") } else { MatrixError::unknown("unknown db error") } } Self::HttpStatus(e) => match e.code { StatusCode::NOT_FOUND => MatrixError::not_found(e.brief), StatusCode::FORBIDDEN => MatrixError::forbidden(e.brief, None), StatusCode::UNAUTHORIZED => MatrixError::unauthorized(e.brief), code => { let mut e = MatrixError::unknown(e.brief); e.status_code = Some(code); e } }, Self::Data(e) => { e.write(req, depot, res).await; return; } e => { tracing::error!(error = ?e, "unknown error"); MatrixError::unknown("unknown error happened") } }; matrix.write(req, depot, res).await; } } impl EndpointOutRegister for AppError { fn register(components: &mut oapi::Components, operation: &mut oapi::Operation) { operation.responses.insert( StatusCode::INTERNAL_SERVER_ERROR.as_str(), oapi::Response::new("Internal server error") .add_content("application/json", StatusError::to_schema(components)), ); operation.responses.insert( StatusCode::NOT_FOUND.as_str(), oapi::Response::new("Not found") .add_content("application/json", StatusError::to_schema(components)), ); operation.responses.insert( StatusCode::BAD_REQUEST.as_str(), oapi::Response::new("Bad request") .add_content("application/json", StatusError::to_schema(components)), ); } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/admin.rs
crates/server/src/admin.rs
pub(crate) mod appservice; mod console; // pub(crate) mod debug; pub(crate) mod federation; pub(crate) mod media; pub(crate) mod room; pub(crate) mod server; pub(crate) mod user; pub(crate) use console::Console; mod utils; pub(crate) use utils::*; mod executor; mod processor; use std::pin::Pin; use std::{fmt, time::SystemTime}; use clap::Parser; use futures_util::{ Future, FutureExt, TryFutureExt, io::{AsyncWriteExt, BufWriter}, lock::Mutex, }; use regex::Regex; use tokio::sync::mpsc; use crate::AppResult; use crate::core::ServerName; use crate::core::events::room::message::RoomMessageEventContent; use crate::core::identifiers::*; pub(crate) use crate::macros::admin_command_dispatch; use self::{ appservice::AppserviceCommand, federation::FederationCommand, media::MediaCommand, room::RoomCommand, server::ServerCommand, user::UserCommand, }; pub use executor::*; pub(crate) const PAGE_SIZE: usize = 100; crate::macros::rustc_flags_capture! {} /// Inputs to a command are a multi-line string and optional reply_id. #[derive(Clone, Debug, Default)] pub struct CommandInput { pub command: String, pub reply_id: Option<OwnedEventId>, } /// Prototype of the tab-completer. The input is buffered text when tab /// asserted; the output will fully replace the input buffer. pub type Completer = fn(&str) -> String; /// Prototype of the command processor. This is a callback supplied by the /// reloadable admin module. pub type Processor = fn(CommandInput) -> ProcessorFuture; /// Return type of the processor pub type ProcessorFuture = Pin<Box<dyn Future<Output = ProcessorResult> + Send>>; /// Result wrapping of a command's handling. Both variants are complete message /// events which have digested any prior errors. The wrapping preserves whether /// the command failed without interpreting the text. Ok(None) outputs are /// dropped to produce no response. pub type ProcessorResult = Result<Option<CommandOutput>, CommandOutput>; /// Alias for the output structure. pub type CommandOutput = RoomMessageEventContent; #[derive(Debug, Parser)] #[command(name = "palpo", version = crate::info::version())] pub(crate) enum AdminCommand { #[command(subcommand)] /// - Commands for managing appservices Appservice(AppserviceCommand), #[command(subcommand)] /// - Commands for managing local users User(UserCommand), #[command(subcommand)] /// - Commands for managing rooms Room(RoomCommand), #[command(subcommand)] /// - Commands for managing federation Federation(FederationCommand), #[command(subcommand)] /// - Commands for managing the server Server(ServerCommand), #[command(subcommand)] /// - Commands for managing media Media(MediaCommand), // #[command(subcommand)] // /// - Commands for debugging things // Debug(DebugCommand), } #[derive(Debug)] pub enum AdminRoomEvent { ProcessMessage(String), SendMessage(RoomMessageEventContent), } pub(crate) struct Context<'a> { pub(crate) body: &'a [&'a str], pub(crate) timer: SystemTime, pub(crate) reply_id: Option<&'a EventId>, pub(crate) output: Mutex<BufWriter<Vec<u8>>>, } impl Context<'_> { pub(crate) fn write_fmt( &self, arguments: fmt::Arguments<'_>, ) -> impl Future<Output = AppResult<()>> + Send + '_ + use<'_> { let buf = format!("{arguments}"); self.output.lock().then(async move |mut output| { output.write_all(buf.as_bytes()).map_err(Into::into).await }) } pub(crate) fn write_str<'a>( &'a self, s: &'a str, ) -> impl Future<Output = AppResult<()>> + Send + 'a { self.output .lock() .then(async move |mut output| output.write_all(s.as_bytes()).map_err(Into::into).await) } } pub(crate) struct RoomInfo { pub(crate) id: OwnedRoomId, pub(crate) joined_members: u64, pub(crate) name: String, } pub(crate) fn get_room_info(room_id: &RoomId) -> RoomInfo { RoomInfo { id: room_id.to_owned(), joined_members: crate::room::joined_member_count(room_id).unwrap_or(0), name: crate::room::get_name(room_id).unwrap_or_else(|_| room_id.to_string()), } } #[tracing::instrument(skip_all, name = "command")] pub(super) async fn process(command: AdminCommand, context: &Context<'_>) -> AppResult<()> { use AdminCommand::*; match command { Appservice(command) => appservice::process(command, context).await, Media(command) => media::process(command, context).await, User(command) => user::process(command, context).await, Room(command) => room::process(command, context).await, Federation(command) => federation::process(command, context).await, Server(command) => server::process(command, context).await, // Debug(command) => debug::process(command, context).await, } } /// Maximum number of commands which can be queued for dispatch. const COMMAND_QUEUE_LIMIT: usize = 512; pub async fn start() -> AppResult<()> { executor::init().await; let exec = executor(); let mut signals = exec.signal.subscribe(); let (sender, mut receiver) = mpsc::channel(COMMAND_QUEUE_LIMIT); _ = exec .channel .write() .expect("locked for writing") .insert(sender); tokio::task::yield_now().await; exec.console.start().await; loop { tokio::select! { command = receiver.recv() => match command { Some(command) => exec.handle_command(command).await, None => break, }, sig = signals.recv() => match sig { Ok(sig) => exec.handle_signal(sig).await, Err(_) => continue, }, } } exec.interrupt().await; Ok(()) } // Utility to turn clap's `--help` text to HTML. fn usage_to_html(text: &str, server_name: &ServerName) -> String { // Replace `@palpo:servername:-subcmdname` with `@palpo:servername: subcmdname` let text = text.replace( &format!("@palpo:{server_name}:-"), &format!("@palpo:{server_name}: "), ); // For the palpo admin room, subcommands become main commands let text = text.replace("SUBCOMMAND", "COMMAND"); let text = text.replace("subcommand", "command"); // Escape option names (e.g. `<element-id>`) since they look like HTML tags let text = text.replace('<', "&lt;").replace('>', "&gt;"); // Italicize the first line (command name and version text) let re = Regex::new("^(.*?)\n").expect("Regex compilation should not fail"); let text = re.replace_all(&text, "<em>$1</em>\n"); // Unmerge wrapped lines let text = text.replace("\n ", " "); // Wrap option names in backticks. The lines look like: // -V, --version Prints version information // And are converted to: // <code>-V, --version</code>: Prints version information // (?m) enables multi-line mode for ^ and $ let re = Regex::new("(?m)^ (([a-zA-Z_&;-]+(, )?)+) +(.*)$") .expect("Regex compilation should not fail"); let text = re.replace_all(&text, "<code>$1</code>: $4"); // Look for a `[commandbody]` tag. If it exists, use all lines below it that // start with a `#` in the USAGE section. let mut text_lines: Vec<&str> = text.lines().collect(); let mut command_body = String::new(); if let Some(line_index) = text_lines.iter().position(|line| *line == "[commandbody]") { text_lines.remove(line_index); while text_lines .get(line_index) .map(|line| line.starts_with('#')) .unwrap_or(false) { command_body += if text_lines[line_index].starts_with("# ") { &text_lines[line_index][2..] } else { &text_lines[line_index][1..] }; command_body += "[nobr]\n"; text_lines.remove(line_index); } } let text = text_lines.join("\n"); // Improve the usage section let text = if command_body.is_empty() { // Wrap the usage line in code tags let re = Regex::new("(?m)^USAGE:\n (@palpo:.*)$").expect("Regex compilation should not fail"); re.replace_all(&text, "USAGE:\n<code>$1</code>").to_string() } else { // Wrap the usage line in a code block, and add a yaml block example // This makes the usage of e.g. `register-appservice` more accurate let re = Regex::new("(?m)^USAGE:\n (.*?)\n\n").expect("Regex compilation should not fail"); re.replace_all(&text, "USAGE:\n<pre>$1[nobr]\n[commandbodyblock]</pre>") .replace("[commandbodyblock]", &command_body) }; // Add HTML line-breaks text.replace("\n\n\n", "\n\n") .replace('\n', "<br>\n") .replace("[nobr]<br>", "") }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/auth.rs
crates/server/src/auth.rs
use salvo::oapi::ToParameters; use serde::Deserialize; use crate::appservice::RegistrationInfo; use crate::core::MatrixError; use crate::core::identifiers::*; use crate::core::serde::default_false; use crate::data::user::{DbUser, DbUserDevice}; #[derive(Clone, Debug)] pub struct AuthedInfo { pub user: DbUser, pub user_device: DbUserDevice, pub access_token_id: Option<i64>, pub appservice: Option<RegistrationInfo>, } impl AuthedInfo { pub fn user(&self) -> &DbUser { &self.user } pub fn user_id(&self) -> &UserId { &self.user.id } pub fn device_id(&self) -> &DeviceId { &self.user_device.device_id } pub fn access_token_id(&self) -> Option<i64> { self.access_token_id } pub fn appservice(&self) -> Option<&RegistrationInfo> { self.appservice.as_ref() } pub fn is_admin(&self) -> bool { self.user.is_admin } } #[derive(Debug, Clone, Deserialize, ToParameters)] #[salvo(parameters(default_parameter_in = Query))] pub struct AuthArgs { pub user_id: Option<String>, pub device_id: Option<String>, pub access_token: Option<String>, #[salvo(parameter(parameter_in = Header))] pub authorization: Option<String>, #[serde(default = "default_false")] pub from_appservice: bool, } impl AuthArgs { pub fn require_access_token(&self) -> Result<&str, MatrixError> { if let Some(bearer) = &self.authorization { if let Some(token) = bearer.strip_prefix("Bearer ") { Ok(token) } else { Err(MatrixError::missing_token("Invalid Bearer token.")) } } else if let Some(access_token) = self.access_token.as_deref() { Ok(access_token) } else { Err(MatrixError::missing_token("Token not found.")) } } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/utils.rs
crates/server/src/utils.rs
use std::{cmp::Ordering, fmt, str::FromStr}; use rand::prelude::*; use crate::core::OwnedUserId; use crate::core::signatures::Ed25519KeyPair; use crate::{AppError, AppResult}; pub mod fs; pub mod hash; pub use hash::*; pub mod time; pub use time::*; pub mod stream; pub mod string; pub use stream::*; pub mod content_disposition; mod mutex_map; pub use mutex_map::{MutexMap, MutexMapGuard}; mod sequm_queue; pub use sequm_queue::*; mod defer; pub mod sys; #[macro_export] macro_rules! join_path { ($($part:expr),+) => { { let mut p = std::path::PathBuf::new(); $( p.push($part); )* path_slash::PathBufExt::to_slash_lossy(&p).to_string() } } } #[macro_export] macro_rules! extract_variant { ($e:expr, $variant:path) => { match $e { $variant(value) => Some(value), _ => None, } }; } pub fn select_config_path() -> &'static str { if cfg!(windows) { "palpo.toml" } else { const CANDIDATE_PATHS: [&str; 3] = [ "palpo.toml", "/etc/palpo/palpo.toml", "/var/palpo/palpo.toml", ]; CANDIDATE_PATHS .into_iter() .find(|path| std::fs::exists(path).unwrap_or(false)) .unwrap_or("palpo.toml") } } pub fn shuffle<T>(vec: &mut [T]) { let mut rng = rand::rng(); vec.shuffle(&mut rng); } pub fn increment(old: Option<&[u8]>) -> Option<Vec<u8>> { let number = match old.map(|bytes| bytes.try_into()) { Some(Ok(bytes)) => { let number = u64::from_be_bytes(bytes); number + 1 } _ => 1, // Start at one. since 0 should return the first event in the db }; Some(number.to_be_bytes().to_vec()) } pub fn generate_keypair() -> Ed25519KeyPair { let key_content = Ed25519KeyPair::generate().unwrap(); Ed25519KeyPair::from_der(&key_content, random_string(8)) .unwrap_or_else(|_| panic!("{:?}", &key_content)) } /// Parses the bytes into an u64. pub fn u64_from_bytes(bytes: &[u8]) -> Result<u64, std::array::TryFromSliceError> { let array: [u8; 8] = bytes.try_into()?; Ok(u64::from_be_bytes(array)) } pub fn i64_from_bytes(bytes: &[u8]) -> Result<i64, std::array::TryFromSliceError> { let array: [u8; 8] = bytes.try_into()?; Ok(i64::from_be_bytes(array)) } /// Parses the bytes into a string. pub fn string_from_bytes(bytes: &[u8]) -> Result<String, std::string::FromUtf8Error> { String::from_utf8(bytes.to_vec()) } /// Parses a OwnedUserId from bytes. pub fn user_id_from_bytes(bytes: &[u8]) -> AppResult<OwnedUserId> { OwnedUserId::try_from( string_from_bytes(bytes) .map_err(|_| AppError::public("Failed to parse string from bytes"))?, ) .map_err(|_| AppError::public("Failed to parse user id from bytes")) } pub fn random_string(length: usize) -> String { rand::rng() .sample_iter(&rand::distr::Alphanumeric) .take(length) .map(char::from) .collect() } pub fn common_elements( mut iterators: impl Iterator<Item = impl Iterator<Item = Vec<u8>>>, check_order: impl Fn(&[u8], &[u8]) -> Ordering, ) -> Option<impl Iterator<Item = Vec<u8>>> { let first_iterator = iterators.next()?; let mut other_iterators = iterators.map(|i| i.peekable()).collect::<Vec<_>>(); Some(first_iterator.filter(move |target| { other_iterators.iter_mut().all(|it| { while let Some(element) = it.peek() { match check_order(element, target) { Ordering::Greater => return false, // We went too far Ordering::Equal => return true, // Element is in both iters Ordering::Less => { // Keep searching it.next(); } } } false }) })) } pub fn deserialize_from_str< 'de, D: serde::de::Deserializer<'de>, T: FromStr<Err = E>, E: std::fmt::Display, >( deserializer: D, ) -> Result<T, D::Error> { struct Visitor<T: FromStr<Err = E>, E>(std::marker::PhantomData<T>); impl<'de, T: FromStr<Err = Err>, Err: std::fmt::Display> serde::de::Visitor<'de> for Visitor<T, Err> { type Value = T; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "a parsable string") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error, { v.parse().map_err(serde::de::Error::custom) } } deserializer.deserialize_str(Visitor(std::marker::PhantomData)) } // Copied from librustdoc: // https://github.com/rust-lang/rust/blob/cbaeec14f90b59a91a6b0f17fc046c66fa811892/src/librustdoc/html/escape.rs /// Wrapper struct which will emit the HTML-escaped version of the contained /// string when passed to a format string. pub struct HtmlEscape<'a>(pub &'a str); impl<'a> fmt::Display for HtmlEscape<'a> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { // Because the internet is always right, turns out there's not that many // characters to escape: http://stackoverflow.com/questions/7381974 let HtmlEscape(s) = *self; let pile_o_bits = s; let mut last = 0; for (i, ch) in s.char_indices() { let s = match ch { '>' => "&gt;", '<' => "&lt;", '&' => "&amp;", '\'' => "&#39;", '"' => "&quot;", _ => continue, }; fmt.write_str(&pile_o_bits[last..i])?; fmt.write_str(s)?; // NOTE: we only expect single byte characters here - which is fine as long as we // only match single byte characters last = i + 1; } if last < s.len() { fmt.write_str(&pile_o_bits[last..])?; } Ok(()) } } pub fn usize_to_i64(value: usize) -> i64 { if value as u64 <= i64::MAX as u64 { value as i64 } else { i64::MAX } } pub fn u64_to_i64(value: u64) -> i64 { if value <= i64::MAX as u64 { value as i64 } else { i64::MAX } }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/cjson.rs
crates/server/src/cjson.rs
use palpo_core::serde::CanonicalJsonError; use salvo::http::header::{CONTENT_TYPE, HeaderValue}; use salvo::http::{Response, StatusError}; use salvo::oapi::{ self, Components, Content, EndpointOutRegister, Operation, RefOr, ToResponse, ToSchema, }; use salvo::{Scribe, async_trait}; use serde::Serialize; use crate::core::serde::CanonicalJsonValue; pub struct Cjson<T>(pub T); #[async_trait] impl<T> Scribe for Cjson<T> where T: Serialize + Send, { fn render(self, res: &mut Response) { match try_to_bytes(&self.0) { Ok(bytes) => { res.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_static("application/json; charset=utf-8"), ); res.write_body(bytes).ok(); } Err(e) => { tracing::error!(error = ?e, "JsonContent write error"); res.render(StatusError::internal_server_error()); } } } } impl<C> ToResponse for Cjson<C> where C: ToSchema, { fn to_response(components: &mut Components) -> RefOr<oapi::Response> { let schema = <C as ToSchema>::to_schema(components); oapi::Response::new("Response with json format data") .add_content("application/json", Content::new(schema)) .into() } } impl<C> EndpointOutRegister for Cjson<C> where C: ToSchema, { #[inline] fn register(components: &mut Components, operation: &mut Operation) { operation .responses .insert("200", Self::to_response(components)); } } fn try_to_bytes<T>(data: &T) -> Result<Vec<u8>, CanonicalJsonError> where T: Serialize + Send, { let value: CanonicalJsonValue = serde_json::to_value(data)?.try_into()?; Ok(serde_json::to_vec(&value)?) }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/membership.rs
crates/server/src/membership.rs
use std::collections::BTreeMap; use std::time::Duration; use diesel::prelude::*; use tokio::sync::RwLock; use crate::core::events::GlobalAccountDataEventType; use crate::core::events::StateEventType; use crate::core::events::direct::DirectEventContent; use crate::core::events::room::create::RoomCreateEventContent; use crate::core::events::room::member::MembershipState; use crate::core::events::{AnyStrippedStateEvent, RoomAccountDataEventType}; use crate::core::identifiers::*; use crate::core::serde::{ CanonicalJsonObject, CanonicalJsonValue, JsonValue, RawJson, RawJsonValue, }; use crate::core::{UnixMillis, federation}; use crate::data::connect; use crate::data::room::NewDbRoomUser; use crate::data::schema::*; use crate::room::state::ensure_field; use crate::{AppError, AppResult, MatrixError, SigningKeys, room}; mod banned; mod forget; mod invite; mod join; mod knock; mod leave; pub use banned::*; pub use forget::*; pub use invite::*; pub use join::*; pub use knock::*; pub use leave::*; async fn validate_and_add_event_id( pdu: &RawJsonValue, room_version: &RoomVersionId, _pub_key_map: &RwLock<BTreeMap<String, SigningKeys>>, ) -> AppResult<(OwnedEventId, CanonicalJsonObject)> { let (event_id, mut value) = crate::event::gen_event_id_canonical_json(pdu, room_version)?; // TODO // let back_off = |id| match crate::BAD_EVENT_RATE_LIMITER.write().unwrap().entry(id) { // Entry::Vacant(e) => { // e.insert((Instant::now(), 1)); // } // Entry::Occupied(mut e) => *e.get_mut() = (Instant::now(), e.get().1 + 1), // }; if let Some((time, tries)) = crate::BAD_EVENT_RATE_LIMITER.read().unwrap().get(&event_id) { // Exponential backoff let mut min_elapsed_duration = Duration::from_secs(30) * (*tries) * (*tries); if min_elapsed_duration > Duration::from_secs(60 * 60 * 24) { min_elapsed_duration = Duration::from_secs(60 * 60 * 24); } if time.elapsed() < min_elapsed_duration { debug!("backing off from {}", event_id); return Err(AppError::public("bad event, still backing off")); } } let origin_server_ts = value.get("origin_server_ts").ok_or_else(|| { error!("invalid pdu, no origin_server_ts field"); MatrixError::missing_param("invalid pdu, no origin_server_ts field") })?; let _origin_server_ts: UnixMillis = { let ts = origin_server_ts .as_integer() .ok_or_else(|| MatrixError::invalid_param("origin_server_ts must be an integer"))?; UnixMillis( ts.try_into() .map_err(|_| MatrixError::invalid_param("time must be after the unix epoch"))?, ) }; // let unfiltered_keys = (*pub_key_map.read().await).clone(); // let keys = crate::filter_keys_server_map(unfiltered_keys, origin_server_ts, room_version); // TODO // if let Err(e) = crate::core::signatures::verify_event(&keys, &value, room_version) { // warn!("Event {} failed verification {:?} {}", event_id, pdu, e); // back_off(event_id); // return Err(AppError::public("Event failed verification.")); // } value.insert( "event_id".to_owned(), CanonicalJsonValue::String(event_id.as_str().to_owned()), ); Ok((event_id, value)) } /// Update current membership data. #[tracing::instrument(skip(last_state))] pub fn update_membership( event_id: &EventId, event_sn: i64, room_id: &RoomId, user_id: &UserId, membership: MembershipState, sender_id: &UserId, last_state: Option<Vec<RawJson<AnyStrippedStateEvent>>>, ) -> AppResult<()> { let conf = crate::config::get(); // Keep track what remote users exist by adding them as "deactivated" users if user_id.server_name() != conf.server_name && !crate::data::user::user_exists(user_id)? { crate::user::create_user(user_id, None)?; // TODO: display_name, avatar url } let state_data = if let Some(last_state) = &last_state { Some(serde_json::to_value(last_state)?) } else { None }; match &membership { MembershipState::Join => { // Check if the user never joined this room if !(room::user::is_joined(user_id, room_id)? || room::user::is_left(user_id, room_id)?) { // Check if the room has a predecessor if let Ok(Some(predecessor)) = room::get_state_content::<RoomCreateEventContent>( room_id, &StateEventType::RoomCreate, "", None, ) .map(|c| c.predecessor) { // Copy user settings from predecessor to the current room: // - Push rules // // TODO: finish this once push rules are implemented. // // let mut push_rules_event_content: PushRulesEvent = account_data // .get( // None, // user_id, // EventType::PushRules, // )?; // // NOTE: find where `predecessor.room_id` match // and update to `room_id`. // // account_data // .update( // None, // user_id, // EventType::PushRules, // &push_rules_event_content, // globals, // ) // .ok(); // Copy old tags to new room if let Some(tag_event_content) = crate::data::user::get_room_data::<JsonValue>( user_id, &predecessor.room_id, &RoomAccountDataEventType::Tag.to_string(), )? { crate::data::user::set_data( user_id, Some(room_id.to_owned()), &RoomAccountDataEventType::Tag.to_string(), tag_event_content, ) .ok(); }; // Copy direct chat flag if let Ok(mut direct_event_content) = crate::data::user::get_data::<DirectEventContent>( user_id, None, &GlobalAccountDataEventType::Direct.to_string(), ) { let mut room_ids_updated = false; for room_ids in direct_event_content.0.values_mut() { if room_ids.iter().any(|r| r == &predecessor.room_id) { room_ids.push(room_id.to_owned()); room_ids_updated = true; } } if room_ids_updated { crate::data::user::set_data( user_id, None, &GlobalAccountDataEventType::Direct.to_string(), serde_json::to_value(&direct_event_content)?, )?; } }; } } connect()?.transaction::<_, AppError, _>(|conn| { // let forgotten = room_users::table // .filter(room_users::room_id.eq(room_id)) // .filter(room_users::user_id.eq(user_id)) // .select(room_users::forgotten) // .first::<bool>(conn) // .optional()? // .unwrap_or_default(); diesel::delete( room_users::table .filter(room_users::room_id.eq(room_id)) .filter(room_users::user_id.eq(user_id)), ) .execute(conn)?; diesel::insert_into(room_users::table) .values(&NewDbRoomUser { room_id: room_id.to_owned(), room_server_id: room_id.server_name().ok().map(|v| v.to_owned()), user_id: user_id.to_owned(), user_server_id: user_id.server_name().to_owned(), event_id: event_id.to_owned(), event_sn, sender_id: sender_id.to_owned(), membership: membership.to_string(), forgotten: false, display_name: None, avatar_url: None, state_data, created_at: UnixMillis::now(), }) .execute(conn)?; Ok(()) })?; } MembershipState::Invite | MembershipState::Knock => { // We want to know if the sender is ignored by the receiver if crate::user::user_is_ignored(sender_id, user_id) { return Ok(()); } if let Some(last_state) = &last_state { for event in last_state { if let Ok(event) = event.deserialize() { let _ = ensure_field(&event.event_type(), event.state_key()); } } } let _ = ensure_field(&StateEventType::RoomMember, user_id.as_str()); connect()?.transaction::<_, AppError, _>(|conn| { // let forgotten = room_users::table // .filter(room_users::room_id.eq(room_id)) // .filter(room_users::user_id.eq(user_id)) // .select(room_users::forgotten) // .first::<bool>(conn) // .optional()? // .unwrap_or_default(); diesel::delete( room_users::table .filter(room_users::room_id.eq(room_id)) .filter(room_users::user_id.eq(user_id)), ) .execute(conn)?; diesel::insert_into(room_users::table) .values(&NewDbRoomUser { room_id: room_id.to_owned(), room_server_id: room_id.server_name().ok().map(|v| v.to_owned()), user_id: user_id.to_owned(), user_server_id: user_id.server_name().to_owned(), event_id: event_id.to_owned(), event_sn, sender_id: sender_id.to_owned(), membership: membership.to_string(), forgotten: false, display_name: None, avatar_url: None, state_data, created_at: UnixMillis::now(), }) .execute(conn)?; Ok(()) })?; } MembershipState::Leave | MembershipState::Ban => { connect()?.transaction::<_, AppError, _>(|conn| { // let forgotten = room_users::table // .filter(room_users::room_id.eq(room_id)) // .filter(room_users::user_id.eq(user_id)) // .select(room_users::forgotten) // .first::<bool>(conn) // .optional()? // .unwrap_or_default(); diesel::delete( room_users::table .filter(room_users::room_id.eq(room_id)) .filter(room_users::user_id.eq(user_id)), ) .execute(conn)?; diesel::insert_into(room_users::table) .values(&NewDbRoomUser { room_id: room_id.to_owned(), room_server_id: room_id.server_name().ok().map(|v| v.to_owned()), user_id: user_id.to_owned(), user_server_id: user_id.server_name().to_owned(), event_id: event_id.to_owned(), event_sn, sender_id: sender_id.to_owned(), membership: membership.to_string(), forgotten: false, display_name: None, avatar_url: None, state_data, created_at: UnixMillis::now(), }) .execute(conn)?; Ok(()) })?; } _ => {} } crate::room::update_joined_servers(room_id)?; crate::room::update_currents(room_id)?; Ok(()) }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/env_vars.rs
crates/server/src/env_vars.rs
use std::error::Error; use std::str::FromStr; use anyhow::{Context, anyhow}; /// Reads an environment variable for the current process. /// /// Compared to [std::env::var] there are a couple of differences: /// /// - [var] uses [dotenvy] which loads the `.env` file from the current or /// parent directories before returning the value. /// /// - [var] returns `Ok(None)` (instead of `Err`) if an environment variable /// wasn't set. #[track_caller] pub fn var(key: &str) -> anyhow::Result<Option<String>> { match dotenvy::var(key) { Ok(content) => Ok(Some(content)), Err(dotenvy::Error::EnvVar(std::env::VarError::NotPresent)) => Ok(None), Err(error) => Err(error.into()), } } /// Reads an environment variable for the current process, and fails if it was /// not found. /// /// Compared to [std::env::var] there are a couple of differences: /// /// - [var] uses [dotenvy] which loads the `.env` file from the current or /// parent directories before returning the value. #[track_caller] pub fn required_var(key: &str) -> anyhow::Result<String> { required(var(key), key) } /// Reads an environment variable for the current process, and parses it if /// it is set. /// /// Compared to [std::env::var] there are a couple of differences: /// /// - [var] uses [dotenvy] which loads the `.env` file from the current or /// parent directories before returning the value. /// /// - [var] returns `Ok(None)` (instead of `Err`) if an environment variable /// wasn't set. #[track_caller] pub fn var_parsed<R>(key: &str) -> anyhow::Result<Option<R>> where R: FromStr, R::Err: Error + Send + Sync + 'static, { match var(key) { Ok(Some(content)) => { Ok(Some(content.parse().with_context(|| { format!("Failed to parse {key} environment variable") })?)) } Ok(None) => Ok(None), Err(error) => Err(error), } } /// Reads an environment variable for the current process, and parses it if /// it is set or fails otherwise. /// /// Compared to [std::env::var] there are a couple of differences: /// /// - [var] uses [dotenvy] which loads the `.env` file from the current or /// parent directories before returning the value. #[track_caller] pub fn required_var_parsed<R>(key: &str) -> anyhow::Result<R> where R: FromStr, R::Err: Error + Send + Sync + 'static, { required(var_parsed(key), key) } fn required<T>(res: anyhow::Result<Option<T>>, key: &str) -> anyhow::Result<T> { match res { Ok(opt) => opt.ok_or_else(|| anyhow!("Failed to find required {key} environment variable")), Err(error) => Err(error), } } /// Reads an environment variable and parses it as a comma-separated list, or /// returns an empty list if the variable is not set. #[track_caller] pub fn list(key: &str) -> anyhow::Result<Vec<String>> { let values = match var(key)? { None => vec![], Some(s) if s.is_empty() => vec![], Some(s) => s.split(',').map(str::trim).map(String::from).collect(), }; Ok(values) } /// Reads an environment variable and parses it as a comma-separated list, or /// returns an empty list if the variable is not set. Each individual value is /// parsed using [FromStr]. #[track_caller] pub fn list_parsed<T, E, F, C>(key: &str, f: F) -> anyhow::Result<Vec<T>> where F: Fn(&str) -> C, C: Context<T, E>, { let values = match var(key)? { None => vec![], Some(s) if s.is_empty() => vec![], Some(s) => s .split(',') .map(str::trim) .map(|s| { f(s).with_context(|| { format!("Failed to parse value \"{s}\" of {key} environment variable") }) }) .collect::<Result<_, _>>()?, }; Ok(values) }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/main.rs
crates/server/src/main.rs
#![allow(dead_code, missing_docs)] // #![deny(unused_crate_dependencies)] // #[macro_use] // extern crate diesel; // extern crate dotenvy; // #[macro_use] // extern crate thiserror; // #[macro_use] // extern crate anyhow; // #[macro_use] // mod macros; // #[macro_use] // pub mod permission; #[macro_use] extern crate tracing; pub mod auth; pub mod config; pub mod env_vars; pub mod hoops; pub mod routing; pub mod utils; pub use auth::{AuthArgs, AuthedInfo}; pub mod admin; pub mod appservice; pub mod directory; pub mod event; pub mod exts; pub mod federation; pub mod media; pub mod membership; pub mod room; pub mod sending; pub mod server_key; pub mod state; pub mod transaction_id; pub mod uiaa; pub mod user; pub use exts::*; mod cjson; pub use cjson::Cjson; mod signing_keys; pub mod sync_v3; pub mod sync_v5; pub mod watcher; pub use event::{PduBuilder, PduEvent, SnPduEvent}; pub use signing_keys::SigningKeys; mod global; pub use global::*; mod info; pub mod logging; pub mod error; pub use core::error::MatrixError; pub use error::AppError; pub use palpo_core as core; pub use palpo_data as data; pub use palpo_server_macros as macros; use std::path::PathBuf; use std::time::Duration; use clap::Parser; pub use diesel::result::Error as DieselError; use dotenvy::dotenv; use figment::providers::Env; pub use jsonwebtoken as jwt; use salvo::catcher::Catcher; use salvo::compression::{Compression, CompressionLevel}; use salvo::conn::rustls::{Keycert, RustlsConfig}; use salvo::conn::tcp::DynTcpAcceptors; use salvo::cors::{self, AllowHeaders, Cors}; use salvo::http::Method; use salvo::logging::Logger; use salvo::prelude::*; use tracing_futures::Instrument; use crate::config::ServerConfig; pub type AppResult<T> = Result<T, crate::AppError>; pub type DieselResult<T> = Result<T, diesel::result::Error>; pub type JsonResult<T> = Result<Json<T>, crate::AppError>; pub type CjsonResult<T> = Result<Cjson<T>, crate::AppError>; pub type EmptyResult = Result<Json<EmptyObject>, crate::AppError>; pub fn json_ok<T>(data: T) -> JsonResult<T> { Ok(Json(data)) } pub fn cjson_ok<T>(data: T) -> CjsonResult<T> { Ok(Cjson(data)) } pub fn empty_ok() -> JsonResult<EmptyObject> { Ok(Json(EmptyObject {})) } pub trait OptionalExtension<T> { fn optional(self) -> AppResult<Option<T>>; } impl<T> OptionalExtension<T> for AppResult<T> { fn optional(self) -> AppResult<Option<T>> { match self { Ok(value) => Ok(Some(value)), Err(AppError::Matrix(e)) => { if e.is_not_found() { Ok(None) } else { Err(AppError::Matrix(e)) } } Err(AppError::Diesel(diesel::result::Error::NotFound)) => Ok(None), Err(e) => Err(e), } } } /// Commandline arguments #[derive(Parser, Debug)] #[clap( about, long_about = None, name = "palpo", version = crate::info::version(), )] pub(crate) struct Args { #[arg(short, long)] /// Path to the config TOML file (optional) pub(crate) config: Option<PathBuf>, /// Activate admin command console automatically after startup. #[arg(long, num_args(0))] pub(crate) console: bool, #[arg(long, short, num_args(1), default_value_t = true)] pub(crate) server: bool, } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { if dotenvy::from_filename(".env.local").is_err() { tracing::debug!(".env.local file is not found"); } if let Err(e) = dotenv() { tracing::info!("dotenv not loaded: {:?}", e); } let args = Args::parse(); println!("Args: {:?}", args); let config_path = if let Some(config) = &args.config { config } else { &PathBuf::from( Env::var("PALPO_CONFIG").unwrap_or_else(|| utils::select_config_path().into()), ) }; crate::config::init(config_path); let conf = crate::config::get(); conf.check().expect("config is not valid!"); crate::logging::init()?; crate::data::init(&conf.db.clone().into_data_db_config()); if args.console { tracing::info!("starting admin console..."); if !args.server { crate::admin::start() .await .expect("admin console failed to start"); tracing::info!("admin console stopped"); return Ok(()); } else { tokio::spawn(async move { crate::admin::start() .await .expect("admin console failed to start"); tracing::info!("admin console stopped"); }); } } if !args.server { tracing::info!("server is not started, exiting..."); return Ok(()); } crate::sending::guard::start(); let router = routing::root(); // let doc = OpenApi::new("palpo api", "0.0.1").merge_router(&router); // let router = router // .unshift(doc.into_router("/api-doc/openapi.json")) // .unshift( // Scalar::new("/api-doc/openapi.json") // .title("Palpo - Scalar") // .into_router("/scalar"), // ) // .unshift(SwaggerUi::new("/api-doc/openapi.json").into_router("/swagger-ui")); let catcher = Catcher::default().hoop(hoops::catch_status_error); let service = Service::new(router) .catcher(catcher) .hoop(hoops::default_accept_json) .hoop(Logger::new()) .hoop( Cors::new() .allow_origin(cors::Any) .allow_methods([ Method::GET, Method::POST, Method::PUT, Method::DELETE, Method::OPTIONS, ]) .allow_headers(AllowHeaders::list([ salvo::http::header::ACCEPT, salvo::http::header::CONTENT_TYPE, salvo::http::header::AUTHORIZATION, salvo::http::header::RANGE, ])) .max_age(Duration::from_secs(86400)) .into_handler(), ) .hoop(hoops::remove_json_utf8); let service = if conf.compression.is_enabled() { let mut compression = Compression::new(); if conf.compression.enable_brotli { compression = compression.enable_zstd(CompressionLevel::Fastest); } if conf.compression.enable_zstd { compression = compression.enable_zstd(CompressionLevel::Fastest); } if conf.compression.enable_gzip { compression = compression.enable_gzip(CompressionLevel::Fastest); } service.hoop(compression) } else { service }; let _ = crate::data::user::unset_all_presences(); salvo::http::request::set_global_secure_max_size(8 * 1024 * 1024); let conf = crate::config::get(); let mut acceptors = vec![]; for listener_conf in &conf.listeners { if let Some(tls_conf) = listener_conf.enabled_tls() { tracing::info!("Listening on: {} with TLS", listener_conf.address); let acceptor = TcpListener::new(&listener_conf.address) .rustls(RustlsConfig::new( Keycert::new() .cert_from_path(&tls_conf.cert)? .key_from_path(&tls_conf.key)?, )) .bind() .await .into_boxed(); acceptors.push(acceptor); } else { tracing::info!("Listening on: {}", listener_conf.address); let acceptor = TcpListener::new(&listener_conf.address) .bind() .await .into_boxed(); acceptors.push(acceptor); } } Server::new(DynTcpAcceptors::new(acceptors)) .serve(service) .instrument(tracing::info_span!("server.serve")) .await; Ok(()) }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/logging.rs
crates/server/src/logging.rs
pub mod capture; pub mod color; pub mod console; pub mod fmt; pub mod fmt_span; mod reload; mod suppress; use std::sync::{Arc, OnceLock}; use tracing_subscriber::{Layer, Registry, layer::SubscriberExt}; pub use capture::Capture; pub use console::{ConsoleFormat, ConsoleWriter, is_systemd_mode}; pub use reload::{LogLevelReloadHandles, ReloadHandle}; pub use suppress::Suppress; pub use tracing::Level; pub use tracing_core::{Event, Metadata}; pub use tracing_subscriber::EnvFilter; use crate::AppResult; pub static LOGGER: OnceLock<Logger> = OnceLock::new(); /// Logging subsystem. This is a singleton member of super::Server which holds /// all logging and tracing related state rather than shoving it all in /// super::Server directly. pub struct Logger { /// General log level reload handles. pub reload: LogLevelReloadHandles, /// Tracing capture state for ephemeral/oneshot uses. pub capture: std::sync::Arc<capture::State>, } impl std::fmt::Debug for Logger { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Logger").finish_non_exhaustive() } } pub fn init() -> AppResult<()> { let conf = &crate::config::get().logger; let reload_handles = LogLevelReloadHandles::default(); let console_span_events = fmt_span::from_str(&conf.span_events).expect("failed to parse span events"); let console_filter = EnvFilter::builder() .with_regex(conf.filter_regex) .parse(&conf.level) .expect("failed to parse log level"); let console_layer = tracing_subscriber::fmt::Layer::new() .with_ansi(conf.ansi_colors) .with_thread_ids(conf.thread_ids) .with_span_events(console_span_events) .event_format(ConsoleFormat::new(conf)) .fmt_fields(ConsoleFormat::new(conf)) .with_writer(ConsoleWriter::new(conf)); let (console_reload_filter, _console_reload_handle) = tracing_subscriber::reload::Layer::new(console_filter); // TODO: fix https://github.com/tokio-rs/tracing/pull/2956 // reload_handles.add("console", Box::new(console_reload_handle)); let cap_state = Arc::new(capture::State::new()); let cap_layer = capture::Layer::new(&cap_state); let subscriber = Registry::default() .with(console_layer.with_filter(console_reload_filter)) .with(cap_layer); tracing::subscriber::set_global_default(subscriber) .expect("the global default tracing subscriber failed to be initialized"); let logger = Logger { reload: reload_handles, capture: cap_state, }; LOGGER.set(logger).expect("logger should be set only once"); Ok(()) } pub fn get() -> &'static Logger { LOGGER.get().expect("Logger not initialized") } // // Wraps for logging macros. // #[macro_export] // #[collapse_debuginfo(yes)] // macro_rules! event { // ( $level:expr_2021, $($x:tt)+ ) => { ::tracing::event!( $level, $($x)+ ) } // } // #[macro_export] // macro_rules! error { // ( $($x:tt)+ ) => { ::tracing::error!( $($x)+ ) } // } // #[macro_export] // macro_rules! warn { // ( $($x:tt)+ ) => { ::tracing::warn!( $($x)+ ) } // } // #[macro_export] // macro_rules! info { // ( $($x:tt)+ ) => { ::tracing::info!( $($x)+ ) } // } // #[macro_export] // macro_rules! debug { // ( $($x:tt)+ ) => { ::tracing::debug!( $($x)+ ) } // } // #[macro_export] // macro_rules! trace { // ( $($x:tt)+ ) => { ::tracing::trace!( $($x)+ ) } // }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/sync_v5.rs
crates/server/src/sync_v5.rs
use std::cmp::Ordering; use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::sync::{Arc, LazyLock, Mutex}; use crate::core::Seqnum; use crate::core::client::filter::RoomEventFilter; use crate::core::client::sync_events::{self, v5::*}; use crate::core::device::DeviceLists; use crate::core::events::receipt::{SyncReceiptEvent, combine_receipt_event_contents}; use crate::core::events::room::member::{MembershipState, RoomMemberEventContent}; use crate::core::events::{AnyRawAccountDataEvent, StateEventType, TimelineEventType}; use crate::core::identifiers::*; use crate::event::BatchToken; use crate::event::ignored_filter; use crate::room::{self, filter_rooms, state, timeline}; use crate::sync_v3::{DEFAULT_BUMP_TYPES, TimelineData, share_encrypted_room}; use crate::{AppResult, data, extract_variant}; #[derive(Debug, Default)] struct SlidingSyncCache { lists: BTreeMap<String, sync_events::v5::ReqList>, subscriptions: BTreeMap<OwnedRoomId, sync_events::v5::RoomSubscription>, known_rooms: KnownRooms, // For every room, the room_since_sn number extensions: sync_events::v5::ExtensionsConfig, required_state: BTreeSet<Seqnum>, } static CONNECTIONS: LazyLock< Mutex<BTreeMap<(OwnedUserId, OwnedDeviceId, Option<String>), Arc<Mutex<SlidingSyncCache>>>>, > = LazyLock::new(Default::default); #[tracing::instrument(skip_all)] pub async fn sync_events( sender_id: &UserId, device_id: &DeviceId, since_sn: Seqnum, req_body: &SyncEventsReqBody, known_rooms: &KnownRooms, ) -> AppResult<SyncEventsResBody> { let curr_sn = data::curr_sn()?; crate::seqnum_reach(curr_sn).await; let next_batch = curr_sn + 1; if since_sn > curr_sn { return Ok(SyncEventsResBody::new(next_batch.to_string())); } let all_joined_rooms = data::user::joined_rooms(sender_id)?; let all_invited_rooms = data::user::invited_rooms(sender_id, 0)?; let all_invited_rooms: Vec<&RoomId> = all_invited_rooms.iter().map(|r| r.0.as_ref()).collect(); let all_knocked_rooms = data::user::knocked_rooms(sender_id, 0)?; let all_knocked_rooms: Vec<&RoomId> = all_knocked_rooms.iter().map(|r| r.0.as_ref()).collect(); let all_rooms: Vec<&RoomId> = all_joined_rooms .iter() .map(AsRef::as_ref) .chain(all_invited_rooms.iter().map(AsRef::as_ref)) .chain(all_knocked_rooms.iter().map(AsRef::as_ref)) .collect(); let all_joined_rooms = all_joined_rooms.iter().map(AsRef::as_ref).collect(); let all_invited_rooms = all_invited_rooms.iter().map(AsRef::as_ref).collect(); let mut todo_rooms: TodoRooms = BTreeMap::new(); let sync_info = SyncInfo { sender_id, device_id, since_sn, req_body, }; let mut res_body = SyncEventsResBody { txn_id: req_body.txn_id.clone(), pos: next_batch.to_string(), lists: BTreeMap::new(), rooms: BTreeMap::new(), extensions: Extensions { account_data: collect_account_data(sync_info)?, e2ee: collect_e2ee(sync_info, &all_joined_rooms)?, to_device: collect_to_device(sync_info, next_batch), receipts: collect_receipts(), typing: collect_typing(sync_info, next_batch, all_rooms.iter().cloned()).await?, }, }; process_lists( sync_info, &all_invited_rooms, &all_joined_rooms, &all_rooms, &mut todo_rooms, known_rooms, &mut res_body, ) .await; fetch_subscriptions(sync_info, &mut todo_rooms, known_rooms)?; res_body.rooms = process_rooms( sync_info, &all_invited_rooms, &todo_rooms, known_rooms, &mut res_body, ) .await?; Ok(res_body) } #[allow(clippy::too_many_arguments)] async fn process_lists( SyncInfo { sender_id, device_id, since_sn, req_body, }: SyncInfo<'_>, all_invited_rooms: &Vec<&RoomId>, all_joined_rooms: &Vec<&RoomId>, all_rooms: &Vec<&RoomId>, todo_rooms: &mut TodoRooms, known_rooms: &KnownRooms, res_body: &mut SyncEventsResBody, ) -> KnownRooms { for (list_id, list) in &req_body.lists { let active_rooms = match list.filters.clone().and_then(|f| f.is_invite) { Some(true) => all_invited_rooms, Some(false) => all_joined_rooms, None => all_rooms, }; let active_rooms = match list.filters.clone().map(|f| f.not_room_types) { Some(filter) if filter.is_empty() => active_rooms, Some(value) => &filter_rooms(active_rooms, &value, true), None => active_rooms, }; let mut new_known_rooms: BTreeSet<OwnedRoomId> = BTreeSet::new(); let mut ranges = list.ranges.clone(); if ranges.is_empty() { ranges.push((0, 50)); } for mut range in ranges { if range == (0, 0) { range.1 = active_rooms.len().min(range.0 + 19); } else { range.1 = range.1.clamp(range.0, active_rooms.len().max(range.0)); } let room_ids = active_rooms[range.0..range.1].to_vec(); let new_rooms: BTreeSet<OwnedRoomId> = room_ids.clone().into_iter().map(From::from).collect(); new_known_rooms.extend(new_rooms); //new_known_rooms.extend(room_ids..cloned()); for room_id in room_ids { let todo_room = todo_rooms.entry(room_id.to_owned()).or_insert(TodoRoom { required_state: BTreeSet::new(), timeline_limit: 0_usize, room_since_sn: since_sn, }); let limit = list.room_details.timeline_limit.min(100); todo_room.required_state.extend( list.room_details .required_state .iter() .map(|(ty, sk)| (ty.clone(), sk.as_str().into())), ); todo_room.timeline_limit = todo_room.timeline_limit.max(limit); todo_room.room_since_sn = todo_room.room_since_sn.min( known_rooms .get(list_id.as_str()) .and_then(|k| k.get(room_id)) .copied() .unwrap_or(since_sn), ); } } res_body.lists.insert( list_id.clone(), sync_events::v5::SyncList { count: active_rooms.len(), }, ); crate::sync_v5::update_sync_known_rooms( sender_id.to_owned(), device_id.to_owned(), req_body.conn_id.clone(), list_id.clone(), new_known_rooms, since_sn, ); } BTreeMap::default() } fn fetch_subscriptions( SyncInfo { sender_id, device_id, since_sn, req_body, }: SyncInfo<'_>, todo_rooms: &mut TodoRooms, known_rooms: &KnownRooms, ) -> AppResult<()> { let mut known_subscription_rooms = BTreeSet::new(); for (room_id, room) in &req_body.room_subscriptions { if !crate::room::room_exists(room_id)? { continue; } let todo_room = todo_rooms.entry(room_id.clone()).or_insert(TodoRoom::new( BTreeSet::new(), 0_usize, i64::MAX, )); let limit = room.timeline_limit; todo_room.required_state.extend( room.required_state .iter() .map(|(ty, sk)| (ty.clone(), sk.as_str().into())), ); todo_room.timeline_limit = todo_room.timeline_limit.max(limit as usize); todo_room.room_since_sn = todo_room.room_since_sn.min( known_rooms .get("subscriptions") .and_then(|k| k.get(room_id)) .copied() .unwrap_or(since_sn), ); known_subscription_rooms.insert(room_id.clone()); } // where this went (protomsc says it was removed) //for r in req_body.unsubscribe_rooms { // known_subscription_rooms.remove(&r); // req_body.room_subscriptions.remove(&r); //} crate::sync_v5::update_sync_known_rooms( sender_id.to_owned(), device_id.to_owned(), req_body.conn_id.clone(), "subscriptions".to_owned(), known_subscription_rooms, since_sn, ); Ok(()) } async fn process_rooms( SyncInfo { sender_id, req_body, device_id, .. }: SyncInfo<'_>, all_invited_rooms: &[&RoomId], todo_rooms: &TodoRooms, known_rooms: &KnownRooms, response: &mut SyncEventsResBody, ) -> AppResult<BTreeMap<OwnedRoomId, sync_events::v5::SyncRoom>> { let mut rooms = BTreeMap::new(); for ( room_id, TodoRoom { required_state, timeline_limit, room_since_sn, }, ) in todo_rooms { let mut timestamp: Option<_> = None; let mut invite_state = None; let new_room_id: &RoomId = (*room_id).as_ref(); let timeline = if all_invited_rooms.contains(&new_room_id) { // TODO: figure out a timestamp we can use for remote invites invite_state = crate::room::user::invite_state(sender_id, room_id).ok(); TimelineData { events: Default::default(), limited: false, prev_batch: None, next_batch: None, } } else { crate::sync_v3::load_timeline( sender_id, room_id, Some(BatchToken::new_live(*room_since_sn)), Some(BatchToken::LIVE_MAX), Some(&RoomEventFilter::with_limit(*timeline_limit)), )? }; if req_body.extensions.account_data.enabled == Some(true) { response.extensions.account_data.rooms.insert( room_id.to_owned(), data::user::data_changes(Some(room_id), sender_id, *room_since_sn, None)? .into_iter() .filter_map(|e| extract_variant!(e, AnyRawAccountDataEvent::Room)) .collect::<Vec<_>>(), ); } let last_private_read_update = data::room::receipt::last_private_read_update_sn(sender_id, room_id) .unwrap_or_default() > *room_since_sn; let private_read_event = if last_private_read_update { crate::room::receipt::last_private_read(sender_id, room_id).ok() } else { None }; let mut receipts = data::room::receipt::read_receipts(room_id, *room_since_sn)? .into_iter() .filter_map(|(read_user, content)| { if !crate::user::user_is_ignored(&read_user, sender_id) { Some(content) } else { None } }) .collect::<Vec<_>>(); if let Some(private_read_event) = private_read_event { receipts.push(private_read_event); } let receipt_size = receipts.len(); if receipt_size > 0 { response.extensions.receipts.rooms.insert( room_id.clone(), SyncReceiptEvent { content: combine_receipt_event_contents(receipts), }, ); } if room_since_sn != &0 && timeline.events.is_empty() && invite_state.is_none() && receipt_size == 0 { continue; } let prev_batch = timeline .events .first() .and_then(|(sn, _)| if *sn == 0 { None } else { Some(sn.to_string()) }); let room_events: Vec<_> = timeline .events .iter() .filter(|item| ignored_filter(*item, sender_id)) .map(|(_, pdu)| pdu.to_sync_room_event()) .collect(); for (_, pdu) in &timeline.events { let ts = pdu.origin_server_ts; if DEFAULT_BUMP_TYPES.binary_search(&pdu.event_ty).is_ok() && timestamp.is_none_or(|time| time <= ts) { timestamp = Some(ts); } } let required_state = required_state .iter() .filter_map(|state| { let state_key = match state.1.as_str() { "$LAZY" | "*" => return None, "$ME" => sender_id.as_str(), _ => state.1.as_str(), }; let pdu = room::get_state(room_id, &state.0, state_key, None); if let Ok(pdu) = &pdu { if is_required_state_send( sender_id.to_owned(), device_id.to_owned(), req_body.conn_id.clone(), pdu.event_sn, ) { None } else { mark_required_state_sent( sender_id.to_owned(), device_id.to_owned(), req_body.conn_id.clone(), pdu.event_sn, ); Some(pdu.to_sync_state_event()) } } else { pdu.map(|s| s.to_sync_state_event()).ok() } }) .collect::<Vec<_>>(); // Heroes let heroes: Vec<_> = room::get_members(room_id)? .into_iter() .filter(|member| *member != sender_id) .filter_map(|user_id| { room::get_member(room_id, &user_id, None) .ok() .map(|member| sync_events::v5::SyncRoomHero { user_id, name: member.display_name, avatar: member.avatar_url, }) }) .take(5) .collect(); let name = match heroes.len().cmp(&(1_usize)) { Ordering::Greater => { let firsts = heroes[1..] .iter() .map(|h: &SyncRoomHero| h.name.clone().unwrap_or_else(|| h.user_id.to_string())) .collect::<Vec<_>>() .join(", "); let last = heroes[0] .name .clone() .unwrap_or_else(|| heroes[0].user_id.to_string()); Some(format!("{firsts} and {last}")) } Ordering::Equal => Some( heroes[0] .name .clone() .unwrap_or_else(|| heroes[0].user_id.to_string()), ), Ordering::Less => None, }; let heroes_avatar = if heroes.len() == 1 { heroes[0].avatar.clone() } else { None }; let notify_summary = room::user::notify_summary(sender_id, room_id)?; rooms.insert( room_id.clone(), SyncRoom { name: room::get_name(room_id).ok().or(name), avatar: match heroes_avatar { Some(heroes_avatar) => Some(heroes_avatar), _ => room::get_avatar_url(room_id).ok().flatten(), }, initial: Some( room_since_sn == &0 || !known_rooms .values() .any(|rooms| rooms.contains_key(room_id)), ), is_dm: None, invite_state, unread_notifications: sync_events::UnreadNotificationsCount { notification_count: Some(notify_summary.all_notification_count()), highlight_count: Some(notify_summary.all_highlight_count()), }, timeline: room_events, required_state, prev_batch, limited: timeline.limited, joined_count: Some( crate::room::joined_member_count(room_id) .unwrap_or(0) .try_into() .unwrap_or(0), ), invited_count: Some( crate::room::invited_member_count(room_id) .unwrap_or(0) .try_into() .unwrap_or(0), ), num_live: None, // Count events in timeline greater than global sync counter bump_stamp: timestamp.map(|t| t.get() as i64), heroes: Some(heroes), }, ); } Ok(rooms) } fn collect_account_data( SyncInfo { sender_id, since_sn, req_body, .. }: SyncInfo<'_>, ) -> AppResult<sync_events::v5::AccountData> { let mut account_data = sync_events::v5::AccountData { global: Vec::new(), rooms: BTreeMap::new(), }; if !req_body.extensions.account_data.enabled.unwrap_or(false) { return Ok(sync_events::v5::AccountData::default()); } account_data.global = data::user::data_changes(None, sender_id, since_sn, None)? .into_iter() .filter_map(|e| extract_variant!(e, AnyRawAccountDataEvent::Global)) .collect(); if let Some(rooms) = &req_body.extensions.account_data.rooms { for room in rooms { account_data.rooms.insert( room.clone(), data::user::data_changes(Some(room), sender_id, since_sn, None)? .into_iter() .filter_map(|e| extract_variant!(e, AnyRawAccountDataEvent::Room)) .collect(), ); } } Ok(account_data) } fn collect_e2ee( SyncInfo { sender_id, device_id, since_sn, req_body, }: SyncInfo<'_>, all_joined_rooms: &Vec<&RoomId>, ) -> AppResult<sync_events::v5::E2ee> { if !req_body.extensions.e2ee.enabled.unwrap_or(false) { return Ok(sync_events::v5::E2ee::default()); } let mut left_encrypted_users = HashSet::new(); // Users that have left any encrypted rooms the sender was in let mut device_list_changes = HashSet::new(); let mut device_list_left = HashSet::new(); // Look for device list updates of this account device_list_changes.extend(data::user::keys_changed_users(sender_id, since_sn, None)?); for room_id in all_joined_rooms { let Ok(current_frame_id) = crate::room::get_frame_id(room_id, None) else { error!("Room {room_id} has no state"); continue; }; let since_frame_id = crate::event::get_last_frame_id(room_id, Some(since_sn)).ok(); let encrypted_room = state::get_state(current_frame_id, &StateEventType::RoomEncryption, "").is_ok(); if let Some(since_frame_id) = since_frame_id { // // Skip if there are only timeline changes // if since_frame_id == current_frame_id { // continue; // } let since_encryption = state::get_state(since_frame_id, &StateEventType::RoomEncryption, "").ok(); let joined_since_last_sync = room::user::join_sn(sender_id, room_id)? >= since_sn; let new_encrypted_room = encrypted_room && since_encryption.is_none(); if encrypted_room { let current_state_ids = state::get_full_state_ids(current_frame_id)?; let since_state_ids = state::get_full_state_ids(since_frame_id)?; for (key, id) in current_state_ids { if since_state_ids.get(&key) != Some(&id) { let Ok(pdu) = timeline::get_pdu(&id) else { error!("pdu in state not found: {id}"); continue; }; if pdu.event_ty == TimelineEventType::RoomMember && let Some(Ok(user_id)) = pdu.state_key.as_deref().map(UserId::parse) { if user_id == sender_id { continue; } let content: RoomMemberEventContent = pdu.get_content()?; match content.membership { MembershipState::Join => { // A new user joined an encrypted room if !share_encrypted_room(sender_id, &user_id, Some(room_id))? { device_list_changes.insert(user_id.to_owned()); } } MembershipState::Leave => { // Write down users that have left encrypted rooms we // are in left_encrypted_users.insert(user_id.to_owned()); } _ => {} } } } } if joined_since_last_sync || new_encrypted_room { // If the user is in a new encrypted room, give them all joined users device_list_changes.extend( room::get_members(room_id)? .into_iter() // Don't send key updates from the sender to the sender .filter(|user_id| sender_id != *user_id) // Only send keys if the sender doesn't share an encrypted room with the target // already .filter_map(|user_id| { if !share_encrypted_room(sender_id, &user_id, Some(room_id)) .unwrap_or(false) { Some(user_id.to_owned()) } else { None } }) .collect::<Vec<_>>(), ); } } } // Look for device list updates in this room device_list_changes.extend(crate::room::keys_changed_users(room_id, since_sn, None)?); } for user_id in left_encrypted_users { let Ok(share_encrypted_room) = share_encrypted_room(sender_id, &user_id, None) else { continue; }; // If the user doesn't share an encrypted room with the target anymore, we need // to tell them if !share_encrypted_room { device_list_left.insert(user_id); } } Ok(E2ee { device_lists: DeviceLists { changed: device_list_changes.into_iter().collect(), left: device_list_left.into_iter().collect(), }, device_one_time_keys_count: data::user::count_one_time_keys(sender_id, device_id)?, device_unused_fallback_key_types: None, }) } fn collect_to_device( SyncInfo { sender_id, device_id, since_sn, req_body, }: SyncInfo<'_>, next_batch: Seqnum, ) -> Option<sync_events::v5::ToDevice> { if !req_body.extensions.to_device.enabled.unwrap_or(false) { return None; } data::user::device::remove_to_device_events(sender_id, device_id, since_sn - 1).ok()?; let events = data::user::device::get_to_device_events(sender_id, device_id, None, Some(next_batch)) .ok()?; Some(sync_events::v5::ToDevice { next_batch: next_batch.to_string(), events, }) } fn collect_receipts() -> sync_events::v5::Receipts { sync_events::v5::Receipts { rooms: BTreeMap::new(), } // TODO: get explicitly requested read receipts } async fn collect_typing<'a, Rooms>( SyncInfo { req_body, .. }: SyncInfo<'_>, _next_batch: Seqnum, rooms: Rooms, ) -> AppResult<sync_events::v5::Typing> where Rooms: Iterator<Item = &'a RoomId> + Send + 'a, { use sync_events::v5::Typing; if !req_body.extensions.typing.enabled.unwrap_or(false) { return Ok(Typing::default()); } let mut typing = Typing::new(); for room_id in rooms { typing.rooms.insert( room_id.to_owned(), room::typing::all_typings(room_id).await?, ); } Ok(typing) } pub fn forget_sync_request_connection( user_id: OwnedUserId, device_id: OwnedDeviceId, conn_id: Option<String>, ) { CONNECTIONS .lock() .unwrap() .remove(&(user_id, device_id, conn_id)); } /// load params from cache if body doesn't contain it, as long as it's allowed /// in some cases we may need to allow an empty list as an actual value fn list_or_sticky<T: Clone>(target: &mut Vec<T>, cached: &Vec<T>) { if target.is_empty() { target.clone_from(cached); } } fn some_or_sticky<T>(target: &mut Option<T>, cached: Option<T>) { if target.is_none() { *target = cached; } } pub fn update_sync_request_with_cache( user_id: OwnedUserId, device_id: OwnedDeviceId, req_body: &mut sync_events::v5::SyncEventsReqBody, ) -> BTreeMap<String, BTreeMap<OwnedRoomId, i64>> { let mut cache = CONNECTIONS.lock().unwrap(); let cached = Arc::clone( cache .entry((user_id, device_id, req_body.conn_id.clone())) .or_default(), ); let cached = &mut cached.lock().unwrap(); drop(cache); for (list_id, list) in &mut req_body.lists { if let Some(cached_list) = cached.lists.get(list_id) { list_or_sticky( &mut list.room_details.required_state, &cached_list.room_details.required_state, ); // some_or_sticky(&mut list.include_heroes, cached_list.include_heroes); match (&mut list.filters, cached_list.filters.clone()) { (Some(filters), Some(cached_filters)) => { some_or_sticky(&mut filters.is_invite, cached_filters.is_invite); // TODO (morguldir): Find out how a client can unset this, probably need // to change into an option inside palpo list_or_sticky(&mut filters.not_room_types, &cached_filters.not_room_types); } (_, Some(cached_filters)) => list.filters = Some(cached_filters), (Some(list_filters), _) => list.filters = Some(list_filters.clone()), (..) => {} } } cached.lists.insert(list_id.clone(), list.clone()); } cached .subscriptions .extend(req_body.room_subscriptions.clone()); req_body .room_subscriptions .extend(cached.subscriptions.clone()); req_body.extensions.e2ee.enabled = req_body .extensions .e2ee .enabled .or(cached.extensions.e2ee.enabled); req_body.extensions.to_device.enabled = req_body .extensions .to_device .enabled .or(cached.extensions.to_device.enabled); req_body.extensions.account_data.enabled = req_body .extensions .account_data .enabled .or(cached.extensions.account_data.enabled); req_body.extensions.account_data.lists = req_body .extensions .account_data .lists .clone() .or(cached.extensions.account_data.lists.clone()); req_body.extensions.account_data.rooms = req_body .extensions .account_data .rooms .clone() .or(cached.extensions.account_data.rooms.clone()); some_or_sticky( &mut req_body.extensions.typing.enabled, cached.extensions.typing.enabled, ); some_or_sticky( &mut req_body.extensions.typing.rooms, cached.extensions.typing.rooms.clone(), ); some_or_sticky( &mut req_body.extensions.typing.lists, cached.extensions.typing.lists.clone(), ); some_or_sticky( &mut req_body.extensions.receipts.enabled, cached.extensions.receipts.enabled, ); some_or_sticky( &mut req_body.extensions.receipts.rooms, cached.extensions.receipts.rooms.clone(), ); some_or_sticky( &mut req_body.extensions.receipts.lists, cached.extensions.receipts.lists.clone(), ); cached.extensions = req_body.extensions.clone(); cached.known_rooms.clone() } pub fn update_sync_subscriptions( user_id: OwnedUserId, device_id: OwnedDeviceId, conn_id: Option<String>, subscriptions: BTreeMap<OwnedRoomId, sync_events::v5::RoomSubscription>, ) { let mut cache = CONNECTIONS.lock().unwrap(); let cached = Arc::clone(cache.entry((user_id, device_id, conn_id)).or_default()); let cached = &mut cached.lock().unwrap(); drop(cache); cached.subscriptions = subscriptions; } pub fn update_sync_known_rooms( user_id: OwnedUserId, device_id: OwnedDeviceId, conn_id: Option<String>, list_id: String, new_cached_rooms: BTreeSet<OwnedRoomId>, since_sn: i64, ) { let mut cache = CONNECTIONS.lock().unwrap(); let cached = Arc::clone(cache.entry((user_id, device_id, conn_id)).or_default()); let cached = &mut cached.lock().unwrap(); drop(cache); for (roomid, last_since) in cached .known_rooms .entry(list_id.clone()) .or_default() .iter_mut() { if !new_cached_rooms.contains(roomid) { *last_since = 0; } } let list = cached.known_rooms.entry(list_id).or_default(); for room_id in new_cached_rooms { list.insert(room_id, since_sn); } } pub fn mark_required_state_sent( user_id: OwnedUserId, device_id: OwnedDeviceId, conn_id: Option<String>, event_sn: Seqnum, ) { let mut cache = CONNECTIONS.lock().unwrap(); let cached = Arc::clone(cache.entry((user_id, device_id, conn_id)).or_default()); let cached = &mut cached.lock().unwrap(); drop(cache); cached.required_state.insert(event_sn); } pub fn is_required_state_send( user_id: OwnedUserId, device_id: OwnedDeviceId, conn_id: Option<String>, event_sn: Seqnum, ) -> bool { let cache = CONNECTIONS.lock().unwrap(); let Some(cached) = cache.get(&(user_id, device_id, conn_id)) else { return false; }; cached.lock().unwrap().required_state.contains(&event_sn) }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/server_key.rs
crates/server/src/server_key.rs
mod acquire; mod request; mod verify; use std::borrow::Borrow; use std::{collections::BTreeMap, time::Duration}; pub use acquire::*; use diesel::prelude::*; pub use request::*; use serde_json::value::RawValue as RawJsonValue; pub use verify::*; use crate::core::federation::discovery::{ServerSigningKeys, VerifyKey}; use crate::core::serde::{Base64, CanonicalJsonObject, JsonValue, RawJson}; use crate::core::signatures::{self, PublicKeyMap, PublicKeySet}; use crate::core::{ OwnedServerSigningKeyId, RoomVersionId, ServerName, ServerSigningKeyId, UnixMillis, room_version_rules::RoomVersionRules, }; use crate::data::connect; use crate::data::misc::DbServerSigningKeys; use crate::data::schema::*; use crate::utils::timepoint_from_now; use crate::{AppError, AppResult, config, exts::*}; pub type VerifyKeys = BTreeMap<OwnedServerSigningKeyId, VerifyKey>; pub type PubKeyMap = PublicKeyMap; pub type PubKeys = PublicKeySet; fn add_signing_keys(new_keys: ServerSigningKeys) -> AppResult<()> { let server: &palpo_core::OwnedServerName = &new_keys.server_name; // (timo) Not atomic, but this is not critical let keys = server_signing_keys::table .find(server) .select(server_signing_keys::key_data) .first::<JsonValue>(&mut connect()?) .optional()?; let mut keys = if let Some(keys) = keys { serde_json::from_value::<ServerSigningKeys>(keys)? } else { // Just insert "now", it doesn't matter ServerSigningKeys::new(server.to_owned(), UnixMillis::now()) }; keys.verify_keys.extend(new_keys.verify_keys); keys.old_verify_keys.extend(new_keys.old_verify_keys); diesel::insert_into(server_signing_keys::table) .values(DbServerSigningKeys { server_id: server.to_owned(), key_data: serde_json::to_value(&keys)?, updated_at: UnixMillis::now(), created_at: UnixMillis::now(), }) .on_conflict(server_signing_keys::server_id) .do_update() .set(( server_signing_keys::key_data.eq(serde_json::to_value(&keys)?), server_signing_keys::updated_at.eq(UnixMillis::now()), )) .execute(&mut connect()?)?; Ok(()) } pub fn verify_key_exists(server: &ServerName, key_id: &ServerSigningKeyId) -> AppResult<bool> { type KeysMap<'a> = BTreeMap<&'a str, &'a RawJsonValue>; let key_data = server_signing_keys::table .filter(server_signing_keys::server_id.eq(server)) .select(server_signing_keys::key_data) .first::<JsonValue>(&mut connect()?) .optional()?; let Some(keys) = key_data else { return Ok(false); }; let keys: RawJson<ServerSigningKeys> = RawJson::from_value(&keys)?; if let Ok(Some(verify_keys)) = keys.get_field::<KeysMap<'_>>("verify_keys") && verify_keys.contains_key(&key_id.as_str()) { return Ok(true); } if let Ok(Some(old_verify_keys)) = keys.get_field::<KeysMap<'_>>("old_verify_keys") && old_verify_keys.contains_key(&key_id.as_str()) { return Ok(true); } Ok(false) } pub fn verify_keys_for(server: &ServerName) -> VerifyKeys { let mut keys = signing_keys_for(server) .map(|keys| merge_old_keys(keys).verify_keys) .unwrap_or_default(); if !server.is_remote() { let keypair = config::keypair(); let verify_key = VerifyKey { key: Base64::new(keypair.public_key().to_vec()), }; let id = format!("ed25519:{}", keypair.version()); let verify_keys: VerifyKeys = [(id.try_into().expect("should work"), verify_key)].into(); keys.extend(verify_keys); } keys } pub fn signing_keys_for(server: &ServerName) -> AppResult<ServerSigningKeys> { let key_data = server_signing_keys::table .filter(server_signing_keys::server_id.eq(server)) .select(server_signing_keys::key_data) .first::<JsonValue>(&mut connect()?)?; Ok(serde_json::from_value(key_data)?) } fn minimum_valid_ts() -> UnixMillis { let timepoint = timepoint_from_now(Duration::from_secs(3600)).expect("SystemTime should not overflow"); UnixMillis::from_system_time(timepoint).expect("UInt should not overflow") } fn merge_old_keys(mut keys: ServerSigningKeys) -> ServerSigningKeys { keys.verify_keys.extend( keys.old_verify_keys .clone() .into_iter() .map(|(key_id, old)| (key_id, VerifyKey::new(old.key))), ); keys } fn extract_key(mut keys: ServerSigningKeys, key_id: &ServerSigningKeyId) -> Option<VerifyKey> { keys.verify_keys.remove(key_id).or_else(|| { keys.old_verify_keys .remove(key_id) .map(|old| VerifyKey::new(old.key)) }) } fn key_exists(keys: &ServerSigningKeys, key_id: &ServerSigningKeyId) -> bool { keys.verify_keys.contains_key(key_id) || keys.old_verify_keys.contains_key(key_id) } pub async fn get_event_keys( object: &CanonicalJsonObject, version: &RoomVersionRules, ) -> AppResult<PubKeyMap> { let required = match signatures::required_keys(object, version) { Ok(required) => required, Err(e) => { return Err(AppError::public(format!( "failed to determine keys required to verify: {e}" ))); } }; let batch = required .iter() .map(|(s, ids)| (s.borrow(), ids.iter().map(Borrow::borrow))); Ok(get_pubkeys(batch).await) } pub async fn get_pubkeys<'a, S, K>(batch: S) -> PubKeyMap where S: Iterator<Item = (&'a ServerName, K)> + Send, K: Iterator<Item = &'a ServerSigningKeyId> + Send, { let mut keys = PubKeyMap::new(); for (server, key_ids) in batch { let pubkeys = get_pubkeys_for(server, key_ids).await; keys.insert(server.into(), pubkeys); } keys } pub async fn get_pubkeys_for<'a, I>(origin: &ServerName, key_ids: I) -> PubKeys where I: Iterator<Item = &'a ServerSigningKeyId> + Send, { let mut keys = PubKeys::new(); for key_id in key_ids { if let Ok(verify_key) = get_verify_key(origin, key_id).await { keys.insert(key_id.into(), verify_key.key); } } keys } pub async fn get_verify_key( origin: &ServerName, key_id: &ServerSigningKeyId, ) -> AppResult<VerifyKey> { let notary_first = crate::config::get().query_trusted_key_servers_first; let notary_only = crate::config::get().only_query_trusted_key_servers; if let Some(result) = verify_keys_for(origin).remove(key_id) { return Ok(result); } if notary_first && let Ok(result) = get_verify_key_from_notaries(origin, key_id).await { return Ok(result); } if !notary_only && let Ok(result) = get_verify_key_from_origin(origin, key_id).await { return Ok(result); } if !notary_first && let Ok(result) = get_verify_key_from_notaries(origin, key_id).await { return Ok(result); } tracing::error!(?key_id, ?origin, "failed to fetch federation signing-key"); Err(AppError::public("failed to fetch federation signing-key")) } async fn get_verify_key_from_notaries( origin: &ServerName, key_id: &ServerSigningKeyId, ) -> AppResult<VerifyKey> { for notary in &crate::config::get().trusted_servers { if let Ok(server_keys) = notary_request(notary, origin).await { for server_key in server_keys.clone() { add_signing_keys(server_key)?; } for server_key in server_keys { if let Some(result) = extract_key(server_key, key_id) { return Ok(result); } } } } Err(AppError::public( "failed to fetch signing-key from notaries", )) } async fn get_verify_key_from_origin( origin: &ServerName, key_id: &ServerSigningKeyId, ) -> AppResult<VerifyKey> { if let Ok(server_key) = server_request(origin).await { add_signing_keys(server_key.clone())?; if let Some(result) = extract_key(server_key, key_id) { return Ok(result); } } Err(AppError::public("failed to fetch signing-key from origin")) } pub fn sign_json(object: &mut CanonicalJsonObject) -> AppResult<()> { signatures::sign_json( config::get().server_name.as_str(), config::keypair(), object, ) .map_err(Into::into) } pub fn hash_and_sign_event( object: &mut CanonicalJsonObject, room_version: &RoomVersionId, ) -> AppResult<()> { let version_rules = crate::room::get_version_rules(room_version)?; signatures::hash_and_sign_event( config::get().server_name.as_str(), config::keypair(), object, &version_rules.redaction, )?; Ok(()) }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/uiaa.rs
crates/server/src/uiaa.rs
use std::collections::BTreeMap; use std::sync::LazyLock; use diesel::prelude::*; use super::LazyRwLock; use crate::SESSION_ID_LENGTH; use crate::core::client::uiaa::{ AuthData, AuthError, AuthType, Password, UiaaInfo, UserIdentifier, }; use crate::core::identifiers::*; use crate::core::serde::CanonicalJsonValue; use crate::core::serde::JsonValue; use crate::data::connect; use crate::data::schema::*; use crate::{AppResult, MatrixError, data, utils}; static UIAA_REQUESTS: LazyRwLock< BTreeMap<(OwnedUserId, OwnedDeviceId, String), CanonicalJsonValue>, > = LazyLock::new(Default::default); /// Creates a new Uiaa session. Make sure the session token is unique. pub fn create_session( user_id: &UserId, device_id: &DeviceId, uiaa_info: &UiaaInfo, json_body: CanonicalJsonValue, ) -> AppResult<()> { set_uiaa_request( user_id, device_id, uiaa_info.session.as_ref().expect("session should be set"), // TODO: better session error handling (why is it optional in palpo?) json_body, ); update_session( user_id, device_id, uiaa_info.session.as_ref().expect("session should be set"), Some(uiaa_info), ) } pub fn update_session( user_id: &UserId, device_id: &DeviceId, session: &str, uiaa_info: Option<&UiaaInfo>, ) -> AppResult<()> { if let Some(uiaa_info) = uiaa_info { let uiaa_info = serde_json::to_value(uiaa_info)?; diesel::insert_into(user_uiaa_datas::table) .values(( user_uiaa_datas::user_id.eq(user_id), user_uiaa_datas::device_id.eq(device_id), user_uiaa_datas::session.eq(session), user_uiaa_datas::uiaa_info.eq(&uiaa_info), )) .on_conflict(( user_uiaa_datas::user_id, user_uiaa_datas::device_id, user_uiaa_datas::session, )) .do_update() .set(user_uiaa_datas::uiaa_info.eq(&uiaa_info)) .execute(&mut connect()?)?; } else { diesel::delete( user_uiaa_datas::table .filter(user_uiaa_datas::user_id.eq(user_id)) .filter(user_uiaa_datas::device_id.eq(user_id)) .filter(user_uiaa_datas::session.eq(session)), ) .execute(&mut connect()?)?; }; Ok(()) } pub fn get_session(user_id: &UserId, device_id: &DeviceId, session: &str) -> AppResult<UiaaInfo> { let uiaa_info = user_uiaa_datas::table .filter(user_uiaa_datas::user_id.eq(user_id)) .filter(user_uiaa_datas::device_id.eq(device_id)) .filter(user_uiaa_datas::session.eq(session)) .select(user_uiaa_datas::uiaa_info) .first::<JsonValue>(&mut connect()?)?; Ok(serde_json::from_value(uiaa_info)?) } pub fn try_auth( user_id: &UserId, device_id: &DeviceId, auth: &AuthData, uiaa_info: &UiaaInfo, ) -> AppResult<(bool, UiaaInfo)> { let mut uiaa_info = auth .session() .map(|session| get_session(user_id, device_id, session)) .unwrap_or_else(|| Ok(uiaa_info.clone()))?; if uiaa_info.session.is_none() { uiaa_info.session = Some(utils::random_string(SESSION_ID_LENGTH)); } let conf = crate::config::get(); match auth { // Find out what the user completed AuthData::Password(Password { identifier, password, .. }) => { let username = match identifier { UserIdentifier::UserIdOrLocalpart(username) => username, _ => { return Err(MatrixError::unauthorized("identifier type not recognized.").into()); } }; let auth_user_id = UserId::parse_with_server_name(username.clone(), &conf.server_name) .map_err(|_| MatrixError::unauthorized("User ID is invalid."))?; if user_id != auth_user_id { return Err(MatrixError::forbidden("User ID does not match.", None).into()); } let Ok(user) = data::user::get_user(&auth_user_id) else { return Err(MatrixError::unauthorized("user not found.").into()); }; crate::user::verify_password(&user, password)?; } AuthData::RegistrationToken(t) => { if Some(t.token.trim()) == conf.registration_token.as_deref() { uiaa_info.completed.push(AuthType::RegistrationToken); } else { uiaa_info.auth_error = Some(AuthError::forbidden("Invalid registration token.", None)); return Ok((false, uiaa_info)); } } AuthData::Dummy(_) => { uiaa_info.completed.push(AuthType::Dummy); } k => error!("type not supported: {:?}", k), } // Check if a flow now succeeds let mut completed = false; 'flows: for flow in &mut uiaa_info.flows { for stage in &flow.stages { if !uiaa_info.completed.contains(stage) { continue 'flows; } } // We didn't break, so this flow succeeded! completed = true; } if !completed { crate::uiaa::update_session( user_id, device_id, uiaa_info.session.as_ref().expect("session is always set"), Some(&uiaa_info), )?; return Ok((false, uiaa_info)); } // UIAA was successful! Remove this session and return true crate::uiaa::update_session( user_id, device_id, uiaa_info.session.as_ref().expect("session is always set"), None, )?; Ok((true, uiaa_info)) } pub fn set_uiaa_request( user_id: &UserId, device_id: &DeviceId, session: &str, request: CanonicalJsonValue, ) { UIAA_REQUESTS .write() .expect("write UIAA_REQUESTS failed") .insert( (user_id.to_owned(), device_id.to_owned(), session.to_owned()), request, ); } pub fn get_uiaa_request( user_id: &UserId, device_id: &DeviceId, session: &str, ) -> Option<CanonicalJsonValue> { UIAA_REQUESTS .read() .expect("read UIAA_REQUESTS failed") .get(&(user_id.to_owned(), device_id.to_owned(), session.to_owned())) .cloned() }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/room.rs
crates/server/src/room.rs
use std::collections::HashSet; use std::sync::OnceLock; use diesel::prelude::*; use serde::de::DeserializeOwned; use crate::appservice::RegistrationInfo; use crate::core::directory::RoomTypeFilter; use crate::core::events::StateEventType; use crate::core::events::room::avatar::RoomAvatarEventContent; use crate::core::events::room::canonical_alias::RoomCanonicalAliasEventContent; use crate::core::events::room::create::RoomCreateEventContent; use crate::core::events::room::encryption::RoomEncryptionEventContent; use crate::core::events::room::guest_access::{GuestAccess, RoomGuestAccessEventContent}; use crate::core::events::room::history_visibility::{ HistoryVisibility, RoomHistoryVisibilityEventContent, }; use crate::core::events::room::join_rule::RoomJoinRulesEventContent; use crate::core::events::room::member::{MembershipState, RoomMemberEventContent}; use crate::core::events::room::name::RoomNameEventContent; use crate::core::events::room::power_levels::{RoomPowerLevels, RoomPowerLevelsEventContent}; use crate::core::events::room::topic::RoomTopicEventContent; use crate::core::identifiers::*; use crate::core::room::{JoinRule, RoomType}; use crate::core::room_version_rules::RoomVersionRules; use crate::core::state::events::RoomCreateEvent; use crate::core::{Seqnum, UnixMillis}; use crate::data::room::{DbRoomCurrent, NewDbRoom}; use crate::data::schema::*; use crate::data::{connect, diesel_exists}; use crate::{ APPSERVICE_IN_ROOM_CACHE, AppError, AppResult, IsRemoteOrLocal, RoomMutexGuard, RoomMutexMap, SnPduEvent, config, data, membership, room, utils, }; pub mod alias; pub use alias::*; pub mod auth_chain; mod current; pub mod directory; pub mod lazy_loading; pub mod pdu_metadata; pub mod receipt; pub mod space; pub mod state; pub mod timeline; pub mod typing; pub mod user; pub use current::*; pub mod push_action; pub mod thread; pub use state::get_room_frame_id as get_frame_id; pub async fn lock_state(room_id: &RoomId) -> RoomMutexGuard { static ROOM_STATE_MUTEX: OnceLock<RoomMutexMap> = OnceLock::new(); ROOM_STATE_MUTEX .get_or_init(Default::default) .lock(room_id) .await } pub fn create_room(new_room: NewDbRoom) -> AppResult<OwnedRoomId> { diesel::insert_into(rooms::table) .values(&new_room) .execute(&mut connect()?)?; Ok(new_room.id) } pub fn ensure_room(id: &RoomId, room_version_id: &RoomVersionId) -> AppResult<OwnedRoomId> { if room_exists(id)? { Ok(id.to_owned()) } else { create_room(NewDbRoom { id: id.to_owned(), version: room_version_id.to_string(), is_public: false, min_depth: 0, has_auth_chain_index: false, created_at: UnixMillis::now(), }) } } /// Checks if a room exists. pub fn room_exists(room_id: &RoomId) -> AppResult<bool> { diesel_exists!(rooms::table.filter(rooms::id.eq(room_id)), &mut connect()?).map_err(Into::into) } pub fn get_room_sn(room_id: &RoomId) -> AppResult<Seqnum> { let room_sn = rooms::table .filter(rooms::id.eq(room_id)) .select(rooms::sn) .first::<Seqnum>(&mut connect()?)?; Ok(room_sn) } /// Returns the room's version. pub fn get_version(room_id: &RoomId) -> AppResult<RoomVersionId> { if let Some(room_version) = rooms::table .find(room_id) .select(rooms::version) .first::<String>(&mut connect()?) .optional()? { return Ok(RoomVersionId::try_from(&*room_version)?); } let create_event_content = get_state_content::<RoomCreateEventContent>( room_id, &StateEventType::RoomCreate, "", None, )?; Ok(create_event_content.room_version) } pub fn get_current_frame_id(room_id: &RoomId) -> AppResult<Option<i64>> { rooms::table .find(room_id) .select(rooms::state_frame_id) .first(&mut connect()?) .optional() .map(|v| v.flatten()) .map_err(Into::into) } pub fn is_disabled(room_id: &RoomId) -> AppResult<bool> { rooms::table .filter(rooms::id.eq(room_id)) .select(rooms::disabled) .first(&mut connect()?) .map_err(Into::into) } pub fn disable_room(room_id: &RoomId, disabled: bool) -> AppResult<()> { diesel::update(rooms::table.filter(rooms::id.eq(room_id))) .set(rooms::disabled.eq(disabled)) .execute(&mut connect()?) .map(|_| ()) .map_err(Into::into) } pub fn update_currents(room_id: &RoomId) -> AppResult<()> { let joined_members = room_users::table .filter(room_users::room_id.eq(room_id)) .filter(room_users::membership.eq("join")) .count() .get_result::<i64>(&mut connect()?)?; let invited_members = room_users::table .filter(room_users::room_id.eq(room_id)) .filter(room_users::membership.eq("invite")) .count() .get_result::<i64>(&mut connect()?)?; let left_members = room_users::table .filter(room_users::room_id.eq(room_id)) .filter(room_users::membership.eq("leave")) .count() .get_result::<i64>(&mut connect()?)?; let banned_members = room_users::table .filter(room_users::room_id.eq(room_id)) .filter(room_users::membership.eq("banned")) .count() .get_result::<i64>(&mut connect()?)?; let knocked_members = room_users::table .filter(room_users::room_id.eq(room_id)) .filter(room_users::membership.eq("knocked")) .count() .get_result::<i64>(&mut connect()?)?; let current = DbRoomCurrent { room_id: room_id.to_owned(), state_events: 0, //TODO: fixme joined_members, invited_members, left_members, banned_members, knocked_members, local_users_in_room: 0, //TODO: fixme completed_delta_stream_id: 0, //TODO: fixme }; diesel::insert_into(stats_room_currents::table) .values(&current) .on_conflict(stats_room_currents::room_id) .do_update() .set(&current) .execute(&mut connect()?)?; Ok(()) } pub fn update_joined_servers(room_id: &RoomId) -> AppResult<()> { let joined_servers = room_users::table .filter(room_users::room_id.eq(room_id)) .filter(room_users::membership.eq("join")) .select(room_users::user_id) .distinct() .load::<OwnedUserId>(&mut connect()?)? .into_iter() .map(|user_id| user_id.server_name().to_owned()) .collect::<HashSet<OwnedServerName>>() .into_iter() .collect::<Vec<_>>(); diesel::delete( room_joined_servers::table .filter(room_joined_servers::room_id.eq(room_id)) .filter(room_joined_servers::server_id.ne_all(&joined_servers)), ) .execute(&mut connect()?)?; for joined_server in joined_servers { data::room::add_joined_server(room_id, &joined_server)?; } Ok(()) } pub fn get_our_real_users(room_id: &RoomId) -> AppResult<Vec<OwnedUserId>> { room_users::table .filter(room_users::room_id.eq(room_id)) .select(room_users::user_id) .load::<OwnedUserId>(&mut connect()?) .map_err(Into::into) } pub fn appservice_in_room(room_id: &RoomId, appservice: &RegistrationInfo) -> AppResult<bool> { let maybe = APPSERVICE_IN_ROOM_CACHE .read() .unwrap() .get(room_id) .and_then(|map| map.get(&appservice.registration.id)) .copied(); if let Some(b) = maybe { Ok(b) } else { let bridge_user_id = UserId::parse_with_server_name( appservice.registration.sender_localpart.as_str(), &config::get().server_name, ) .ok(); let in_room = bridge_user_id.is_some_and(|id| user::is_joined(&id, room_id).unwrap_or(false)) || { let user_ids = room_users::table .filter(room_users::room_id.eq(room_id)) .select(room_users::user_id) .load::<String>(&mut connect()?)?; user_ids .iter() .any(|user_id| appservice.users.is_match(user_id.as_str())) }; APPSERVICE_IN_ROOM_CACHE .write() .unwrap() .entry(room_id.to_owned()) .or_default() .insert(appservice.registration.id.clone(), in_room); Ok(in_room) } } pub fn is_room_exists(room_id: &RoomId) -> AppResult<bool> { diesel_exists!( rooms::table.filter(rooms::id.eq(room_id)).select(rooms::id), &mut connect()? ) .map_err(Into::into) } pub async fn should_join_on_remote_servers( sender_id: &UserId, room_id: &RoomId, servers: &[OwnedServerName], ) -> AppResult<(bool, Vec<OwnedServerName>)> { if room_id.is_local() { return Ok((false, vec![])); } if !is_server_joined(&config::get().server_name, room_id).unwrap_or(false) { return Ok((true, servers.to_vec())); } let Ok(join_rule) = room::get_join_rule(room_id) else { return Ok((true, servers.to_vec())); }; if !join_rule.is_restricted() { return Ok((false, servers.to_vec())); } let users = membership::get_users_can_issue_invite(room_id, sender_id, &join_rule.restriction_rooms()) .await?; let mut allowed_servers = crate::get_servers_from_users(&users); if let Ok(room_server) = room_id.server_name() { let room_server = room_server.to_owned(); if !allowed_servers.contains(&room_server) { allowed_servers.push(room_server); } } Ok((true, allowed_servers)) } pub fn is_server_joined(server: &ServerName, room_id: &RoomId) -> AppResult<bool> { let query = room_joined_servers::table .filter(room_joined_servers::room_id.eq(room_id)) .filter(room_joined_servers::server_id.eq(server)); diesel_exists!(query, &mut connect()?).map_err(Into::into) } pub fn joined_servers(room_id: &RoomId) -> AppResult<Vec<OwnedServerName>> { room_joined_servers::table .filter(room_joined_servers::room_id.eq(room_id)) .select(room_joined_servers::server_id) .load::<OwnedServerName>(&mut connect()?) .map_err(Into::into) } pub fn has_any_other_server(room_id: &RoomId, server: &ServerName) -> AppResult<bool> { let query = room_joined_servers::table .filter(room_joined_servers::room_id.eq(room_id)) .filter(room_joined_servers::server_id.ne(server)); diesel_exists!(query, &mut connect()?).map_err(Into::into) } #[tracing::instrument(level = "trace")] pub fn lookup_servers(room_id: &RoomId) -> AppResult<Vec<OwnedServerName>> { room_lookup_servers::table .filter(room_lookup_servers::room_id.eq(room_id)) .select(room_lookup_servers::server_id) .load::<OwnedServerName>(&mut connect()?) .map_err(Into::into) } pub fn joined_member_count(room_id: &RoomId) -> AppResult<u64> { stats_room_currents::table .find(room_id) .select(stats_room_currents::joined_members) .first::<i64>(&mut connect()?) .optional() .map(|c| c.unwrap_or_default() as u64) .map_err(Into::into) } #[tracing::instrument] pub fn invited_member_count(room_id: &RoomId) -> AppResult<u64> { stats_room_currents::table .find(room_id) .select(stats_room_currents::invited_members) .first::<i64>(&mut connect()?) .optional() .map(|c| c.unwrap_or_default() as u64) .map_err(Into::into) } pub fn joined_users(room_id: &RoomId, until_sn: Option<i64>) -> AppResult<Vec<OwnedUserId>> { get_state_users(room_id, &MembershipState::Join, until_sn) } pub fn invited_users(room_id: &RoomId, until_sn: Option<i64>) -> AppResult<Vec<OwnedUserId>> { get_state_users(room_id, &MembershipState::Invite, until_sn) } pub fn active_local_users_in_room(room_id: &RoomId) -> AppResult<Vec<OwnedUserId>> { // TODO: only active user? Ok(get_state_users(room_id, &MembershipState::Join, None)? .into_iter() .filter(|user_id| user_id.is_local()) .collect()) } pub fn list_banned_rooms() -> AppResult<Vec<OwnedRoomId>> { let room_ids = banned_rooms::table .select(banned_rooms::room_id) .load(&mut connect()?)?; Ok(room_ids) } pub fn get_state_users( room_id: &RoomId, state: &MembershipState, until_sn: Option<i64>, ) -> AppResult<Vec<OwnedUserId>> { if let Some(until_sn) = until_sn { room_users::table .filter(room_users::event_sn.le(until_sn)) .filter(room_users::room_id.eq(room_id)) .filter(room_users::membership.eq(state.to_string())) .select(room_users::user_id) .load(&mut connect()?) .map_err(Into::into) } else { room_users::table .filter(room_users::room_id.eq(room_id)) .filter(room_users::membership.eq(state.to_string())) .select(room_users::user_id) .load(&mut connect()?) .map_err(Into::into) } } pub fn server_name(room_id: &RoomId) -> AppResult<OwnedServerName> { if let Ok(server_name) = room_id.server_name() { return Ok(server_name.to_owned()); } let create_event = get_create(room_id)?; Ok(create_event.creator()?.server_name().to_owned()) } /// Returns an list of all servers participating in this room. pub fn participating_servers( room_id: &RoomId, include_self_server: bool, ) -> AppResult<Vec<OwnedServerName>> { if include_self_server { room_joined_servers::table .filter(room_joined_servers::room_id.eq(room_id)) .select(room_joined_servers::server_id) .load(&mut connect()?) .map_err(Into::into) } else { room_joined_servers::table .filter(room_joined_servers::room_id.eq(room_id)) .filter(room_joined_servers::server_id.ne(config::server_name())) .select(room_joined_servers::server_id) .load(&mut connect()?) .map_err(Into::into) } } pub fn admin_servers( room_id: &RoomId, include_self_server: bool, ) -> AppResult<Vec<OwnedServerName>> { let power_levels = get_state_content::<RoomPowerLevelsEventContent>( room_id, &StateEventType::RoomPowerLevels, "", None, )?; let mut admin_servers = power_levels .users .iter() .filter(|(_, level)| **level > power_levels.users_default) .map(|(user_id, _)| user_id.server_name()) .collect::<HashSet<_>>(); if !include_self_server { admin_servers.remove(config::server_name()); } Ok(admin_servers.into_iter().map(|s| s.to_owned()).collect()) } pub fn public_room_ids() -> AppResult<Vec<OwnedRoomId>> { rooms::table .filter(rooms::is_public.eq(true)) .select(rooms::id) .order_by(rooms::sn.desc()) .load(&mut connect()?) .map_err(Into::into) } pub fn all_room_ids() -> AppResult<Vec<OwnedRoomId>> { rooms::table .select(rooms::id) .load(&mut connect()?) .map_err(Into::into) } pub fn filter_rooms<'a>( rooms: &[&'a RoomId], filter: &[RoomTypeFilter], negate: bool, ) -> Vec<&'a RoomId> { rooms .iter() .filter_map(|r| { let r = *r; let room_type = get_room_type(r).ok()?; let room_type_filter = RoomTypeFilter::from(room_type); let include = if negate { !filter.contains(&room_type_filter) } else { filter.is_empty() || filter.contains(&room_type_filter) }; include.then_some(r) }) .collect() } pub async fn room_available_servers( room_id: &RoomId, room_alias: &RoomAliasId, pre_servers: Vec<OwnedServerName>, ) -> AppResult<Vec<OwnedServerName>> { // find active servers in room state cache to suggest let mut servers: Vec<OwnedServerName> = joined_servers(room_id)?; // push any servers we want in the list already (e.g. responded remote alias // servers, room alias server itself) servers.extend(pre_servers); servers.sort_unstable(); servers.dedup(); // shuffle list of servers randomly after sort and dedup utils::shuffle(&mut servers); // insert our server as the very first choice if in list, else check if we can // prefer the room alias server first match servers .iter() .position(|server_name| server_name.is_local()) { Some(server_index) => { servers.swap_remove(server_index); servers.insert(0, config::get().server_name.to_owned()); } _ => { if let Some(alias_server_index) = servers .iter() .position(|server| server == room_alias.server_name()) { servers.swap_remove(alias_server_index); servers.insert(0, room_alias.server_name().into()); } } } Ok(servers) } pub fn get_state( room_id: &RoomId, event_type: &StateEventType, state_key: &str, until_sn: Option<Seqnum>, ) -> AppResult<SnPduEvent> { let frame_id = get_frame_id(room_id, until_sn)?; state::get_state(frame_id, event_type, state_key) } pub fn get_state_content<T>( room_id: &RoomId, event_type: &StateEventType, state_key: &str, until_sn: Option<Seqnum>, ) -> AppResult<T> where T: DeserializeOwned, { let frame_id = get_frame_id(room_id, until_sn)?; state::get_state_content(frame_id, event_type, state_key) } pub fn get_create(room_id: &RoomId) -> AppResult<RoomCreateEvent<SnPduEvent>> { get_state(room_id, &StateEventType::RoomCreate, "", None).map(RoomCreateEvent::new) } pub fn get_name(room_id: &RoomId) -> AppResult<String> { get_state_content::<RoomNameEventContent>(room_id, &StateEventType::RoomName, "", None) .map(|c| c.name) } pub fn get_avatar_url(room_id: &RoomId) -> AppResult<Option<OwnedMxcUri>> { get_state_content::<RoomAvatarEventContent>(room_id, &StateEventType::RoomAvatar, "", None) .map(|c| c.url) } pub fn get_member( room_id: &RoomId, user_id: &UserId, until_sn: Option<Seqnum>, ) -> AppResult<RoomMemberEventContent> { get_state_content::<RoomMemberEventContent>( room_id, &StateEventType::RoomMember, user_id.as_str(), until_sn, ) } pub fn get_topic(room_id: &RoomId) -> AppResult<String> { get_topic_content(room_id).map(|c| c.topic) } pub fn get_topic_content(room_id: &RoomId) -> AppResult<RoomTopicEventContent> { get_state_content::<RoomTopicEventContent>(room_id, &StateEventType::RoomTopic, "", None) } pub fn get_canonical_alias(room_id: &RoomId) -> AppResult<Option<OwnedRoomAliasId>> { get_state_content::<RoomCanonicalAliasEventContent>( room_id, &StateEventType::RoomCanonicalAlias, "", None, ) .map(|c| c.alias) } pub fn get_join_rule(room_id: &RoomId) -> AppResult<JoinRule> { get_state_content::<RoomJoinRulesEventContent>( room_id, &StateEventType::RoomJoinRules, "", None, ) .map(|c| c.join_rule) } pub async fn get_power_levels(room_id: &RoomId) -> AppResult<RoomPowerLevels> { let create = get_create(room_id)?; let room_version = create.room_version()?; let version_rules = crate::room::get_version_rules(&room_version)?; let creators = create.creators()?; let content = get_power_levels_event_content(room_id)?; let power_levels = RoomPowerLevels::new(content.into(), &version_rules.authorization, creators); Ok(power_levels) } pub fn get_power_levels_event_content(room_id: &RoomId) -> AppResult<RoomPowerLevelsEventContent> { get_state_content::<RoomPowerLevelsEventContent>( room_id, &StateEventType::RoomPowerLevels, "", None, ) } pub fn get_room_type(room_id: &RoomId) -> AppResult<Option<RoomType>> { get_state_content::<RoomCreateEventContent>(room_id, &StateEventType::RoomCreate, "", None) .map(|c| c.room_type) } pub fn get_history_visibility(room_id: &RoomId) -> AppResult<HistoryVisibility> { get_state_content::<RoomHistoryVisibilityEventContent>( room_id, &StateEventType::RoomHistoryVisibility, "", None, ) .map(|c| c.history_visibility) } pub fn is_world_readable(room_id: &RoomId) -> bool { get_history_visibility(room_id) .map(|visibility| visibility == HistoryVisibility::WorldReadable) .unwrap_or(false) } pub fn guest_can_join(room_id: &RoomId) -> bool { get_state_content::<RoomGuestAccessEventContent>( room_id, &StateEventType::RoomGuestAccess, "", None, ) .map(|c| c.guest_access == GuestAccess::CanJoin) .unwrap_or(false) } pub async fn user_can_invite(room_id: &RoomId, sender_id: &UserId, _target_user: &UserId) -> bool { if let Ok(create_event) = crate::room::get_create(room_id) && let Ok(creators) = create_event.creators() && creators.contains(sender_id) { return true; } if let Ok(power_levels) = get_power_levels(room_id).await { power_levels.user_can_invite(sender_id) } else { false } } pub fn get_encryption(room_id: &RoomId) -> AppResult<EventEncryptionAlgorithm> { get_state_content(room_id, &StateEventType::RoomEncryption, "", None) .map(|content: RoomEncryptionEventContent| content.algorithm) } pub fn is_encrypted(room_id: &RoomId) -> bool { get_state(room_id, &StateEventType::RoomEncryption, "", None).is_ok() } /// Gets the room ID of the admin room /// /// Errors are propagated from the database, and will have None if there is no admin room pub fn get_admin_room() -> AppResult<OwnedRoomId> { crate::room::resolve_local_alias(config::admin_alias()) } pub fn is_admin_room(room_id: &RoomId) -> AppResult<bool> { let result = get_admin_room(); match result { Ok(admin_room_id) => Ok(admin_room_id == room_id), Err(e) => { if e.is_not_found() { Ok(false) } else { Err(e) } } } } /// Returns an iterator of all our local users in the room, even if they're /// deactivated/guests #[tracing::instrument(level = "debug")] // TODO: local? pub fn local_users_in_room(room_id: &RoomId) -> AppResult<Vec<OwnedUserId>> { room_users::table .filter(room_users::room_id.eq(room_id)) .filter(room_users::user_server_id.eq(&config::get().server_name)) .select(room_users::user_id) .load::<OwnedUserId>(&mut connect()?) .map_err(Into::into) } /// Returns an iterator of all our local users in the room, even if they're /// deactivated/guests #[tracing::instrument(level = "debug")] pub fn get_members(room_id: &RoomId) -> AppResult<Vec<OwnedUserId>> { room_users::table .filter(room_users::room_id.eq(room_id)) .select(room_users::user_id) .load::<OwnedUserId>(&mut connect()?) .map_err(Into::into) } pub fn keys_changed_users( room_id: &RoomId, since_sn: i64, until_sn: Option<i64>, ) -> AppResult<Vec<OwnedUserId>> { if let Some(until_sn) = until_sn { e2e_key_changes::table .filter(e2e_key_changes::room_id.eq(room_id)) .filter(e2e_key_changes::occur_sn.ge(since_sn)) .filter(e2e_key_changes::occur_sn.le(until_sn)) .select(e2e_key_changes::user_id) .load::<OwnedUserId>(&mut connect()?) .map_err(Into::into) } else { e2e_key_changes::table .filter(e2e_key_changes::room_id.eq(room_id.as_str())) .filter(e2e_key_changes::occur_sn.ge(since_sn)) .select(e2e_key_changes::user_id) .load::<OwnedUserId>(&mut connect()?) .map_err(Into::into) } } pub fn ban_room(room_id: &RoomId, banned: bool) -> AppResult<()> { if banned { diesel::insert_into(banned_rooms::table) .values(( banned_rooms::room_id.eq(room_id), banned_rooms::created_at.eq(UnixMillis::now()), )) .on_conflict_do_nothing() .execute(&mut connect()?) .map(|_| ()) .map_err(Into::into) } else { diesel::delete(banned_rooms::table.filter(banned_rooms::room_id.eq(room_id))) .execute(&mut connect()?) .map(|_| ()) .map_err(Into::into) } } pub fn get_version_rules(room_version: &RoomVersionId) -> AppResult<RoomVersionRules> { room_version.rules().ok_or_else(|| { AppError::public(format!( "Cannot verify event for unknown room version {room_version:?}." )) }) }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false
palpo-im/palpo
https://github.com/palpo-im/palpo/blob/066b5b15ce094d4e9f6d28484cbc9cb8bd913e67/crates/server/src/directory.rs
crates/server/src/directory.rs
use crate::core::ServerName; use crate::core::directory::{ PublicRoomFilter, PublicRoomJoinRule, PublicRoomsChunk, PublicRoomsResBody, RoomNetwork, }; use crate::core::events::StateEventType; use crate::core::events::room::join_rule::RoomJoinRulesEventContent; use crate::core::federation::directory::{PublicRoomsReqBody, public_rooms_request}; use crate::core::room::JoinRule; use crate::exts::*; use crate::{AppError, AppResult, MatrixError, config, room}; pub async fn get_public_rooms( server: Option<&ServerName>, limit: Option<usize>, since: Option<&str>, filter: &PublicRoomFilter, network: &RoomNetwork, ) -> AppResult<PublicRoomsResBody> { if let Some(other_server) = server.filter(|server| *server != config::get().server_name.as_str()) { let body = public_rooms_request( &other_server.origin().await, PublicRoomsReqBody { limit, since: since.map(ToOwned::to_owned), filter: PublicRoomFilter { generic_search_term: filter.generic_search_term.clone(), room_types: filter.room_types.clone(), }, room_network: RoomNetwork::Matrix, }, )? .send() .await?; Ok(body) } else { get_local_public_rooms(limit, since, filter, network) } } fn get_local_public_rooms( limit: Option<usize>, since: Option<&str>, filter: &PublicRoomFilter, _network: &RoomNetwork, ) -> AppResult<PublicRoomsResBody> { let limit = limit.unwrap_or(10); let mut num_since = 0_u64; if let Some(s) = &since { let mut characters = s.chars(); let backwards = match characters.next() { Some('n') => false, Some('p') => true, _ => return Err(MatrixError::invalid_param("Invalid `since` token").into()), }; num_since = characters .collect::<String>() .parse() .map_err(|_| MatrixError::invalid_param("Invalid `since` token."))?; if backwards { num_since = num_since.saturating_sub(limit as u64); } } let search_term = filter .generic_search_term .as_ref() .map(|q| q.to_lowercase()); let public_room_ids = room::public_room_ids()?; let mut all_rooms: Vec<_> = public_room_ids .into_iter() .map(|room_id| { let chunk = PublicRoomsChunk { canonical_alias: room::get_canonical_alias(&room_id).ok().flatten(), name: room::get_name(&room_id).ok(), num_joined_members: room::joined_member_count(&room_id).unwrap_or_else(|_| { warn!("Room {} has no member count", room_id); 0 }), topic: room::get_topic(&room_id).ok(), world_readable: room::is_world_readable(&room_id), guest_can_join: room::guest_can_join(&room_id), avatar_url: room::get_avatar_url(&room_id).ok().flatten(), join_rule: room::get_state_content::<RoomJoinRulesEventContent>( &room_id, &StateEventType::RoomJoinRules, "", None, ) .map(|c| match c.join_rule { JoinRule::Public => Some(PublicRoomJoinRule::Public), JoinRule::Knock => Some(PublicRoomJoinRule::Knock), JoinRule::KnockRestricted(..) => Some(PublicRoomJoinRule::KnockRestricted), _ => None, })? .ok_or_else(|| AppError::public("Missing room join rule event for room."))?, room_type: room::get_room_type(&room_id).ok().flatten(), room_id, }; Ok(chunk) }) .filter_map(|r: AppResult<_>| r.ok()) // Filter out buggy rooms .filter(|chunk| { if let Some(search_term) = &search_term { if let Some(name) = &chunk.name && name.as_str().to_lowercase().contains(search_term) { return true; } if let Some(topic) = &chunk.topic && topic.to_lowercase().contains(search_term) { return true; } if let Some(canonical_alias) = &chunk.canonical_alias && canonical_alias .as_str() .to_lowercase() .contains(search_term) { return true; } false } else { // No search term true } }) // We need to collect all, so we can sort by member count .collect(); all_rooms.sort_by(|l, r| r.num_joined_members.cmp(&l.num_joined_members)); let total_room_count_estimate = (all_rooms.len() as u32).into(); let chunk: Vec<_> = all_rooms .into_iter() .skip(num_since as usize) .take(limit) .collect(); let prev_batch = if num_since == 0 { None } else { Some(format!("p{num_since}")) }; let next_batch = if chunk.len() < limit { None } else { Some(format!("n{}", num_since + limit as u64)) }; Ok(PublicRoomsResBody { chunk, prev_batch, next_batch, total_room_count_estimate: Some(total_room_count_estimate), }) }
rust
Apache-2.0
066b5b15ce094d4e9f6d28484cbc9cb8bd913e67
2026-01-04T20:22:21.242775Z
false