chanserv: entrymsg, enforce, getkey, seen, clone, aop/sop/vop

Tracks channel membership (join/part/kick), the current key, and per-nick
last-seen in the network view. Entry messages greet joiners; enforce
re-applies the lock, access modes and auto-kicks to everyone present;
getkey reports the key; seen reports last activity; clone copies a
channel's settings; aop/sop/vop are tiered shortcuts over the access list.
This commit is contained in:
Jean Chevronnet 2026-07-12 11:53:48 +00:00
parent 674f543b40
commit e8b55bdb27
No known key found for this signature in database
12 changed files with 479 additions and 26 deletions

View file

@ -47,6 +47,7 @@ pub enum Event {
ChannelAkickDel { channel: String, mask: String },
ChannelFounderSet { channel: String, founder: String },
ChannelDescSet { channel: String, desc: String },
ChannelEntryMsgSet { channel: String, msg: String },
}
// An access-list entry: an account and its level ("op" or "voice").
@ -81,6 +82,9 @@ pub struct ChannelInfo {
// Free-text description, shown in INFO.
#[serde(default)]
pub desc: String,
// Message noticed to users as they join.
#[serde(default)]
pub entrymsg: String,
}
impl ChannelInfo {
@ -403,6 +407,9 @@ impl Db {
if !c.desc.is_empty() {
snapshot.push(Event::ChannelDescSet { channel: c.name.clone(), desc: c.desc.clone() });
}
if !c.entrymsg.is_empty() {
snapshot.push(Event::ChannelEntryMsgSet { channel: c.name.clone(), msg: c.entrymsg.clone() });
}
}
self.log.compact(snapshot)?;
tracing::info!(before, after = self.log.len(), "compacted event log");
@ -543,7 +550,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() });
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() });
Ok(())
}
@ -660,6 +667,19 @@ impl Db {
Ok(())
}
/// Set `channel`'s entry message (empty clears it).
pub fn set_entrymsg(&mut self, channel: &str, msg: &str) -> Result<(), ChanError> {
let k = key(channel);
if !self.channels.contains_key(&k) {
return Err(ChanError::NoChannel);
}
self.log
.append(Event::ChannelEntryMsgSet { channel: channel.to_string(), msg: msg.to_string() })
.map_err(|_| ChanError::Internal)?;
self.channels.get_mut(&k).unwrap().entrymsg = msg.to_string();
Ok(())
}
/// Unregister `name`.
pub fn drop_channel(&mut self, name: &str) -> Result<(), ChanError> {
let k = key(name);
@ -692,7 +712,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(), akick: Vec::new(), desc: String::new() });
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() });
}
Event::ChannelDropped { name } => {
channels.remove(&key(&name));
@ -735,6 +755,11 @@ fn apply(accounts: &mut HashMap<String, Account>, channels: &mut HashMap<String,
c.desc = desc;
}
}
Event::ChannelEntryMsgSet { channel, msg } => {
if let Some(c) = channels.get_mut(&key(&channel)) {
c.entrymsg = msg;
}
}
}
}

View file

