| 1 | use std::sync::Arc; |
| 2 | |
| 3 | use axum::{ |
| 4 | Router, |
| 5 | extract::{DefaultBodyLimit, Multipart, Query, State}, |
| 6 | http::{HeaderMap, StatusCode}, |
| 7 | middleware, |
| 8 | response::{IntoResponse, Response, Sse, sse::Event as SseEvent}, |
| 9 | routing::{get, post}, |
| 10 | }; |
| 11 | use futures_util::StreamExt; |
| 12 | use macltok::Retain; |
| 13 | use malice_core::{ |
| 14 | feed::subscribe, |
| 15 | login::LoginInput, |
| 16 | request::{Reply, Request, dispatch}, |
| 17 | }; |
| 18 | use serde::{Deserialize, Serialize}; |
| 19 | use tower_http::{ |
| 20 | services::{ServeDir, ServeFile}, |
| 21 | trace::TraceLayer, |
| 22 | }; |
| 23 | |
| 24 | use crate::{ |
| 25 | csrf::{csrf_guard, session_sid, set_cookie_value}, |
| 26 | error::{ApiError, json_ok, no_content}, |
| 27 | state::{AppState, RestoreError, UserSession}, |
| 28 | }; |
| 29 | |
| 30 | #[derive(Debug, Deserialize)] |
| 31 | struct RoomIdBody { |
| 32 | #[serde(default)] |
| 33 | room_id: String, |
| 34 | } |
| 35 | |
| 36 | #[derive(Debug, Deserialize)] |
| 37 | struct SendBody { |
| 38 | #[serde(default)] |
| 39 | room_id: String, |
| 40 | #[serde(default)] |
| 41 | body: String, |
| 42 | #[serde(default)] |
| 43 | formatted_body: Option<String>, |
| 44 | #[serde(default)] |
| 45 | reply_to: Option<String>, |
| 46 | #[serde(default)] |
| 47 | mentions: Vec<String>, |
| 48 | #[serde(default)] |
| 49 | emote: bool, |
| 50 | } |
| 51 | |
| 52 | #[derive(Debug, Deserialize)] |
| 53 | struct PaginateBody { |
| 54 | #[serde(default)] |
| 55 | room_id: String, |
| 56 | } |
| 57 | |
| 58 | #[derive(Debug, Deserialize)] |
| 59 | struct JoinBody { |
| 60 | #[serde(default)] |
| 61 | room: String, |
| 62 | } |
| 63 | |
| 64 | #[derive(Debug, Deserialize)] |
| 65 | struct CreateBody { |
| 66 | #[serde(default)] |
| 67 | name: String, |
| 68 | #[serde(default)] |
| 69 | topic: Option<String>, |
| 70 | } |
| 71 | |
| 72 | #[derive(Debug, Deserialize)] |
| 73 | struct ReactBody { |
| 74 | #[serde(default)] |
| 75 | room_id: String, |
| 76 | #[serde(default)] |
| 77 | event_id: String, |
| 78 | #[serde(default)] |
| 79 | key: String, |
| 80 | #[serde(default)] |
| 81 | shortcode: Option<String>, |
| 82 | } |
| 83 | |
| 84 | #[derive(Debug, Deserialize)] |
| 85 | struct EditBody { |
| 86 | #[serde(default)] |
| 87 | room_id: String, |
| 88 | #[serde(default)] |
| 89 | event_id: String, |
| 90 | #[serde(default)] |
| 91 | body: String, |
| 92 | #[serde(default)] |
| 93 | formatted_body: Option<String>, |
| 94 | #[serde(default)] |
| 95 | mentions: Vec<String>, |
| 96 | } |
| 97 | |
| 98 | #[derive(Debug, Deserialize)] |
| 99 | struct ReadBody { |
| 100 | #[serde(default)] |
| 101 | room_id: String, |
| 102 | #[serde(default)] |
| 103 | event_id: String, |
| 104 | } |
| 105 | |
| 106 | #[derive(Debug, Deserialize)] |
| 107 | struct MembersQuery { |
| 108 | #[serde(default)] |
| 109 | room_id: String, |
| 110 | } |
| 111 | #[derive(Debug, Deserialize)] |
| 112 | struct RecoverBody { |
| 113 | recovery_key: String, |
| 114 | } |
| 115 | |
| 116 | #[derive(Debug, Deserialize)] |
| 117 | struct VerifyBody { |
| 118 | action: String, |
| 119 | } |
| 120 | |
| 121 | #[derive(Debug, Deserialize)] |
| 122 | struct MediaQuery { |
| 123 | mxc: String, |
| 124 | } |
| 125 | #[derive(Debug, Deserialize)] |
| 126 | struct MessageMediaQuery { |
| 127 | media_id: String, |
| 128 | size: String, |
| 129 | } |
| 130 | |
| 131 | #[derive(Debug, Deserialize)] |
| 132 | struct TypingBody { |
| 133 | #[serde(default)] |
| 134 | room_id: String, |
| 135 | #[serde(default)] |
| 136 | typing: bool, |
| 137 | } |
| 138 | |
| 139 | #[derive(Debug, Deserialize)] |
| 140 | struct AccountDataQuery { |
| 141 | event_type: String, |
| 142 | } |
| 143 | |
| 144 | #[derive(Debug, Deserialize)] |
| 145 | struct UrlPreviewQuery { |
| 146 | #[serde(default)] |
| 147 | room_id: String, |
| 148 | #[serde(default)] |
| 149 | url: String, |
| 150 | } |
| 151 | |
| 152 | #[derive(Debug, Deserialize)] |
| 153 | struct AccountDataBody { |
| 154 | event_type: String, |
| 155 | content: serde_json::Value, |
| 156 | } |
| 157 | |
| 158 | #[derive(Debug, Serialize)] |
| 159 | struct SoftLogoutInfo { |
| 160 | user_id: String, |
| 161 | homeserver: String, |
| 162 | } |
| 163 | |
| 164 | #[derive(Debug, Serialize)] |
| 165 | struct SessionResponse { |
| 166 | user_id: Option<String>, |
| 167 | #[serde(skip_serializing_if = "Option::is_none")] |
| 168 | soft_logout: Option<SoftLogoutInfo>, |
| 169 | } |
| 170 | |
| 171 | async fn auth( |
| 172 | state: &AppState, |
| 173 | headers: &HeaderMap, |
| 174 | ) -> Result<(Arc<UserSession>, String), ApiError> { |
| 175 | let Some(sid) = session_sid(headers) else { |
| 176 | return Err(ApiError::unauthorized("not signed in")); |
| 177 | }; |
| 178 | match state.get_or_restore(&sid).await { |
| 179 | Ok(user) => Ok((user, sid)), |
| 180 | Err(RestoreError::NotFound) => Err(ApiError::unauthorized_stale( |
| 181 | "session expired; sign in again", |
| 182 | state.cookie_secure(), |
| 183 | )), |
| 184 | Err(RestoreError::SoftLoggedOut { .. }) => Err(ApiError::unauthorized( |
| 185 | "signed out by the server, sign in again", |
| 186 | )), |
| 187 | Err(RestoreError::Stale(message)) => { |
| 188 | state.remove_session(&sid, Retain::Nothing).await; |
| 189 | Err(ApiError::unauthorized_stale(message, state.cookie_secure())) |
| 190 | } |
| 191 | Err(RestoreError::Unavailable(message)) => { |
| 192 | Err(ApiError::new(StatusCode::BAD_GATEWAY, message)) |
| 193 | } |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | /// commands answer when they're done, so the browser gets the outcome in the response |
| 198 | fn respond(result: Result<Reply, malice_core::error::CoreError>) -> Response { |
| 199 | match result { |
| 200 | Ok(Reply::Done) => no_content(None), |
| 201 | Ok(Reply::Json(value)) => json_ok(&value, None), |
| 202 | Ok(Reply::Avatar { |
| 203 | bytes, |
| 204 | content_type, |
| 205 | }) => ( |
| 206 | [ |
| 207 | (axum::http::header::CONTENT_TYPE, content_type), |
| 208 | // mxc uris name immutable content, a changed avatar gets a new uri |
| 209 | ( |
| 210 | axum::http::header::CACHE_CONTROL, |
| 211 | "private, max-age=31536000, immutable", |
| 212 | ), |
| 213 | (axum::http::header::X_CONTENT_TYPE_OPTIONS, "nosniff"), |
| 214 | ], |
| 215 | bytes, |
| 216 | ) |
| 217 | .into_response(), |
| 218 | Ok(Reply::Attachment { |
| 219 | bytes, |
| 220 | content_type, |
| 221 | }) => ( |
| 222 | [ |
| 223 | ( |
| 224 | axum::http::header::CONTENT_TYPE, |
| 225 | content_type.unwrap_or("application/octet-stream"), |
| 226 | ), |
| 227 | ( |
| 228 | axum::http::header::CONTENT_DISPOSITION, |
| 229 | if content_type.is_some() { |
| 230 | "inline" |
| 231 | } else { |
| 232 | "attachment" |
| 233 | }, |
| 234 | ), |
| 235 | (axum::http::header::CACHE_CONTROL, "private, max-age=3600"), |
| 236 | (axum::http::header::X_CONTENT_TYPE_OPTIONS, "nosniff"), |
| 237 | (axum::http::header::CONTENT_SECURITY_POLICY, "sandbox"), |
| 238 | ], |
| 239 | bytes, |
| 240 | ) |
| 241 | .into_response(), |
| 242 | Err(error) => ApiError::from(error).into_response(), |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | async fn get_session(State(state): State<AppState>, headers: HeaderMap) -> Response { |
| 247 | let Some(sid) = session_sid(&headers) else { |
| 248 | return json_ok( |
| 249 | &SessionResponse { |
| 250 | user_id: None, |
| 251 | soft_logout: None, |
| 252 | }, |
| 253 | None, |
| 254 | ); |
| 255 | }; |
| 256 | match state.get_or_restore(&sid).await { |
| 257 | Ok(user) => json_ok( |
| 258 | &SessionResponse { |
| 259 | user_id: Some(user.user_id.clone()), |
| 260 | soft_logout: None, |
| 261 | }, |
| 262 | None, |
| 263 | ), |
| 264 | Err(RestoreError::NotFound) => json_ok( |
| 265 | &SessionResponse { |
| 266 | user_id: None, |
| 267 | soft_logout: None, |
| 268 | }, |
| 269 | None, |
| 270 | ), |
| 271 | Err(RestoreError::SoftLoggedOut { |
| 272 | user_id, |
| 273 | homeserver, |
| 274 | }) => json_ok( |
| 275 | &SessionResponse { |
| 276 | user_id: None, |
| 277 | soft_logout: Some(SoftLogoutInfo { |
| 278 | user_id, |
| 279 | homeserver, |
| 280 | }), |
| 281 | }, |
| 282 | None, |
| 283 | ), |
| 284 | Err(RestoreError::Stale(message)) => { |
| 285 | state.remove_session(&sid, Retain::Nothing).await; |
| 286 | ApiError::unauthorized_stale(message, state.cookie_secure()).into_response() |
| 287 | } |
| 288 | Err(RestoreError::Unavailable(message)) => { |
| 289 | ApiError::new(StatusCode::BAD_GATEWAY, message).into_response() |
| 290 | } |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | async fn post_login( |
| 295 | State(state): State<AppState>, |
| 296 | headers: HeaderMap, |
| 297 | body: axum::Json<LoginInput>, |
| 298 | ) -> Response { |
| 299 | let username = body.0.username.trim().to_owned(); |
| 300 | let password = body.0.password.clone(); |
| 301 | let login = match body.0.into_login(state.allow_http_homeserver()) { |
| 302 | Ok(login) => login, |
| 303 | Err(error) => return ApiError::from(error).into_response(), |
| 304 | }; |
| 305 | let cookie_sid = session_sid(&headers); |
| 306 | match state |
| 307 | .login(cookie_sid.as_deref(), login, &username, password) |
| 308 | .await |
| 309 | { |
| 310 | Ok(user) => json_ok( |
| 311 | &serde_json::json!({ "user_id": user.user_id }), |
| 312 | Some(set_cookie_value(&user.sid, state.cookie_secure())), |
| 313 | ), |
| 314 | Err(error) => ApiError::from(error).into_response(), |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | async fn post_logout(State(state): State<AppState>, headers: HeaderMap) -> Response { |
| 319 | if let Some(sid) = session_sid(&headers) { |
| 320 | state.logout(&sid).await; |
| 321 | } |
| 322 | let mut response = no_content(Some(crate::csrf::clear_cookie_value(state.cookie_secure()))); |
| 323 | response.headers_mut().insert( |
| 324 | axum::http::header::HeaderName::from_static("clear-site-data"), |
| 325 | axum::http::HeaderValue::from_static("\"cache\""), |
| 326 | ); |
| 327 | response |
| 328 | } |
| 329 | |
| 330 | async fn get_rooms(State(state): State<AppState>, headers: HeaderMap) -> Response { |
| 331 | let (user, _) = match auth(&state, &headers).await { |
| 332 | Ok(pair) => pair, |
| 333 | Err(error) => return error.into_response(), |
| 334 | }; |
| 335 | respond(dispatch(&user.handle, &user.mirror, Request::Rooms).await) |
| 336 | } |
| 337 | |
| 338 | async fn get_members( |
| 339 | State(state): State<AppState>, |
| 340 | headers: HeaderMap, |
| 341 | Query(query): Query<MembersQuery>, |
| 342 | ) -> Response { |
| 343 | let (user, _) = match auth(&state, &headers).await { |
| 344 | Ok(pair) => pair, |
| 345 | Err(error) => return error.into_response(), |
| 346 | }; |
| 347 | respond( |
| 348 | dispatch( |
| 349 | &user.handle, |
| 350 | &user.mirror, |
| 351 | Request::Members { |
| 352 | room_id: query.room_id, |
| 353 | }, |
| 354 | ) |
| 355 | .await, |
| 356 | ) |
| 357 | } |
| 358 | |
| 359 | async fn rooms_open( |
| 360 | State(state): State<AppState>, |
| 361 | headers: HeaderMap, |
| 362 | body: axum::Json<RoomIdBody>, |
| 363 | ) -> Response { |
| 364 | let (user, _) = match auth(&state, &headers).await { |
| 365 | Ok(pair) => pair, |
| 366 | Err(error) => return error.into_response(), |
| 367 | }; |
| 368 | respond( |
| 369 | dispatch( |
| 370 | &user.handle, |
| 371 | &user.mirror, |
| 372 | Request::Open { |
| 373 | room_id: body.0.room_id, |
| 374 | }, |
| 375 | ) |
| 376 | .await, |
| 377 | ) |
| 378 | } |
| 379 | |
| 380 | async fn rooms_close( |
| 381 | State(state): State<AppState>, |
| 382 | headers: HeaderMap, |
| 383 | body: axum::Json<RoomIdBody>, |
| 384 | ) -> Response { |
| 385 | let (user, _) = match auth(&state, &headers).await { |
| 386 | Ok(pair) => pair, |
| 387 | Err(error) => return error.into_response(), |
| 388 | }; |
| 389 | respond( |
| 390 | dispatch( |
| 391 | &user.handle, |
| 392 | &user.mirror, |
| 393 | Request::Close { |
| 394 | room_id: body.0.room_id, |
| 395 | }, |
| 396 | ) |
| 397 | .await, |
| 398 | ) |
| 399 | } |
| 400 | |
| 401 | async fn rooms_send( |
| 402 | State(state): State<AppState>, |
| 403 | headers: HeaderMap, |
| 404 | body: axum::Json<SendBody>, |
| 405 | ) -> Response { |
| 406 | let (user, _) = match auth(&state, &headers).await { |
| 407 | Ok(pair) => pair, |
| 408 | Err(error) => return error.into_response(), |
| 409 | }; |
| 410 | respond( |
| 411 | dispatch( |
| 412 | &user.handle, |
| 413 | &user.mirror, |
| 414 | Request::Send { |
| 415 | room_id: body.0.room_id, |
| 416 | body: body.0.body, |
| 417 | formatted_body: body.0.formatted_body, |
| 418 | reply_to: body.0.reply_to, |
| 419 | mentions: body.0.mentions, |
| 420 | emote: body.0.emote, |
| 421 | }, |
| 422 | ) |
| 423 | .await, |
| 424 | ) |
| 425 | } |
| 426 | |
| 427 | async fn rooms_upload( |
| 428 | State(state): State<AppState>, |
| 429 | headers: HeaderMap, |
| 430 | mut upload: Multipart, |
| 431 | ) -> Response { |
| 432 | let (user, _) = match auth(&state, &headers).await { |
| 433 | Ok(pair) => pair, |
| 434 | Err(error) => return error.into_response(), |
| 435 | }; |
| 436 | let mut room_id = None; |
| 437 | let mut caption = None; |
| 438 | let mut formatted_caption = None; |
| 439 | let mut reply_to = None; |
| 440 | let mut mentions = Vec::new(); |
| 441 | let mut file = None; |
| 442 | loop { |
| 443 | let field = match upload.next_field().await { |
| 444 | Ok(Some(field)) => field, |
| 445 | Ok(None) => break, |
| 446 | Err(_) => return ApiError::bad_request("invalid upload form").into_response(), |
| 447 | }; |
| 448 | match field.name() { |
| 449 | Some("room_id") if room_id.is_none() => { |
| 450 | room_id = match field.text().await { |
| 451 | Ok(value) => Some(value), |
| 452 | Err(_) => return ApiError::bad_request("invalid room_id").into_response(), |
| 453 | }; |
| 454 | } |
| 455 | Some("caption") if caption.is_none() => { |
| 456 | caption = match field.text().await { |
| 457 | Ok(value) => Some(value), |
| 458 | Err(_) => return ApiError::bad_request("invalid caption").into_response(), |
| 459 | }; |
| 460 | } |
| 461 | Some("formatted_caption") if formatted_caption.is_none() => { |
| 462 | formatted_caption = match field.text().await { |
| 463 | Ok(value) => Some(value), |
| 464 | Err(_) => return ApiError::bad_request("invalid caption").into_response(), |
| 465 | }; |
| 466 | } |
| 467 | Some("reply_to") if reply_to.is_none() => { |
| 468 | reply_to = match field.text().await { |
| 469 | Ok(value) => Some(value), |
| 470 | Err(_) => return ApiError::bad_request("invalid reply_to").into_response(), |
| 471 | }; |
| 472 | } |
| 473 | Some("mentions") => match field.text().await { |
| 474 | Ok(value) => mentions.push(value), |
| 475 | Err(_) => return ApiError::bad_request("invalid mention").into_response(), |
| 476 | }, |
| 477 | Some("file") if file.is_none() => { |
| 478 | let filename = field.file_name().unwrap_or("attachment").to_owned(); |
| 479 | let mimetype = field |
| 480 | .content_type() |
| 481 | .unwrap_or("application/octet-stream") |
| 482 | .to_owned(); |
| 483 | let bytes = match field.bytes().await { |
| 484 | Ok(bytes) => bytes, |
| 485 | Err(_) => return ApiError::bad_request("invalid file").into_response(), |
| 486 | }; |
| 487 | if bytes.is_empty() || bytes.len() > 20 * 1024 * 1024 { |
| 488 | return ApiError::bad_request("file must be between 1 byte and 20 MiB") |
| 489 | .into_response(); |
| 490 | } |
| 491 | file = Some((filename, mimetype, bytes)); |
| 492 | } |
| 493 | _ => return ApiError::bad_request("unexpected upload field").into_response(), |
| 494 | } |
| 495 | } |
| 496 | let Some(room_id) = room_id else { |
| 497 | return ApiError::bad_request("room_id is required").into_response(); |
| 498 | }; |
| 499 | let Some((filename, mimetype, bytes)) = file else { |
| 500 | return ApiError::bad_request("file is required").into_response(); |
| 501 | }; |
| 502 | respond( |
| 503 | dispatch( |
| 504 | &user.handle, |
| 505 | &user.mirror, |
| 506 | Request::Upload { |
| 507 | room_id, |
| 508 | filename, |
| 509 | mimetype, |
| 510 | caption, |
| 511 | formatted_caption, |
| 512 | reply_to, |
| 513 | mentions, |
| 514 | bytes: bytes.to_vec(), |
| 515 | }, |
| 516 | ) |
| 517 | .await, |
| 518 | ) |
| 519 | } |
| 520 | |
| 521 | /// Ops added after the per-route handlers, taken as the core request JSON. Anything |
| 522 | /// carrying bytes or reading state stays on its own route. |
| 523 | async fn post_command( |
| 524 | State(state): State<AppState>, |
| 525 | headers: HeaderMap, |
| 526 | body: axum::Json<Request>, |
| 527 | ) -> Response { |
| 528 | let (user, _) = match auth(&state, &headers).await { |
| 529 | Ok(pair) => pair, |
| 530 | Err(error) => return error.into_response(), |
| 531 | }; |
| 532 | let request = body.0; |
| 533 | if !matches!( |
| 534 | request, |
| 535 | Request::Kick { .. } |
| 536 | | Request::Ban { .. } |
| 537 | | Request::Unban { .. } |
| 538 | | Request::SetPowerLevel { .. } |
| 539 | | Request::SetDisplayName { .. } |
| 540 | | Request::SetAvatar { .. } |
| 541 | | Request::Invite { .. } |
| 542 | | Request::Direct { .. } |
| 543 | | Request::Redact { .. } |
| 544 | ) { |
| 545 | return ApiError::bad_request("op is not available as a command").into_response(); |
| 546 | } |
| 547 | respond(dispatch(&user.handle, &user.mirror, request).await) |
| 548 | } |
| 549 | |
| 550 | async fn profile_avatar( |
| 551 | State(state): State<AppState>, |
| 552 | headers: HeaderMap, |
| 553 | bytes: axum::body::Bytes, |
| 554 | ) -> Response { |
| 555 | let (user, _) = match auth(&state, &headers).await { |
| 556 | Ok(pair) => pair, |
| 557 | Err(error) => return error.into_response(), |
| 558 | }; |
| 559 | respond( |
| 560 | dispatch( |
| 561 | &user.handle, |
| 562 | &user.mirror, |
| 563 | Request::UploadAvatar { |
| 564 | bytes: bytes.to_vec(), |
| 565 | }, |
| 566 | ) |
| 567 | .await, |
| 568 | ) |
| 569 | } |
| 570 | |
| 571 | async fn rooms_paginate( |
| 572 | State(state): State<AppState>, |
| 573 | headers: HeaderMap, |
| 574 | body: axum::Json<PaginateBody>, |
| 575 | ) -> Response { |
| 576 | let (user, _) = match auth(&state, &headers).await { |
| 577 | Ok(pair) => pair, |
| 578 | Err(error) => return error.into_response(), |
| 579 | }; |
| 580 | respond( |
| 581 | dispatch( |
| 582 | &user.handle, |
| 583 | &user.mirror, |
| 584 | Request::Paginate { |
| 585 | room_id: body.0.room_id, |
| 586 | }, |
| 587 | ) |
| 588 | .await, |
| 589 | ) |
| 590 | } |
| 591 | |
| 592 | async fn rooms_join( |
| 593 | State(state): State<AppState>, |
| 594 | headers: HeaderMap, |
| 595 | body: axum::Json<JoinBody>, |
| 596 | ) -> Response { |
| 597 | let (user, _) = match auth(&state, &headers).await { |
| 598 | Ok(pair) => pair, |
| 599 | Err(error) => return error.into_response(), |
| 600 | }; |
| 601 | respond( |
| 602 | dispatch( |
| 603 | &user.handle, |
| 604 | &user.mirror, |
| 605 | Request::Join { room: body.0.room }, |
| 606 | ) |
| 607 | .await, |
| 608 | ) |
| 609 | } |
| 610 | |
| 611 | async fn rooms_create( |
| 612 | State(state): State<AppState>, |
| 613 | headers: HeaderMap, |
| 614 | body: axum::Json<CreateBody>, |
| 615 | ) -> Response { |
| 616 | let (user, _) = match auth(&state, &headers).await { |
| 617 | Ok(pair) => pair, |
| 618 | Err(error) => return error.into_response(), |
| 619 | }; |
| 620 | respond( |
| 621 | dispatch( |
| 622 | &user.handle, |
| 623 | &user.mirror, |
| 624 | Request::Create { |
| 625 | name: body.0.name, |
| 626 | topic: body.0.topic, |
| 627 | }, |
| 628 | ) |
| 629 | .await, |
| 630 | ) |
| 631 | } |
| 632 | |
| 633 | async fn rooms_leave( |
| 634 | State(state): State<AppState>, |
| 635 | headers: HeaderMap, |
| 636 | body: axum::Json<RoomIdBody>, |
| 637 | ) -> Response { |
| 638 | let (user, _) = match auth(&state, &headers).await { |
| 639 | Ok(pair) => pair, |
| 640 | Err(error) => return error.into_response(), |
| 641 | }; |
| 642 | respond( |
| 643 | dispatch( |
| 644 | &user.handle, |
| 645 | &user.mirror, |
| 646 | Request::Leave { |
| 647 | room_id: body.0.room_id, |
| 648 | }, |
| 649 | ) |
| 650 | .await, |
| 651 | ) |
| 652 | } |
| 653 | |
| 654 | async fn rooms_edit( |
| 655 | State(state): State<AppState>, |
| 656 | headers: HeaderMap, |
| 657 | body: axum::Json<EditBody>, |
| 658 | ) -> Response { |
| 659 | let (user, _) = match auth(&state, &headers).await { |
| 660 | Ok(pair) => pair, |
| 661 | Err(error) => return error.into_response(), |
| 662 | }; |
| 663 | respond( |
| 664 | dispatch( |
| 665 | &user.handle, |
| 666 | &user.mirror, |
| 667 | Request::Edit { |
| 668 | room_id: body.0.room_id, |
| 669 | event_id: body.0.event_id, |
| 670 | body: body.0.body, |
| 671 | formatted_body: body.0.formatted_body, |
| 672 | mentions: body.0.mentions, |
| 673 | }, |
| 674 | ) |
| 675 | .await, |
| 676 | ) |
| 677 | } |
| 678 | |
| 679 | async fn rooms_react( |
| 680 | State(state): State<AppState>, |
| 681 | headers: HeaderMap, |
| 682 | body: axum::Json<ReactBody>, |
| 683 | ) -> Response { |
| 684 | let (user, _) = match auth(&state, &headers).await { |
| 685 | Ok(pair) => pair, |
| 686 | Err(error) => return error.into_response(), |
| 687 | }; |
| 688 | respond( |
| 689 | dispatch( |
| 690 | &user.handle, |
| 691 | &user.mirror, |
| 692 | Request::React { |
| 693 | room_id: body.0.room_id, |
| 694 | event_id: body.0.event_id, |
| 695 | key: body.0.key, |
| 696 | shortcode: body.0.shortcode, |
| 697 | }, |
| 698 | ) |
| 699 | .await, |
| 700 | ) |
| 701 | } |
| 702 | |
| 703 | async fn rooms_read( |
| 704 | State(state): State<AppState>, |
| 705 | headers: HeaderMap, |
| 706 | body: axum::Json<ReadBody>, |
| 707 | ) -> Response { |
| 708 | let (user, _) = match auth(&state, &headers).await { |
| 709 | Ok(pair) => pair, |
| 710 | Err(error) => return error.into_response(), |
| 711 | }; |
| 712 | respond( |
| 713 | dispatch( |
| 714 | &user.handle, |
| 715 | &user.mirror, |
| 716 | Request::Read { |
| 717 | room_id: body.0.room_id, |
| 718 | event_id: body.0.event_id, |
| 719 | }, |
| 720 | ) |
| 721 | .await, |
| 722 | ) |
| 723 | } |
| 724 | |
| 725 | async fn get_profile(State(state): State<AppState>, headers: HeaderMap) -> Response { |
| 726 | let (user, _) = match auth(&state, &headers).await { |
| 727 | Ok(pair) => pair, |
| 728 | Err(error) => return error.into_response(), |
| 729 | }; |
| 730 | respond(dispatch(&user.handle, &user.mirror, Request::Profile).await) |
| 731 | } |
| 732 | |
| 733 | async fn get_space_children( |
| 734 | State(state): State<AppState>, |
| 735 | headers: HeaderMap, |
| 736 | Query(query): Query<MembersQuery>, |
| 737 | ) -> Response { |
| 738 | let (user, _) = match auth(&state, &headers).await { |
| 739 | Ok(pair) => pair, |
| 740 | Err(error) => return error.into_response(), |
| 741 | }; |
| 742 | respond( |
| 743 | dispatch( |
| 744 | &user.handle, |
| 745 | &user.mirror, |
| 746 | Request::SpaceChildren { |
| 747 | room_id: query.room_id, |
| 748 | }, |
| 749 | ) |
| 750 | .await, |
| 751 | ) |
| 752 | } |
| 753 | |
| 754 | async fn get_media( |
| 755 | State(state): State<AppState>, |
| 756 | headers: HeaderMap, |
| 757 | Query(query): Query<MediaQuery>, |
| 758 | ) -> Response { |
| 759 | let (user, _) = match auth(&state, &headers).await { |
| 760 | Ok(pair) => pair, |
| 761 | Err(error) => return error.into_response(), |
| 762 | }; |
| 763 | respond( |
| 764 | dispatch( |
| 765 | &user.handle, |
| 766 | &user.mirror, |
| 767 | Request::Avatar { mxc: query.mxc }, |
| 768 | ) |
| 769 | .await, |
| 770 | ) |
| 771 | } |
| 772 | |
| 773 | async fn get_message_media( |
| 774 | State(state): State<AppState>, |
| 775 | headers: HeaderMap, |
| 776 | Query(query): Query<MessageMediaQuery>, |
| 777 | ) -> Response { |
| 778 | let (user, _) = match auth(&state, &headers).await { |
| 779 | Ok(pair) => pair, |
| 780 | Err(error) => return error.into_response(), |
| 781 | }; |
| 782 | // the declared mimetype is the sender's claim, so the bytes get sniffed instead |
| 783 | respond( |
| 784 | dispatch( |
| 785 | &user.handle, |
| 786 | &user.mirror, |
| 787 | Request::Media { |
| 788 | media_id: query.media_id, |
| 789 | size: query.size, |
| 790 | }, |
| 791 | ) |
| 792 | .await, |
| 793 | ) |
| 794 | } |
| 795 | |
| 796 | async fn get_encryption(State(state): State<AppState>, headers: HeaderMap) -> Response { |
| 797 | let (user, _) = match auth(&state, &headers).await { |
| 798 | Ok(pair) => pair, |
| 799 | Err(error) => return error.into_response(), |
| 800 | }; |
| 801 | respond(dispatch(&user.handle, &user.mirror, Request::Encryption).await) |
| 802 | } |
| 803 | |
| 804 | async fn recover_encryption( |
| 805 | State(state): State<AppState>, |
| 806 | headers: HeaderMap, |
| 807 | body: axum::Json<RecoverBody>, |
| 808 | ) -> Response { |
| 809 | let (user, _) = match auth(&state, &headers).await { |
| 810 | Ok(pair) => pair, |
| 811 | Err(error) => return error.into_response(), |
| 812 | }; |
| 813 | respond( |
| 814 | dispatch( |
| 815 | &user.handle, |
| 816 | &user.mirror, |
| 817 | Request::Recover { |
| 818 | recovery_key: body.0.recovery_key, |
| 819 | }, |
| 820 | ) |
| 821 | .await, |
| 822 | ) |
| 823 | } |
| 824 | |
| 825 | async fn start_verification(State(state): State<AppState>, headers: HeaderMap) -> Response { |
| 826 | let (user, _) = match auth(&state, &headers).await { |
| 827 | Ok(pair) => pair, |
| 828 | Err(error) => return error.into_response(), |
| 829 | }; |
| 830 | respond(dispatch(&user.handle, &user.mirror, Request::StartVerification).await) |
| 831 | } |
| 832 | |
| 833 | async fn verify_encryption( |
| 834 | State(state): State<AppState>, |
| 835 | headers: HeaderMap, |
| 836 | body: axum::Json<VerifyBody>, |
| 837 | ) -> Response { |
| 838 | let (user, _) = match auth(&state, &headers).await { |
| 839 | Ok(pair) => pair, |
| 840 | Err(error) => return error.into_response(), |
| 841 | }; |
| 842 | respond( |
| 843 | dispatch( |
| 844 | &user.handle, |
| 845 | &user.mirror, |
| 846 | Request::Verify { |
| 847 | action: body.0.action, |
| 848 | }, |
| 849 | ) |
| 850 | .await, |
| 851 | ) |
| 852 | } |
| 853 | |
| 854 | async fn rooms_typing( |
| 855 | State(state): State<AppState>, |
| 856 | headers: HeaderMap, |
| 857 | body: axum::Json<TypingBody>, |
| 858 | ) -> Response { |
| 859 | let (user, _) = match auth(&state, &headers).await { |
| 860 | Ok(pair) => pair, |
| 861 | Err(error) => return error.into_response(), |
| 862 | }; |
| 863 | respond( |
| 864 | dispatch( |
| 865 | &user.handle, |
| 866 | &user.mirror, |
| 867 | Request::Typing { |
| 868 | room_id: body.0.room_id, |
| 869 | typing: body.0.typing, |
| 870 | }, |
| 871 | ) |
| 872 | .await, |
| 873 | ) |
| 874 | } |
| 875 | |
| 876 | async fn get_account_data( |
| 877 | State(state): State<AppState>, |
| 878 | headers: HeaderMap, |
| 879 | Query(query): Query<AccountDataQuery>, |
| 880 | ) -> Response { |
| 881 | let (user, _) = match auth(&state, &headers).await { |
| 882 | Ok(pair) => pair, |
| 883 | Err(error) => return error.into_response(), |
| 884 | }; |
| 885 | respond( |
| 886 | dispatch( |
| 887 | &user.handle, |
| 888 | &user.mirror, |
| 889 | Request::GetAccountData { |
| 890 | event_type: query.event_type, |
| 891 | }, |
| 892 | ) |
| 893 | .await, |
| 894 | ) |
| 895 | } |
| 896 | |
| 897 | async fn get_url_preview( |
| 898 | State(state): State<AppState>, |
| 899 | headers: HeaderMap, |
| 900 | Query(query): Query<UrlPreviewQuery>, |
| 901 | ) -> Response { |
| 902 | let (user, _) = match auth(&state, &headers).await { |
| 903 | Ok(pair) => pair, |
| 904 | Err(error) => return error.into_response(), |
| 905 | }; |
| 906 | respond( |
| 907 | dispatch( |
| 908 | &user.handle, |
| 909 | &user.mirror, |
| 910 | Request::UrlPreview { |
| 911 | room_id: query.room_id, |
| 912 | url: query.url, |
| 913 | }, |
| 914 | ) |
| 915 | .await, |
| 916 | ) |
| 917 | } |
| 918 | |
| 919 | async fn set_account_data( |
| 920 | State(state): State<AppState>, |
| 921 | headers: HeaderMap, |
| 922 | body: axum::Json<AccountDataBody>, |
| 923 | ) -> Response { |
| 924 | let (user, _) = match auth(&state, &headers).await { |
| 925 | Ok(pair) => pair, |
| 926 | Err(error) => return error.into_response(), |
| 927 | }; |
| 928 | let body = body.0; |
| 929 | respond( |
| 930 | dispatch( |
| 931 | &user.handle, |
| 932 | &user.mirror, |
| 933 | Request::SetAccountData { |
| 934 | event_type: body.event_type, |
| 935 | content: body.content, |
| 936 | }, |
| 937 | ) |
| 938 | .await, |
| 939 | ) |
| 940 | } |
| 941 | |
| 942 | async fn get_events(State(state): State<AppState>, headers: HeaderMap) -> Response { |
| 943 | let (user, _) = match auth(&state, &headers).await { |
| 944 | Ok(pair) => pair, |
| 945 | Err(error) => return error.into_response(), |
| 946 | }; |
| 947 | let body = subscribe(&user.mirror).map(|event| { |
| 948 | let json = serde_json::to_string(&event).unwrap_or_else(|_| "{\"type\":\"error\"}".into()); |
| 949 | Ok::<_, std::convert::Infallible>(SseEvent::default().data(json)) |
| 950 | }); |
| 951 | Sse::new(body).into_response() |
| 952 | } |
| 953 | |
| 954 | async fn get_health() -> Response { |
| 955 | json_ok(&serde_json::json!({ "status": "ok" }), None) |
| 956 | } |
| 957 | |
| 958 | async fn static_shell() -> Response { |
| 959 | ( |
| 960 | StatusCode::SERVICE_UNAVAILABLE, |
| 961 | axum::Json(serde_json::json!({ "message": "frontend assets missing; run npm --prefix web run build or use the Nix package" })), |
| 962 | ) |
| 963 | .into_response() |
| 964 | } |
| 965 | |
| 966 | pub fn router(state: AppState, web_dir: Option<String>) -> Router { |
| 967 | let api = Router::new() |
| 968 | .route("/session", get(get_session)) |
| 969 | .route("/login", post(post_login)) |
| 970 | .route("/logout", post(post_logout)) |
| 971 | .route("/rooms", get(get_rooms)) |
| 972 | .route("/events", get(get_events)) |
| 973 | .route("/health", get(get_health)) |
| 974 | .route("/rooms/open", post(rooms_open)) |
| 975 | .route("/rooms/close", post(rooms_close)) |
| 976 | .route("/rooms/send", post(rooms_send)) |
| 977 | .route("/rooms/paginate", post(rooms_paginate)) |
| 978 | .route( |
| 979 | "/rooms/upload", |
| 980 | post(rooms_upload).layer(DefaultBodyLimit::max(21 * 1024 * 1024)), |
| 981 | ) |
| 982 | .route("/rooms/join", post(rooms_join)) |
| 983 | .route("/rooms/create", post(rooms_create)) |
| 984 | .route("/rooms/leave", post(rooms_leave)) |
| 985 | .route("/rooms/react", post(rooms_react)) |
| 986 | .route("/rooms/edit", post(rooms_edit)) |
| 987 | .route("/rooms/read", post(rooms_read)) |
| 988 | .route("/rooms/typing", post(rooms_typing)) |
| 989 | .route( |
| 990 | "/account-data", |
| 991 | get(get_account_data).post(set_account_data), |
| 992 | ) |
| 993 | .route("/url-preview", get(get_url_preview)) |
| 994 | .route("/profile", get(get_profile)) |
| 995 | .route( |
| 996 | "/profile/avatar", |
| 997 | post(profile_avatar).layer(DefaultBodyLimit::max(10 * 1024 * 1024)), |
| 998 | ) |
| 999 | .route("/command", post(post_command)) |
| 1000 | .route("/media", get(get_media)) |
| 1001 | .route("/message-media", get(get_message_media)) |
| 1002 | .route("/spaces/children", get(get_space_children)) |
| 1003 | .route("/rooms/members", get(get_members)) |
| 1004 | .route("/encryption", get(get_encryption)) |
| 1005 | .route("/encryption/recover", post(recover_encryption)) |
| 1006 | .route("/encryption/start", post(start_verification)) |
| 1007 | .route("/encryption/verify", post(verify_encryption)); |
| 1008 | let api = Router::new() |
| 1009 | .nest("/api", api) |
| 1010 | .layer(middleware::from_fn(csrf_guard)); |
| 1011 | let router = api.with_state(state).layer(TraceLayer::new_for_http()); |
| 1012 | match web_dir { |
| 1013 | Some(dir) => { |
| 1014 | let files = |
| 1015 | ServeDir::new(&dir).not_found_service(ServeFile::new(format!("{dir}/index.html"))); |
| 1016 | router.fallback_service(files) |
| 1017 | } |
| 1018 | None => router.fallback(static_shell), |
| 1019 | } |
| 1020 | } |