garage44.eu/jeroen/cartopolis

logclone: git clone https://garage44.eu/jeroen/cartopolis.git

cartopolis-agent · 2026-11-28T16:54:11Z

feat(admin): block and unblock fediverse servers from the app

Admin gets a Servers area with one page, Blocked servers, over the
operator API the simulator already had (/api/admin/fediverse/blocks),
which nothing outside the simulator called. It lists the servers blocked
here, each with Unblock (asked twice), and the shared list's entries,
which are read-only: the daily import would bring an unblocked one back.
A field takes a server name, or a pasted address cut down to its server,
and narrows both lists as it is typed, so it also answers whether a
server is blocked already. Offered to whoever may triage reports, the
permission the API checks.
crates/cartopolis/src/systems/gui/admin.rs     | 212 ++++++++++++++++++++++++-
 crates/cartopolis/src/systems/gui/lib_admin.rs | 133 +++++++++++++++-
 2 files changed, 341 insertions(+), 4 deletions(-)

diff --git a/crates/cartopolis/src/systems/gui/admin.rs b/crates/cartopolis/src/systems/gui/admin.rs
index f461c9f4..20d42ce7 100644
--- a/crates/cartopolis/src/systems/gui/admin.rs
+++ b/crates/cartopolis/src/systems/gui/admin.rs
@@ -117,6 +117,51 @@ struct ClaimsDoc {
     buildings: Vec<Claim>,
 }
 
