diff --git a/config.example.toml b/config.example.toml index 26a82623..09822cb2 100644 --- a/config.example.toml +++ b/config.example.toml @@ -90,6 +90,8 @@ concurrency = 16 comments = true comment_days = 60 comments_per_pass = 2000 +# spotters known for spam and fakes, read once a day; "" for none +blacklist_url = "https://spotlist.store/spotnet/blacklist.xml" [category] enabled = true diff --git a/src/config.rs b/src/config.rs index d3d6f922..80fae823 100644 --- a/src/config.rs +++ b/src/config.rs @@ -553,6 +553,8 @@ pub struct SpotsConfig { pub comment_days: u32, /// comments whose text is read in one pass at most; the rest wait for the next pub comments_per_pass: usize, + /// the Spotnet blacklist of spotters, read once a day (`spotnet::blacklist`); empty for none + pub blacklist_url: String, } impl Default for SpotsConfig { @@ -566,6 +568,7 @@ impl Default for SpotsConfig { comments: true, comment_days: 60, comments_per_pass: 2_000, + blacklist_url: crate::spotnet::blacklist::DEFAULT_URL.to_string(), } } } @@ -599,6 +602,9 @@ impl SpotsConfig { if let Some(n) = int("comments_per_pass", 1, 100_000) { c.comments_per_pass = n as usize; } + if let Some(url) = v.get("blacklist_url").and_then(|u| u.as_str()) { + c.blacklist_url = url.trim().to_string(); + } c } } @@ -1683,7 +1689,7 @@ mod tests { assert_eq!(Config::from_value(&json!({})).spots, SpotsConfig::default()); let c = Config::from_value( &json!({"spots": {"enabled": false, "poll_minutes": 0, "first_articles": 500, "per_pass": 20, "concurrency": 99, - "comments": false, "comment_days": 0, "comments_per_pass": 50}}), + "comments": false, "comment_days": 0, "comments_per_pass": 50, "blacklist_url": " "}}), ) .spots; assert_eq!( @@ -1697,6 +1703,7 @@ mod tests { comments: false, comment_days: 1, comments_per_pass: 50, + blacklist_url: String::new(), } ); assert_eq!(Config::from_value(&json!({"spots": "no"})).spots, SpotsConfig::default()); diff --git a/src/spotnet/blacklist.rs b/src/spotnet/blacklist.rs new file mode 100644 index 00000000..460e2be4 --- /dev/null +++ b/src/spotnet/blacklist.rs @@ -0,0 +1,148 @@ +//! The Spotnet blacklist: spotters known for spam, fakes and the like, as Spotweb takes them from `blacklist_url` +//! (an XML list of the spotters' public keys, `MODULUS...`). Kept in the main +//! database's `spot_blacklist` by spotter id, read again once a day. A blacklisted spotter's spots aren't fetched, +//! their releases lose the spot tag, and their comments are hidden (`store::disposed_sql`). + +use std::time::Duration; + +use anyhow::{Result, anyhow, bail}; +use rusqlite::{Connection, params}; + +/// Where Spotweb reads the blacklist. +pub const DEFAULT_URL: &str = "https://spotlist.store/spotnet/blacklist.xml"; +/// How often the list is read again. +pub const REFRESH_SECS: i64 = 86_400; +/// The largest list read: the real one is under 100 KB. +const MAX_BYTES: u64 = 4 * 1024 * 1024; +/// When the list was last read, in the main database's `meta`. +const READ_AT: &str = "spot_blacklist_at"; + +/// The main database's table, if missing. +pub fn create(conn: &Connection) -> rusqlite::Result<()> { + conn.execute_batch("create table if not exists spot_blacklist (spotter TEXT PRIMARY KEY) without rowid") +} + +/// The spotter ids a blacklist names, each once. Spotweb takes ids of 3 to 6 characters, and so does this. +pub fn parse(xml: &str) -> Vec { + let mut out = Vec::new(); + let mut rest = xml; + while let Some(open) = rest.find("` is the list, not a key + if !rest.starts_with(['>', ' ', '\t', '\r', '\n']) { + continue; + } + let Some(start) = rest.find('>') else { break }; + let Some(end) = rest[start..].find("") else { break }; + let key = rest[start + 1..start + end].trim(); + if let Some(id) = super::header::spotter_id(key).filter(|id| (3..=6).contains(&id.len())) + && !out.contains(&id) + { + out.push(id); + } + rest = &rest[start + end..]; + } + out +} + +/// Reads the list at `url`. Blocking: call it off the runtime's threads. +pub fn fetch(url: &str) -> Result { + let agent: ureq::Agent = ureq::Agent::config_builder() + .timeout_global(Some(Duration::from_secs(60))) + .user_agent(concat!("atlas/", env!("CARGO_PKG_VERSION"))) + .build() + .into(); + let mut response = agent.get(url).call().map_err(|e| anyhow!("{url}: {e}"))?; + Ok(response.body_mut().with_config().limit(MAX_BYTES).read_to_string()?) +} + +/// Whether the list is due to be read again at `now`. +pub fn due(conn: &Connection, now: i64) -> rusqlite::Result { + let at = super::store::read_cursor(conn, READ_AT)?.and_then(|at| i64::try_from(at).ok()); + Ok(at.is_none_or(|at| now - at >= REFRESH_SECS)) +} + +/// Puts `spotters` in place of the list kept, and notes when. An empty list is no list (a page that changed or an +/// error page): the one kept stays, and it's read again at the next refresh. Returns how many are listed. +pub fn replace(conn: &mut Connection, spotters: &[String], now: i64) -> Result { + if spotters.is_empty() { + bail!("the blacklist names no spotters"); + } + let tx = conn.transaction()?; + tx.execute("delete from spot_blacklist", [])?; + { + let mut insert = tx.prepare_cached("insert or ignore into spot_blacklist (spotter) values (?)")?; + for s in spotters { + insert.execute(params![s])?; + } + } + super::store::write_cursor(&tx, READ_AT, now.max(0) as u64)?; + tx.commit()?; + Ok(spotters.len()) +} + +/// Empties the list kept, for a blacklist turned off; the next one turned on is read at once. Returns how many +/// spotters it named. +pub fn clear(conn: &Connection) -> rusqlite::Result { + let n = conn.execute("delete from spot_blacklist", [])?; + conn.execute("delete from meta where key = ?", [READ_AT])?; + Ok(n) +} + +/// Notes a failed read, so it's tried again at the next refresh, not every pass. +pub fn tried(conn: &Connection, now: i64) -> rusqlite::Result<()> { + super::store::write_cursor(conn, READ_AT, now.max(0) as u64) +} + +#[cfg(test)] +mod tests { + use super::*; + + // two entries of the real list (spotlist.store, November 2026), one key twice, a blank and a non-key + const LIST: &str = r#" + rKflaUf7aBQ6pFGm34N/sf1klvSsk9RmCLQClebgdFfo8lXr1l7NKuty77wo4qsn + 1COQWpNScg8ugJwHAvRVD9V2+HlaMTv2yKhdrKRJgZ2DirCXT/EmripwUvXMqMlz + rKflaUf7aBQ6pFGm34N/sf1klvSsk9RmCLQClebgdFfo8lXr1l7NKuty77wo4qsn + + not a key +"#; + + #[test] + fn reads_the_spotter_ids() { + let ids = parse(LIST); + assert_eq!(ids.len(), 2, "{ids:?}"); + assert_eq!( + ids[0], + crate::spotnet::header::spotter_id("rKflaUf7aBQ6pFGm34N/sf1klvSsk9RmCLQClebgdFfo8lXr1l7NKuty77wo4qsn") + .unwrap() + ); + assert!(parse("not found").is_empty()); + } + + #[test] + fn replaces_the_list_and_keeps_it_on_an_empty_one() { + let mut conn = Connection::open_in_memory().unwrap(); + conn.execute_batch("create table meta (key TEXT PRIMARY KEY, value INTEGER)").unwrap(); + create(&conn).unwrap(); + assert!(due(&conn, 100).unwrap()); + assert_eq!(replace(&mut conn, &["abc".into(), "def".into()], 100).unwrap(), 2); + assert!(!due(&conn, 100 + REFRESH_SECS - 1).unwrap()); + assert!(due(&conn, 100 + REFRESH_SECS).unwrap()); + assert!(replace(&mut conn, &[], 200).is_err()); + assert_eq!(replace(&mut conn, &["xyz".into()], 300).unwrap(), 1); + let left: Vec = conn + .prepare("select spotter from spot_blacklist") + .unwrap() + .query_map([], |r| r.get(0)) + .unwrap() + .map(|r| r.unwrap()) + .collect(); + assert_eq!(left, ["xyz"]); + tried(&conn, 400).unwrap(); + assert!(!due(&conn, 401).unwrap()); + // turned off: nothing left, and turned on again it's read at once + assert_eq!(clear(&conn).unwrap(), 1); + assert_eq!(clear(&conn).unwrap(), 0); + assert!(due(&conn, 402).unwrap()); + } +} diff --git a/src/spotnet/ingest.rs b/src/spotnet/ingest.rs index 3fab6f40..d97489fd 100644 --- a/src/spotnet/ingest.rs +++ b/src/spotnet/ingest.rs @@ -19,7 +19,7 @@ use crate::indexer::{Db, on_db}; use crate::nntp::{Pool, says_absent}; use super::store::{self, SAVED, SKIPPED, Settled, SpotRow}; -use super::{MAX_XML_BYTES, SPOT_GROUP, binary, comments, full, header, release, sign}; +use super::{MAX_XML_BYTES, SPOT_GROUP, binary, blacklist, comments, full, header, release, sign}; /// Overview lines asked for in one XOVER. const XOVER_STEP: u64 = 5_000; @@ -117,6 +117,16 @@ pub async fn pass(pool: &Arc, db: &Db, config: &SpotsConfig, stopping: &im let comments_off = !config.comments; on_db(db, move |conn| Ok(store::prune(conn, now)? + if comments_off { comments::prune(conn, now)? } else { 0 })) .await?; + if config.blacklist_url.is_empty() { + // turned off: the list kept goes too, so it no longer removes anything + match on_db(db, |conn| Ok(blacklist::clear(conn)?)).await { + Ok(0) => {} + Ok(n) => println!("spots: the blacklist is off, {n} spotters taken off it"), + Err(e) => eprintln!("spots: blacklist: {e:#}"), + } + } else { + refresh_blacklist(db, &config.blacklist_url, now).await; + } match backfill_xml(pool, db, stopping).await { Ok(0) => {} Ok(n) => println!("spots: read the XML of {n} spots saved before it was kept"), @@ -177,6 +187,34 @@ pub async fn pass(pool: &Arc, db: &Db, config: &SpotsConfig, stopping: &im Ok(done) } +/// Reads the blacklist again when it's a day old. A failed read is logged, the list kept stays, and it's tried +/// again a day later. +async fn refresh_blacklist(db: &Db, url: &str, now: i64) { + match on_db(db, move |conn| Ok(blacklist::due(conn, now)?)).await { + Ok(true) => {} + Ok(false) => return, + Err(e) => return eprintln!("spots: blacklist: {e:#}"), + } + let u = url.to_string(); + let read = tokio::task::spawn_blocking(move || blacklist::fetch(&u).map(|xml| blacklist::parse(&xml))) + .await + .map_err(|e| anyhow!("{e}")) + .and_then(|r| r); + let done = match read { + Ok(spotters) => on_db(db, move |conn| blacklist::replace(conn, &spotters, now)).await, + Err(e) => Err(e), + }; + match done { + Ok(n) => println!("spots: the blacklist names {n} spotters"), + Err(e) => { + eprintln!("spots: blacklist {url}: {e:#}"); + if let Err(e) = on_db(db, move |conn| Ok(blacklist::tried(conn, now)?)).await { + eprintln!("spots: blacklist: {e:#}"); + } + } + } +} + /// What a spot task came to: settled (`SAVED`, `SKIPPED`, or None for one more try), or left for a later pass. enum Waited { Done(Option), diff --git a/src/spotnet/mod.rs b/src/spotnet/mod.rs index 7439e1ae..a489eb9e 100644 --- a/src/spotnet/mod.rs +++ b/src/spotnet/mod.rs @@ -9,6 +9,7 @@ //! spot's signatures. pub mod binary; +pub mod blacklist; pub mod category; pub mod comments; pub mod full; diff --git a/src/spotnet/store.rs b/src/spotnet/store.rs index d1df491d..0472bd8d 100644 --- a/src/spotnet/store.rs +++ b/src/spotnet/store.rs @@ -58,6 +58,7 @@ pub fn create_main(conn: &Connection) -> Result<()> { PRIMARY KEY (message_id, spotter) ) without rowid;", )?; + super::blacklist::create(conn)?; super::comments::create(conn) } @@ -148,15 +149,17 @@ pub struct Disposal { /// How long after a spot its spotter's own removal of it holds, as in Spotweb: five days. pub const OWN_DISPOSAL_SECS: i64 = 5 * 86_400; -/// SQL for whether a disposal removes the row `s` (with its spot's `message_id`, and its spotter id in column -/// `spotter`), aliasing the disposal `d`. `created` is the column with when the spot was made, when the row has -/// one: a spotter's own removal holds only `OWN_DISPOSAL_SECS` after it. +/// SQL for whether the row `s` (with its spot's `message_id`, and its spotter id in column `spotter`) was removed: +/// by a disposal, aliased `d`, or because its spotter is on the blacklist (`blacklist`). `created` is the column +/// with when the spot was made, when the row has one: a spotter's own removal holds only `OWN_DISPOSAL_SECS` after +/// it. pub(crate) fn disposed_sql(d: &str, s: &str, spotter: &str, created: Option<&str>) -> String { // 0: the spot's XML had no date, so not known, as NULL let made = created.map_or(format!("{d}.at"), |c| format!("coalesce(nullif({s}.{c}, 0), {d}.at)")); format!( - "exists (select 1 from main.spot_disposals {d} where {d}.message_id = {s}.message_id - and ({d}.spotter = '' or ({d}.spotter = {s}.{spotter} and {d}.at - {made} <= {OWN_DISPOSAL_SECS})))" + "(exists (select 1 from main.spot_disposals {d} where {d}.message_id = {s}.message_id + and ({d}.spotter = '' or ({d}.spotter = {s}.{spotter} and {d}.at - {made} <= {OWN_DISPOSAL_SECS}))) + or exists (select 1 from main.spot_blacklist {d}_b where {d}_b.spotter = {s}.{spotter}))" ) } @@ -597,15 +600,25 @@ pub struct Detail { /// categories, size, when it was made) pub spot: FullSpot, pub xml: Xml, - /// when the spot was removed, and whether by a Spotnet moderator (else by its spotter) + /// when the spot was removed, and by whom pub removed: Option, } /// A spot's removal, for its release page. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Removed { + /// when the removal was posted; 0 for the blacklist, which says no when pub at: i64, - pub by_moderator: bool, + pub by: RemovedBy, +} + +/// Who took a spot back. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RemovedBy { + Moderator, + Spotter, + /// its spotter is on the Spotnet blacklist + Blacklist, } /// Release `id`'s spot, from its shard, when it has one. @@ -652,19 +665,29 @@ pub fn detail_of_with(conn: &Connection, id: i64) -> Result> { } /// The removal of spot `message_id`, posted by `spotter_id` and made at `created` (0: not known), when there is -/// one that holds (`disposed_sql`): a moderator's first. +/// one that holds (`disposed_sql`): a moderator's first, then the spotter's own, then the blacklist. fn removal(conn: &Connection, message_id: &str, spotter_id: Option<&str>, created: i64) -> Result> { - conn.query_row( - &format!( - "select at, spotter = '' from main.spot_disposals + let posted = conn + .query_row( + &format!( + "select at, spotter = '' from main.spot_disposals where message_id = ?1 and (spotter = '' or (spotter = ?2 and at - coalesce(nullif(?3, 0), at) <= {OWN_DISPOSAL_SECS})) order by spotter = '' desc, at limit 1" - ), - params![message_id, spotter_id, created], - |r| Ok(Removed { at: r.get(0)?, by_moderator: r.get(1)? }), - ) - .optional() + ), + params![message_id, spotter_id, created], + |r| { + let by = if r.get(1)? { RemovedBy::Moderator } else { RemovedBy::Spotter }; + Ok(Removed { at: r.get(0)?, by }) + }, + ) + .optional()?; + if posted.is_some() { + return Ok(posted); + } + let listed = + conn.query_row("select 1 from main.spot_blacklist where spotter = ?", [spotter_id], |_| Ok(())).optional()?; + Ok(listed.map(|()| Removed { at: 0, by: RemovedBy::Blacklist })) } /// Spots of this shard saved before their XML was kept: (release id, spot message-id), at most `limit`, in no @@ -1067,11 +1090,18 @@ mod tests { left.sort(); assert_eq!(left, ["forged@spot.net", "kept@spot.net", "late@spot.net"], "removed past five days of the spot"); let removed = |n: usize| detail_of_with(&conn, ids[n]).unwrap().unwrap().removed; - assert_eq!(removed(0), Some(Removed { at: 10, by_moderator: true })); - assert_eq!(removed(1), Some(Removed { at: 10, by_moderator: false })); + assert_eq!(removed(0), Some(Removed { at: 10, by: RemovedBy::Moderator })); + assert_eq!(removed(1), Some(Removed { at: 10, by: RemovedBy::Spotter })); assert_eq!(removed(2), None); assert_eq!(removed(4), None); + // a blacklisted spotter: their saved spot loses its tag, and their waiting one isn't fetched + conn.execute("insert into spot_blacklist (spotter) values ('ddd')", []).unwrap(); + assert_eq!(removed(3), Some(Removed { at: 0, by: RemovedBy::Blacklist })); + assert!(!spots_of_with(&conn, &ids).unwrap().contains_key(&ids[3])); + assert_eq!(todo(&conn, 10).unwrap(), ["forged@spot.net"]); + conn.execute("delete from spot_blacklist", []).unwrap(); + // removals of nothing kept go after `KEEP_DAYS`; one of a saved spot or a spot still waiting stays let saved = Settled { state: SAVED, release_id: Some(ids[0]), ..Default::default() }; settle(&conn, "mod@spot.net", Some(&saved), 0).unwrap(); diff --git a/src/web.rs b/src/web.rs index 944a9ae8..6310cd07 100644 --- a/src/web.rs +++ b/src/web.rs @@ -2022,14 +2022,15 @@ fn spot_html(d: &crate::spotnet::store::Detail, said: &SpotSaid) -> String { fn spot_removed(removed: crate::spotnet::store::Removed) -> String { let when = chrono::DateTime::from_timestamp(removed.at, 0).map_or(String::new(), |t| t.format(" on %Y-%m-%d").to_string()); - let body = if removed.by_moderator { - format!( + use crate::spotnet::store::RemovedBy; + let body = match removed.by { + RemovedBy::Moderator => format!( "A Spotnet moderator removed this spot{when}, which they do for fakes, spam and spots in the wrong category. The release is still here, but the spot no longer vouches for what it is." - ) - } else { - format!( + ), + RemovedBy::Spotter => format!( "Its spotter removed this spot{when}, which they do when they repost it or it was wrong. The release is still here, but the spot no longer vouches for what it is." - ) + ), + RemovedBy::Blacklist => "Its spotter is on the Spotnet blacklist, which lists spotters known for spam and fakes. The release is still here, but the spot no longer vouches for what it is.".to_string(), }; diag("caution", "this spot was removed", &body) } @@ -4652,16 +4653,28 @@ mod tests { assert!(!h.contains("
Rating
"), "{h}"); assert!(!h.contains("
Key
") && !h.contains("
Sender
"), "{h}"); let removed = crate::spotnet::store::Detail { - removed: Some(crate::spotnet::store::Removed { at: 1_793_000_000, by_moderator: true }), + removed: Some(crate::spotnet::store::Removed { + at: 1_793_000_000, + by: crate::spotnet::store::RemovedBy::Moderator, + }), ..bare.clone() }; let h = super::spot_html(&removed, &super::SpotSaid::default()); assert!(h.contains("A Spotnet moderator removed this spot on 2026-10-26"), "{h}"); let own = crate::spotnet::store::Detail { - removed: Some(crate::spotnet::store::Removed { at: 1_793_000_000, by_moderator: false }), + removed: Some(crate::spotnet::store::Removed { + at: 1_793_000_000, + by: crate::spotnet::store::RemovedBy::Spotter, + }), ..bare.clone() }; assert!(super::spot_html(&own, &super::SpotSaid::default()).contains("Its spotter removed this spot")); + let listed = crate::spotnet::store::Detail { + removed: Some(crate::spotnet::store::Removed { at: 0, by: crate::spotnet::store::RemovedBy::Blacklist }), + ..bare.clone() + }; + let h = super::spot_html(&listed, &super::SpotSaid::default()); + assert!(h.contains("Its spotter is on the Spotnet blacklist") && !h.contains("1970"), "{h}"); assert!(!super::spot_html(&bare, &super::SpotSaid::default()).contains("removed")); let gone = crate::spotnet::store::Detail { xml: crate::spotnet::store::Xml::Gone, ..bare }; assert!(super::spot_html(&gone, &super::SpotSaid::default()).contains("could no longer be read"));