content: remote word list and premium IP-ban exemption

Phase 7 of PLAN.md.

- `words_source` names a [sources.<name>] word list matched alongside
  the static `filters`, with the same homoglyph-insensitive folding. The
  normalized copy is rebuilt on the note path only when a reload swaps
  the snapshot (Arc::ptr_eq); about 80 ms for 10k words in release, then
  ~90 us per note.
- `exempt_source` names a pubkey list (premium). Active members skip the
  IP-ban check and their matches never strike the IP, but their notes
  are still word-checked and shadow-rejected on a match.
- README: document the content filter, which had no section.

Non-exempt behavior is unchanged (golden test, existing content tests).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-10-29 07:23:23 +00:00
co-authored by Claude Opus 5.5
parent a9e4c044bf
commit 9ee6254697
2 changed files with 164 additions and 14 deletions
+15
View File
@@ -175,6 +175,21 @@ The blacklist filter blocks notes that match any pubkey, ip, or CIDR range:
- `message` *optional*: the error message for a blocked note. Default is: `blocked: pubkey/ip is blacklisted`
### Content
* name: `content`
Silently drops (shadow-rejects) notes whose content contains a blocked word or
phrase. Matching is case- and homoglyph-insensitive.
- `filters`: a list of words or phrases to block
- `words_source` *optional*: the name of a `[sources.<name>]` word list (see [Sources](#sources)) matched in addition to `filters`
- `ban_after`, `ban_duration_secs` *optional*: IP-ban an IP after this many matching notes (cumulative); a banned IP has every note silently dropped
- `exempt_source` *optional*: the name of a `[sources.<name>]` pubkey list, typically premium members. Active members skip the IP-ban check, so they can post from an IP banned because of someone else. Their notes are still checked against the words, but a match does not count against their IP.
### Kinds
* name: `kinds`
+149 -14
View File
@@ -1,6 +1,8 @@
use crate::filters::ban::BanTracker;
use crate::sources::{PubkeyRef, WordList, WordsRef};
use crate::{Action, InputMessage, NoteFilter, OutputMessage};
use serde::Deserialize;
use std::sync::Arc;
use std::time::Instant;
use unicode_security::skeleton;
@@ -15,6 +17,20 @@ pub struct Content {
#[serde(skip)]
normalized: Option<Vec<String>>,
/// A `[sources.<name>]` word list matched in addition to `filters`, with
/// the same homoglyph-insensitive matching.
words_source: Option<WordsRef>,
/// Normalized copy of the `words_source` snapshot it was built from,
/// rebuilt on the note path whenever a reload swaps in a new snapshot.
#[serde(skip)]
remote_normalized: Option<(Arc<WordList>, Vec<String>)>,
/// A `[sources.<name>]` pubkey list (e.g. premium members) whose active
/// members skip the IP-ban check. Their notes are still word-checked, but
/// a match does not count against their IP.
exempt_source: Option<PubkeyRef>,
/// IP-ban repeat offenders. Content violations accrue *cumulatively* per IP
/// (a matching note never resets the count); once they cross `ban_after`
/// every note from that IP is shadow-rejected until the ban expires. See
@@ -32,29 +48,58 @@ fn normalize(s: &str) -> String {
skeleton(&s.to_lowercase()).collect::<String>().to_lowercase()
}
impl Content {
/// Whether `content` contains any static or remote term, both sides folded
/// through [`normalize`].
fn matches(&mut self, content: &str) -> bool {
let content = normalize(content);
let normalized = self
.normalized
.get_or_insert_with(|| self.filters.iter().map(|f| normalize(f)).collect());
if normalized.iter().any(|filter| content.contains(filter)) {
return true;
}
let Some(current) = self.words_source.as_ref().and_then(WordsRef::get) else {
return false;
};
// Re-normalize only when a reload swapped the snapshot.
let stale = self
.remote_normalized
.as_ref()
.is_none_or(|(seen, _)| !Arc::ptr_eq(seen, &current));
if stale {
let words = current.0.iter().map(|w| normalize(w)).collect();
self.remote_normalized = Some((current, words));
}
self.remote_normalized
.as_ref()
.is_some_and(|(_, words)| words.iter().any(|w| content.contains(w)))
}
}
impl NoteFilter for Content {
fn filter_note(&mut self, msg: &InputMessage) -> OutputMessage {
let now = Instant::now();
let exempt = self
.exempt_source
.as_ref()
.is_some_and(|source| source.is_active(&msg.event.pubkey));
// A banned IP has everything silently dropped, not just matching notes —
// shadow-rejected to keep the ban invisible to the offender, like a
// content match itself.
if self.ban.is_banned(&msg.source_info, now) {
// content match itself. Exempt (premium) authors are not subject to it.
if !exempt && self.ban.is_banned(&msg.source_info, now) {
return OutputMessage::new(msg.event.id.clone(), Action::ShadowReject, None);
}
let matched = {
let normalized = self
.normalized
.get_or_insert_with(|| self.filters.iter().map(|f| normalize(f)).collect());
let content = normalize(&msg.event.content);
normalized.iter().any(|filter| content.contains(filter))
};
if matched {
if self.matches(&msg.event.content) {
// Count the violation (may trip a ban for next time); either way this
// note is shadow-rejected.
self.ban.strike(&msg.source_info, now);
// note is shadow-rejected. An exempt author's match never strikes the
// IP, so they cannot get a shared IP banned for everyone else.
if !exempt {
self.ban.strike(&msg.source_info, now);
}
return OutputMessage::new(msg.event.id.clone(), Action::ShadowReject, None);
}
@@ -69,14 +114,19 @@ impl NoteFilter for Content {
#[cfg(test)]
mod tests {
use super::*;
use crate::sources::testing;
use crate::Note;
fn msg(id: &str, ip: &str, content: &str) -> InputMessage {
msg_from(id, ip, content, "pk")
}
fn msg_from(id: &str, ip: &str, content: &str, pubkey: &str) -> InputMessage {
InputMessage {
message_type: "new".to_string(),
event: Note {
id: id.to_string(),
pubkey: "pk".to_string(),
pubkey: pubkey.to_string(),
created_at: 0,
kind: 1,
tags: vec![],
@@ -141,4 +191,89 @@ mod tests {
Action::Accept
);
}
fn shadow(c: &mut Content, ip: &str, content: &str, pubkey: &str) -> bool {
c.filter_note(&msg_from("e", ip, content, pubkey)).action == Action::ShadowReject
}
#[test]
fn remote_word_shadow_rejects() {
testing::words("ct_remote", Some(&["casino bonus"]));
let mut c = content("filters = []\nwords_source = \"ct_remote\"\n");
assert!(shadow(&mut c, "1.1.1.1", "Get your CASINO BONUS now", "pk"));
assert!(!shadow(&mut c, "1.1.1.1", "gm", "pk"));
}
#[test]
fn remote_homoglyph_caught() {
testing::words("ct_homoglyph", Some(&["Damus Airdrop"]));
let mut c = content("filters = []\nwords_source = \"ct_homoglyph\"\n");
assert!(shadow(&mut c, "1.1.1.1", "D\u{0430}mus \u{0410}irdrop is open", "pk"));
}
#[test]
fn reload_renormalizes() {
testing::words("ct_reload", Some(&["alpha"]));
let mut c = content("filters = []\nwords_source = \"ct_reload\"\n");
assert!(shadow(&mut c, "1.1.1.1", "alpha", "pk"));
assert!(!shadow(&mut c, "1.1.1.1", "beta", "pk"));
testing::words("ct_reload", Some(&["beta"]));
assert!(!shadow(&mut c, "1.1.1.1", "alpha", "pk"));
assert!(shadow(&mut c, "1.1.1.1", "beta", "pk"));
}
#[test]
fn static_words_still_apply() {
testing::words("ct_static", None);
let mut c = content("filters = [\"spam\"]\nwords_source = \"ct_static\"\n");
assert!(shadow(&mut c, "1.1.1.1", "spam", "pk"));
assert!(!shadow(&mut c, "1.1.1.1", "ham", "pk"));
}
#[test]
fn premium_skips_ip_ban() {
testing::pubkeys("ct_premium_ban", Some(&[("member", None)]));
let mut c = content(
"filters = [\"spam\"]\nban_after = 1\nexempt_source = \"ct_premium_ban\"\n",
);
assert!(shadow(&mut c, "5.5.5.5", "spam", "pk"));
// The IP is now banned: a clean note from a non-member is dropped,
// a clean note from a member is not.
assert!(shadow(&mut c, "5.5.5.5", "hello", "pk"));
assert!(!shadow(&mut c, "5.5.5.5", "hello", "member"));
}
#[test]
fn premium_still_word_checked() {
testing::pubkeys("ct_premium_words", Some(&[("member", None)]));
let mut c = content("filters = [\"spam\"]\nexempt_source = \"ct_premium_words\"\n");
assert!(shadow(&mut c, "5.5.5.5", "spam", "member"));
}
#[test]
fn premium_match_does_not_strike() {
testing::pubkeys("ct_premium_strike", Some(&[("member", None)]));
let mut c = content(
"filters = [\"spam\"]\nban_after = 1\nexempt_source = \"ct_premium_strike\"\n",
);
assert!(shadow(&mut c, "3.3.3.3", "spam", "member"));
// No strike was counted, so the IP is not banned for others.
assert!(!shadow(&mut c, "3.3.3.3", "hello", "pk"));
}
#[test]
#[ignore = "timing probe, run with --ignored --nocapture"]
fn normalize_10k_words_timing() {
let words: Vec<String> = (0..10_000).map(|i| format!("spam phrase number {i}")).collect();
let refs: Vec<&str> = words.iter().map(String::as_str).collect();
testing::words("ct_timing", Some(&refs));
let mut c = content("filters = []\nwords_source = \"ct_timing\"\n");
let start = std::time::Instant::now();
c.filter_note(&msg("e", "1.1.1.1", "hello"));
let first = start.elapsed();
let start = std::time::Instant::now();
c.filter_note(&msg("e", "1.1.1.1", "hello"));
println!("first note (normalize 10k): {first:?}, next note: {:?}", start.elapsed());
}
}