From b25870e14beeb539cad986588ef094aabae085fa Mon Sep 17 00:00:00 2001 From: Jean Date: Mon, 13 Jul 2026 13:42:14 +0000 Subject: [PATCH] botserv: ASSIGN / UNASSIGN a bot to a channel A channel gains a typed assigned_bot (event-logged, snapshotted). ASSIGN <#channel> / UNASSIGN <#channel> is founder-gated (or admin oper). The engine reconcile now also diffs channel assignments against tracked bot memberships: a live bot IJOINs its assigned channels and PARTs unassigned ones (new ServiceJoin/ServicePart actions), at burst and after commands; a deleted bot's memberships are dropped. Engine test for join-on-assign / part-on-unassign. --- api/src/lib.rs | 7 +++++ botserv/src/lib.rs | 43 ++++++++++++++++++++++++++++-- inspircd/src/lib.rs | 2 ++ src/engine/db.rs | 55 ++++++++++++++++++++++++++++++++++++-- src/engine/mod.rs | 65 +++++++++++++++++++++++++++++++++++++++++++++ src/grpc.rs | 2 ++ 6 files changed, 170 insertions(+), 4 deletions(-) diff --git a/api/src/lib.rs b/api/src/lib.rs index b4a633c..e250a13 100644 --- a/api/src/lib.rs +++ b/api/src/lib.rs @@ -67,6 +67,9 @@ pub enum NetAction { ForceJoin { uid: String, channel: String, key: String }, // Remove one of our pseudo-clients (e.g. a deleted bot) from the network. QuitUser { uid: String, reason: String }, + // A services pseudo-client (a bot) joins / parts a channel. + ServiceJoin { uid: String, channel: String }, + ServicePart { uid: String, channel: String }, // Set channel modes from services, e.g. +r on a registered channel. `from` is // the pseudoclient uid to source it from (empty = the services server). The // protocol stamps a timestamp the ircd will accept. @@ -368,6 +371,8 @@ pub struct ChannelView { pub suspended: bool, // Last known topic (for KEEPTOPIC / TOPICLOCK). pub topic: String, + // BotServ bot assigned to this channel, if any. + pub assigned_bot: Option, } // A single ChanServ SET option, named for the typed `set_channel_setting` call. @@ -520,6 +525,8 @@ pub trait Store { fn bot_add(&mut self, nick: &str, user: &str, host: &str, gecos: &str) -> Result<(), ChanError>; fn bot_del(&mut self, nick: &str) -> Result; fn bots(&self) -> Vec; + fn assign_bot(&mut self, channel: &str, bot: &str) -> Result<(), ChanError>; + fn unassign_bot(&mut self, channel: &str) -> Result; // MemoServ: per-account memos (index is a 0-based position in memo_list). fn memo_send(&mut self, account: &str, from: &str, text: &str) -> Result<(), RegError>; fn memo_list(&self, account: &str) -> Vec; diff --git a/botserv/src/lib.rs b/botserv/src/lib.rs index bee1279..01e10d6 100644 --- a/botserv/src/lib.rs +++ b/botserv/src/lib.rs @@ -23,13 +23,52 @@ impl Service for BotServ { let me = self.uid.as_str(); match args.first().map(|s| s.to_ascii_uppercase()).as_deref() { Some("BOT") => bot(me, from, args, ctx, db), - Some("HELP") => ctx.notice(me, from.uid, "BotServ keeps service bots for your channels. Operator commands: \x02BOT\x02 ADD|DEL|LIST."), + Some("ASSIGN") => assign(me, from, args, ctx, db, true), + Some("UNASSIGN") => assign(me, from, args, ctx, db, false), + Some("HELP") | None => ctx.notice(me, from.uid, "BotServ keeps service bots for your channels: \x02ASSIGN\x02 <#channel> puts a bot in your channel, \x02UNASSIGN\x02 <#channel> removes it. Operators also have \x02BOT\x02 ADD|DEL|LIST."), Some(other) => ctx.notice(me, from.uid, format!("I don't know the command \x02{other}\x02. Try \x02HELP\x02.")), - None => {} } } } +// ASSIGN <#channel> / UNASSIGN <#channel>: put a bot in a channel (or take +// it out). Channel founder only (or a services admin). +fn assign(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, db: &mut dyn Store, assigning: bool) { + let Some(&chan) = args.get(1) else { + let syntax = if assigning { "Syntax: ASSIGN <#channel> " } else { "Syntax: UNASSIGN <#channel>" }; + ctx.notice(me, from.uid, syntax); + return; + }; + let Some(founder) = db.channel(chan).map(|c| c.founder) else { + ctx.notice(me, from.uid, format!("\x02{chan}\x02 isn't registered.")); + return; + }; + if from.account != Some(founder.as_str()) && !from.privs.has(Priv::Admin) { + ctx.notice(me, from.uid, format!("Only \x02{chan}\x02's founder can assign a bot to it.")); + return; + } + if !assigning { + match db.unassign_bot(chan) { + Ok(true) => ctx.notice(me, from.uid, format!("The bot has left \x02{chan}\x02.")), + Ok(false) => ctx.notice(me, from.uid, format!("\x02{chan}\x02 has no bot assigned.")), + Err(_) => ctx.notice(me, from.uid, "Sorry, that didn't work. Please try again in a moment."), + } + return; + } + let Some(&bot) = args.get(2) else { + ctx.notice(me, from.uid, "Syntax: ASSIGN <#channel> "); + return; + }; + let Some(botnick) = db.bots().into_iter().find(|b| b.nick.eq_ignore_ascii_case(bot)).map(|b| b.nick) else { + ctx.notice(me, from.uid, format!("There's no bot named \x02{bot}\x02. See \x02BOT LIST\x02.")); + return; + }; + match db.assign_bot(chan, &botnick) { + Ok(()) => ctx.notice(me, from.uid, format!("Bot \x02{botnick}\x02 is now assigned to \x02{chan}\x02.")), + Err(_) => ctx.notice(me, from.uid, "Sorry, that didn't work. Please try again in a moment."), + } +} + // BOT ADD [gecos] | BOT DEL | BOT LIST — manage the // bot registry. Administering bots is oper-only (Priv::Admin). fn bot(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, db: &mut dyn Store) { diff --git a/inspircd/src/lib.rs b/inspircd/src/lib.rs index 54e4999..f3e1d85 100644 --- a/inspircd/src/lib.rs +++ b/inspircd/src/lib.rs @@ -262,6 +262,8 @@ impl Protocol for InspIrcd { // SVSNICK — the new nick takes the current // time as its TS so it wins any collision resolution. 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)], 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))] diff --git a/src/engine/db.rs b/src/engine/db.rs index 6cbb108..a3fa600 100644 --- a/src/engine/db.rs +++ b/src/engine/db.rs @@ -97,6 +97,8 @@ pub enum Event { ChannelTopicSet { channel: String, topic: String }, ChannelSuspended { channel: String, by: String, reason: String, ts: u64, expires: Option }, ChannelUnsuspended { channel: String }, + ChannelBotAssigned { channel: String, bot: String }, + ChannelBotUnassigned { channel: String }, BotAdded(Bot), BotRemoved { nick: String }, } @@ -144,6 +146,8 @@ impl Event { | Event::ChannelTopicSet { .. } | Event::ChannelSuspended { .. } | Event::ChannelUnsuspended { .. } + | Event::ChannelBotAssigned { .. } + | Event::ChannelBotUnassigned { .. } | Event::BotAdded(_) | Event::BotRemoved { .. } => Scope::Local, } @@ -257,6 +261,9 @@ pub struct ChannelInfo { // Services suspension, if any (channel frozen while set and unexpired). #[serde(default)] pub suspension: Option, + // BotServ bot assigned to sit in this channel, if any (its nick). + #[serde(default)] + pub assigned_bot: Option, } impl ChannelInfo { @@ -672,6 +679,9 @@ impl Db { if let Some(s) = &c.suspension { snapshot.push(Event::ChannelSuspended { channel: c.name.clone(), by: s.by.clone(), reason: s.reason.clone(), ts: s.ts, expires: s.expires }); } + if let Some(bot) = &c.assigned_bot { + snapshot.push(Event::ChannelBotAssigned { channel: c.name.clone(), bot: bot.clone() }); + } } for (nick, account) in &self.grouped { snapshot.push(Event::NickGrouped { nick: nick.clone(), account: account.clone() }); @@ -1102,7 +1112,7 @@ impl Db { self.log .append(Event::ChannelRegistered { name: name.to_string(), founder: founder.to_string(), ts }) .map_err(|_| ChanError::Internal)?; - self.channels.insert(k, ChannelInfo { name: name.to_string(), founder: founder.to_string(), ts, lock_on: String::new(), lock_off: String::new(), access: Vec::new(), akick: Vec::new(), desc: String::new(), entrymsg: String::new(), settings: ChanSettings::default(), topic: String::new(), suspension: None }); + self.channels.insert(k, ChannelInfo { name: name.to_string(), founder: founder.to_string(), ts, lock_on: String::new(), lock_off: String::new(), access: Vec::new(), akick: Vec::new(), desc: String::new(), entrymsg: String::new(), settings: ChanSettings::default(), topic: String::new(), suspension: None, assigned_bot: None }); Ok(()) } @@ -1334,6 +1344,30 @@ impl Db { self.bots.values() } + /// Assign a bot to a channel. + pub fn assign_bot(&mut self, channel: &str, bot: &str) -> Result<(), ChanError> { + let k = key(channel); + if !self.channels.contains_key(&k) { + return Err(ChanError::NoChannel); + } + self.log.append(Event::ChannelBotAssigned { channel: channel.to_string(), bot: bot.to_string() }).map_err(|_| ChanError::Internal)?; + self.channels.get_mut(&k).unwrap().assigned_bot = Some(bot.to_string()); + Ok(()) + } + + /// Unassign a channel's bot. Returns whether one was assigned. + pub fn unassign_bot(&mut self, channel: &str) -> Result { + let k = key(channel); + match self.channels.get(&k) { + None => return Err(ChanError::NoChannel), + Some(c) if c.assigned_bot.is_none() => return Ok(false), + Some(_) => {} + } + self.log.append(Event::ChannelBotUnassigned { channel: channel.to_string() }).map_err(|_| ChanError::Internal)?; + self.channels.get_mut(&k).unwrap().assigned_bot = None; + Ok(true) + } + /// Append a memo to an account's mailbox. pub fn memo_send(&mut self, account: &str, from: &str, text: &str) -> Result<(), RegError> { let k = key(account); @@ -1514,7 +1548,7 @@ fn apply(accounts: &mut HashMap, channels: &mut HashMap { - channels.insert(key(&name), ChannelInfo { name, founder, ts, lock_on: String::new(), lock_off: String::new(), access: Vec::new(), akick: Vec::new(), desc: String::new(), entrymsg: String::new(), settings: ChanSettings::default(), topic: String::new(), suspension: None }); + channels.insert(key(&name), ChannelInfo { name, founder, ts, lock_on: String::new(), lock_off: String::new(), access: Vec::new(), akick: Vec::new(), desc: String::new(), entrymsg: String::new(), settings: ChanSettings::default(), topic: String::new(), suspension: None, assigned_bot: None }); } Event::ChannelDropped { name } => { channels.remove(&key(&name)); @@ -1577,6 +1611,16 @@ fn apply(accounts: &mut HashMap, channels: &mut HashMap { + if let Some(c) = channels.get_mut(&key(&channel)) { + c.assigned_bot = Some(bot); + } + } + Event::ChannelBotUnassigned { channel } => { + if let Some(c) = channels.get_mut(&key(&channel)) { + c.assigned_bot = None; + } + } Event::BotAdded(b) => { bots.insert(key(&b.nick), b); } @@ -1793,6 +1837,12 @@ impl Store for Db { fn bots(&self) -> Vec { Db::bots(self).map(|b| BotView { nick: b.nick.clone(), user: b.user.clone(), host: b.host.clone(), gecos: b.gecos.clone() }).collect() } + fn assign_bot(&mut self, channel: &str, bot: &str) -> Result<(), ChanError> { + Db::assign_bot(self, channel, bot) + } + fn unassign_bot(&mut self, channel: &str) -> Result { + Db::unassign_bot(self, channel) + } fn memo_send(&mut self, account: &str, from: &str, text: &str) -> Result<(), RegError> { Db::memo_send(self, account, from, text) } @@ -1847,6 +1897,7 @@ fn channel_view(c: &ChannelInfo) -> ChannelView { topiclock: c.settings.topiclock, topic: c.topic.clone(), suspended: c.suspension.as_ref().is_some_and(|s| s.expires.is_none_or(|e| e > now())), + assigned_bot: c.assigned_bot.clone(), } } diff --git a/src/engine/mod.rs b/src/engine/mod.rs index 5b4e6e4..35c19f5 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -94,6 +94,7 @@ pub struct Engine { sid: String, // our services SID, for minting bot uids bot_uids: HashMap, // casefolded bot nick -> live uid (per connection) next_bot_index: u32, + bot_channels: std::collections::HashSet<(String, String)>, // (bot nick lc, channel) the bot has joined } impl Engine { @@ -113,6 +114,7 @@ impl Engine { sid: String::new(), bot_uids: HashMap::new(), next_bot_index: 0, + bot_channels: std::collections::HashSet::new(), } } @@ -159,6 +161,28 @@ impl Engine { if let Some(uid) = self.bot_uids.remove(&k) { out.push(NetAction::QuitUser { uid, reason: "Bot removed".to_string() }); } + self.bot_channels.retain(|(b, _)| *b != k); // its channel memberships go with it + } + // Join assigned channels, part unassigned ones (for still-live bots). + let assigned: Vec<(String, String)> = self.db.channels() + .filter_map(|c| c.assigned_bot.as_ref().map(|b| (b.to_ascii_lowercase(), c.name.clone()))) + .collect(); + let desired: std::collections::HashSet<(String, String)> = + assigned.into_iter().filter(|(b, _)| self.bot_uids.contains_key(b)).collect(); + for (bot_lc, chan) in &desired { + if !self.bot_channels.contains(&(bot_lc.clone(), chan.clone())) { + if let Some(uid) = self.bot_uids.get(bot_lc) { + out.push(NetAction::ServiceJoin { uid: uid.clone(), channel: chan.clone() }); + self.bot_channels.insert((bot_lc.clone(), chan.clone())); + } + } + } + let to_part: Vec<(String, String)> = self.bot_channels.iter().filter(|bc| !desired.contains(*bc)).cloned().collect(); + for (bot_lc, chan) in to_part { + self.bot_channels.remove(&(bot_lc.clone(), chan.clone())); + if let Some(uid) = self.bot_uids.get(&bot_lc) { + out.push(NetAction::ServicePart { uid: uid.clone(), channel: chan }); + } } out } @@ -426,6 +450,7 @@ impl Engine { pub fn startup_actions(&mut self) -> Vec { // Fresh link: forget bot uids minted on any previous connection. self.bot_uids.clear(); + self.bot_channels.clear(); self.next_bot_index = 0; let mut out = vec![NetAction::Burst]; for svc in &self.services { @@ -1674,6 +1699,46 @@ mod tests { assert!(e.startup_actions().iter().any(|a| matches!(a, NetAction::IntroduceUser { nick, .. } if nick == "Roger")), "introduced at burst"); } + // ASSIGN puts the bot in the channel; UNASSIGN takes it out. + #[test] + fn botserv_assign_joins_and_unassign_parts() { + use fedserv_botserv::BotServ; + use fedserv_nickserv::NickServ; + let path = std::env::temp_dir().join("fedserv-bsassign.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("staff", "password1", None).unwrap(); + db.register_channel("#c", "boss").unwrap(); + let mut e = Engine::new( + vec![ + Box::new(NickServ { uid: "42SAAAAAA".into(), guest_nick: "Guest".into(), guest_seq: 0 }), + Box::new(BotServ { uid: "42SAAAAAD".into() }), + ], + db, + ); + e.set_sid("42S".into()); + let mut opers = std::collections::HashMap::new(); + opers.insert("staff".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 bs = |e: &mut Engine, uid: &str, t: &str| e.handle(NetEvent::Privmsg { from: uid.into(), to: "42SAAAAAD".into(), text: t.into() }); + + e.handle(NetEvent::UserConnect { uid: "000AAAAAB".into(), nick: "boss".into(), host: "h".into() }); + e.handle(NetEvent::UserConnect { uid: "000AAAAAC".into(), nick: "staff".into(), host: "h".into() }); + ns(&mut e, "000AAAAAB", "IDENTIFY password1"); + ns(&mut e, "000AAAAAC", "IDENTIFY password1"); + bs(&mut e, "000AAAAAC", "BOT ADD Bendy bot serv.host Helper"); // goes live + + // The founder assigns the bot: it joins the channel. + let out = bs(&mut e, "000AAAAAB", "ASSIGN #c Bendy"); + assert!(out.iter().any(|a| matches!(a, NetAction::ServiceJoin { channel, .. } if channel == "#c")), "joins on assign: {out:?}"); + // Unassigning parts it. + let out = bs(&mut e, "000AAAAAB", "UNASSIGN #c"); + assert!(out.iter().any(|a| matches!(a, NetAction::ServicePart { channel, .. } if channel == "#c")), "parts on unassign: {out:?}"); + } + // MemoServ delivers a memo to an offline account and notifies them on login. #[test] fn memoserv_delivers_and_notifies_on_login() { diff --git a/src/grpc.rs b/src/grpc.rs index 324b8e8..e743287 100644 --- a/src/grpc.rs +++ b/src/grpc.rs @@ -139,6 +139,8 @@ fn to_wire(entry: &LogEntry) -> Option { | Event::ChannelTopicSet { .. } | Event::ChannelSuspended { .. } | Event::ChannelUnsuspended { .. } + | Event::ChannelBotAssigned { .. } + | Event::ChannelBotUnassigned { .. } | Event::BotAdded(_) | Event::BotRemoved { .. } => return None, };