//! `/admin/message`: a message from the administrator to every enabled account. //! //! The message is queued as one mail per account, in that account's language, through the same outbox as //! every other mail. The subject is one line of at most 150 characters; the body is at most 10 000 //! characters, and blank lines separate its paragraphs. Each send counts against a small rate limit, so a //! form that is submitted again and again cannot queue thousands of mails. use std::time::Instant; use im_core::model::AuditAction; use im_core::names::{multi_line, single_line}; use serde::Deserialize; use serde_json::json; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::Form; use topcoat::router::error::SeeOther; use topcoat::router::{page, route}; use topcoat::view::{View, view}; use crate::audit::{Actor, record}; use crate::auth::{require_admin, require_admin_csrf}; use crate::i18n::Lang; use crate::i18n::admin::{A, text}; use crate::mail::{self, Mail, Recipient}; use crate::pages::admin::{ FlashQuery, Tab, changed, done, error_text, flash_messages, frame_info, notice_text, refused, tabs, }; use crate::state::AppState; use crate::views::{ViewerInfo, field, page_lang, shell}; /// The longest subject, in characters. const SUBJECT_MAX: usize = 150; /// The longest body, in characters. const BODY_MAX: usize = 10_000; /// Sends that the limit allows in one window of the throttle. const SENDS_PER_WINDOW: usize = 5; /// Path of the message form. The router raises the body limit for this path (see `boot.rs`). pub const MESSAGE_ROUTE: &str = "/admin/message"; /// The body limit of the message form: every character of the subject and the body at its longest /// encoding (4 bytes of UTF-8, 3 bytes each once percent-encoded), plus room for the field names and the /// CSRF token. Smaller would refuse a long Turkish or CJK message before its own length check runs. pub const MESSAGE_BODY_LIMIT: usize = (SUBJECT_MAX + BODY_MAX) * 4 * 3 + 4 * 1024; /// The throttle key of the message form. const THROTTLE_KEY: &str = "admin-message"; /// The message form. #[derive(Deserialize, Default)] struct MessageForm { #[serde(default)] csrf: String, #[serde(default, deserialize_with = "single_line")] subject: String, #[serde(default, deserialize_with = "multi_line")] body: String, } /// `GET /admin/message`. #[page("/admin/message")] async fn message_page(cx: &Cx, Form(query): Form) -> Result { let viewer = require_admin(cx).await?; let (lang, info) = frame_info(cx, &viewer); Ok(message_view( cx, lang, info, viewer.session.csrf_token.clone(), notice_text(lang, &query.notice).map(str::to_owned), error_text(lang, &query.error).map(str::to_owned), )) } /// `POST /admin/message`: queues the message for every enabled account. #[route(POST "/admin/message")] async fn send_message(cx: &Cx, Form(form): Form) -> Result { let viewer = require_admin_csrf(cx, &form.csrf).await?; let state = app_context::(cx); let subject = form.subject.trim(); let body = form.body.replace("\r\n", "\n"); let body = body.trim(); if subject.is_empty() || body.is_empty() { return Ok(refused("/admin/message", "message-empty")); } if subject.chars().count() > SUBJECT_MAX || subject.contains(['\r', '\n']) { return Ok(refused("/admin/message", "message-subject")); } if body.chars().count() > BODY_MAX { return Ok(refused("/admin/message", "message-body")); } // Counted before the sends, so parallel submits cannot all pass the limit. A send is what is limited, so // the count stays whatever the outcome. if state .throttle .reserve(THROTTLE_KEY, SENDS_PER_WINDOW, Instant::now()) .is_err() { return Ok(refused("/admin/message", "rate-limited")); } let request = page_lang(cx, Some(&viewer)); let users = state.store.list_users(None, None, u32::MAX).await?; let mut recipients = 0_usize; for user in users.iter().filter(|user| user.disabled_at.is_none()) { let Ok(to) = Recipient::new(Some(&user.name), &user.email) else { tracing::error!(user = %user.id, "message not queued: stored address is not valid"); continue; }; let lang = mail::lang_for(user, request); let mail = Mail::Notice { subject, body }; mail::queue(&state.store, &state.key, &to, lang, &mail).await?; recipients += 1; } record( cx, Actor::User(&viewer.user.id), AuditAction::MessageSent, None, json!({ "recipients": recipients }), ) .await; changed(&state.live); Ok(done("/admin/message", "message-sent")) } /// The message page: the subject and body fields, and the send button. fn message_view( cx: &Cx, lang: Lang, info: ViewerInfo, csrf: String, success: Option, problem: Option, ) -> impl View { view! { cx => shell(title: text(lang, A::MessageTitle), lang: lang, viewer: Some(info), tabs(lang: lang, current: Tab::Message)

(text(lang, A::MessageTitle))

(text(lang, A::MessageIntro))

flash_messages(success: success, problem: problem)
field(label: text(lang, A::MessageSubject), name: "subject", kind: "text", autocomplete: "off", value: String::new())
) } }