botserv: ASSIGN / UNASSIGN a bot to a channel

A channel gains a typed assigned_bot (event-logged, snapshotted). ASSIGN
<#channel> <bot> / 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.
This commit is contained in:
Jean Chevronnet 2026-07-13 13:42:14 +00:00
parent f94b0afcd9
commit b25870e14b
No known key found for this signature in database
6 changed files with 170 additions and 4 deletions

View file

@ -67,6 +67,9 @@ pub enum NetAction {
ForceJoin { uid: String, channel: String, key: String }, ForceJoin { uid: String, channel: String, key: String },
// Remove one of our pseudo-clients (e.g. a deleted bot) from the network. // Remove one of our pseudo-clients (e.g. a deleted bot) from the network.
QuitUser { uid: String, reason: String }, 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 // 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 // the pseudoclient uid to source it from (empty = the services server). The
// protocol stamps a timestamp the ircd will accept. // protocol stamps a timestamp the ircd will accept.
@ -368,6 +371,8 @@ pub struct ChannelView {
pub suspended: bool, pub suspended: bool,
// Last known topic (for KEEPTOPIC / TOPICLOCK). // Last known topic (for KEEPTOPIC / TOPICLOCK).
pub topic: String, pub topic: String,
// BotServ bot assigned to this channel, if any.
pub assigned_bot: Option<String>,
} }
// A single ChanServ SET option, named for the typed `set_channel_setting` call. // 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_add(&mut self, nick: &str, user: &str, host: &str, gecos: &str) -> Result<(), ChanError>;
fn bot_del(&mut self, nick: &str) -> Result<bool, ChanError>; fn bot_del(&mut self, nick: &str) -> Result<bool, ChanError>;
fn bots(&self) -> Vec<BotView>; fn bots(&self) -> Vec<BotView>;
fn assign_bot(&mut self, channel: &str, bot: &str) -> Result<(), ChanError>;
fn unassign_bot(&mut self, channel: &str) -> Result<bool, ChanError>;
// MemoServ: per-account memos (index is a 0-based position in memo_list). // 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_send(&mut self, account: &str, from: &str, text: &str) -> Result<(), RegError>;
fn memo_list(&self, account: &str) -> Vec<MemoView>; fn memo_list(&self, account: &str) -> Vec<MemoView>;

View file

