diff --git a/api/src/lib.rs b/api/src/lib.rs index 05745f9..49365af 100644 --- a/api/src/lib.rs +++ b/api/src/lib.rs @@ -449,6 +449,14 @@ pub struct AkillView { pub expires: Option, } +// A services ignore held by OperServ. +#[derive(Debug, Clone)] +pub struct IgnoreView { + pub mask: String, + pub reason: String, + pub expires: Option, +} + #[derive(Debug, Clone)] pub struct BotView { pub nick: String, @@ -701,6 +709,10 @@ pub trait Store { fn akill_add(&mut self, kind: &str, mask: &str, setter: &str, reason: &str, expires: Option) -> Result; fn akill_del(&mut self, kind: &str, mask: &str) -> Result; fn akills(&self) -> Vec; + // Services ignores (node-local, oper-only). + fn ignore_add(&mut self, mask: &str, reason: &str, expires: Option); + fn ignore_del(&mut self, mask: &str) -> bool; + fn ignores(&self) -> Vec; fn register_channel(&mut self, name: &str, founder: &str) -> Result<(), ChanError>; fn drop_channel(&mut self, name: &str) -> Result<(), ChanError>; fn set_mlock(&mut self, name: &str, on: &str, off: &str) -> Result<(), ChanError>; diff --git a/operserv/src/ignore.rs b/operserv/src/ignore.rs new file mode 100644 index 0000000..0b751eb --- /dev/null +++ b/operserv/src/ignore.rs @@ -0,0 +1,80 @@ +use fedserv_api::{parse_duration, Priv, Sender, ServiceCtx, Store}; +use std::time::{SystemTime, UNIX_EPOCH}; + +// IGNORE ADD [+expiry] [reason] | DEL | LIST: services silently +// drop commands from a matching user. A mask with an '@' matches nick!*@host +// (ident isn't tracked); a bare mask matches the nick. Admin-only, node-local. +pub fn handle(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, db: &mut dyn Store) { + if !from.privs.has(Priv::Admin) { + ctx.notice(me, from.uid, "Access denied — IGNORE needs the \x02admin\x02 privilege."); + return; + } + match args.get(1).map(|s| s.to_ascii_uppercase()).as_deref() { + Some("ADD") => add(me, from, &args[2..], ctx, db), + Some("DEL") | Some("REMOVE") => del(me, from, args.get(2).copied(), ctx, db), + Some("LIST") | Some("VIEW") => list(me, from, ctx, db), + _ => ctx.notice(me, from.uid, "Syntax: IGNORE ADD [+expiry] [reason] | IGNORE DEL | IGNORE LIST"), + } +} + +fn add(me: &str, from: &Sender, rest: &[&str], ctx: &mut ServiceCtx, db: &mut dyn Store) { + let mut rest = rest; + let duration = rest.first().and_then(|t| t.strip_prefix('+')).and_then(parse_duration); + if duration.is_some() { + rest = &rest[1..]; + } + let Some((&mask, reason_words)) = rest.split_first() else { + ctx.notice(me, from.uid, "Syntax: IGNORE ADD [+expiry] [reason]"); + return; + }; + if mask.is_empty() || mask.chars().all(|c| c == '*' || c == '?') { + ctx.notice(me, from.uid, "That mask is too wide."); + return; + } + let reason = if reason_words.is_empty() { "No reason given".to_string() } else { reason_words.join(" ") }; + let expires = duration.map(|secs| now() + secs); + db.ignore_add(mask, &reason, expires); + let expiry = if expires.is_some() { " (temporary)" } else { "" }; + ctx.notice(me, from.uid, format!("Now ignoring \x02{mask}\x02{expiry}.")); +} + +fn del(me: &str, from: &Sender, arg: Option<&str>, ctx: &mut ServiceCtx, db: &mut dyn Store) { + let Some(mask) = arg else { + ctx.notice(me, from.uid, "Syntax: IGNORE DEL "); + return; + }; + if db.ignore_del(mask) { + ctx.notice(me, from.uid, format!("No longer ignoring \x02{mask}\x02.")); + } else { + ctx.notice(me, from.uid, format!("\x02{mask}\x02 isn't on the ignore list.")); + } +} + +fn list(me: &str, from: &Sender, ctx: &mut ServiceCtx, db: &mut dyn Store) { + let ignores = db.ignores(); + if ignores.is_empty() { + ctx.notice(me, from.uid, "The services ignore list is empty."); + return; + } + for (i, ig) in ignores.iter().enumerate() { + let expiry = match ig.expires { + Some(e) => format!(", expires in {}", human_secs(e.saturating_sub(now()))), + None => String::new(), + }; + ctx.notice(me, from.uid, format!("{}. \x02{}\x02 — {}{}", i + 1, ig.mask, ig.reason, expiry)); + } + ctx.notice(me, from.uid, format!("End of ignore list ({} shown).", ignores.len())); +} + +fn human_secs(secs: u64) -> String { + match secs { + 0 => "moments".to_string(), + s if s < 3600 => format!("{}m", s / 60), + s if s < 86_400 => format!("{}h", s / 3600), + s => format!("{}d", s / 86_400), + } +} + +fn now() -> u64 { + SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) +} diff --git a/operserv/src/lib.rs b/operserv/src/lib.rs index 9309cf5..b66c81f 100644 --- a/operserv/src/lib.rs +++ b/operserv/src/lib.rs @@ -15,6 +15,8 @@ mod kill; mod kick; #[path = "mode.rs"] mod mode; +#[path = "ignore.rs"] +mod ignore; pub struct OperServ { pub uid: String, @@ -45,6 +47,7 @@ impl Service for OperServ { Some(cmd) if cmd.eq_ignore_ascii_case("KILL") => kill::handle(me, from, args, ctx, net), Some(cmd) if cmd.eq_ignore_ascii_case("KICK") => kick::handle(me, from, args, ctx, net), Some(cmd) if cmd.eq_ignore_ascii_case("MODE") => mode::handle(me, from, args, ctx, net), + Some(cmd) if cmd.eq_ignore_ascii_case("IGNORE") => ignore::handle(me, from, args, ctx, db), Some(cmd) if cmd.eq_ignore_ascii_case("HELP") => help(me, from, ctx), None => help(me, from, ctx), Some(other) => ctx.notice(me, from.uid, format!("I don't know \x02{other}\x02. Try \x02HELP\x02.")), @@ -53,5 +56,5 @@ impl Service for OperServ { } fn help(me: &str, from: &Sender, ctx: &mut ServiceCtx) { - ctx.notice(me, from.uid, "OperServ holds network operator tools (Priv::Admin): \x02AKILL\x02 ADD|DEL|LIST (user@host bans), \x02SQLINE\x02 ADD|DEL|LIST (nick bans), \x02GLOBAL\x02 (announce to everyone), \x02KILL\x02 [reason] (disconnect a user), \x02KICK\x02 <#chan> [reason], \x02MODE\x02 <#chan> [params]."); + ctx.notice(me, from.uid, "OperServ holds network operator tools (Priv::Admin): \x02AKILL\x02 ADD|DEL|LIST (user@host bans), \x02SQLINE\x02 ADD|DEL|LIST (nick bans), \x02GLOBAL\x02 (announce to everyone), \x02KILL\x02 [reason] (disconnect a user), \x02KICK\x02 <#chan> [reason], \x02MODE\x02 <#chan> [params], \x02IGNORE\x02 ADD|DEL|LIST (silence a user from services)."); } diff --git a/src/engine/db.rs b/src/engine/db.rs index 8761b20..2ba8fc3 100644 --- a/src/engine/db.rs +++ b/src/engine/db.rs @@ -30,7 +30,7 @@ use super::scram::{self, Hash}; // fedserv-api SDK crate; re-exported so the engine keeps naming them locally and // modules importing `crate::engine::db::{ChanError, ...}` are unaffected. pub use fedserv_api::{ - AccountView, AjoinView, AkillView, BotView, MemoView, SuspensionView, ChanAccessView, ChanAkickView, ChanError, ChanSetting, ChannelView, CertError, CodeKind, Kicker, RegError, Store, TriggerView, VhostView, + AccountView, AjoinView, AkillView, BotView, IgnoreView, MemoView, SuspensionView, ChanAccessView, ChanAkickView, ChanError, ChanSetting, ChannelView, CertError, CodeKind, Kicker, RegError, Store, TriggerView, VhostView, }; #[derive(Debug, Clone, Serialize, Deserialize)] @@ -315,6 +315,16 @@ fn gline_kind() -> String { "G".to_string() } +// A services ignore: services silently drop commands from a matching user. Node- +// local and in-memory (like the auth throttle) — a fast, transient moderation +// tool, not persisted or federated. +#[derive(Debug, Clone)] +pub struct Ignore { + pub mask: String, + pub reason: String, + pub expires: Option, +} + // A memo left for an account (MemoServ). #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Memo { @@ -881,6 +891,8 @@ pub struct Db { host_cfg: HostConfig, // Network bans (OperServ AKILL), in insertion order. akills: Vec, + // Services ignores (OperServ IGNORE), node-local and in-memory. + ignores: Vec, } // Network-wide HostServ configuration, rebuilt from the event log. @@ -936,7 +948,7 @@ impl Db { apply(&mut accounts, &mut channels, &mut grouped, &mut bots, &mut host_cfg, &mut akills, event); } tracing::info!(accounts = accounts.len(), channels = channels.len(), "account store loaded"); - Self { accounts, channels, grouped, log, scram_iterations: scram::DEFAULT_ITERATIONS, email_enabled: false, email_brand: "Network Services".to_string(), email_accent: "#4f46e5".to_string(), email_logo: String::new(), codes: HashMap::new(), auth_fails: HashMap::new(), vhost_req_times: HashMap::new(), bots, host_cfg, akills } + Self { accounts, channels, grouped, log, scram_iterations: scram::DEFAULT_ITERATIONS, email_enabled: false, email_brand: "Network Services".to_string(), email_accent: "#4f46e5".to_string(), email_logo: String::new(), codes: HashMap::new(), auth_fails: HashMap::new(), vhost_req_times: HashMap::new(), bots, host_cfg, akills, ignores: Vec::new() } } /// Fold an entry authored by another node into the store — the services-side @@ -1794,6 +1806,48 @@ impl Db { .collect() } + /// Add a services ignore, replacing any existing entry for the same mask. + pub fn ignore_add(&mut self, mask: &str, reason: &str, expires: Option) { + self.ignores.retain(|i| !i.mask.eq_ignore_ascii_case(mask)); + self.ignores.push(Ignore { mask: mask.to_string(), reason: reason.to_string(), expires }); + } + + /// Remove a services ignore. Returns whether a live one was removed. + pub fn ignore_del(&mut self, mask: &str) -> bool { + let now = now(); + let existed = self.ignores.iter().any(|i| i.mask.eq_ignore_ascii_case(mask) && i.expires.is_none_or(|e| e > now)); + self.ignores.retain(|i| !i.mask.eq_ignore_ascii_case(mask)); + existed + } + + /// The live services ignores (expired hidden lazily), oldest first. + pub fn ignores(&self) -> Vec { + let now = now(); + self.ignores + .iter() + .filter(|i| i.expires.is_none_or(|e| e > now)) + .map(|i| IgnoreView { mask: i.mask.clone(), reason: i.reason.clone(), expires: i.expires }) + .collect() + } + + /// Whether a user is currently ignored by services. A mask with an `@` is + /// matched against `nick!*@host` (we don't track ident); a bare mask against + /// the nick. Expired entries are swept as they're encountered. + pub fn is_ignored(&mut self, nick: &str, host: &str) -> bool { + let now = now(); + self.ignores.retain(|i| i.expires.is_none_or(|e| e > now)); + let full = format!("{}!*@{}", nick.to_ascii_lowercase(), host.to_ascii_lowercase()); + let nick_lc = nick.to_ascii_lowercase(); + self.ignores.iter().any(|i| { + let m = i.mask.to_ascii_lowercase(); + if m.contains('@') { + glob_match(&m, &full) + } else { + glob_match(&m, &nick_lc) + } + }) + } + /// The account's suspension record, if any (shown in INFO even once expired). pub fn suspension(&self, account: &str) -> Option { self.accounts @@ -2952,6 +3006,15 @@ impl Store for Db { fn akills(&self) -> Vec { Db::akills(self) } + fn ignore_add(&mut self, mask: &str, reason: &str, expires: Option) { + Db::ignore_add(self, mask, reason, expires) + } + fn ignore_del(&mut self, mask: &str) -> bool { + Db::ignore_del(self, mask) + } + fn ignores(&self) -> Vec { + Db::ignores(self) + } fn register_channel(&mut self, name: &str, founder: &str) -> Result<(), ChanError> { Db::register_channel(self, name, founder) } diff --git a/src/engine/mod.rs b/src/engine/mod.rs index 4771e0c..d68581b 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -1131,6 +1131,14 @@ impl Engine { self.bump("botserv.messages"); } } else { + // A services ignore silences a user's commands entirely — but an oper + // can never be ignored (else they could lock themselves out). + if !privs.any() { + let host = self.network.host_of(from).unwrap_or("").to_string(); + if self.db.is_ignored(&nick, &host) { + return Vec::new(); + } + } let mut matched: Option = None; { let Self { services, network, db, .. } = self; @@ -4006,6 +4014,54 @@ mod tests { } } + // OperServ IGNORE: an admin silences a user, whose service commands are then + // dropped; DEL restores them; opers are never silenced. + #[test] + fn operserv_ignore_silences_and_restores() { + use fedserv_operserv::OperServ; + let path = std::env::temp_dir().join("fedserv-osignore.jsonl"); + let _ = std::fs::remove_file(&path); + let mut db = Db::open(&path, "42S"); + db.scram_iterations = 4096; + db.register("staff", "password1", None).unwrap(); + let mut e = Engine::new( + vec![ + Box::new(NickServ { uid: "42SAAAAAA".into(), guest_nick: "Guest".into(), guest_seq: 0 }), + Box::new(OperServ { uid: "42SAAAAAH".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 os = |e: &mut Engine, uid: &str, t: &str| e.handle(NetEvent::Privmsg { from: uid.into(), to: "42SAAAAAH".into(), text: t.into() }); + let ns = |e: &mut Engine, uid: &str, t: &str| e.handle(NetEvent::Privmsg { from: uid.into(), to: "42SAAAAAA".into(), text: t.into() }); + + e.handle(NetEvent::UserConnect { uid: "000AAAAAS".into(), nick: "staff".into(), host: "h".into() }); + e.handle(NetEvent::Privmsg { from: "000AAAAAS".into(), to: "42SAAAAAA".into(), text: "IDENTIFY password1".into() }); + e.handle(NetEvent::UserConnect { uid: "000AAAAAM".into(), nick: "menace".into(), host: "bad.host".into() }); + + // Before the ignore, a NickServ command gets a reply. + assert!(!ns(&mut e, "000AAAAAM", "INFO").is_empty(), "responds before ignore"); + + // Ignore by host mask, then the same command yields nothing at all. + os(&mut e, "000AAAAAS", "IGNORE ADD *!*@bad.host flooding"); + assert!(ns(&mut e, "000AAAAAM", "INFO").is_empty(), "ignored user's command is dropped"); + assert!(os(&mut e, "000AAAAAM", "HELP").is_empty(), "ignored across every service"); + + // The operator is never silenced by an ignore against them. + os(&mut e, "000AAAAAS", "IGNORE ADD *!*@h staffignore"); + assert!(!ns(&mut e, "000AAAAAS", "INFO").is_empty(), "an oper can't be ignored"); + + // DEL restores the menace. + os(&mut e, "000AAAAAS", "IGNORE DEL *!*@bad.host"); + assert!(!ns(&mut e, "000AAAAAM", "INFO").is_empty(), "responds again after DEL"); + + // A non-admin (no longer ignored) can't manage the list — it's refused. + assert!(os(&mut e, "000AAAAAM", "IGNORE LIST").iter().any(|a| matches!(a, NetAction::Notice { text, .. } if text.contains("Access denied"))), "non-admin refused"); + } + // NOEXPIRE is oper-only. #[test] fn noexpire_command_is_oper_gated() {