+/// A server nobody here hears from or sends to (`fediverse::blocklist` on the
+/// server): blocked by an admin here (`source` `admin`) or by the shared list
+/// the server reads every day (`shared`).
+#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
+pub struct ServerBlock {
+    pub host: String,
+    pub source: String,
+    #[serde(default)]
+    pub reason: String,
+}
+
+impl ServerBlock {
+    /// Blocked by an admin here, not by the shared list.
+    #[must_use]
+    pub fn ours(&self) -> bool {
+        self.source != "shared"
+    }
+}
+
+/// What was typed as a server to block, as the server will take it
+/// (`add_server_block`'s check): `example.org`, lowercased, no trailing dot.
+/// A pasted address (`https://bad.example/@x`, `@x@bad.example`) is cut down
+/// to its server.
+pub fn server_host(typed: &str) -> Result<String, &'static str> {
+    let mut host = typed.trim();
+    host = host
+        .strip_prefix("https://")
+        .or_else(|| host.strip_prefix("http://"))
+        .unwrap_or(host);
+    host = host.split('/').next().unwrap_or(host);
+    host = host.rsplit('@').next().unwrap_or(host);
+    let host = host.trim_end_matches('.').to_ascii_lowercase();
+    if host.is_empty() || !host.contains('.') || host.contains([' ', ':']) {
+        return Err("a server is a name like example.org");
+    }
+    Ok(host)
+}
+
+/// The blocks whose server contains `needle` (lowercased), the operator's own
+/// first as the server lists them.
+#[must_use]
+pub fn servers_matching<'a>(list: &'a [ServerBlock], needle: &str) -> Vec<&'a ServerBlock> {
+    list.iter().filter(|b| b.host.contains(needle)).collect()
+}
+
 /// Something fetched: not yet asked, on its way, here, or refused.
 #[derive(Clone, Debug, Default, PartialEq)]
 pub enum Load<T> {
@@ -147,6 +192,8 @@ pub enum Page {
     Account(String),
     Roles,
     Claims,
+    /// The fediverse servers blocked, and blocking one.
+    Servers,
 }
 
 /// What a task posted back.
@@ -155,6 +202,7 @@ enum Reply {
     Accounts(Result<AccountsDoc, String>),
     Roles(Result<Vec<Role>, String>),
     Claims(Result<Vec<Claim>, String>),
+    Servers(Result<Vec<ServerBlock>, String>),
     /// A change went through: say so, and fetch these again.
     Done(String, Refetch),
     Failed(String),
@@ -166,6 +214,7 @@ enum Refetch {
     Reports,
     Accounts,
     Claims,
+    Servers,
 }
 
 #[derive(Resource, Default)]
@@ -177,6 +226,11 @@ pub struct AdminState {
     pub accounts: Load<AccountsDoc>,
     pub roles: Load<Vec<Role>>,
     pub claims: Load<Vec<Claim>>,
+    pub servers: Load<Vec<ServerBlock>>,
+    /// The Blocked servers page's server field, which also narrows the list.
+    pub new_server: String,
+    /// Why, as typed beside it.
+    pub new_reason: String,
     /// The Accounts page's search.
     pub search: String,
     /// What was done about the open report, as typed.
@@ -433,6 +487,18 @@ impl AdminState {
         });
     }
 
+    fn fetch_servers(&mut self) {
+        if self.demo {
+            return;
+        }
+        if !matches!(self.servers, Load::Ready(_)) {
+            self.servers = Load::Loading;
+        }
+        self.spawn(async {
+            Reply::Servers(get_json::<Vec<ServerBlock>>("/api/admin/fediverse/blocks").await)
+        });
+    }
+
     /// Make a change, then say `done` and fetch `then` again.
     fn change(
         &self,
@@ -474,12 +540,14 @@ impl AdminState {
                 Reply::Accounts(r) => self.accounts = r.map_or_else(Load::Failed, Load::Ready),
                 Reply::Roles(r) => self.roles = r.map_or_else(Load::Failed, Load::Ready),
                 Reply::Claims(r) => self.claims = r.map_or_else(Load::Failed, Load::Ready),
+                Reply::Servers(r) => self.servers = r.map_or_else(Load::Failed, Load::Ready),
                 Reply::Done(said, then) => {
                     self.notice = Some((said, false));
                     match then {
                         Refetch::Reports => self.fetch_reports(),
                         Refetch::Accounts => self.fetch_accounts(),
                         Refetch::Claims => self.fetch_claims(),
+                        Refetch::Servers => self.fetch_servers(),
                     }
                 }
                 Reply::Failed(e) => self.notice = Some((format!("Not done: {e}"), true)),
@@ -534,6 +602,7 @@ impl AdminState {
             Page::Account(_) => self.fetch_roles(),
             Page::Roles => self.fetch_roles(),
             Page::Claims => self.fetch_claims(),
+            Page::Servers => self.fetch_servers(),
         }
         self.page = page;
     }
@@ -544,7 +613,9 @@ impl AdminState {
     pub fn parent(&self) -> Option<Page> {
         match self.page {
             Page::Home => None,
-            Page::Reports | Page::Accounts | Page::Roles | Page::Claims => Some(Page::Home),
+            Page::Reports | Page::Accounts | Page::Roles | Page::Claims | Page::Servers => {
+                Some(Page::Home)
+            }
             Page::Report(_) => Some(Page::Reports),
             Page::Account(_) => Some(Page::Accounts),
         }
@@ -687,6 +758,60 @@ impl AdminState {
             Refetch::Claims,
         );
     }
+
+    /// Block the server typed in `new_server`, for the reason in `new_reason`:
+    /// nothing is heard from it or sent to it from now on. A name the server
+    /// would refuse is said so here, and nothing is sent.
+    pub fn block_server(&mut self) {
+        let host = match server_host(&self.new_server) {
+            Ok(h) => h,
+            Err(e) => {
+                self.notice = Some((format!("Not done: {e}"), true));
+                return;
+            }
+        };
+        let reason = self.new_reason.trim().to_string();
+        let body = serde_json::json!({ "host": host, "reason": reason }).to_string();
+        if self.demo {
+            if let Load::Ready(list) = &mut self.servers {
+                list.retain(|b| b.host != host);
+                list.insert(
+                    0,
+                    ServerBlock {
+                        host: host.clone(),
+                        source: "admin".into(),
+                        reason,
+                    },
+                );
+            }
+        }
+        self.change(
+            async move {
+                crate::systems::model_assets::api_post("/api/admin/fediverse/blocks", Some(body))
+                    .await
+                    .map(|_| ())
+            },
+            format!("Blocked {host}: nothing comes from it or goes to it."),
+            Refetch::Servers,
+        );
+        self.new_server.clear();
+        self.new_reason.clear();
+    }
+
+    /// Take a server off the list again.
+    pub fn unblock_server(&mut self, host: &str) {
+        let path = format!("/api/admin/fediverse/blocks/{host}");
+        if self.demo {
+            if let Load::Ready(list) = &mut self.servers {
+                list.retain(|b| b.host != host);
+            }
+        }
+        self.change(
+            async move { crate::systems::model_assets::api_delete(&path).await },
+            format!("Unblocked {host}."),
+            Refetch::Servers,
+        );
+    }
 }
 
 async fn get_json<T: serde::de::DeserializeOwned>(path: &str) -> Result<T, String> {
@@ -779,7 +904,8 @@ pub fn short_date(stamp: &str) -> String {
 }
 
 /// Stand-in data for a scripted capture (`--ui admin`, `--ui adminreports`,
-/// `--ui adminreport`, `--ui adminaccount`): a capture has no server to ask.
+/// `--ui adminreport`, `--ui adminaccount`, `--ui adminservers`): a capture
+/// has no server to ask.
 pub fn seed_demo(admin: &mut AdminState, screen: &str) {
     admin.demo = true;
     admin.reports = Load::Ready(vec![
@@ -862,7 +988,19 @@ pub fn seed_demo(admin: &mut AdminState, screen: &str) {
         claimed_at: "2026-10-02 14:00:00".into(),
         username: Some("sanne".into()),
     }]);
+    let block = |host: &str, source: &str, reason: &str| ServerBlock {
+        host: host.into(),
+        source: source.into(),
+        reason: reason.into(),
+    };
+    admin.servers = Load::Ready(vec![
+        block("spam.example", "admin", "Floods every community with ads"),
+        block("bad.example", "shared", "Hate speech, harassment"),
+        block("nazi.example", "shared", "Hate speech"),
+        block("trolls.example", "shared", "Harassment campaigns"),
+    ]);
     admin.page = match screen {
+        "adminservers" => Page::Servers,
         "adminreports" => Page::Reports,
         "adminreport" => Page::Report(2),
         "adminaccount" => Page::Account("a2".into()),
@@ -909,6 +1047,76 @@ mod tests {
         assert_eq!(claims.buildings[0].username.as_deref(), Some("anna"));
     }
 
+    #[test]
+    fn a_typed_server_is_cut_to_its_name_or_refused() {
+        assert_eq!(server_host(" Bad.Example. ").unwrap(), "bad.example");
+        assert_eq!(
+            server_host("https://bad.example/@troll").unwrap(),
+            "bad.example"
+        );
+        assert_eq!(server_host("@troll@bad.example").unwrap(), "bad.example");
+        assert!(server_host("").is_err());
+        assert!(server_host("localhost").is_err());
+        assert!(server_host("bad.example:8080").is_err());
+        assert!(server_host("bad example.org").is_err());
+    }
+
+    #[test]
+    fn the_block_list_parses_and_narrows() {
+        let list: Vec<ServerBlock> = serde_json::from_str(
+            r#"[{"host":"mine.example","source":"admin","reason":"ours"},
+                {"host":"spam.example","source":"shared","reason":""}]"#,
+        )
+        .unwrap();
+        assert!(list[0].ours());
+        assert!(!list[1].ours());
+        let hosts = |n: &str| {
+            servers_matching(&list, n)
+                .into_iter()
+                .map(|b| b.host.as_str())
+                .collect::<Vec<_>>()
+        };
+        assert_eq!(hosts(""), ["mine.example", "spam.example"]);
+        assert_eq!(hosts("spam"), ["spam.example"]);
+        assert!(hosts("nothing").is_empty());
+    }
+
+    #[test]
+    fn blocking_and_unblocking_a_server_change_the_list() {
+        let mut admin = AdminState::default();
+        seed_demo(&mut admin, "adminservers");
+        assert_eq!(admin.page, Page::Servers);
+        admin.new_server = "https://Evil.example/@x".into();
+        admin.new_reason = " spam ".into();
+        admin.block_server();
+        admin.drain();
+        let list = admin.servers.ready().unwrap();
+        assert_eq!(
+            list[0],
+            ServerBlock {
+                host: "evil.example".into(),
+                source: "admin".into(),
+                reason: "spam".into()
+            }
+        );
+        assert!(admin.new_server.is_empty() && admin.new_reason.is_empty());
+        assert_eq!(admin.notice.as_ref().map(|n| n.1), Some(false));
+
+        admin.unblock_server("evil.example");
+        admin.drain();
+        let list = admin.servers.ready().unwrap();
+        assert!(list.iter().all(|b| b.host != "evil.example"));
+
+        // A name the server would refuse is refused here, and nothing changes.
+        let before = list.len();
+        admin.new_server = "localhost".into();
+        admin.block_server();
+        admin.drain();
+        assert_eq!(admin.servers.ready().unwrap().len(), before);
+        assert_eq!(admin.notice.as_ref().map(|n| n.1), Some(true));
+        assert_eq!(admin.new_server, "localhost");
+    }
+
     #[test]
     fn only_an_account_that_may_run_something_sees_admin() {
         let mut id = AuthIdentity::default();
diff --git a/crates/cartopolis/src/systems/gui/lib_admin.rs b/crates/cartopolis/src/systems/gui/lib_admin.rs
index baea3c80..b21f842a 100644
--- a/crates/cartopolis/src/systems/gui/lib_admin.rs
+++ b/crates/cartopolis/src/systems/gui/lib_admin.rs
@@ -27,7 +27,7 @@ use mithril::prelude::{Button, Event};
 
 use crate::resources::{AuthIdentity, RightPanel};
 use crate::systems::admin::{
-    self, Account, AccountsDoc, AdminState, Claim, Load, Offers, Page, Report, Role,
+    self, Account, AccountsDoc, AdminState, Claim, Load, Offers, Page, Report, Role, ServerBlock,
 };
 use crate::systems::chats::ChatsView;
 use crate::systems::lib_settings::LibScreens;
@@ -53,6 +53,10 @@ enum Act {
     Delete(String),
     /// A claimed building's `pand_id`.
     Release(String),
+    /// Block the server typed on the Blocked servers page.
+    BlockServer,
+    /// A blocked server, to unblock.
+    Unblock(String),
     /// From an account to the open reports.
     ReportsOf,
     DismissNotice,
@@ -76,11 +80,14 @@ struct Live {
     accounts: Signal<Load<AccountsDoc>>,
     roles: Signal<Load<Vec<Role>>>,
     claims: Signal<Load<Vec<Claim>>>,
+    servers: Signal<Load<Vec<ServerBlock>>>,
     /// Whether the open report is handled (`None`: no report page). Its own
     /// signal, so the field under it is mounted once per report.
     resolved: Signal<Option<bool>>,
     search: Signal<String>,
     resolution: Signal<String>,
+    new_server: Signal<String>,
+    new_reason: Signal<String>,
     /// Open | Handled on the Reports page.
     handled: Signal<bool>,
     /// The destructive button pressed once, by key (`suspend:<id>`,
@@ -159,9 +166,12 @@ pub fn drive_lib_admin(
                     accounts: signal(admin.accounts.clone()),
                     roles: signal(admin.roles.clone()),
                     claims: signal(admin.claims.clone()),
+                    servers: signal(admin.servers.clone()),
                     resolved: signal(resolved_of(&admin)),
                     search: signal(admin.search.clone()),
                     resolution: signal(admin.resolution.clone()),
+                    new_server: signal(admin.new_server.clone()),
+                    new_reason: signal(admin.new_reason.clone()),
                     handled: signal(admin.show_handled),
                     armed: signal(None),
                     acts: Rc::new(RefCell::new(Vec::new())),
@@ -191,6 +201,14 @@ pub fn drive_lib_admin(
                 if typed != admin.resolution {
                     admin.resolution = typed;
                 }
+                let typed = live.new_server.get_untracked();
+                if typed != admin.new_server {
+                    admin.new_server = typed;
+                }
+                let typed = live.new_reason.get_untracked();
+                if typed != admin.new_reason {
+                    admin.new_reason = typed;
+                }
                 let handled = live.handled.get_untracked();
                 if handled != admin.show_handled {
                     admin.show_handled = handled;
@@ -212,6 +230,8 @@ pub fn drive_lib_admin(
                 }
                 mirror!(live.search, admin.search.clone());
                 mirror!(live.resolution, admin.resolution.clone());
+                mirror!(live.new_server, admin.new_server.clone());
+                mirror!(live.new_reason, admin.new_reason.clone());
                 mirror!(live.handled, admin.show_handled);
                 if live.page.get_untracked() != admin.page {
                     live.armed.set(None);
@@ -224,6 +244,7 @@ pub fn drive_lib_admin(
                 mirror!(live.accounts, admin.accounts.clone());
                 mirror!(live.roles, admin.roles.clone());
                 mirror!(live.claims, admin.claims.clone());
+                mirror!(live.servers, admin.servers.clone());
                 mirror!(live.resolved, resolved_of(&admin));
             }
         }
@@ -269,6 +290,8 @@ fn act(a: Act, admin: &mut AdminState, right_panel: &mut RightPanel, view: &mut
                 admin.release_claim(&c);
             }
         }
+        Act::BlockServer => admin.block_server(),
+        Act::Unblock(host) => admin.unblock_server(&host),
         Act::ReportsOf => admin.reports_of(),
         Act::DismissNotice => admin.notice = None,
         Act::Close => *right_panel = RightPanel::None,
@@ -393,6 +416,7 @@ fn panel(l: &Live) -> View {
                 Page::Account(id) => account(&l, id),
                 Page::Roles => roles(&l),
                 Page::Claims => claims(&l),
+                Page::Servers => servers(&l),
             }
         }
     };
@@ -447,6 +471,7 @@ fn header(l: &Live) -> View {
             .map_or_else(|| "Account".into(), |a| a.username.clone()),
         Page::Roles => "Roles".into(),
         Page::Claims => "Building claims".into(),
+        Page::Servers => "Blocked servers".into(),
     };
     view! {
         <div style={ROW}>
@@ -513,6 +538,17 @@ fn home(l: &Live) -> View {
         } else {
             View::Empty
         };
+        let servers: View = if o.triage {
+            view! {
+                <Section title={gold("Servers")}>
+                    <List>
+                        <ListItem icon={icon(icons::CAM_EARTH)} sub="Fediverse servers nobody here hears from" tone={warn} chevron=true onclick={l.act(Act::Open(Page::Servers))}>"Blocked servers"</ListItem>
+                    </List>
+                </Section>
+            }
+        } else {
+            View::Empty
+        };
         let content: View = if o.overrides || o.library {
             let overrides: View = if o.overrides {
                 view! {
@@ -547,7 +583,7 @@ fn home(l: &Live) -> View {
         } else {
             View::Empty
         };
-        view! { {people}{content}{data} }
+        view! { {people}{servers}{content}{data} }
     })
     .into_view()
 }
@@ -998,3 +1034,96 @@ fn claims(l: &Live) -> View {
         {list}
     }
 }
+
+/// The fediverse servers blocked: a field to block one more, the ones blocked
+/// here (each with Unblock, asked twice), and the shared list's. What is typed
+/// in the field narrows both lists, so it also answers "is it blocked already?".
+fn servers(l: &Live) -> View {
+    let list = {
+        let l = l.clone();
+        move || -> View {
+            let load = l.servers.get();
+            if let Some(v) = not_ready(&load) {
+                return v;
+            }
+            let all = load.ready().cloned().unwrap_or_default();
+            let needle = admin::server_host(&l.new_server.get())
+                .unwrap_or_else(|_| l.new_server.get_untracked().trim().to_lowercase());
+            let matching = admin::servers_matching(&all, &needle);
+            let (ours, shared): (Vec<&ServerBlock>, Vec<&ServerBlock>) =
+                matching.into_iter().partition(|b| b.ours());
+            let ours: View = if ours.is_empty() {
+                note(if needle.is_empty() {
+                    "No server blocked here yet."
+                } else {
+                    "None of yours matches."
+                })
+            } else {
+                let rows: Vec<View> = ours
+                    .iter()
+                    .map(|b| {
+                        let unblock = confirm(
+                            &l,
+                            format!("unblock:{}", b.host),
+                            "Unblock…".into(),
+                            "Unblock: let it in again",
+                            Act::Unblock(b.host.clone()),
+                        );
+                        let host = b.host.clone();
+                        let reason = b.reason.clone();
+                        view! {
+                            <div style="display: flex; flex-direction: column; gap: 10px; padding-bottom: 12px">
+                                <ListItem icon={icon(icons::CLEAR)} sub={reason} tone={Some(Tone::Danger)}>{host}</ListItem>
+                                <div style="padding-left: 16px">{unblock}</div>
+                            </div>
+                        }
+                    })
+                    .collect();
+                view! { <List>{rows}</List> }
+            };
+            let total = all.iter().filter(|b| !b.ours()).count();
+            let shared_title = format!("From the shared list · {total}");
+            let shared_rows: Vec<View> = shared
+                .iter()
+                .take(100)
+                .map(|b| {
+                    let host = b.host.clone();
+                    let reason = b.reason.clone();
+                    view! { <ListItem icon={icon(icons::CLEAR)} sub={reason}>{host}</ListItem> }
+                })
+                .collect();
+            let more: View = if shared.len() > 100 {
+                note(format!(
+                    "{} more: type a name above to find one.",
+                    shared.len() - 100
+                ))
+            } else {
+                View::Empty
+            };
+            let shared: View = if shared_rows.is_empty() {
+                note(if total == 0 {
+                    "The shared list has not been read yet."
+                } else {
+                    "None of the shared list matches."
+                })
+            } else {
+                view! { <List>{shared_rows}</List> }
+            };
+            view! {
+                <Section title={gold("Blocked here")}>{ours}</Section>
+                <Section title={shared_title}>
+                    {note("Kept by people who moderate fediverse servers, and read again every day. Its entries are not yours to unblock: block one here and it stays blocked if the list drops it.")}
+                    {shared}
+                    {more}
+                </Section>
+            }
+        }
+    };
+    view! {
+        {note("Nothing from a blocked server reaches anyone here, and nothing is sent to it, its subdomains included.")}
+        <FieldText model={l.new_server.clone()} placeholder="Server, like example.org" autocomplete="off" prefix={icon(icons::SEARCH)} id="admin-server" />
+        <FieldText model={l.new_reason.clone()} placeholder="Why (optional)" autocomplete="off" id="admin-server-reason" />
+        <div><Button variant=Variant::Danger onclick={l.act(Act::BlockServer)}>"Block server"</Button></div>
+        {list}
+    }
+}