@ -23,13 +23,52 @@ impl Service for BotServ {
let me = self.uid.as_str(); let me = self.uid.as_str();
match args.first().map(|s| s.to_ascii_uppercase()).as_deref() { match args.first().map(|s| s.to_ascii_uppercase()).as_deref() {
Some("BOT") => bot(me, from, args, ctx, db), 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> <bot> 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.")), Some(other) => ctx.notice(me, from.uid, format!("I don't know the command \x02{other}\x02. Try \x02HELP\x02.")),
None => {}
} }
} }
} }
// ASSIGN <#channel> <bot> / 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> <bot>" } 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> <bot>");
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 <nick> <user> <host> [gecos] | BOT DEL <nick> | BOT LIST — manage the // BOT ADD <nick> <user> <host> [gecos] | BOT DEL <nick> | BOT LIST — manage the
// bot registry. Administering bots is oper-only (Priv::Admin). // bot registry. Administering bots is oper-only (Priv::Admin).
fn bot(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, db: &mut dyn Store) { fn bot(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, db: &mut dyn Store) {

View file

@ -262,6 +262,8 @@ impl Protocol for InspIrcd {
// SVSNICK <uid> <newnick> <nickts> — the new nick takes the current // SVSNICK <uid> <newnick> <nickts> — the new nick takes the current
// time as its TS so it wins any collision resolution. // time as its TS so it wins any collision resolution.
NetAction::QuitUser { uid, reason } => vec![format!(":{} QUIT :{}", uid, reason)], 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 } => { NetAction::ForceNick { uid, nick } => {
let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(self.ts); 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))] vec![self.from_us(format!("SVSNICK {} {} {}", uid, nick, now))]

View file

@ -97,6 +97,8 @@ pub enum Event {
ChannelTopicSet { channel: String, topic: String }, ChannelTopicSet { channel: String, topic: String },
ChannelSuspended { channel: String, by: String, reason: String, ts: u64, expires: Option<u64> }, ChannelSuspended { channel: String, by: String, reason: String, ts: u64, expires: Option<u64> },
ChannelUnsuspended { channel: String }, ChannelUnsuspended { channel: String },
ChannelBotAssigned { channel: String, bot: String },
ChannelBotUnassigned { channel: String },
BotAdded(Bot), BotAdded(Bot),
BotRemoved { nick: String }, BotRemoved { nick: String },
} }
@ -144,6 +146,8 @@ impl Event {
| Event::ChannelTopicSet { .. } | Event::ChannelTopicSet { .. }
| Event::ChannelSuspended { .. } | Event::ChannelSuspended { .. }
| Event::ChannelUnsuspended { .. } | Event::ChannelUnsuspended { .. }
| Event::ChannelBotAssigned { .. }
| Event::ChannelBotUnassigned { .. }
| Event::BotAdded(_) | Event::BotAdded(_)
| Event::BotRemoved { .. } => Scope::Local, | Event::BotRemoved { .. } => Scope::Local,
} }
@ -257,6 +261,9 @@ pub struct ChannelInfo {
// Services suspension, if any (channel frozen while set and unexpired). // Services suspension, if any (channel frozen while set and unexpired).
#[serde(default)] #[serde(default)]
pub suspension: Option<Suspension>, pub suspension: Option<Suspension>,
// BotServ bot assigned to sit in this channel, if any (its nick).
#[serde(default)]
pub assigned_bot: Option<String>,
} }
impl ChannelInfo { impl ChannelInfo {
@ -672,6 +679,9 @@ impl Db {
if let Some(s) = &c.suspension { 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 }); 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 { for (nick, account) in &self.grouped {
snapshot.push(Event::NickGrouped { nick: nick.clone(), account: account.clone() }); snapshot.push(Event::NickGrouped { nick: nick.clone(), account: account.clone() });
@ -1102,7 +1112,7 @@ impl Db {
self.log self.log
.append(Event::ChannelRegistered { name: name.to_string(), founder: founder.to_string(), ts }) .append(Event::ChannelRegistered { name: name.to_string(), founder: founder.to_string(), ts })
.map_err(|_| ChanError::Internal)?; .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(()) Ok(())
} }
@ -1334,6 +1344,30 @@ impl Db {
self.bots.values() 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<bool, ChanError> {
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. /// Append a memo to an account's mailbox.
pub fn memo_send(&mut self, account: &str, from: &str, text: &str) -> Result<(), RegError> { pub fn memo_send(&mut self, account: &str, from: &str, text: &str) -> Result<(), RegError> {
let k = key(account); let k = key(account);
@ -1514,7 +1548,7 @@ fn apply(accounts: &mut HashMap<String, Account>, channels: &mut HashMap<String,
grouped.remove(&key(&nick)); grouped.remove(&key(&nick));
} }
Event::ChannelRegistered { name, founder, ts } => { Event::ChannelRegistered { name, founder, ts } => {
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 } => { Event::ChannelDropped { name } => {
channels.remove(&key(&name)); channels.remove(&key(&name));
@ -1577,6 +1611,16 @@ fn apply(accounts: &mut HashMap<String, Account>, channels: &mut HashMap<String,
c.suspension = None; c.suspension = None;
} }
} }
Event::ChannelBotAssigned { channel, bot } => {
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) => { Event::BotAdded(b) => {
bots.insert(key(&b.nick), b); bots.insert(key(&b.nick), b);
} }
@ -1793,6 +1837,12 @@ impl Store for Db {
fn bots(&self) -> Vec<BotView> { fn bots(&self) -> Vec<BotView> {
Db::bots(self).map(|b| BotView { nick: b.nick.clone(), user: b.user.clone(), host: b.host.clone(), gecos: b.gecos.clone() }).collect() 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<bool, ChanError> {
Db::unassign_bot(self, channel)
}
fn memo_send(&mut self, account: &str, from: &str, text: &str) -> Result<(), RegError> { fn memo_send(&mut self, account: &str, from: &str, text: &str) -> Result<(), RegError> {
Db::memo_send(self, account, from, text) Db::memo_send(self, account, from, text)
} }
@ -1847,6 +1897,7 @@ fn channel_view(c: &ChannelInfo) -> ChannelView {
topiclock: c.settings.topiclock, topiclock: c.settings.topiclock,
topic: c.topic.clone(), topic: c.topic.clone(),
suspended: c.suspension.as_ref().is_some_and(|s| s.expires.is_none_or(|e| e > now())), suspended: c.suspension.as_ref().is_some_and(|s| s.expires.is_none_or(|e| e > now())),
assigned_bot: c.assigned_bot.clone(),
} }
} }

View file

@ -94,6 +94,7 @@ pub struct Engine {
sid: String, // our services SID, for minting bot uids sid: String, // our services SID, for minting bot uids
bot_uids: HashMap<String, String>, // casefolded bot nick -> live uid (per connection) bot_uids: HashMap<String, String>, // casefolded bot nick -> live uid (per connection)
next_bot_index: u32, next_bot_index: u32,
bot_channels: std::collections::HashSet<(String, String)>, // (bot nick lc, channel) the bot has joined
} }
impl Engine { impl Engine {
@ -113,6 +114,7 @@ impl Engine {
sid: String::new(), sid: String::new(),
bot_uids: HashMap::new(), bot_uids: HashMap::new(),
next_bot_index: 0, 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) { if let Some(uid) = self.bot_uids.remove(&k) {
out.push(NetAction::QuitUser { uid, reason: "Bot removed".to_string() }); 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 out
} }
@ -426,6 +450,7 @@ impl Engine {
pub fn startup_actions(&mut self) -> Vec<NetAction> { pub fn startup_actions(&mut self) -> Vec<NetAction> {
// Fresh link: forget bot uids minted on any previous connection. // Fresh link: forget bot uids minted on any previous connection.
self.bot_uids.clear(); self.bot_uids.clear();
self.bot_channels.clear();
self.next_bot_index = 0; self.next_bot_index = 0;
let mut out = vec![NetAction::Burst]; let mut out = vec![NetAction::Burst];
for svc in &self.services { 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"); 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. // MemoServ delivers a memo to an offline account and notifies them on login.
#[test] #[test]
fn memoserv_delivers_and_notifies_on_login() { fn memoserv_delivers_and_notifies_on_login() {

View file

@ -139,6 +139,8 @@ fn to_wire(entry: &LogEntry) -> Option<ReplicationEvent> {
| Event::ChannelTopicSet { .. } | Event::ChannelTopicSet { .. }
| Event::ChannelSuspended { .. } | Event::ChannelSuspended { .. }
| Event::ChannelUnsuspended { .. } | Event::ChannelUnsuspended { .. }
| Event::ChannelBotAssigned { .. }
| Event::ChannelBotUnassigned { .. }
| Event::BotAdded(_) | Event::BotAdded(_)
| Event::BotRemoved { .. } => return None, | Event::BotRemoved { .. } => return None,
}; };