From d93415eab9dd61231ae35662395f0a047a51c90b Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Sat, 7 Nov 2026 13:54:46 -0600 Subject: [PATCH 1/2] spots: apply moderators' and spotters' removals A key-2 DISPOSE, DELETE or REMOVE in free.pt whose signatures hold is kept in spot_disposals: a moderator's removes any spot or comment, a spotter's own (their key must sign its message-id) only theirs, within five days of the spot as in Spotweb. A removed spot isn't fetched, its release loses the spot tag in listings and the API, and its page shows a SPOT REMOVED tag and says who removed it and when. The release stays. Removed comments are hidden. Removals are kept as long as what they remove may be. Co-Authored-By: Claude Opus 5.5 --- src/spotnet/comments.rs | 7 +- src/spotnet/header.rs | 19 ++++ src/spotnet/ingest.rs | 32 ++++++- src/spotnet/sign.rs | 2 +- src/spotnet/store.rs | 198 +++++++++++++++++++++++++++++++++++++--- src/web.rs | 37 +++++++- 6 files changed, 272 insertions(+), 23 deletions(-) diff --git a/src/spotnet/comments.rs b/src/spotnet/comments.rs index dfb6107f..fecce2e2 100644 --- a/src/spotnet/comments.rs +++ b/src/spotnet/comments.rs @@ -254,14 +254,15 @@ pub struct Comment { pub body: String, } -/// What's been said about release `release_id`'s spot: its comments, oldest first, and how many spam reports it -/// has. `spot` is the message-id its row has; the spots of the same NZB that tagged it before count too. +/// What's been said about release `release_id`'s spot: its comments, oldest first (but those removed by a +/// moderator or their poster), and how many spam reports it has. `spot` is the message-id its row has; the spots of the same NZB that tagged it before count too. pub fn about(conn: &Connection, release_id: i64, spot: &str) -> Result<(Vec, i64)> { let spots = "select ?2 union select message_id from main.spots_seen where release_id = ?1 and state = ?3"; let comments = conn .prepare_cached(&format!( "select at, rating, coalesce(poster, ''), spotter_id, state, coalesce(body, '') - from main.spot_comments where spot in ({spots}) order by at, message_id" + from main.spot_comments c where spot in ({spots}) and not {} order by at, message_id", + super::store::disposed_sql("d", "c", "spotter_id", None) ))? .query_map(params![release_id, spot, SAVED], |r| { Ok(Comment { diff --git a/src/spotnet/header.rs b/src/spotnet/header.rs index 2d328aea..f891a2f7 100644 --- a/src/spotnet/header.rs +++ b/src/spotnet/header.rs @@ -41,6 +41,20 @@ impl SpotHeader { self.key_id == MODERATOR_KEY } + /// The spot (or comment) a key-2 command removes: `DISPOSE - `, or `DELETE` or `REMOVE`. + pub fn removes(&self) -> Option<String> { + if !self.is_moderation() { + return None; + } + let mut words = self.title.split_whitespace(); + let command = words.next()?; + if !["dispose", "delete", "remove"].iter().any(|c| command.eq_ignore_ascii_case(c)) { + return None; + } + let id = words.next()?.trim_matches(['<', '>']); + super::valid_message_id(id).then(|| id.to_string()) + } + /// Whether this is a spot worth fetching whole: signed, not a moderator's command, movies or TV. pub fn wanted(&self) -> bool { self.signed && !self.is_moderation() && self.kind().is_some() @@ -278,6 +292,11 @@ mod tests { assert!(h.is_moderation()); assert_eq!(h.kind(), Some(Kind::Movie)); assert!(!h.wanted()); + assert_eq!(h.removes().as_deref(), Some("hzqY4qMS5McHhOuQESoUdhzD@spot.net")); assert!(parse("Movie (2026) | tag", FROM).unwrap().wanted()); + assert_eq!(parse("DISPOSE a@spot.net", FROM).unwrap().removes(), None); + assert_eq!(parse("remove <a@spot.net>", from).unwrap().removes().as_deref(), Some("a@spot.net")); + assert_eq!(parse("Hello a@spot.net", from).unwrap().removes(), None); + assert_eq!(parse("DISPOSE nothing", from).unwrap().removes(), None); } } diff --git a/src/spotnet/ingest.rs b/src/spotnet/ingest.rs index 2b846e87..45e81cf7 100644 --- a/src/spotnet/ingest.rs +++ b/src/spotnet/ingest.rs @@ -454,6 +454,8 @@ async fn read_overview( Err(e) => return Err(e.into()), }; read += rows.len() as u64; + let now = chrono::Utc::now().timestamp(); + let removals: Vec<store::Disposal> = rows.iter().filter_map(|r| removal(r, now)).collect(); let wanted: Vec<store::Noted> = rows .iter() .filter_map(|r| { @@ -467,13 +469,39 @@ async fn read_overview( }) .collect(); let key = host.clone(); - let now = chrono::Utc::now().timestamp(); - noted += on_db(db, move |conn| Ok(store::note_read(conn, &key, to, &wanted, now)?)).await?; + // the removals first: the cursor moves with the spots + noted += on_db(db, move |conn| { + let removed = store::note_disposals(conn, &removals)?; + if removed > 0 { + println!("spots: {removed} spots or comments removed by a moderator or their spotter"); + } + Ok(store::note_read(conn, &key, to, &wanted, now)?) + }) + .await?; from = to + 1; } Ok((read, noted)) } +/// The removal an overview line is, when it's a moderator's (or a spotter's own) `DISPOSE` whose signatures hold. +/// A spotter's own needs their key to have signed its message-id: it removes only their posts. +fn removal(r: &crate::nntp::Overview, now: i64) -> Option<store::Disposal> { + let h = header::parse(&r.subject, &r.from)?; + let message_id = h.removes()?; + let verdict = sign::verify(&h.title, &r.from, &r.message_id); + if !verdict.verified { + return None; + } + // a spotter id from the header signature alone could be replayed onto another message-id + let spotter = match verdict.personal { + true if verdict.message_id_signed => verdict.spotter_id?, + true => return None, + false => String::new(), + }; + let at = crate::dates::posted_timestamp(&r.date).unwrap_or(now); + Some(store::Disposal { message_id, spotter, at }) +} + /// What one pass read of what's said about spots, for the log. #[derive(Debug, Default, PartialEq, Eq)] struct Said { diff --git a/src/spotnet/sign.rs b/src/spotnet/sign.rs index 1895761d..597c6629 100644 --- a/src/spotnet/sign.rs +++ b/src/spotnet/sign.rs @@ -71,7 +71,7 @@ pub fn verify(title: &str, from: &str, message_id: &str) -> Verdict { return no; } let mut signed = Vec::from(title.as_bytes()); - signed.extend_from_slice(header[..header.len() - header_sig.len() - 1].as_bytes()); + signed.extend_from_slice(&header.as_bytes()[..header.len() - header_sig.len() - 1]); signed.extend_from_slice(poster); let Some(header_sig) = decode_base64(&unprepare_base64(header_sig)) else { return no }; let (user_key, user_sig) = match local.split_once('.') { diff --git a/src/spotnet/store.rs b/src/spotnet/store.rs index 3e380e65..ca5e364d 100644 --- a/src/spotnet/store.rs +++ b/src/spotnet/store.rs @@ -50,7 +50,13 @@ pub fn create_main(conn: &Connection) -> Result<()> { create index if not exists spots_seen_todo on spots_seen(state, number); create index if not exists spots_seen_ref on spots_seen(nzb_ref) where nzb_ref is not null; create index if not exists spots_seen_key on spots_seen(nzb_key) where nzb_key is not null; - create index if not exists spots_seen_release on spots_seen(release_id) where release_id is not null;", + create index if not exists spots_seen_release on spots_seen(release_id) where release_id is not null; + create table if not exists spot_disposals ( + message_id TEXT NOT NULL, + spotter TEXT NOT NULL DEFAULT '', + at INTEGER NOT NULL, + PRIMARY KEY (message_id, spotter) + ) without rowid;", )?; super::comments::create(conn) } @@ -129,22 +135,66 @@ pub fn note_read(conn: &mut Connection, server: &str, last: u64, spots: &[Noted] Ok(added) } +/// A spot (or comment) removed with a `DISPOSE`, `DELETE` or `REMOVE` in `free.pt`: by a Spotnet moderator +/// (`spotter` empty), or by its own spotter (`spotter` their id), which holds only for that spotter's posts. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Disposal { + pub message_id: String, + pub spotter: String, + /// when the command was posted + pub at: i64, +} + +/// 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. +pub(crate) fn disposed_sql(d: &str, s: &str, spotter: &str, created: Option<&str>) -> String { + let made = created.map_or(format!("{d}.at"), |c| format!("coalesce({s}.{c}, {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})))" + ) +} + +/// Notes removals read in the overview. Kept whatever they name, now or later: a spot noted, saved or commented on +/// after its removal is still removed (`todo`, `spots_of`, `comments::about`). Returns how many were new. +pub fn note_disposals(conn: &mut Connection, disposals: &[Disposal]) -> Result<usize> { + let tx = conn.transaction()?; + let mut added = 0; + { + let mut insert = + tx.prepare_cached("insert or ignore into spot_disposals (message_id, spotter, at) values (?, ?, ?)")?; + for d in disposals { + added += insert.execute(params![d.message_id, d.spotter, d.at])?; + } + } + tx.commit()?; + Ok(added) +} + /// Spots to fetch. Half of `limit` goes to the oldest waiting, whoever posted them, so every spot gets its turn /// however many new ones come in. The rest goes to each spotter's newest, a spotter at a time in turn /// (`PER_SPOTTER` deep at most). pub fn todo(conn: &Connection, limit: usize) -> Result<Vec<String>> { let oldest: Vec<String> = conn - .prepare_cached("select message_id from spots_seen where state = ?1 order by number limit ?2")? + .prepare_cached(&format!( + "select message_id from spots_seen where state = ?1 and not {} order by number limit ?2", + seen_disposed() + ))? .query_map(params![TODO, (limit / 2) as i64], |r| r.get(0))? .collect::<Result<_>>()?; let newest: Vec<String> = conn - .prepare_cached( + .prepare_cached(&format!( "select message_id from ( select message_id, number, row_number() over (partition by coalesce(spotter, '') order by number desc) as turn - from spots_seen where state = ?1 + from spots_seen where state = ?1 and not {} ) where turn <= ?2 order by turn, number desc limit ?3", - )? + seen_disposed() + ))? .query_map(params![TODO, PER_SPOTTER, limit as i64], |r| r.get(0))? .collect::<Result<_>>()?; let mut out = oldest; @@ -161,11 +211,21 @@ pub fn todo(conn: &Connection, limit: usize) -> Result<Vec<String>> { /// Spots waiting to be fetched. pub fn waiting(conn: &Connection) -> Result<i64> { - conn.query_row("select count(*) from spots_seen where state = ?", [TODO], |r| r.get(0)) + conn.query_row( + &format!("select count(*) from spots_seen where state = ? and not {}", seen_disposed()), + [TODO], + |r| r.get(0), + ) +} + +/// Whether the `spots_seen` row was removed: a spot waiting has no `created`, so a spotter's own removal holds +/// whenever it came. +fn seen_disposed() -> String { + disposed_sql("d", "spots_seen", "spotter", None) } /// Gives up on spots waiting past `TODO_DAYS` and on the oldest past `MAX_TODO`, and forgets the ones that came to -/// nothing past `KEEP_DAYS`. Saved ones stay. Returns the rows it changed. +/// nothing past `KEEP_DAYS`, and removals of nothing kept. Saved ones stay. Returns the rows it changed. pub fn prune(conn: &Connection, now: i64) -> Result<usize> { let day = 86_400; let mut n = conn.execute( @@ -181,6 +241,13 @@ pub fn prune(conn: &Connection, now: i64) -> Result<usize> { "delete from spots_seen where state not in (?1, ?2) and at < ?3", params![TODO, SAVED, now - KEEP_DAYS * day], )?; + // a removal is kept as long as what it removes may be: a saved spot or a comment, kept for good + n += conn.execute( + "delete from spot_disposals where at < ?1 + and message_id not in (select message_id from spots_seen where state = ?2) + and message_id not in (select message_id from spot_comments)", + params![now - KEEP_DAYS * day, SAVED], + )?; Ok(n) } @@ -403,7 +470,8 @@ pub struct Tagged { pub subcats: String, } -/// The spots of these releases, by release id, from each one's shard. +/// The spots of these releases, by release id, from each one's shard. A spot that was removed (`Disposal`) leaves +/// its release untagged. pub fn spots_of(ids: &[i64]) -> Result<HashMap<i64, Tagged>> { if ids.is_empty() { return Ok(HashMap::new()); @@ -420,8 +488,9 @@ pub fn spots_of_with(conn: &Connection, ids: &[i64]) -> Result<HashMap<i64, Tagg for (shard, list) in by_shard { let sql = format!( "select release_id, message_id, kind, title, coalesce(poster, ''), coalesce(tag, ''), spotter_id, imdb_id, - coalesce(subcats, '') from s{shard}.spots where release_id in ({})", - list.join(",") + coalesce(subcats, '') from s{shard}.spots s where release_id in ({}) and not {}", + list.join(","), + disposed_sql("d", "s", "spotter_id", Some("created")) ); let mut stmt = conn.prepare(&sql)?; let rows = stmt.query_map([], |r| { @@ -470,6 +539,15 @@ 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) + pub removed: Option<Removed>, +} + +/// A spot's removal, for its release page. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Removed { + pub at: i64, + pub by_moderator: bool, } /// Release `id`'s spot, from its shard, when it has one. @@ -500,7 +578,7 @@ pub fn detail_of_with(conn: &Connection, id: i64) -> Result<Option<Detail>> { Ok((parts, columns, r.get::<_, Option<String>>(10)?)) }) .optional()?; - Ok(row.map(|((message_id, spotter_id, imdb_id), columns, xml)| { + let row = row.map(|((message_id, spotter_id, imdb_id), columns, xml)| { let parsed = xml.as_deref().filter(|x| !x.is_empty()).and_then(super::full::parse); let state = match (&parsed, &xml) { (Some(_), _) => Xml::Kept, @@ -508,8 +586,27 @@ pub fn detail_of_with(conn: &Connection, id: i64) -> Result<Option<Detail>> { (None, Some(_)) => Xml::Gone, }; let imdb_id = parsed.as_ref().map_or(imdb_id, FullSpot::imdb_id); - Detail { message_id, spotter_id, imdb_id, spot: parsed.unwrap_or(columns), xml: state } - })) + Detail { message_id, spotter_id, imdb_id, spot: parsed.unwrap_or(columns), xml: state, removed: None } + }); + let Some(mut detail) = row else { return Ok(None) }; + detail.removed = removal(conn, &detail.message_id, detail.spotter_id.as_deref(), detail.spot.created)?; + Ok(Some(detail)) +} + +/// 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. +fn removal(conn: &Connection, message_id: &str, spotter_id: Option<&str>, created: i64) -> Result<Option<Removed>> { + 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() } /// Spots of this shard saved before their XML was kept: (release id, spot message-id), at most `limit`, in no @@ -765,7 +862,7 @@ mod tests { #[test] fn spots_of_reads_each_shard() { - let conn = Connection::open_in_memory().unwrap(); + let conn = main_db(); let (a, b) = (crate::store::global_id(1, 0), crate::store::global_id(1, 3)); for shard in [0, 3] { conn.execute(&format!("attach ':memory:' as s{shard}"), []).unwrap(); @@ -780,6 +877,75 @@ mod tests { assert_eq!(found[&b].kind, "series"); } + #[test] + fn removed_spots_are_not_fetched_tagged_or_shown_as_spots() { + let mut conn = main_db(); + let day = 86_400; + let spots = vec![ + ("mod@spot.net".to_string(), 1, Some("aaa".to_string())), + ("own@spot.net".to_string(), 2, Some("bbb".to_string())), + ("forged@spot.net".to_string(), 3, Some("ccc".to_string())), + ("kept@spot.net".to_string(), 4, Some("ddd".to_string())), + ]; + note_read(&mut conn, "s", 4, &spots, 0).unwrap(); + let d = |id: &str, spotter: &str, at: i64| Disposal { message_id: id.into(), spotter: spotter.into(), at }; + let removals = [ + d("mod@spot.net", "", 10), + d("own@spot.net", "bbb", 10), + // a spotter's own removal of someone else's spot holds for nothing + d("forged@spot.net", "bbb", 10), + // and its spotter removing it late holds only while it waits (no `created` yet) + d("late@spot.net", "eee", 10 * day), + ]; + assert_eq!(note_disposals(&mut conn, &removals).unwrap(), 4); + assert_eq!(note_disposals(&mut conn, &removals).unwrap(), 0, "noted once"); + assert_eq!(todo(&conn, 10).unwrap(), ["forged@spot.net", "kept@spot.net"]); + assert_eq!(waiting(&conn).unwrap(), 2); + // noted after its removal: still not fetched + note_read(&mut conn, "s", 5, &[("late@spot.net".to_string(), 5, Some("eee".to_string()))], 0).unwrap(); + assert_eq!(todo(&conn, 10).unwrap(), ["forged@spot.net", "kept@spot.net"]); + + // saved ones lose their tag, and their page says why + conn.execute("attach ':memory:' as s0", []).unwrap(); + conn.execute_batch(&SPOTS.create.replace("exists spots", "exists s0.spots")).unwrap(); + let ids: Vec<i64> = (1..=5).map(|n| crate::store::global_id(n, 0)).collect(); + for (id, (spot, spotter, created)) in ids.iter().zip([ + ("mod@spot.net", "aaa", 0), + ("own@spot.net", "bbb", 0), + ("forged@spot.net", "ccc", 0), + ("kept@spot.net", "ddd", 0), + ("late@spot.net", "eee", 1), + ]) { + conn.execute( + "insert into s0.spots (release_id, message_id, kind, title, spotter_id, created) values (?, ?, 'movie', 'T', ?, ?)", + params![id, spot, spotter, created], + ) + .unwrap(); + } + let tagged = spots_of_with(&conn, &ids).unwrap(); + let mut left: Vec<&str> = tagged.values().map(|t| t.message_id.as_str()).collect(); + 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(2), None); + assert_eq!(removed(4), None); + + // removals of nothing kept go after `KEEP_DAYS`; one of a saved spot stays + let saved = Settled { state: SAVED, release_id: Some(ids[0]), ..Default::default() }; + settle(&conn, "mod@spot.net", Some(&saved), 0).unwrap(); + prune(&conn, KEEP_DAYS * day + 11).unwrap(); + let kept: Vec<String> = conn + .prepare("select message_id from spot_disposals order by message_id") + .unwrap() + .query_map([], |r| r.get(0)) + .unwrap() + .collect::<Result<_>>() + .unwrap(); + assert_eq!(kept, ["late@spot.net", "mod@spot.net"]); + } + #[test] fn a_frozen_release_with_the_title_counts_as_another_post() { let conn = Connection::open_in_memory().unwrap(); @@ -812,7 +978,7 @@ mod tests { } #[test] fn the_page_reads_the_spot_whole_or_from_its_columns() { - let conn = Connection::open_in_memory().unwrap(); + let conn = main_db(); let id = crate::store::global_id(4, 2); conn.execute("attach ':memory:' as s2", []).unwrap(); conn.execute_batch(&SPOTS.create.replace("exists spots", "exists s2.spots")).unwrap(); @@ -850,6 +1016,8 @@ mod tests { shard.execute("attach ':memory:' as s2", []).unwrap(); shard.execute_batch(&SPOTS.create.replace("exists spots", "exists s2.spots")).unwrap(); shard.execute("insert into s2.spots select * from main.spots", []).unwrap(); + shard.execute_batch("create table meta (key TEXT PRIMARY KEY, value INTEGER)").unwrap(); + create_main(&shard).unwrap(); let d = detail_of_with(&shard, id).unwrap().unwrap(); assert_eq!(d.xml, Xml::Kept); assert_eq!(d.imdb_id, None, "the XML has no IMDb link"); diff --git a/src/web.rs b/src/web.rs index 87bb4930..50fce263 100644 --- a/src/web.rs +++ b/src/web.rs @@ -1770,11 +1770,28 @@ fn spot_html(d: &crate::spotnet::store::Detail, said: &SpotSaid) -> String { format!("<div class=\"panel spot-desc\">{}</div>", crate::spotnet::ubb::to_html(&spot.description)) }; format!( - "<h2>Spot</h2><div class=\"panel\"><dl class=\"facts\">{facts}</dl></div><h3>Description</h3>{description}{}", + "<h2>Spot</h2>{}<div class=\"panel\"><dl class=\"facts\">{facts}</dl></div><h3>Description</h3>{description}{}", + d.removed.map_or(String::new(), spot_removed), spot_comments_html(&said.comments) ) } +/// Says a spot was taken back: the release stays, but the spot no longer vouches for it. +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!( + "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!( + "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." + ) + }; + diag("caution", "this spot was removed", &body) +} + /// A spot's comments, oldest first: who wrote each (and their spotter id), when, the rating it gives, and its text. fn spot_comments_html(comments: &[crate::spotnet::comments::Comment]) -> String { use crate::spotnet::comments::{GONE, READ}; @@ -2496,7 +2513,10 @@ fn release_html( None }); if let Some(spot) = &spot { - tags.push_str(&spot_tag(&spot.spot.poster, &spot.spot.title)); + match spot.removed { + Some(_) => tags.push_str(&tag("tag-warn", "SPOT REMOVED")), + None => tags.push_str(&spot_tag(&spot.spot.poster, &spot.spot.title)), + } } tags.push_str(&if r.complete { tag("tag-ok", "COMPLETE") } else { tag("tag-warn", "INCOMPLETE") }); if names.is_some_and(|n| n.obfuscated) { @@ -4206,6 +4226,7 @@ mod tests { imdb_id: spot.imdb_id(), spot, xml: crate::spotnet::store::Xml::Kept, + removed: None, }; use crate::spotnet::comments::{Comment, GONE, READ, WAITING}; let said = super::SpotSaid { @@ -4271,6 +4292,18 @@ mod tests { assert!(h.contains("<dt>Spam reports</dt><dd>0</dd>") && h.contains("No comments on this spot yet"), "{h}"); assert!(!h.contains("<dt>Rating</dt>"), "{h}"); assert!(!h.contains("<dt>Key</dt>") && !h.contains("<dt>Sender</dt>"), "{h}"); + let removed = crate::spotnet::store::Detail { + removed: Some(crate::spotnet::store::Removed { at: 1_793_000_000, by_moderator: true }), + ..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 }), + ..bare.clone() + }; + assert!(super::spot_html(&own, &super::SpotSaid::default()).contains("Its spotter removed this spot")); + 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")); } From 3e9d695502a26fc6d6caf0586d83a9cd27d309f0 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Sat, 7 Nov 2026 14:06:33 -0600 Subject: [PATCH 2/2] spots: review fixes for removals A spotter's own removal needs their key to have signed its title (which names the target) as well as its message-id; a spot's created of 0 counts as unknown in the listing filter as on its page; and a removal of a spot still waiting is kept until the spot ages out. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/spotnet/ingest.rs | 7 ++++--- src/spotnet/sign.rs | 14 ++++++++++++-- src/spotnet/store.rs | 23 ++++++++++++++++------- 3 files changed, 32 insertions(+), 12 deletions(-) diff --git a/src/spotnet/ingest.rs b/src/spotnet/ingest.rs index 45e81cf7..48cf0b2d 100644 --- a/src/spotnet/ingest.rs +++ b/src/spotnet/ingest.rs @@ -484,7 +484,7 @@ async fn read_overview( } /// The removal an overview line is, when it's a moderator's (or a spotter's own) `DISPOSE` whose signatures hold. -/// A spotter's own needs their key to have signed its message-id: it removes only their posts. +/// A spotter's own needs their key to have signed its title and message-id: it removes only their posts. fn removal(r: &crate::nntp::Overview, now: i64) -> Option<store::Disposal> { let h = header::parse(&r.subject, &r.from)?; let message_id = h.removes()?; @@ -492,9 +492,10 @@ fn removal(r: &crate::nntp::Overview, now: i64) -> Option<store::Disposal> { if !verdict.verified { return None; } - // a spotter id from the header signature alone could be replayed onto another message-id + // their key must sign both the title, which names the target, and the message-id: the header signature alone + // could be replayed onto another message-id, the message-id's alone onto another title let spotter = match verdict.personal { - true if verdict.message_id_signed => verdict.spotter_id?, + true if verdict.message_id_signed && verdict.title_signed => verdict.spotter_id?, true => return None, false => String::new(), }; diff --git a/src/spotnet/sign.rs b/src/spotnet/sign.rs index 597c6629..19cb5ff6 100644 --- a/src/spotnet/sign.rs +++ b/src/spotnet/sign.rs @@ -40,6 +40,9 @@ pub struct Verdict { /// the spotter's key signed the message-id itself. A spotter id from the header signature alone can be /// replayed: that signature covers the title, header and nickname, not the message-id pub message_id_signed: bool, + /// the header signature (over the title, header and nickname) holds: under Spotnet's key, or for a key-7 spot + /// or a spotter's own command under the spotter's key + pub title_signed: bool, } /// Checks the signatures of the spot (or moderator's command) whose overview gives `subject`, `from` and @@ -87,6 +90,7 @@ pub fn verify(title: &str, from: &str, message_id: &str) -> Verdict { verdict.verified = hashcash(&message_id); if verdict.verified && by_user() { verdict.spotter_id = spotter_id(&user_key); + verdict.title_signed = true; } } else if let Some((_, modulus)) = SPOTNET_KEYS.iter().find(|(k, _)| *k == key_id) { if key_id == 2 && user_key.len() > PERSONAL_KEY_LEN { @@ -94,10 +98,12 @@ pub fn verify(title: &str, from: &str, message_id: &str) -> Verdict { verdict.verified = hashcash(&message_id); if verdict.verified && by_user() { verdict.spotter_id = spotter_id(&user_key); + verdict.title_signed = true; } } else { let modulus = decode_base64(modulus).expect("Spotnet's keys are base64"); verdict.verified = rsa_sha1(&signed, &header_sig, &modulus); + verdict.title_signed = verdict.verified; } } // a `From` with the spotter's key and signature: the message-id must be signed with that key too (a key that @@ -192,7 +198,7 @@ mod tests { #[test] fn a_moderators_command() { let v = verify(MOD_TITLE, MOD_FROM, MOD_ID); - assert_eq!(v, Verdict { verified: true, ..Verdict::default() }); + assert_eq!(v, Verdict { verified: true, title_signed: true, ..Verdict::default() }); // the signed title names the spot: another spot's id breaks it let other = MOD_TITLE.replace("vhcUXQS5", "vhcUXQS6"); assert_eq!(verify(&other, MOD_FROM, MOD_ID), Verdict::default()); @@ -207,7 +213,11 @@ mod tests { #[test] fn a_spotters_own_dispose() { let v = verify(OWN_TITLE, OWN_FROM, OWN_ID); - assert!(v.verified && v.personal && v.message_id_signed); + assert!(v.verified && v.personal && v.message_id_signed && v.title_signed); + // another target in the title: the spotter's header signature no longer holds + let other = OWN_TITLE.replace("x9FBYiqq", "x9FBYiqr"); + let v = verify(&other, OWN_FROM, OWN_ID); + assert!(v.verified && v.message_id_signed && !v.title_signed); assert_eq!(v.spotter_id, spotter_id("4CGr2alVHshWG91Ajiozvi3D5D1MPD8Iwh5veSiUvGdrhFl5LBcyN5jV6GwHXqZB")); assert!(v.spotter_id.is_some()); } diff --git a/src/spotnet/store.rs b/src/spotnet/store.rs index ca5e364d..47468ca3 100644 --- a/src/spotnet/store.rs +++ b/src/spotnet/store.rs @@ -152,7 +152,8 @@ pub const OWN_DISPOSAL_SECS: i64 = 5 * 86_400; /// `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. pub(crate) fn disposed_sql(d: &str, s: &str, spotter: &str, created: Option<&str>) -> String { - let made = created.map_or(format!("{d}.at"), |c| format!("coalesce({s}.{c}, {d}.at)")); + // 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})))" @@ -241,12 +242,13 @@ pub fn prune(conn: &Connection, now: i64) -> Result<usize> { "delete from spots_seen where state not in (?1, ?2) and at < ?3", params![TODO, SAVED, now - KEEP_DAYS * day], )?; - // a removal is kept as long as what it removes may be: a saved spot or a comment, kept for good + // a removal is kept as long as what it removes may be: a spot waiting, or a saved spot or a comment (kept for + // good) n += conn.execute( "delete from spot_disposals where at < ?1 - and message_id not in (select message_id from spots_seen where state = ?2) + and message_id not in (select message_id from spots_seen where state in (?2, ?3)) and message_id not in (select message_id from spot_comments)", - params![now - KEEP_DAYS * day, SAVED], + params![now - KEEP_DAYS * day, SAVED, TODO], )?; Ok(n) } @@ -932,10 +934,16 @@ mod tests { assert_eq!(removed(2), None); assert_eq!(removed(4), None); - // removals of nothing kept go after `KEEP_DAYS`; one of a saved spot stays + // 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(); - prune(&conn, KEEP_DAYS * day + 11).unwrap(); + let skipped = Settled { state: SKIPPED, ..Default::default() }; + settle(&conn, "forged@spot.net", Some(&skipped), 0).unwrap(); + // an old removal of a spot just noted (an overview read far back) stays while the spot waits + let now = KEEP_DAYS * day + 11; + note_disposals(&mut conn, &[d("fresh@spot.net", "", 5)]).unwrap(); + note_read(&mut conn, "s", 6, &[("fresh@spot.net".to_string(), 6, None)], now).unwrap(); + prune(&conn, now).unwrap(); let kept: Vec<String> = conn .prepare("select message_id from spot_disposals order by message_id") .unwrap() @@ -943,7 +951,8 @@ mod tests { .unwrap() .collect::<Result<_>>() .unwrap(); - assert_eq!(kept, ["late@spot.net", "mod@spot.net"]); + assert_eq!(kept, ["fresh@spot.net", "late@spot.net", "mod@spot.net"]); + assert!(todo(&conn, 10).unwrap().is_empty(), "{:?}", todo(&conn, 10)); } #[test]