From 1227e26b955590f61e485ce3ca0985a3162695de Mon Sep 17 00:00:00 2001 From: Jean Date: Mon, 13 Jul 2026 21:26:38 +0000 Subject: [PATCH] Add HostServ: virtual hosts New HostServ pseudo-service assigns and applies vhosts. A vhost is a typed Option{host,setter,ts} on the account (VhostSet/VhostDeleted events), applied to the displayed host on identify and re-applied by ON; OFF restores the normal host for the session. Operators SET/DEL (applied at once to online sessions) and LIST; hosts are validated as dot-separated labels. New SetHost NetAction -> InspIRCd ENCAP CHGHOST . --- Cargo.lock | 8 ++++ Cargo.toml | 3 +- api/src/lib.rs | 22 +++++++++++ hostserv/Cargo.toml | 8 ++++ hostserv/src/del.rs | 26 ++++++++++++ hostserv/src/lib.rs | 70 +++++++++++++++++++++++++++++++++ hostserv/src/list.rs | 17 ++++++++ hostserv/src/off.rs | 22 +++++++++++ hostserv/src/on.rs | 16 ++++++++ hostserv/src/set.rs | 30 ++++++++++++++ inspircd/src/lib.rs | 12 ++++++ nickserv/src/identify.rs | 4 ++ src/config.rs | 2 +- src/engine/db.rs | 85 ++++++++++++++++++++++++++++++++++++++-- src/engine/mod.rs | 50 ++++++++++++++++++++++- src/grpc.rs | 3 ++ src/main.rs | 6 +++ 17 files changed, 378 insertions(+), 6 deletions(-) create mode 100644 hostserv/Cargo.toml create mode 100644 hostserv/src/del.rs create mode 100644 hostserv/src/lib.rs create mode 100644 hostserv/src/list.rs create mode 100644 hostserv/src/off.rs create mode 100644 hostserv/src/on.rs create mode 100644 hostserv/src/set.rs diff --git a/Cargo.lock b/Cargo.lock index 9595812..fbfdd1c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -329,6 +329,7 @@ dependencies = [ "fedserv-botserv", "fedserv-chanserv", "fedserv-example", + "fedserv-hostserv", "fedserv-inspircd", "fedserv-memoserv", "fedserv-nickserv", @@ -377,6 +378,13 @@ dependencies = [ "fedserv-api", ] +[[package]] +name = "fedserv-hostserv" +version = "0.0.1" +dependencies = [ + "fedserv-api", +] + [[package]] name = "fedserv-inspircd" version = "0.0.1" diff --git a/Cargo.toml b/Cargo.toml index ac869f9..6e2644d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["api", "inspircd", "chanserv", "nickserv", "example", "botserv", "memoserv", "statserv"] +members = ["api", "inspircd", "chanserv", "nickserv", "example", "botserv", "memoserv", "statserv", "hostserv"] [package] name = "fedserv" @@ -16,6 +16,7 @@ fedserv-example = { path = "example" } fedserv-botserv = { path = "botserv" } fedserv-memoserv = { path = "memoserv" } fedserv-statserv = { path = "statserv" } +fedserv-hostserv = { path = "hostserv" } tokio = { version = "1", features = ["net", "io-util", "rt-multi-thread", "macros", "time", "sync", "process"] } serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/api/src/lib.rs b/api/src/lib.rs index 3410c1f..415c11c 100644 --- a/api/src/lib.rs +++ b/api/src/lib.rs @@ -64,6 +64,8 @@ pub enum NetAction { // Force a user's nick (SVSNICK), e.g. renaming to a guest nick on logout. // The protocol stamps the new nick's timestamp. ForceNick { uid: String, nick: String }, + // Set a user's displayed host (a vhost), or restore it. + SetHost { uid: String, host: String }, // Force a user into a channel (SVSJOIN), e.g. applying an account's auto-join // list on identify. `key` is empty for keyless channels. ForceJoin { uid: String, channel: String, key: String }, @@ -255,6 +257,14 @@ impl ServiceCtx { }); } + // Set (or restore) a user's displayed host — a HostServ vhost. + pub fn set_host(&mut self, uid: &str, host: &str) { + self.actions.push(NetAction::SetHost { + uid: uid.to_string(), + host: host.to_string(), + }); + } + // Force a user into a channel (SVSJOIN), e.g. an account's auto-join list. pub fn force_join(&mut self, uid: &str, channel: &str, key: &str) { self.actions.push(NetAction::ForceJoin { @@ -354,6 +364,13 @@ pub struct TriggerView { pub cooldown: u32, } +#[derive(Debug, Clone)] +pub struct VhostView { + pub account: String, + pub host: String, + pub setter: String, +} + #[derive(Debug, Clone)] pub struct BotView { pub nick: String, @@ -564,6 +581,11 @@ pub trait Store { fn verify_account(&mut self, account: &str) -> Result<(), RegError>; fn set_email(&mut self, account: &str, email: Option) -> Result<(), RegError>; fn set_greet(&mut self, account: &str, greet: &str) -> Result<(), RegError>; + // HostServ vhosts. + fn set_vhost(&mut self, account: &str, host: &str, setter: &str) -> Result<(), RegError>; + fn del_vhost(&mut self, account: &str) -> Result; + fn vhost(&self, account: &str) -> Option; + fn vhosts(&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/Cargo.toml b/hostserv/Cargo.toml new file mode 100644 index 0000000..d6c4e84 --- /dev/null +++ b/hostserv/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "fedserv-hostserv" +version = "0.0.1" +edition = "2021" +description = "HostServ: assign and apply virtual hosts (vhosts)." + +[dependencies] +fedserv-api = { path = "../api" } diff --git a/hostserv/src/del.rs b/hostserv/src/del.rs new file mode 100644 index 0000000..fd0bd3a --- /dev/null +++ b/hostserv/src/del.rs @@ -0,0 +1,26 @@ +use fedserv_api::{NetView, Sender, ServiceCtx, Store}; + +// DEL : remove an account's vhost, restoring the normal host on any +// online sessions. Operators only. +pub fn handle(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, net: &dyn NetView, db: &mut dyn Store) { + if !super::require_oper(me, from, ctx) { + return; + } + let Some(&account) = args.get(1) else { + ctx.notice(me, from.uid, "Syntax: DEL "); + return; + }; + match db.del_vhost(account) { + Ok(true) => { + for uid in net.uids_logged_into(account) { + if let Some(host) = net.host_of(&uid) { + let host = host.to_string(); + ctx.set_host(&uid, &host); + } + } + ctx.notice(me, from.uid, format!("Vhost for \x02{account}\x02 removed.")); + } + Ok(false) => ctx.notice(me, from.uid, format!("\x02{account}\x02 has no vhost.")), + Err(_) => ctx.notice(me, from.uid, format!("\x02{account}\x02 isn't registered.")), + } +} diff --git a/hostserv/src/lib.rs b/hostserv/src/lib.rs new file mode 100644 index 0000000..f181ca7 --- /dev/null +++ b/hostserv/src/lib.rs @@ -0,0 +1,70 @@ +//! HostServ assigns virtual hosts (vhosts) to accounts and applies them to the +//! displayed host. Members toggle their own with ON/OFF; operators assign them +//! with SET/DEL and review with LIST. `lib.rs` holds the dispatcher; each +//! command lives in its own file. + +use fedserv_api::{NetView, Priv, Sender, Service, ServiceCtx, Store}; + +#[path = "on.rs"] +mod on; +#[path = "off.rs"] +mod off; +#[path = "set.rs"] +mod set; +#[path = "del.rs"] +mod del; +#[path = "list.rs"] +mod list; + +pub struct HostServ { + pub uid: String, +} + +impl Service for HostServ { + fn nick(&self) -> &str { + "HostServ" + } + fn uid(&self) -> &str { + &self.uid + } + fn gecos(&self) -> &str { + "Host Services" + } + + fn on_command(&mut self, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, net: &dyn NetView, db: &mut dyn Store) { + let me = self.uid.as_str(); + 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), + Some("LIST") => list::handle(me, from, 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. Operators use \x02SET\x02 , \x02DEL\x02 and \x02LIST\x02."), + Some(other) => ctx.notice(me, from.uid, format!("I don't know the command \x02{other}\x02. Try \x02HELP\x02.")), + } + } +} + +// Operator gate for vhost administration. +fn require_oper(me: &str, from: &Sender, ctx: &mut ServiceCtx) -> bool { + if from.privs.has(Priv::Admin) { + return true; + } + ctx.notice(me, from.uid, "Access denied — assigning vhosts is for services operators."); + false +} + +// Whether `host` is a syntactically valid vhost: a hostname of dot-separated +// labels using letters, digits and hyphens, not too long. +pub(crate) fn valid_vhost(host: &str) -> bool { + if host.is_empty() || host.len() > 64 || !host.contains('.') { + return false; + } + host.split('.').all(|label| { + !label.is_empty() + && label.len() <= 63 + && !label.starts_with('-') + && !label.ends_with('-') + && label.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') + }) +} diff --git a/hostserv/src/list.rs b/hostserv/src/list.rs new file mode 100644 index 0000000..10d88a8 --- /dev/null +++ b/hostserv/src/list.rs @@ -0,0 +1,17 @@ +use fedserv_api::{Sender, ServiceCtx, Store}; + +// LIST: every account with an assigned vhost. Operators only. +pub fn handle(me: &str, from: &Sender, ctx: &mut ServiceCtx, db: &dyn Store) { + if !super::require_oper(me, from, ctx) { + return; + } + let vhosts = db.vhosts(); + if vhosts.is_empty() { + ctx.notice(me, from.uid, "No vhosts have been assigned."); + return; + } + ctx.notice(me, from.uid, format!("Assigned vhosts ({}):", vhosts.len())); + for v in &vhosts { + ctx.notice(me, from.uid, format!(" \x02{}\x02 — {} (by {})", v.account, v.host, v.setter)); + } +} diff --git a/hostserv/src/off.rs b/hostserv/src/off.rs new file mode 100644 index 0000000..09cf65c --- /dev/null +++ b/hostserv/src/off.rs @@ -0,0 +1,22 @@ +use fedserv_api::{NetView, Sender, ServiceCtx, Store}; + +// OFF: restore your normal host for this session (the vhost stays assigned and +// re-applies next time you identify). +pub fn handle(me: &str, from: &Sender, ctx: &mut ServiceCtx, net: &dyn NetView, db: &dyn Store) { + let Some(account) = from.account else { + ctx.notice(me, from.uid, "You need to identify to NickServ first."); + return; + }; + if db.vhost(account).is_none() { + ctx.notice(me, from.uid, "You have no vhost assigned."); + return; + } + match net.host_of(from.uid) { + Some(host) => { + let host = host.to_string(); + ctx.set_host(from.uid, &host); + ctx.notice(me, from.uid, "Your vhost is off; your normal host is restored."); + } + None => ctx.notice(me, from.uid, "Sorry, that didn't work. Please try again in a moment."), + } +} diff --git a/hostserv/src/on.rs b/hostserv/src/on.rs new file mode 100644 index 0000000..e1b8ecc --- /dev/null +++ b/hostserv/src/on.rs @@ -0,0 +1,16 @@ +use fedserv_api::{Sender, ServiceCtx, Store}; + +// ON: activate the vhost assigned to your account. +pub fn handle(me: &str, from: &Sender, ctx: &mut ServiceCtx, db: &dyn Store) { + let Some(account) = from.account else { + ctx.notice(me, from.uid, "You need to identify to NickServ first."); + return; + }; + match db.vhost(account) { + Some(v) => { + ctx.set_host(from.uid, &v.host); + ctx.notice(me, from.uid, format!("Your vhost \x02{}\x02 is now active.", v.host)); + } + None => ctx.notice(me, from.uid, "You have no vhost assigned."), + } +} diff --git a/hostserv/src/set.rs b/hostserv/src/set.rs new file mode 100644 index 0000000..b9d930a --- /dev/null +++ b/hostserv/src/set.rs @@ -0,0 +1,30 @@ +use fedserv_api::{NetView, Sender, ServiceCtx, Store}; + +// SET : assign a vhost to an account, applying it at once to any +// online sessions. Operators only. +pub fn handle(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, net: &dyn NetView, db: &mut dyn Store) { + if !super::require_oper(me, from, ctx) { + return; + } + let (Some(&account), Some(&host)) = (args.get(1), args.get(2)) else { + ctx.notice(me, from.uid, "Syntax: SET "); + return; + }; + if !super::valid_vhost(host) { + ctx.notice(me, from.uid, format!("\x02{host}\x02 isn't a valid host (letters, digits, hyphens and dots).")); + return; + } + if db.account(account).is_none() { + ctx.notice(me, from.uid, format!("\x02{account}\x02 isn't registered.")); + return; + } + match db.set_vhost(account, host, from.nick) { + Ok(()) => { + for uid in net.uids_logged_into(account) { + ctx.set_host(&uid, host); + } + ctx.notice(me, from.uid, format!("Vhost \x02{host}\x02 assigned to \x02{account}\x02.")); + } + Err(_) => ctx.notice(me, from.uid, "Sorry, that didn't work. Please try again in a moment."), + } +} diff --git a/inspircd/src/lib.rs b/inspircd/src/lib.rs index 2737300..299b895 100644 --- a/inspircd/src/lib.rs +++ b/inspircd/src/lib.rs @@ -270,6 +270,11 @@ impl Protocol for InspIrcd { NetAction::QuitUser { uid, reason } => vec![format!(":{} QUIT :{}", uid, reason)], NetAction::ServiceJoin { uid, channel } => vec![format!(":{} IJOIN {}", uid, channel)], NetAction::ServicePart { uid, channel } => vec![format!(":{} PART {}", uid, channel)], + // ENCAP the target's server: CHGHOST , to set a vhost. + NetAction::SetHost { uid, host } => { + let target = uid.get(..3).unwrap_or(uid.as_str()); + vec![self.from_us(format!("ENCAP {} CHGHOST {} {}", target, uid, host))] + } NetAction::ForceNick { uid, nick } => { let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(self.ts); vec![self.from_us(format!("SVSNICK {} {} {}", uid, nick, now))] @@ -448,6 +453,13 @@ mod tests { assert!(ev.iter().any(|e| matches!(e, NetEvent::ChannelVoice { uid, voice: true, .. } if uid == "0IRAAAAAD")), "join voice: {ev:?}"); } + // A vhost is set by ENCAP'ing the target's own server with CHGHOST. + #[test] + fn serializes_set_host() { + let lines = proto().serialize(&NetAction::SetHost { uid: "0IRAAAAAB".into(), host: "cool.example".into() }); + assert_eq!(lines, vec![":42S ENCAP 0IR CHGHOST 0IRAAAAAB cool.example".to_string()]); + } + #[test] fn parses_ftopic_and_filters_own() { let ev = proto().parse(":0IRAAAAAB FTOPIC #chan 1783845132 1783845140 :Welcome all"); diff --git a/nickserv/src/identify.rs b/nickserv/src/identify.rs index 69c50ba..9d4d1d2 100644 --- a/nickserv/src/identify.rs +++ b/nickserv/src/identify.rs @@ -59,6 +59,10 @@ pub fn handle(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, db: for entry in db.ajoin_list(&account) { ctx.force_join(from.uid, &entry.channel, &entry.key); } + // Apply the account's vhost (HostServ), if it has one. + if let Some(v) = db.vhost(&account) { + ctx.set_host(from.uid, &v.host); + } // Let them know about waiting memos. let unread = db.unread_memos(&account); if unread > 0 { diff --git a/src/config.rs b/src/config.rs index 68d38f7..0d1eb4c 100644 --- a/src/config.rs +++ b/src/config.rs @@ -73,7 +73,7 @@ impl Default for Modules { } fn default_services() -> Vec { - vec!["nickserv".to_string(), "chanserv".to_string(), "botserv".to_string(), "memoserv".to_string(), "statserv".to_string()] + vec!["nickserv".to_string(), "chanserv".to_string(), "botserv".to_string(), "memoserv".to_string(), "statserv".to_string(), "hostserv".to_string()] } #[derive(Debug, Deserialize, Clone)] diff --git a/src/engine/db.rs b/src/engine/db.rs index d08c1f7..c8fc080 100644 --- a/src/engine/db.rs +++ b/src/engine/db.rs @@ -30,7 +30,7 @@ use super::scram::{self, Hash}; // fedserv-api SDK crate; re-exported so the engine keeps naming them locally and // modules importing `crate::engine::db::{ChanError, ...}` are unaffected. pub use fedserv_api::{ - AccountView, AjoinView, BotView, MemoView, SuspensionView, ChanAccessView, ChanAkickView, ChanError, ChanSetting, ChannelView, CertError, CodeKind, Kicker, RegError, Store, TriggerView, + AccountView, AjoinView, BotView, MemoView, SuspensionView, ChanAccessView, ChanAkickView, ChanError, ChanSetting, ChannelView, CertError, CodeKind, Kicker, RegError, Store, TriggerView, VhostView, }; #[derive(Debug, Clone, Serialize, Deserialize)] @@ -73,6 +73,17 @@ pub struct Account { // Personal greet a bot shows when this account joins a greet-enabled channel. #[serde(default)] pub greet: String, + // Assigned vhost (HostServ), applied to the displayed host on identify. + #[serde(default)] + pub vhost: Option, +} + +// A HostServ virtual host: the displayed host, who assigned it, and when. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Vhost { + pub host: String, + pub setter: String, + pub ts: u64, } fn verified_default() -> bool { @@ -95,6 +106,8 @@ pub enum Event { AccountVerified { account: String }, AjoinAdded { account: String, channel: String, key: String }, AjoinRemoved { account: String, channel: String }, + VhostSet { account: String, host: String, setter: String, ts: u64 }, + VhostDeleted { account: String }, AccountSuspended { account: String, by: String, reason: String, ts: u64, expires: Option }, AccountUnsuspended { account: String }, MemoSent { account: String, from: String, text: String, ts: u64 }, @@ -148,6 +161,8 @@ impl Event { | Event::AccountVerified { .. } | Event::AjoinAdded { .. } | Event::AjoinRemoved { .. } + | Event::VhostSet { .. } + | Event::VhostDeleted { .. } | Event::AccountSuspended { .. } | Event::AccountUnsuspended { .. } | Event::MemoSent { .. } @@ -970,6 +985,7 @@ impl Db { suspension: None, memos: Vec::new(), greet: String::new(), + vhost: None, }; self.log.append(Event::AccountRegistered(account.clone())).map_err(|_| RegError::Internal)?; self.accounts.insert(key(name), account); @@ -1139,6 +1155,47 @@ impl Db { Ok(()) } + /// Assign a vhost to `account`. `setter` is who did it, for the record. + pub fn set_vhost(&mut self, account: &str, host: &str, setter: &str) -> Result<(), RegError> { + let k = key(account); + if !self.accounts.contains_key(&k) { + return Err(RegError::Internal); + } + let ts = now(); + self.log.append(Event::VhostSet { account: account.to_string(), host: host.to_string(), setter: setter.to_string(), ts }).map_err(|_| RegError::Internal)?; + self.accounts.get_mut(&k).unwrap().vhost = Some(Vhost { host: host.to_string(), setter: setter.to_string(), ts }); + Ok(()) + } + + /// Remove `account`'s vhost. Returns whether one was set. + pub fn del_vhost(&mut self, account: &str) -> Result { + let k = key(account); + match self.accounts.get(&k) { + Some(a) if a.vhost.is_some() => {} + Some(_) => return Ok(false), + None => return Err(RegError::Internal), + } + self.log.append(Event::VhostDeleted { account: account.to_string() }).map_err(|_| RegError::Internal)?; + self.accounts.get_mut(&k).unwrap().vhost = None; + 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()) + } + + /// 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 + .accounts + .values() + .filter_map(|a| a.vhost.as_ref().map(|v| (a.name.clone(), v.host.clone(), v.setter.clone()))) + .collect(); + out.sort_by(|a, b| a.0.cmp(&b.0)); + out + } + /// Set (or clear, when empty) `account`'s personal greet. pub fn set_greet(&mut self, account: &str, greet: &str) -> Result<(), RegError> { let k = key(account); @@ -1985,6 +2042,16 @@ fn apply(accounts: &mut HashMap, channels: &mut HashMap { + if let Some(a) = accounts.get_mut(&key(&account)) { + a.vhost = Some(Vhost { host, setter, ts }); + } + } + Event::VhostDeleted { account } => { + if let Some(a) = accounts.get_mut(&key(&account)) { + a.vhost = None; + } + } Event::AccountSuspended { account, by, reason, ts, expires } => { if let Some(a) = accounts.get_mut(&key(&account)) { a.suspension = Some(Suspension { by, reason, ts, expires }); @@ -2251,6 +2318,18 @@ impl Store for Db { fn set_greet(&mut self, account: &str, greet: &str) -> Result<(), RegError> { Db::set_greet(self, account, greet) } + fn set_vhost(&mut self, account: &str, host: &str, setter: &str) -> Result<(), RegError> { + Db::set_vhost(self, account, host, setter) + } + fn del_vhost(&mut self, account: &str) -> Result { + Db::del_vhost(self, account) + } + fn vhost(&self, account: &str) -> Option { + Db::account(self, account).and_then(|a| a.vhost.as_ref().map(|v| VhostView { account: a.name.clone(), host: v.host.clone(), setter: v.setter.clone() })) + } + fn vhosts(&self) -> Vec { + Db::vhosts(self).into_iter().map(|(account, host, setter)| VhostView { account, host, setter }).collect() + } fn group_nick(&mut self, nick: &str, account: &str) -> Result<(), RegError> { Db::group_nick(self, nick, account) } @@ -2490,7 +2569,7 @@ mod tests { fn account_conflict_resolves_deterministically() { let alice = |hash: &str, ts: u64, home: &str| Account { name: "alice".into(), password_hash: hash.into(), email: None, - ts, home: home.into(), scram256: None, scram512: None, certfps: vec![], verified: true, ajoin: vec![], suspension: None, memos: vec![], greet: String::new(), + ts, home: home.into(), scram256: None, scram512: None, certfps: vec![], verified: true, ajoin: vec![], suspension: None, memos: vec![], greet: String::new(), vhost: None, }; let converge = |first: &Account, second: &Account| { let (mut acc, mut ch, mut gr, mut bo) = (HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new()); @@ -2766,7 +2845,7 @@ mod tests { db.register("alice", "pw", None).unwrap(); let bob = Account { name: "bob".into(), password_hash: "x".into(), email: None, - ts: 0, home: "peer".into(), scram256: None, scram512: None, certfps: vec![], verified: true, ajoin: vec![], suspension: None, memos: vec![], greet: String::new(), + ts: 0, home: "peer".into(), scram256: None, scram512: None, certfps: vec![], verified: true, ajoin: vec![], suspension: None, memos: vec![], greet: String::new(), vhost: None, }; let entry = LogEntry { origin: "peer".into(), seq: 0, lamport: 1, event: Event::AccountRegistered(bob) }; db.ingest(entry).unwrap(); diff --git a/src/engine/mod.rs b/src/engine/mod.rs index 4d0b3a3..4da843f 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -1914,7 +1914,7 @@ mod tests { // An earlier claim from another node wins and takes the name over. let winner = db::Account { name: "alice".into(), password_hash: "OTHER".into(), email: None, - ts: 0, home: "peer".into(), scram256: None, scram512: None, certfps: vec![], verified: true, ajoin: vec![], suspension: None, memos: vec![], greet: String::new(), + ts: 0, home: "peer".into(), scram256: None, scram512: None, certfps: vec![], verified: true, ajoin: vec![], suspension: None, memos: vec![], greet: String::new(), vhost: None, }; let entry = LogEntry::for_test("peer", 0, 1, db::Event::AccountRegistered(winner)); e.gossip_ingest(entry).unwrap(); @@ -2638,6 +2638,54 @@ mod tests { assert!(kicked(&vote(&mut e, "000AAAAAC", "!votekick victim")), "2 distinct votes: kicked"); } + // HostServ: a vhost is applied on identify and by SET, listed and removed by + // operators, and its administration is oper-gated with host validation. + #[test] + fn hostserv_assigns_and_applies_vhosts() { + use fedserv_hostserv::HostServ; + use fedserv_nickserv::NickServ; + let path = std::env::temp_dir().join("fedserv-hostserv.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(); + db.set_vhost("alice", "alice.vhost.example", "system").unwrap(); // pre-assigned + 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() }); + let sethost = |out: &[NetAction], uid: &str, host: &str| out.iter().any(|a| matches!(a, NetAction::SetHost { uid: u, host: h } if u == uid && h == host)); + + // Identifying applies the pre-assigned vhost. + assert!(sethost(&ns(&mut e, "000AAAAAV", "IDENTIFY password1"), "000AAAAAV", "alice.vhost.example"), "vhost applied on identify"); + ns(&mut e, "000AAAAAB", "IDENTIFY password1"); + + // An operator SET applies at once to the online session. + assert!(sethost(&hs(&mut e, "000AAAAAB", "SET alice new.host.example"), "000AAAAAV", "new.host.example"), "SET applies online"); + // ON re-activates the account's vhost. + assert!(sethost(&hs(&mut e, "000AAAAAV", "ON"), "000AAAAAV", "new.host.example"), "ON re-applies"); + // LIST shows it. + assert!(hs(&mut e, "000AAAAAB", "LIST").iter().any(|a| matches!(a, NetAction::Notice { text, .. } if text.contains("alice") && text.contains("new.host.example"))), "listed"); + // DEL restores the real host on the online session. + assert!(sethost(&hs(&mut e, "000AAAAAB", "DEL alice"), "000AAAAAV", "realhost"), "DEL restores real host"); + + // Non-operators can't SET; invalid hosts are rejected. + assert!(hs(&mut e, "000AAAAAV", "SET boss x.y").iter().any(|a| matches!(a, NetAction::Notice { text, .. } if text.contains("Access denied"))), "oper-gated"); + 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"); + } + // StatServ reports per-channel activity (#channel) and the global registry // (SERVER, operators only). #[test] diff --git a/src/grpc.rs b/src/grpc.rs index aa328cc..14ae173 100644 --- a/src/grpc.rs +++ b/src/grpc.rs @@ -127,6 +127,8 @@ fn to_wire(entry: &LogEntry) -> Option { | Event::AccountGreetSet { .. } | Event::AjoinAdded { .. } | Event::AjoinRemoved { .. } + | Event::VhostSet { .. } + | Event::VhostDeleted { .. } | Event::AccountSuspended { .. } | Event::AccountUnsuspended { .. } | Event::MemoSent { .. } @@ -397,6 +399,7 @@ mod tests { suspension: None, memos: vec![], greet: String::new(), + vhost: None, }; let registered = LogEntry::for_test("A", 0, 1, Event::AccountRegistered(acct)); let wire = to_wire(®istered).expect("account registration replicates"); diff --git a/src/main.rs b/src/main.rs index 6bceb81..6d07e51 100644 --- a/src/main.rs +++ b/src/main.rs @@ -19,6 +19,7 @@ use fedserv_botserv::BotServ; use fedserv_chanserv::ChanServ; use fedserv_memoserv::MemoServ; use fedserv_statserv::StatServ; +use fedserv_hostserv::HostServ; use fedserv_example::ExampleServ; use fedserv_inspircd::InspIrcd; use fedserv_nickserv::NickServ; @@ -76,6 +77,11 @@ async fn main() -> Result<()> { uid: format!("{}AAAAAF", cfg.server.sid), })); } + if enabled("hostserv") { + services.push(Box::new(HostServ { + uid: format!("{}AAAAAG", cfg.server.sid), + })); + } if enabled("example") { services.push(Box::new(ExampleServ { uid: format!("{}AAAAAC", cfg.server.sid),