chanserv: SET TOPICLOCK and KEEPTOPIC (topic subsystem)

Adds topic tracking: a TopicChange event (parsed from InspIRCd FTOPIC, our own
changes filtered by SID like FMODE) and a stored topic on the channel, folded
through the event log. TOPICLOCK reverts a topic change by a user without
op-level access back to the stored topic; KEEPTOPIC remembers the topic and
restores it when a registered channel is recreated. Both via the typed
ChanSettings path; shown in INFO. Parse + engine tests cover both.
This commit is contained in:
Jean Chevronnet 2026-07-13 03:30:04 +00:00
parent d2c6448c6b
commit 4600ee062c
No known key found for this signature in database
7 changed files with 135 additions and 7 deletions

View file

@ -33,6 +33,9 @@ pub enum NetEvent {
ChannelModeChange { channel: String, modes: String },
// A channel's key (+k/-k) changed, tracked so GETKEY can report it.
ChannelKey { channel: String, key: Option<String> },
// A channel's topic changed (FTOPIC), for KEEPTOPIC / TOPICLOCK. `setter` is
// the source uid; our own changes are filtered out by the protocol layer.
TopicChange { channel: String, setter: String, topic: String },
Quit { uid: String },
// An ircd relaying an IRCv3 account-registration request to us as the authority.
AccountRequest { reqid: String, origin: String, kind: String, account: String, p2: String, p3: String },
@ -296,6 +299,10 @@ pub struct ChannelView {
pub private: bool,
pub peace: bool,
pub secureops: bool,
pub keeptopic: bool,
pub topiclock: bool,
// Last known topic (for KEEPTOPIC / TOPICLOCK).
pub topic: String,
}
// A single ChanServ SET option, named for the typed `set_channel_setting` call.
@ -305,6 +312,8 @@ pub enum ChanSetting {
Private,
Peace,
SecureOps,
KeepTopic,
TopicLock,
}
impl ChannelView {
@ -432,6 +441,7 @@ pub trait Store {
fn set_mlock(&mut self, name: &str, on: &str, off: &str) -> Result<(), ChanError>;
fn set_desc(&mut self, channel: &str, desc: &str) -> Result<(), ChanError>;
fn set_channel_setting(&mut self, channel: &str, setting: ChanSetting, on: bool) -> Result<(), ChanError>;
fn set_channel_topic(&mut self, channel: &str, topic: &str) -> Result<(), ChanError>;
fn set_entrymsg(&mut self, channel: &str, msg: &str) -> Result<(), ChanError>;
fn set_founder(&mut self, channel: &str, account: &str) -> Result<(), ChanError>;
fn access_add(&mut self, channel: &str, account: &str, level: &str) -> Result<(), ChanError>;

View file

@ -106,6 +106,8 @@ impl Service for ChanServ {
if info.private { opts.push("PRIVATE"); }
if info.peace { opts.push("PEACE"); }
if info.secureops { opts.push("SECUREOPS"); }
if info.keeptopic { opts.push("KEEPTOPIC"); }
if info.topiclock { opts.push("TOPICLOCK"); }
if !opts.is_empty() {
ctx.notice(me, from.uid, format!(" Options : {}", opts.join(", ")));
}

View file

@ -43,7 +43,9 @@ pub fn handle(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, db:
Some("PRIVATE") => toggle(me, from, ctx, db, chan, ChanSetting::Private, args.get(3).copied(), "PRIVATE"),
Some("PEACE") => toggle(me, from, ctx, db, chan, ChanSetting::Peace, args.get(3).copied(), "PEACE"),
Some("SECUREOPS") => toggle(me, from, ctx, db, chan, ChanSetting::SecureOps, args.get(3).copied(), "SECUREOPS"),
_ => ctx.notice(me, from.uid, "Syntax: SET <#channel> FOUNDER <account> | DESC <text> | SIGNKICK {ON|OFF} | PRIVATE {ON|OFF} | PEACE {ON|OFF} | SECUREOPS {ON|OFF}"),
Some("KEEPTOPIC") => toggle(me, from, ctx, db, chan, ChanSetting::KeepTopic, args.get(3).copied(), "KEEPTOPIC"),
Some("TOPICLOCK") => toggle(me, from, ctx, db, chan, ChanSetting::TopicLock, args.get(3).copied(), "TOPICLOCK"),
_ => ctx.notice(me, from.uid, "Syntax: SET <#channel> FOUNDER <account> | DESC <text> | SIGNKICK {ON|OFF} | PRIVATE {ON|OFF} | PEACE {ON|OFF} | SECUREOPS {ON|OFF} | KEEPTOPIC {ON|OFF} | TOPICLOCK {ON|OFF}"),
}
}

View file

@ -165,6 +165,17 @@ impl Protocol for InspIrcd {
_ => vec![],
}
}
// :<src> FTOPIC <chan> <chants> <topicts> [setby] :<topic> — a topic
// change. Skip changes we made ourselves so enforcement can't loop.
"FTOPIC" => {
let a: Vec<&str> = tokens.collect();
match (source.as_deref(), a.first()) {
(Some(src), Some(chan)) if !src.starts_with(self.sid.as_str()) && chan.starts_with('#') => {
vec![NetEvent::TopicChange { channel: chan.to_string(), setter: src.to_string(), topic: trailing(rest) }]
}
_ => vec![],
}
}
"QUIT" => vec![NetEvent::Quit { uid: source.unwrap_or_default() }],
// account-registration relay from an ircd:
// ACCTREGISTER <reqid> <origin> <kind> <account> <p2> :<p3>
@ -412,6 +423,21 @@ mod tests {
assert!(!ev.iter().any(|e| matches!(e, NetEvent::ChannelModeChange { .. })), "own change filtered: {ev:?}");
}
#[test]
fn parses_ftopic_and_filters_own() {
let ev = proto().parse(":0IRAAAAAB FTOPIC #chan 1783845132 1783845140 :Welcome all");
assert!(
matches!(ev.as_slice(), [NetEvent::TopicChange { channel, setter, topic }] if channel == "#chan" && setter == "0IRAAAAAB" && topic == "Welcome all"),
"{ev:?}"
);
// The burst/RESYNC form carries a setby field before the topic.
let ev = proto().parse(":0IRAAAAAB FTOPIC #chan 1783845132 1783845140 someone!u@h :Hi there");
assert!(matches!(ev.as_slice(), [NetEvent::TopicChange { topic, .. }] if topic == "Hi there"), "{ev:?}");
// Our own topic changes are filtered so enforcement can't loop.
let ev = proto().parse(":42S FTOPIC #chan 1 1 :nope");
assert!(!ev.iter().any(|e| matches!(e, NetEvent::TopicChange { .. })), "own change filtered: {ev:?}");
}
// FJOIN members and IJOIN both surface as Join events.
#[test]
fn parses_joins() {

View file

@ -83,6 +83,7 @@ pub enum Event {
ChannelDescSet { channel: String, desc: String },
ChannelEntryMsgSet { channel: String, msg: String },
ChannelSettingsSet { channel: String, settings: ChanSettings },
ChannelTopicSet { channel: String, topic: String },
}
// Whether an event replicates across the federation. Account identity is Global
@ -119,7 +120,8 @@ impl Event {
| Event::ChannelFounderSet { .. }
| Event::ChannelDescSet { .. }
| Event::ChannelEntryMsgSet { .. }
| Event::ChannelSettingsSet { .. } => Scope::Local,
| Event::ChannelSettingsSet { .. }
| Event::ChannelTopicSet { .. } => Scope::Local,
}
}
}
@ -163,6 +165,12 @@ pub struct ChanSettings {
// Strip channel-operator status from anyone without op-level access.
#[serde(default)]
pub secureops: bool,
// Remember the topic and restore it when the channel is recreated.
#[serde(default)]
pub keeptopic: bool,
// Revert topic changes made by users without op-level access.
#[serde(default)]
pub topiclock: bool,
}
// A registered channel and who owns it.
@ -189,6 +197,9 @@ pub struct ChannelInfo {
// On/off options set via ChanServ SET.
#[serde(default)]
pub settings: ChanSettings,
// Last known topic, kept for KEEPTOPIC / TOPICLOCK.
#[serde(default)]
pub topic: String,
}
impl ChannelInfo {
@ -592,9 +603,12 @@ impl Db {
if !c.entrymsg.is_empty() {
snapshot.push(Event::ChannelEntryMsgSet { channel: c.name.clone(), msg: c.entrymsg.clone() });
}
if c.settings.signkick || c.settings.private || c.settings.peace || c.settings.secureops {
if c.settings.signkick || c.settings.private || c.settings.peace || c.settings.secureops || c.settings.keeptopic || c.settings.topiclock {
snapshot.push(Event::ChannelSettingsSet { channel: c.name.clone(), settings: c.settings });
}
if !c.topic.is_empty() {
snapshot.push(Event::ChannelTopicSet { channel: c.name.clone(), topic: c.topic.clone() });
}
}
for (nick, account) in &self.grouped {
snapshot.push(Event::NickGrouped { nick: nick.clone(), account: account.clone() });
@ -977,7 +991,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() });
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() });
Ok(())
}
@ -1123,6 +1137,8 @@ impl Db {
ChanSetting::Private => settings.private = on,
ChanSetting::Peace => settings.peace = on,
ChanSetting::SecureOps => settings.secureops = on,
ChanSetting::KeepTopic => settings.keeptopic = on,
ChanSetting::TopicLock => settings.topiclock = on,
}
self.log
.append(Event::ChannelSettingsSet { channel: channel.to_string(), settings })
@ -1131,6 +1147,19 @@ impl Db {
Ok(())
}
/// Remember a channel's topic (KEEPTOPIC / TOPICLOCK).
pub fn set_channel_topic(&mut self, channel: &str, topic: &str) -> Result<(), ChanError> {
let k = key(channel);
if !self.channels.contains_key(&k) {
return Err(ChanError::NoChannel);
}
self.log
.append(Event::ChannelTopicSet { channel: channel.to_string(), topic: topic.to_string() })
.map_err(|_| ChanError::Internal)?;
self.channels.get_mut(&k).unwrap().topic = topic.to_string();
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);
@ -1232,7 +1261,7 @@ fn apply(accounts: &mut HashMap<String, Account>, channels: &mut HashMap<String,
grouped.remove(&key(&nick));
}
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() });
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() });
}
Event::ChannelDropped { name } => {
channels.remove(&key(&name));
@ -1280,6 +1309,11 @@ fn apply(accounts: &mut HashMap<String, Account>, channels: &mut HashMap<String,
c.settings = settings;
}
}
Event::ChannelTopicSet { channel, topic } => {
if let Some(c) = channels.get_mut(&key(&channel)) {
c.topic = topic;
}
}
Event::ChannelEntryMsgSet { channel, msg } => {
if let Some(c) = channels.get_mut(&key(&channel)) {
c.entrymsg = msg;
@ -1454,6 +1488,9 @@ impl Store for Db {
fn set_channel_setting(&mut self, channel: &str, setting: ChanSetting, on: bool) -> Result<(), ChanError> {
Db::set_channel_setting(self, channel, setting, on)
}
fn set_channel_topic(&mut self, channel: &str, topic: &str) -> Result<(), ChanError> {
Db::set_channel_topic(self, channel, topic)
}
fn set_entrymsg(&mut self, channel: &str, msg: &str) -> Result<(), ChanError> {
Db::set_entrymsg(self, channel, msg)
}
@ -1489,6 +1526,9 @@ fn channel_view(c: &ChannelInfo) -> ChannelView {
private: c.settings.private,
peace: c.settings.peace,
secureops: c.settings.secureops,
keeptopic: c.settings.keeptopic,
topiclock: c.settings.topiclock,
topic: c.topic.clone(),
}
}

View file

@ -405,7 +405,14 @@ impl Engine {
NetEvent::ChannelCreate { channel } => {
let from = self.chan_service.clone().unwrap_or_default();
match self.db.channel(&channel) {
Some(info) => vec![NetAction::ChannelMode { from, channel, modes: info.lock_modes() }],
Some(info) => {
let mut out = vec![NetAction::ChannelMode { from: from.clone(), channel: channel.clone(), modes: info.lock_modes() }];
// KEEPTOPIC: restore the remembered topic on a recreated channel.
if info.settings.keeptopic && !info.topic.is_empty() {
out.push(NetAction::Topic { from, channel, topic: info.topic.clone() });
}
out
}
None => Vec::new(),
}
}
@ -485,6 +492,24 @@ impl Engine {
self.network.set_channel_key(&channel, key);
Vec::new()
}
NetEvent::TopicChange { channel, setter, topic } => {
let info = self.db.channel(&channel).map(|c| (c.settings.keeptopic, c.settings.topiclock, c.topic.clone()));
// The setter may change a locked topic only with op-level access.
let authorized = self.network.account_of(&setter).and_then(|a| self.db.channel(&channel).map(|c| c.join_mode(a) == Some("+o"))).unwrap_or(false);
match info {
// TOPICLOCK + unauthorised: put the kept topic back.
Some((_, true, stored)) if !authorized => {
let from = self.chan_service.clone().unwrap_or_default();
vec![NetAction::Topic { from, channel, topic: stored }]
}
// Otherwise remember the new topic if the channel keeps it.
Some((keep, lock, _)) if keep || lock => {
let _ = self.db.set_channel_topic(&channel, &topic);
Vec::new()
}
_ => Vec::new(),
}
}
NetEvent::Quit { uid } => {
self.network.user_quit(&uid);
self.sasl_sessions.remove(&uid); // drop any half-finished exchange
@ -1506,6 +1531,28 @@ mod tests {
assert!(out.is_empty(), "no enforcement when SECUREOPS is off: {out:?}");
}
// TOPICLOCK reverts an unauthorised topic change; KEEPTOPIC restores the
// remembered topic when the channel is recreated.
#[test]
fn topiclock_reverts_and_keeptopic_restores() {
use fedserv_chanserv::ChanServ;
let path = std::env::temp_dir().join("fedserv-topic.jsonl");
let _ = std::fs::remove_file(&path);
let mut db = Db::open(&path, "42S");
db.register_channel("#c", "boss").unwrap();
db.set_channel_setting("#c", db::ChanSetting::KeepTopic, true).unwrap();
db.set_channel_setting("#c", db::ChanSetting::TopicLock, true).unwrap();
db.set_channel_topic("#c", "Official topic").unwrap();
let mut e = Engine::new(vec![Box::new(ChanServ { uid: "42SAAAAAB".into() })], db);
e.handle(NetEvent::UserConnect { uid: "000AAAAAB".into(), nick: "rando".into(), host: "h".into() });
// A user without access changes the topic -> reverted to the stored one.
let out = e.handle(NetEvent::TopicChange { channel: "#c".into(), setter: "000AAAAAB".into(), topic: "hacked".into() });
assert!(out.iter().any(|a| matches!(a, NetAction::Topic { topic, .. } if topic == "Official topic")), "topiclock reverts: {out:?}");
// KEEPTOPIC restores the remembered topic on channel (re)creation.
let out = e.handle(NetEvent::ChannelCreate { channel: "#c".into() });
assert!(out.iter().any(|a| matches!(a, NetAction::Topic { topic, .. } if topic == "Official topic")), "keeptopic restores: {out:?}");
}
// ChanServ: registration needs identification, INFO shows the founder, and
// only the founder can drop.
#[test]

View file

@ -130,7 +130,8 @@ fn to_wire(entry: &LogEntry) -> Option<ReplicationEvent> {
| Event::ChannelAkickAdd { .. }
| Event::ChannelAkickDel { .. }
| Event::ChannelEntryMsgSet { .. }
| Event::ChannelSettingsSet { .. } => return None,
| Event::ChannelSettingsSet { .. }
| Event::ChannelTopicSet { .. } => return None,
};
Some(ReplicationEvent { origin: entry.origin().to_string(), seq: entry.seq(), lamport: entry.lamport(), kind: Some(kind) })
}