chanserv: topic, invite, akick, list, status

Adds the remaining moderation and listing commands. Auto-kick masks are
stored in the event log and enforced on join: a matching user is banned
and kicked. Topic and invite are sourced from the ChanServ pseudoclient.
This commit is contained in:
Jean Chevronnet 2026-07-12 11:30:07 +00:00
parent acd0e60946
commit ba3803e01c
No known key found for this signature in database
11 changed files with 369 additions and 7 deletions

View file

@ -43,6 +43,8 @@ pub enum Event {
ChannelMlock { name: String, on: String, off: String },
ChannelAccessAdd { channel: String, account: String, level: String },
ChannelAccessDel { channel: String, account: String },
ChannelAkickAdd { channel: String, mask: String, reason: String },
ChannelAkickDel { channel: String, mask: String },
}
// An access-list entry: an account and its level ("op" or "voice").
@ -52,6 +54,13 @@ pub struct ChanAccess {
pub level: String,
}
// An auto-kick entry: a nick!user@host mask and why it was added.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChanAkick {
pub mask: String,
pub reason: String,
}
// A registered channel and who owns it.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChannelInfo {
@ -65,6 +74,8 @@ pub struct ChannelInfo {
pub lock_off: String,
#[serde(default)]
pub access: Vec<ChanAccess>,
#[serde(default)]
pub akick: Vec<ChanAkick>,
}
impl ChannelInfo {
@ -85,6 +96,11 @@ impl ChannelInfo {
self.join_mode(account) == Some("+o")
}
/// The matching auto-kick entry for `hostmask` (nick!user@host), if any.
pub fn akick_match(&self, hostmask: &str) -> Option<&ChanAkick> {
self.akick.iter().find(|k| glob_match(&k.mask, hostmask))
}
/// The mode string services keep applied: +r plus the lock.
pub fn lock_modes(&self) -> String {
let mut s = format!("+r{}", self.lock_on);
@ -376,6 +392,9 @@ impl Db {
for a in &c.access {
snapshot.push(Event::ChannelAccessAdd { channel: c.name.clone(), account: a.account.clone(), level: a.level.clone() });
}
for k in &c.akick {
snapshot.push(Event::ChannelAkickAdd { channel: c.name.clone(), mask: k.mask.clone(), reason: k.reason.clone() });
}
}
self.log.compact(snapshot)?;
tracing::info!(before, after = self.log.len(), "compacted event log");
@ -516,7 +535,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() });
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() });
Ok(())
}
@ -525,6 +544,11 @@ impl Db {
self.channels.get(&key(name))
}
/// All registered channels, for listing.
pub fn channels(&self) -> impl Iterator<Item = &ChannelInfo> {
self.channels.values()
}
/// Set the mode-lock (chars to keep set / unset) for a registered channel.
pub fn set_mlock(&mut self, name: &str, on: &str, off: &str) -> Result<(), ChanError> {
let k = key(name);
@ -571,6 +595,37 @@ impl Db {
Ok(true)
}
/// Add an auto-kick `mask` (with `reason`) to `channel`.
pub fn akick_add(&mut self, channel: &str, mask: &str, reason: &str) -> Result<(), ChanError> {
let k = key(channel);
if !self.channels.contains_key(&k) {
return Err(ChanError::NoChannel);
}
self.log
.append(Event::ChannelAkickAdd { channel: channel.to_string(), mask: mask.to_string(), reason: reason.to_string() })
.map_err(|_| ChanError::Internal)?;
let c = self.channels.get_mut(&k).unwrap();
c.akick.retain(|a| !a.mask.eq_ignore_ascii_case(mask));
c.akick.push(ChanAkick { mask: mask.to_string(), reason: reason.to_string() });
Ok(())
}
/// Remove auto-kick `mask` from `channel`. Ok(false) if not present.
pub fn akick_del(&mut self, channel: &str, mask: &str) -> Result<bool, ChanError> {
let k = key(channel);
let Some(c) = self.channels.get(&k) else {
return Err(ChanError::NoChannel);
};
if !c.akick.iter().any(|a| a.mask.eq_ignore_ascii_case(mask)) {
return Ok(false);
}
self.log
.append(Event::ChannelAkickDel { channel: channel.to_string(), mask: mask.to_string() })
.map_err(|_| ChanError::Internal)?;
self.channels.get_mut(&k).unwrap().akick.retain(|a| !a.mask.eq_ignore_ascii_case(mask));
Ok(true)
}
/// Unregister `name`.
pub fn drop_channel(&mut self, name: &str) -> Result<(), ChanError> {
let k = key(name);
@ -603,7 +658,7 @@ fn apply(accounts: &mut HashMap<String, Account>, channels: &mut HashMap<String,
}
}
Event::ChannelRegistered { name, founder, ts } => {
channels.insert(key(&name), ChannelInfo { name, founder, ts, lock_on: String::new(), lock_off: String::new(), access: Vec::new() });
channels.insert(key(&name), ChannelInfo { name, founder, ts, lock_on: String::new(), lock_off: String::new(), access: Vec::new(), akick: Vec::new() });
}
Event::ChannelDropped { name } => {
channels.remove(&key(&name));
@ -625,9 +680,51 @@ fn apply(accounts: &mut HashMap<String, Account>, channels: &mut HashMap<String,
c.access.retain(|a| !a.account.eq_ignore_ascii_case(&account));
}
}
Event::ChannelAkickAdd { channel, mask, reason } => {
if let Some(c) = channels.get_mut(&key(&channel)) {
c.akick.retain(|k| !k.mask.eq_ignore_ascii_case(&mask));
c.akick.push(ChanAkick { mask, reason });
}
}
Event::ChannelAkickDel { channel, mask } => {
if let Some(c) = channels.get_mut(&key(&channel)) {
c.akick.retain(|k| !k.mask.eq_ignore_ascii_case(&mask));
}
}
}
}
// Case-insensitive glob match supporting `*` (any run) and `?` (one char),
// used for auto-kick hostmasks. Iterative with backtracking, no allocation.
fn glob_match(pattern: &str, text: &str) -> bool {
let (p, t): (Vec<char>, Vec<char>) = (
pattern.chars().flat_map(char::to_lowercase).collect(),
text.chars().flat_map(char::to_lowercase).collect(),
);
let (mut pi, mut ti) = (0, 0);
let (mut star, mut mark) = (None, 0);
while ti < t.len() {
if pi < p.len() && (p[pi] == '?' || p[pi] == t[ti]) {
pi += 1;
ti += 1;
} else if pi < p.len() && p[pi] == '*' {
star = Some(pi);
mark = ti;
pi += 1;
} else if let Some(s) = star {
pi = s + 1;
mark += 1;
ti = mark;
} else {
return false;
}
}
while pi < p.len() && p[pi] == '*' {
pi += 1;
}
pi == p.len()
}
fn hash_password(password: &str) -> Option<String> {
let salt = SaltString::generate(&mut OsRng);
Argon2::default().hash_password(password.as_bytes(), &salt).ok().map(|h| h.to_string())
@ -653,6 +750,29 @@ mod tests {
Event::CertAdded { account: account.into(), fp: fp.into() }
}
#[test]
fn glob_matches_hostmasks() {
assert!(glob_match("*!*@host.example", "bob!~b@host.example"));
assert!(glob_match("bob!*@*", "BOB!~b@1.2.3.4"));
assert!(glob_match("*", "anything"));
assert!(glob_match("nick?!*@*", "nickX!~x@h"));
assert!(!glob_match("*!*@host.example", "bob!~b@other"));
assert!(!glob_match("alice!*@*", "bob!~b@h"));
}
#[test]
fn akick_add_del_and_match() {
let mut db = Db::open(&tmp("akick"), "N1");
db.register_channel("#c", "founder").unwrap();
db.akick_add("#c", "*!*@bad.host", "spam").unwrap();
let info = db.channel("#c").unwrap();
assert!(info.akick_match("evil!~e@bad.host").is_some());
assert!(info.akick_match("good!~g@ok.host").is_none());
assert!(db.akick_del("#c", "*!*@bad.host").unwrap());
assert!(!db.akick_del("#c", "*!*@bad.host").unwrap());
assert!(db.channel("#c").unwrap().akick.is_empty());
}
// Locally-authored events get an incrementing per-origin seq and a ticking
// Lamport clock.
#[test]

View file

@ -194,13 +194,28 @@ impl Engine {
// Give the founder and access-list members their status on join.
NetEvent::Join { uid, channel } => {
let account = self.network.account_of(&uid).map(str::to_string);
let from = self.chan_service.clone().unwrap_or_default();
let mode = account.as_deref().and_then(|a| self.db.channel(&channel).and_then(|c| c.join_mode(a)));
match mode {
Some(m) => {
let from = self.chan_service.clone().unwrap_or_default();
vec![NetAction::ChannelMode { from, channel, modes: format!("{m} {uid}") }]
// A user with access gets their status mode.
Some(m) => vec![NetAction::ChannelMode { from, channel, modes: format!("{m} {uid}") }],
// Otherwise, enforce the auto-kick list.
None => {
let nick = self.network.nick_of(&uid).unwrap_or("*");
let host = self.network.host_of(&uid).unwrap_or("*");
let hostmask = format!("{nick}!*@{host}");
match self.db.channel(&channel).and_then(|c| c.akick_match(&hostmask)) {
Some(k) => {
let mask = k.mask.clone();
let reason = if k.reason.is_empty() { "You are banned from this channel.".to_string() } else { k.reason.clone() };
vec![
NetAction::ChannelMode { from: from.clone(), channel: channel.clone(), modes: format!("+b {mask}") },
NetAction::Kick { from, channel, uid, reason },
]
}
None => Vec::new(),
}
}
None => Vec::new(),
}
}
NetEvent::Quit { uid } => {
@ -1033,6 +1048,47 @@ mod tests {
assert!(to_cs(&mut e, "000AAAAAD", "KICK #m alice").iter().any(|a| matches!(a, NetAction::Notice { text, .. } if text.contains("operator access"))));
}
// ChanServ topic, invite, auto-kick (with enforcement on join), list and status.
#[test]
fn chanserv_topic_invite_akick() {
use crate::chanserv::ChanServ;
let path = std::env::temp_dir().join("fedserv-cs-tia.jsonl");
let _ = std::fs::remove_file(&path);
let mut db = Db::open(&path, "42S");
db.scram_iterations = 4096;
db.register("alice", "sesame", None).unwrap();
db.register_channel("#c", "alice").unwrap();
let ns = NickServ { uid: "42SAAAAAA".into(), guest_nick: "Guest".into(), guest_seq: 0 };
let cs = ChanServ { uid: "42SAAAAAB".into() };
let mut e = Engine::new(vec![Box::new(ns), Box::new(cs)], db);
let to_cs = |e: &mut Engine, from: &str, text: &str| {
e.handle(NetEvent::Privmsg { from: from.into(), to: "42SAAAAAB".into(), text: text.into() })
};
e.handle(NetEvent::UserConnect { uid: "000AAAAAB".into(), nick: "alice".into(), host: "h1".into() });
e.handle(NetEvent::Privmsg { from: "000AAAAAB".into(), to: "42SAAAAAA".into(), text: "IDENTIFY sesame".into() });
e.handle(NetEvent::UserConnect { uid: "000AAAAAC".into(), nick: "bob".into(), host: "bad.host".into() });
// TOPIC and INVITE are sourced from ChanServ.
let out = to_cs(&mut e, "000AAAAAB", "TOPIC #c hello there");
assert!(out.iter().any(|a| matches!(a, NetAction::Topic { channel, topic, .. } if channel == "#c" && topic == "hello there")), "{out:?}");
let out = to_cs(&mut e, "000AAAAAB", "INVITE #c bob");
assert!(out.iter().any(|a| matches!(a, NetAction::Invite { uid, channel, .. } if uid == "000AAAAAC" && channel == "#c")), "{out:?}");
// LIST and STATUS.
assert!(to_cs(&mut e, "000AAAAAB", "LIST").iter().any(|a| matches!(a, NetAction::Notice { text, .. } if text.contains("#c"))));
assert!(to_cs(&mut e, "000AAAAAB", "STATUS #c").iter().any(|a| matches!(a, NetAction::Notice { text, .. } if text.contains("founder"))));
// AKICK a mask, then a matching join is banned and kicked.
assert!(to_cs(&mut e, "000AAAAAB", "AKICK #c ADD *!*@bad.host begone").iter().any(|a| matches!(a, NetAction::Notice { text, .. } if text.contains("Added"))));
let out = e.handle(NetEvent::Join { uid: "000AAAAAC".into(), channel: "#c".into() });
assert!(out.iter().any(|a| matches!(a, NetAction::ChannelMode { channel, modes, .. } if channel == "#c" && modes == "+b *!*@bad.host")), "{out:?}");
assert!(out.iter().any(|a| matches!(a, NetAction::Kick { channel, uid, reason, .. } if channel == "#c" && uid == "000AAAAAC" && reason == "begone")), "{out:?}");
// The founder joining is never auto-kicked (they get +o instead).
let out = e.handle(NetEvent::Join { uid: "000AAAAAB".into(), channel: "#c".into() });
assert!(out.iter().any(|a| matches!(a, NetAction::ChannelMode { modes, .. } if modes.starts_with("+o"))), "{out:?}");
}
// A registered channel (re)appearing re-asserts +r; an unregistered one does not.
#[test]
fn channel_create_reasserts_registered_mode() {

View file

@ -99,4 +99,22 @@ impl ServiceCtx {
reason: reason.to_string(),
});
}
// Set a channel's topic, sourced from pseudoclient `from`.
pub fn topic(&mut self, from: &str, channel: &str, topic: &str) {
self.actions.push(NetAction::Topic {
from: from.to_string(),
channel: channel.to_string(),
topic: topic.to_string(),
});
}
// Invite a user to a channel, sourced from pseudoclient `from`.
pub fn invite(&mut self, from: &str, uid: &str, channel: &str) {
self.actions.push(NetAction::Invite {
from: from.to_string(),
uid: uid.to_string(),
channel: channel.to_string(),
});
}
}