From 2c32dcdc634a2d1b964d40fb0df6178355973f5b Mon Sep 17 00:00:00 2001 From: Jean Date: Mon, 13 Jul 2026 22:11:58 +0000 Subject: [PATCH] HostServ: vhost OFFER menu, plus SETALL/DELALL/GROUP A curated self-serve menu: operators OFFER / OFFERDEL , anyone sees OFFERLIST, and a user picks one with TAKE (assigned and applied at once). Offers are a global event-sourced list (VhostOfferAdded/Removed, threaded through apply like bots). SETALL/DELALL alias SET/DEL and GROUP is a no-op reassurance, since the per-account vhost already covers every grouped nick. --- api/src/lib.rs | 3 ++ hostserv/src/lib.rs | 17 ++++++++-- hostserv/src/offer.rs | 51 ++++++++++++++++++++++++++++++ hostserv/src/take.rs | 24 ++++++++++++++ src/engine/db.rs | 73 ++++++++++++++++++++++++++++++++++++------- src/engine/mod.rs | 41 ++++++++++++++++++++++++ src/grpc.rs | 4 ++- 7 files changed, 197 insertions(+), 16 deletions(-) create mode 100644 hostserv/src/offer.rs create mode 100644 hostserv/src/take.rs diff --git a/api/src/lib.rs b/api/src/lib.rs index 3bccd79..7bc7ac8 100644 --- a/api/src/lib.rs +++ b/api/src/lib.rs @@ -603,6 +603,9 @@ pub trait Store { fn request_vhost(&mut self, account: &str, host: &str) -> Result<(), RegError>; fn take_vhost_request(&mut self, account: &str) -> Result, RegError>; fn vhost_requests(&self) -> Vec<(String, String)>; + fn vhost_offer_add(&mut self, host: &str) -> Result; + fn vhost_offer_del(&mut self, index: usize) -> Result, RegError>; + fn vhost_offers(&self) -> Vec; fn group_nick(&mut self, nick: &str, account: &str) -> Result<(), RegError>; fn ungroup_nick(&mut self, nick: &str) -> Result; fn drop_account(&mut self, account: &str) -> Result; diff --git a/hostserv/src/lib.rs b/hostserv/src/lib.rs index dea9015..c06971d 100644 --- a/hostserv/src/lib.rs +++ b/hostserv/src/lib.rs @@ -21,6 +21,10 @@ mod request; mod waiting; #[path = "approve.rs"] mod approve; +#[path = "offer.rs"] +mod offer; +#[path = "take.rs"] +mod take; pub struct HostServ { pub uid: String, @@ -42,14 +46,21 @@ impl Service for HostServ { match args.first().map(|s| s.to_ascii_uppercase()).as_deref() { Some("ON") => on::handle(me, from, ctx, db), Some("OFF") => off::handle(me, from, ctx, net, db), - Some("SET") => set::handle(me, from, args, ctx, net, db), - Some("DEL") => del::handle(me, from, args, ctx, net, db), + // SET(ALL)/DEL(ALL): the per-account model already covers every + // grouped nick, so ALL is an alias, and GROUP is a no-op reassurance. + Some("SET") | Some("SETALL") => set::handle(me, from, args, ctx, net, db), + Some("DEL") | Some("DELALL") => del::handle(me, from, args, ctx, net, db), + Some("GROUP") => ctx.notice(me, from.uid, "Your vhost already applies to all your grouped nicks — nothing to sync."), Some("LIST") => list::handle(me, from, ctx, db), Some("REQUEST") => request::handle(me, from, args, ctx, db), Some("WAITING") => waiting::handle(me, from, ctx, db), Some("ACTIVATE") | Some("APPROVE") => approve::handle(me, from, args, ctx, net, db, true), Some("REJECT") => approve::handle(me, from, args, ctx, net, db, false), - Some("HELP") | None => ctx.notice(me, from.uid, "HostServ gives you a vhost: \x02ON\x02 activates your assigned vhost, \x02OFF\x02 restores your normal host, \x02REQUEST\x02 asks for one. Operators use \x02SET\x02/\x02DEL\x02 , \x02LIST\x02, and \x02WAITING\x02 + \x02ACTIVATE\x02/\x02REJECT\x02 for requests."), + Some("OFFER") => offer::add(me, from, args, ctx, db), + Some("OFFERLIST") => offer::list(me, from, ctx, db), + Some("OFFERDEL") => offer::del(me, from, args, ctx, db), + Some("TAKE") => take::handle(me, from, args, ctx, db), + Some("HELP") | None => ctx.notice(me, from.uid, "HostServ gives you a vhost: \x02ON\x02 activates your assigned vhost, \x02OFF\x02 restores your normal host, \x02REQUEST\x02 asks for one, \x02OFFERLIST\x02 + \x02TAKE\x02 pick from the menu. Operators use \x02SET\x02/\x02DEL\x02 , \x02LIST\x02, \x02WAITING\x02 + \x02ACTIVATE\x02/\x02REJECT\x02, and \x02OFFER\x02/\x02OFFERDEL\x02 for the menu."), Some(other) => ctx.notice(me, from.uid, format!("I don't know the command \x02{other}\x02. Try \x02HELP\x02.")), } } diff --git a/hostserv/src/offer.rs b/hostserv/src/offer.rs new file mode 100644 index 0000000..d1cbac0 --- /dev/null +++ b/hostserv/src/offer.rs @@ -0,0 +1,51 @@ +use fedserv_api::{Sender, ServiceCtx, Store}; + +// OFFER : add a vhost to the self-serve menu (operators). +pub fn add(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, db: &mut dyn Store) { + if !super::require_oper(me, from, ctx) { + return; + } + let Some(&host) = args.get(1) else { + ctx.notice(me, from.uid, "Syntax: OFFER "); + return; + }; + if !super::valid_vhost(host) { + ctx.notice(me, from.uid, format!("\x02{host}\x02 isn't a valid host.")); + return; + } + match db.vhost_offer_add(host) { + Ok(true) => ctx.notice(me, from.uid, format!("\x02{host}\x02 is now on the vhost menu.")), + Ok(false) => ctx.notice(me, from.uid, "That vhost is already on the menu."), + Err(_) => ctx.notice(me, from.uid, "Sorry, that didn't work. Please try again in a moment."), + } +} + +// OFFERLIST: show the self-serve vhost menu (anyone). +pub fn list(me: &str, from: &Sender, ctx: &mut ServiceCtx, db: &dyn Store) { + let offers = db.vhost_offers(); + if offers.is_empty() { + ctx.notice(me, from.uid, "No vhosts are on offer."); + return; + } + ctx.notice(me, from.uid, format!("Vhosts on offer ({}):", offers.len())); + for (i, host) in offers.iter().enumerate() { + ctx.notice(me, from.uid, format!(" {}. {host}", i + 1)); + } + ctx.notice(me, from.uid, "Take one with \x02TAKE\x02 ."); +} + +// OFFERDEL : remove an offer from the menu (operators). +pub fn del(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, db: &mut dyn Store) { + if !super::require_oper(me, from, ctx) { + return; + } + let Some(n) = args.get(1).and_then(|s| s.parse::().ok()) else { + ctx.notice(me, from.uid, "Syntax: OFFERDEL (see OFFERLIST)"); + return; + }; + match db.vhost_offer_del(n) { + Ok(Some(host)) => ctx.notice(me, from.uid, format!("Removed \x02{host}\x02 from the menu.")), + Ok(None) => ctx.notice(me, from.uid, format!("There's no offer #\x02{n}\x02.")), + Err(_) => ctx.notice(me, from.uid, "Sorry, that didn't work. Please try again in a moment."), + } +} diff --git a/hostserv/src/take.rs b/hostserv/src/take.rs new file mode 100644 index 0000000..71d5fd9 --- /dev/null +++ b/hostserv/src/take.rs @@ -0,0 +1,24 @@ +use fedserv_api::{Sender, ServiceCtx, Store}; + +// TAKE : assign yourself the vhost offered at that position on the menu. +pub fn handle(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, db: &mut dyn Store) { + let Some(account) = from.account else { + ctx.notice(me, from.uid, "You need to identify to NickServ first."); + return; + }; + let Some(n) = args.get(1).and_then(|s| s.parse::().ok()) else { + ctx.notice(me, from.uid, "Syntax: TAKE (see OFFERLIST)"); + return; + }; + let Some(host) = n.checked_sub(1).and_then(|i| db.vhost_offers().into_iter().nth(i)) else { + ctx.notice(me, from.uid, format!("There's no offer #\x02{n}\x02. See \x02OFFERLIST\x02.")); + return; + }; + match db.set_vhost(account, &host, "offer") { + Ok(()) => { + ctx.apply_vhost(from.uid, &host); + ctx.notice(me, from.uid, format!("You now have the vhost \x02{host}\x02.")); + } + Err(_) => ctx.notice(me, from.uid, "Sorry, that didn't work. Please try again in a moment."), + } +} diff --git a/src/engine/db.rs b/src/engine/db.rs index e7c30a8..5b2a596 100644 --- a/src/engine/db.rs +++ b/src/engine/db.rs @@ -148,6 +148,8 @@ pub enum Event { ChannelBotUnassigned { channel: String }, BotAdded(Bot), BotRemoved { nick: String }, + VhostOfferAdded { host: String }, + VhostOfferRemoved { host: String }, } // Whether an event replicates across the federation. Account identity is Global @@ -204,7 +206,9 @@ impl Event { | Event::ChannelBotAssigned { .. } | Event::ChannelBotUnassigned { .. } | Event::BotAdded(_) - | Event::BotRemoved { .. } => Scope::Local, + | Event::BotRemoved { .. } + | Event::VhostOfferAdded { .. } + | Event::VhostOfferRemoved { .. } => Scope::Local, } } } @@ -776,6 +780,8 @@ pub struct Db { auth_fails: HashMap, // Registered service bots (BotServ), keyed by casefolded nick. bots: HashMap, + // HostServ vhost offers: a menu of specs users may self-assign with TAKE. + vhost_offers: Vec, } // A pending emailed code and how many wrong guesses remain before it is burned. @@ -814,11 +820,12 @@ impl Db { let mut channels = HashMap::new(); let mut grouped = HashMap::new(); let mut bots = HashMap::new(); + let mut vhost_offers = Vec::new(); for event in events { - apply(&mut accounts, &mut channels, &mut grouped, &mut bots, event); + apply(&mut accounts, &mut channels, &mut grouped, &mut bots, &mut vhost_offers, event); } tracing::info!(accounts = accounts.len(), channels = channels.len(), "account store loaded"); - Self { accounts, channels, grouped, log, scram_iterations: scram::DEFAULT_ITERATIONS, email_enabled: false, email_brand: "Network Services".to_string(), email_accent: "#4f46e5".to_string(), email_logo: String::new(), codes: HashMap::new(), auth_fails: HashMap::new(), bots } + Self { accounts, channels, grouped, log, scram_iterations: scram::DEFAULT_ITERATIONS, email_enabled: false, email_brand: "Network Services".to_string(), email_accent: "#4f46e5".to_string(), email_logo: String::new(), codes: HashMap::new(), auth_fails: HashMap::new(), bots, vhost_offers } } /// Fold an entry authored by another node into the store — the services-side @@ -834,7 +841,7 @@ impl Db { _ => None, }; if let Some(event) = self.log.ingest(entry)? { - apply(&mut self.accounts, &mut self.channels, &mut self.grouped, &mut self.bots, event); + apply(&mut self.accounts, &mut self.channels, &mut self.grouped, &mut self.bots, &mut self.vhost_offers, event); } if let Some((name, prev_home)) = watched { match (prev_home, self.account(&name).map(|c| c.home.clone())) { @@ -895,6 +902,9 @@ impl Db { for b in self.bots.values() { snapshot.push(Event::BotAdded(b.clone())); } + for host in &self.vhost_offers { + snapshot.push(Event::VhostOfferAdded { host: host.clone() }); + } self.log.compact(snapshot)?; tracing::info!(before, after = self.log.len(), "compacted event log"); Ok(()) @@ -1195,10 +1205,6 @@ impl Db { Ok(true) } - /// `account`'s vhost, if any. - pub fn vhost(&self, account: &str) -> Option<&Vhost> { - self.accounts.get(&key(account)).and_then(|a| a.vhost.as_ref()) - } /// Record a pending vhost request for `account` (awaiting approval). pub fn request_vhost(&mut self, account: &str, host: &str) -> Result<(), RegError> { @@ -1238,6 +1244,32 @@ impl Db { out } + /// Add a vhost offer to the self-serve menu. Ok(false) if already offered. + pub fn vhost_offer_add(&mut self, host: &str) -> Result { + if self.vhost_offers.iter().any(|o| o == host) { + return Ok(false); + } + self.log.append(Event::VhostOfferAdded { host: host.to_string() }).map_err(|_| RegError::Internal)?; + self.vhost_offers.push(host.to_string()); + Ok(true) + } + + /// Remove the offer at 1-based `index`. Returns the removed spec, if valid. + pub fn vhost_offer_del(&mut self, index: usize) -> Result, RegError> { + if index == 0 || index > self.vhost_offers.len() { + return Ok(None); + } + let host = self.vhost_offers[index - 1].clone(); + self.log.append(Event::VhostOfferRemoved { host: host.clone() }).map_err(|_| RegError::Internal)?; + self.vhost_offers.retain(|o| o != &host); + Ok(Some(host)) + } + + /// The self-serve vhost offer menu. + pub fn vhost_offers(&self) -> &[String] { + &self.vhost_offers + } + /// Every account that has a vhost, as (account, host, setter). pub fn vhosts(&self) -> Vec<(String, String, String)> { let mut out: Vec<(String, String, String)> = self @@ -2033,7 +2065,7 @@ fn owns_over(held: &Account, claim: &Account) -> bool { // Fold one event into the store. Shared by log replay (`open`) and gossip // ingest, so both routes reconstruct identical state. -fn apply(accounts: &mut HashMap, channels: &mut HashMap, grouped: &mut HashMap, bots: &mut HashMap, event: Event) { +fn apply(accounts: &mut HashMap, channels: &mut HashMap, grouped: &mut HashMap, bots: &mut HashMap, offers: &mut Vec, event: Event) { match event { Event::AccountRegistered(a) => { // Resolve a concurrent registration of the same name deterministically: @@ -2245,6 +2277,14 @@ fn apply(accounts: &mut HashMap, channels: &mut HashMap { bots.remove(&key(&nick)); } + Event::VhostOfferAdded { host } => { + if !offers.iter().any(|o| o == &host) { + offers.push(host); + } + } + Event::VhostOfferRemoved { host } => { + offers.retain(|o| o != &host); + } Event::ChannelEntryMsgSet { channel, msg } => { if let Some(c) = channels.get_mut(&key(&channel)) { c.entrymsg = msg; @@ -2402,6 +2442,15 @@ impl Store for Db { fn vhost_requests(&self) -> Vec<(String, String)> { Db::vhost_requests(self) } + fn vhost_offer_add(&mut self, host: &str) -> Result { + Db::vhost_offer_add(self, host) + } + fn vhost_offer_del(&mut self, index: usize) -> Result, RegError> { + Db::vhost_offer_del(self, index) + } + fn vhost_offers(&self) -> Vec { + Db::vhost_offers(self).to_vec() + } fn group_nick(&mut self, nick: &str, account: &str) -> Result<(), RegError> { Db::group_nick(self, nick, account) } @@ -2644,9 +2693,9 @@ mod tests { ts, home: home.into(), scram256: None, scram512: None, certfps: vec![], verified: true, ajoin: vec![], suspension: None, memos: vec![], greet: String::new(), vhost: None, vhost_request: None, }; let converge = |first: &Account, second: &Account| { - let (mut acc, mut ch, mut gr, mut bo) = (HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new()); - apply(&mut acc, &mut ch, &mut gr, &mut bo, Event::AccountRegistered(first.clone())); - apply(&mut acc, &mut ch, &mut gr, &mut bo, Event::AccountRegistered(second.clone())); + let (mut acc, mut ch, mut gr, mut bo, mut of) = (HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new(), Vec::new()); + apply(&mut acc, &mut ch, &mut gr, &mut bo, &mut of, Event::AccountRegistered(first.clone())); + apply(&mut acc, &mut ch, &mut gr, &mut bo, &mut of, Event::AccountRegistered(second.clone())); acc["alice"].password_hash.clone() }; // Earlier registration wins, regardless of which claim applies first. diff --git a/src/engine/mod.rs b/src/engine/mod.rs index 37834d8..513796f 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -2686,6 +2686,47 @@ mod tests { assert!(hs(&mut e, "000AAAAAB", "SET alice not a host").iter().any(|a| matches!(a, NetAction::Notice { text, .. } if text.contains("isn't a valid host"))), "host validated"); } + // The vhost OFFER menu: operators OFFER specs, users TAKE them self-serve. + #[test] + fn hostserv_offer_menu() { + use fedserv_hostserv::HostServ; + use fedserv_nickserv::NickServ; + let path = std::env::temp_dir().join("fedserv-hsoffer.jsonl"); + let _ = std::fs::remove_file(&path); + let mut db = Db::open(&path, "42S"); + db.scram_iterations = 4096; + db.register("boss", "password1", None).unwrap(); + db.register("alice", "password1", None).unwrap(); + let mut e = Engine::new( + vec![ + Box::new(NickServ { uid: "42SAAAAAA".into(), guest_nick: "Guest".into(), guest_seq: 0 }), + Box::new(HostServ { uid: "42SAAAAAG".into() }), + ], + db, + ); + e.set_sid("42S".into()); + let mut opers = std::collections::HashMap::new(); + opers.insert("boss".to_string(), Privs::default().with(fedserv_api::Priv::Admin)); + e.set_opers(opers); + let ns = |e: &mut Engine, uid: &str, t: &str| e.handle(NetEvent::Privmsg { from: uid.into(), to: "42SAAAAAA".into(), text: t.into() }); + let hs = |e: &mut Engine, uid: &str, t: &str| e.handle(NetEvent::Privmsg { from: uid.into(), to: "42SAAAAAG".into(), text: t.into() }); + e.handle(NetEvent::UserConnect { uid: "000AAAAAB".into(), nick: "boss".into(), host: "realhost".into() }); + e.handle(NetEvent::UserConnect { uid: "000AAAAAV".into(), nick: "alice".into(), host: "realhost".into() }); + ns(&mut e, "000AAAAAB", "IDENTIFY password1"); + ns(&mut e, "000AAAAAV", "IDENTIFY password1"); + let says = |out: &[NetAction], n: &str| out.iter().any(|a| matches!(a, NetAction::Notice { text, .. } if text.contains(n))); + + // An operator offers a vhost; anyone can list it. + hs(&mut e, "000AAAAAB", "OFFER free.cloak.example"); + assert!(says(&hs(&mut e, "000AAAAAV", "OFFERLIST"), "free.cloak.example"), "listed"); + // A user takes it and it applies to them. + let out = hs(&mut e, "000AAAAAV", "TAKE 1"); + assert!(out.iter().any(|a| matches!(a, NetAction::SetHost { uid, host } if uid == "000AAAAAV" && host == "free.cloak.example")), "TAKE applies: {out:?}"); + // The operator removes it; a non-operator can't offer. + assert!(says(&hs(&mut e, "000AAAAAB", "OFFERDEL 1"), "Removed"), "removed"); + assert!(says(&hs(&mut e, "000AAAAAV", "OFFER x.example"), "Access denied"), "oper-gated"); + } + // An ident@host vhost applies both the ident (CHGIDENT) and the host. #[test] fn hostserv_ident_at_host() { diff --git a/src/grpc.rs b/src/grpc.rs index e07aab7..986a37c 100644 --- a/src/grpc.rs +++ b/src/grpc.rs @@ -152,7 +152,9 @@ fn to_wire(entry: &LogEntry) -> Option { | Event::ChannelBotAssigned { .. } | Event::ChannelBotUnassigned { .. } | Event::BotAdded(_) - | Event::BotRemoved { .. } => return None, + | Event::BotRemoved { .. } + | Event::VhostOfferAdded { .. } + | Event::VhostOfferRemoved { .. } => return None, }; Some(ReplicationEvent { origin: entry.origin().to_string(), seq: entry.seq(), lamport: entry.lamport(), kind: Some(kind) }) }