@ -191,32 +191,55 @@ impl Engine {
None => Vec::new(),
}
}
// Give the founder and access-list members their status on join.
// On join: record membership, enforce the auto-kick list, give access
// members their status mode, and send the entry message.
NetEvent::Join { uid, channel } => {
self.network.channel_join(&channel, &uid);
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)));
let entrymsg = self.db.channel(&channel).map(|c| c.entrymsg.clone()).filter(|m| !m.is_empty());
let mut out = Vec::new();
match mode {
// 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.
// A user with access gets their status mode, plus the entry message.
Some(m) => {
if let Some(msg) = entrymsg {
out.push(NetAction::Notice { from: from.clone(), to: uid.clone(), text: msg });
}
out.push(NetAction::ChannelMode { from, channel, modes: format!("{m} {uid}") });
}
// No access: an auto-kick match is banned and kicked, else greeted.
None => {
let nick = self.network.nick_of(&uid).unwrap_or("*");
let host = self.network.host_of(&uid).unwrap_or("*");
let nick = self.network.nick_of(&uid).unwrap_or("*").to_string();
let host = self.network.host_of(&uid).unwrap_or("*").to_string();
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 },
]
let akick = self.db.channel(&channel).and_then(|c| c.akick_match(&hostmask)).map(|k| {
let reason = if k.reason.is_empty() { "You are banned from this channel.".to_string() } else { k.reason.clone() };
(k.mask.clone(), reason)
});
match akick {
Some((mask, reason)) => {
self.network.channel_part(&channel, &uid);
out.push(NetAction::ChannelMode { from: from.clone(), channel: channel.clone(), modes: format!("+b {mask}") });
out.push(NetAction::Kick { from, channel, uid, reason });
}
None => {
if let Some(msg) = entrymsg {
out.push(NetAction::Notice { from, to: uid, text: msg });
}
}
None => Vec::new(),
}
}
}
out
}
NetEvent::Part { uid, channel } => {
self.network.channel_part(&channel, &uid);
Vec::new()
}
NetEvent::ChannelKey { channel, key } => {
self.network.set_channel_key(&channel, key);
Vec::new()
}
NetEvent::Quit { uid } => {
self.network.user_quit(&uid);
@ -1124,6 +1147,61 @@ mod tests {
assert!(notice(&to_cs(&mut e, "000AAAAAB", "SET #c DESC nope"), "founder can change"));
}
// ChanServ entrymsg, enforce, getkey, seen, clone and the xop lists.
#[test]
fn chanserv_extended() {
use crate::chanserv::ChanServ;
let path = std::env::temp_dir().join("fedserv-cs-ext.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("carol", "pw", 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() })
};
let notice = |out: &[NetAction], needle: &str| {
out.iter().any(|a| matches!(a, NetAction::Notice { text, .. } if text.contains(needle)))
};
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() });
// ENTRYMSG: set it, then a joining user is noticed it.
assert!(notice(&to_cs(&mut e, "000AAAAAB", "ENTRYMSG #c welcome aboard"), "updated"));
e.handle(NetEvent::UserConnect { uid: "000AAAAAC".into(), nick: "guest".into(), host: "h2".into() });
let out = e.handle(NetEvent::Join { uid: "000AAAAAC".into(), channel: "#c".into() });
assert!(out.iter().any(|a| matches!(a, NetAction::Notice { to, text, .. } if to == "000AAAAAC" && text == "welcome aboard")), "{out:?}");
// XOP: AOP add shows in the AOP list and grants op access.
assert!(notice(&to_cs(&mut e, "000AAAAAB", "AOP #c ADD carol"), "Added"));
assert!(notice(&to_cs(&mut e, "000AAAAAB", "AOP #c LIST"), "carol"));
// ENFORCE: alice present gets +o, the akick-matching guest is kicked.
e.handle(NetEvent::Join { uid: "000AAAAAB".into(), channel: "#c".into() });
to_cs(&mut e, "000AAAAAB", "AKICK #c ADD *!*@h2 out");
let out = to_cs(&mut e, "000AAAAAB", "ENFORCE #c");
assert!(out.iter().any(|a| matches!(a, NetAction::ChannelMode { modes, .. } if modes == "+o 000AAAAAB")), "{out:?}");
assert!(out.iter().any(|a| matches!(a, NetAction::Kick { uid, .. } if uid == "000AAAAAC")), "{out:?}");
// GETKEY: reflects a tracked key change.
e.handle(NetEvent::ChannelKey { channel: "#c".into(), key: Some("s3cret".into()) });
assert!(notice(&to_cs(&mut e, "000AAAAAB", "GETKEY #c"), "s3cret"));
// SEEN: an online user vs one who quit.
assert!(notice(&to_cs(&mut e, "000AAAAAB", "SEEN alice"), "currently online"));
e.handle(NetEvent::Quit { uid: "000AAAAAC".into() });
assert!(notice(&to_cs(&mut e, "000AAAAAB", "SEEN guest"), "last seen"));
// CLONE: copy #c's settings (incl. the AOP) into a second owned channel.
e.handle(NetEvent::Privmsg { from: "000AAAAAB".into(), to: "42SAAAAAB".into(), text: "REGISTER #d".into() });
assert!(notice(&to_cs(&mut e, "000AAAAAB", "CLONE #c #d"), "Copied"));
assert!(notice(&to_cs(&mut e, "000AAAAAB", "AOP #d LIST"), "carol"));
}
// A registered channel (re)appearing re-asserts +r; an unregistered one does not.
#[test]
fn channel_create_reasserts_registered_mode() {

View file

@ -1,12 +1,14 @@
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::time::{SystemTime, UNIX_EPOCH};
// Live network view, rebuilt from the uplink's burst each connect (ephemeral —
// unlike the account store, which persists).
#[derive(Default)]
pub struct Network {
pub users: HashMap<String, User>, // keyed by UID
pub channels: HashMap<String, Channel>,
channels: HashMap<String, Channel>, // keyed by lowercase name
accounts: HashMap<String, String>, // UID -> logged-in account, until logout/quit
seen: HashMap<String, Seen>, // lowercase nick -> last activity
}
pub struct User {
@ -15,10 +17,26 @@ pub struct User {
pub host: String,
}
#[allow(dead_code)]
// A channel's live membership and current key (+k), tracked from the burst.
#[derive(Default)]
pub struct Channel {
pub name: String,
pub members: HashSet<String>, // uids
pub key: Option<String>,
}
// The last time a nick was seen, and doing what.
pub struct Seen {
pub nick: String,
pub ts: u64,
pub what: String,
}
fn now() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
}
fn lc(s: &str) -> String {
s.to_ascii_lowercase()
}
impl Network {
@ -37,13 +55,20 @@ impl Network {
pub fn user_nick_change(&mut self, uid: &str, nick: String) {
if let Some(user) = self.users.get_mut(uid) {
self.seen.insert(lc(&nick), Seen { nick: nick.clone(), ts: now(), what: format!("changing nick from {}", user.nick) });
user.nick = nick;
}
}
pub fn user_quit(&mut self, uid: &str) {
if let Some(u) = self.users.get(uid) {
self.seen.insert(lc(&u.nick), Seen { nick: u.nick.clone(), ts: now(), what: "quitting".to_string() });
}
self.users.remove(uid);
self.accounts.remove(uid);
for c in self.channels.values_mut() {
c.members.remove(uid);
}
}
pub fn nick_of(&self, uid: &str) -> Option<&str> {
@ -63,4 +88,39 @@ impl Network {
pub fn clear_account(&mut self, uid: &str) {
self.accounts.remove(uid);
}
// A user joined a channel: record membership and last-seen.
pub fn channel_join(&mut self, channel: &str, uid: &str) {
self.channels.entry(lc(channel)).or_default().members.insert(uid.to_string());
if let Some(nick) = self.nick_of(uid) {
self.seen.insert(lc(nick), Seen { nick: nick.to_string(), ts: now(), what: format!("joining {channel}") });
}
}
// A user left a channel (part/kick): drop membership and record last-seen.
pub fn channel_part(&mut self, channel: &str, uid: &str) {
if let Some(c) = self.channels.get_mut(&lc(channel)) {
c.members.remove(uid);
}
if let Some(nick) = self.nick_of(uid) {
self.seen.insert(lc(nick), Seen { nick: nick.to_string(), ts: now(), what: format!("leaving {channel}") });
}
}
// Uids currently in `channel`.
pub fn channel_members(&self, channel: &str) -> impl Iterator<Item = &str> {
self.channels.get(&lc(channel)).into_iter().flat_map(|c| c.members.iter().map(String::as_str))
}
pub fn set_channel_key(&mut self, channel: &str, key: Option<String>) {
self.channels.entry(lc(channel)).or_default().key = key;
}
pub fn channel_key(&self, channel: &str) -> Option<&str> {
self.channels.get(&lc(channel)).and_then(|c| c.key.as_deref())
}
pub fn last_seen(&self, nick: &str) -> Option<&Seen> {
self.seen.get(&lc(nick))
}
}