diff --git a/crates/core/src/connection.rs b/crates/core/src/connection.rs index 8830acf..5e4ab4c 100644 --- a/crates/core/src/connection.rs +++ b/crates/core/src/connection.rs @@ -6144,8 +6144,6 @@ impl ConnectionManager { /// Handle an incoming BlobHeaderDiff — store engagement ops and re-propagate /// to the post's file_holders (flat set, up to 5 most recent). async fn handle_blob_header_diff(&self, payload: BlobHeaderDiffPayload, sender: NodeId) { - use crate::types::BlobHeaderDiffOp; - // Gather policy + followers set + holders, then drop lock immediately. // Remote peer clearly holds this post — record them as a holder. // v0.6.2: `AudienceOnly` → `FollowersOnly`; checked against our public @@ -6172,268 +6170,73 @@ impl ConnectionManager { (policy, follows, holders) }; - // Apply ops in a short lock acquisition - { + // Apply ops in a short lock acquisition. + // + // v0.8 (D) NOVELTY GATE: `apply_diff_ops` returns ONLY the ops that + // moved local state. Everything downstream — the header rebuild, the + // engagement timestamp, and the re-propagation itself — hangs off + // that list, so a diff that told us nothing new dies here instead of + // spawning another round of sends. See `apply_diff_ops` for why the + // test is per-op state change rather than message identity. + let novel_ops = { let storage = self.storage.get().await; - for op in &payload.ops { - match op { - BlobHeaderDiffOp::AddReaction(reaction) => { - if policy.blocklist.contains(&reaction.reactor) { - continue; - } - if let crate::types::ReactPermission::None = policy.allow_reacts { - continue; - } - // Verify signature (skip if empty for backward compat with old nodes) - if !reaction.signature.is_empty() && !crate::crypto::verify_reaction_signature( - &reaction.reactor, - &payload.post_id, - &reaction.emoji, - reaction.timestamp_ms, - &reaction.signature, - ) { - continue; // Skip forged reactions - } - let _ = storage.store_reaction(reaction); + let novel = apply_diff_ops( + &storage, &payload, sender, &policy, &followers_set, now_ms(), + ); + if novel.is_empty() { + trace!( + post_id = hex::encode(payload.post_id), + ops = payload.ops.len(), + peer = hex::encode(sender), + "BlobHeaderDiff carried nothing new — not re-propagating" + ); + } else { + // Rebuild blob header JSON from current DB state so pull-based sync gets fresh data. + // Use _with_tombstones so tombstones propagate through the pull path. + let reactions = storage.get_reactions_with_tombstones(&payload.post_id).unwrap_or_default(); + let comments = storage.get_comments_with_tombstones(&payload.post_id).unwrap_or_default(); + let policy = storage.get_comment_policy(&payload.post_id).ok().flatten().unwrap_or_default(); + let (existing_header_json, _) = storage.get_blob_header(&payload.post_id) + .ok() + .flatten() + .unwrap_or((String::new(), 0)); + let mut header: crate::types::BlobHeader = serde_json::from_str(&existing_header_json).unwrap_or_else(|_| { + crate::types::BlobHeader { + post_id: payload.post_id, + author: payload.author, + reactions: vec![], + comments: vec![], + policy: crate::types::CommentPolicy::default(), + updated_at: 0, + thread_splits: vec![], + receipt_slots: vec![], + comment_slots: vec![], + prior_author: None, } - BlobHeaderDiffOp::RemoveReaction { reactor, emoji, post_id } => { - if *reactor == sender || sender == payload.author { - let _ = storage.remove_reaction(reactor, post_id, emoji); - } - } - BlobHeaderDiffOp::AddComment(comment) => { - // v0.8 (A3): the single shared accept gate — - // signature (digest v2 incl. expiry), TTL sanity, - // policy, FoF four-check gated on - // post.fof_gating (not the policy enum), - // open-slot size buckets + greeting cap, - // registry entry validation + newest-wins. - // Same gate runs on both pull-path merges. - let parent = storage.get_post(&payload.post_id).ok().flatten(); - if accept_incoming_comment( - &storage, - &payload.post_id, - parent.as_ref(), - &policy, - &followers_set, - comment, - now_ms(), - ) { - // Registry newest-wins pruning runs only after - // a SUCCESSFUL store, so a store error can't - // leave the persona with no entry (the gate - // itself is side-effect free). - if storage.store_comment(comment).is_ok() - && comment.post_id == crate::registry::REGISTRY_POST_ID - { - let _ = storage.prune_older_registry_entries( - &comment.post_id, - &comment.author, - comment.timestamp_ms, - ); - } - } - } - BlobHeaderDiffOp::EditComment { .. } => { - // v0.8: remote edits are IGNORED. The old arm - // trusted the attacker-controlled `payload.author` - // (`sender == payload.author` is trivially forged) - // and rewrote stored content without any signature - // — and post-A1 a network-id sender can never - // legitimately match a posting-id author anyway. - // Edits = the author re-sends AddComment with the - // same (author, post_id, timestamp_ms) key and a - // fresh v2 signature; the upsert replaces the row. - } - BlobHeaderDiffOp::DeleteComment { author, post_id, timestamp_ms, signature } => { - // v0.8 (A3): self-certifying delete ONLY — the - // comment author's signature verifies from the op - // alone (works on registry holders that never met - // the persona). The old parent-post-author sender - // override compared against attacker-controlled - // `payload.author` (forgeable), and could never - // fire legitimately anyway (sender is a NETWORK - // id, post authors are POSTING ids). Post-author - // moderation returns later as a SIGNED override; - // bulk moderation = the RevocationEntry off-switch. - if delete_comment_authorized(author, post_id, *timestamp_ms, signature) { - let _ = storage.delete_comment(author, post_id, *timestamp_ms); - } - } - BlobHeaderDiffOp::SetPolicy(_) => { - // v0.8: remote policy writes are IGNORED. The old - // `sender == payload.author` check compared against - // an attacker-controlled field, and A3's accept - // gate consumes the stored policy as its FIRST - // drop condition — one forged SetPolicy(None) - // against REGISTRY_POST_ID would poison this - // holder into rejecting ALL future registrations. - // Policy rows are written only by the author's own - // device (node.set_comment_policy / - // persist_gated_post_author_state); a signed - // policy-change op can reintroduce remote writes. - } - BlobHeaderDiffOp::FoFRevocation { - post_id, revoked_pub_x, revoked_at_ms, reason_code, author_sig, - } => { - // Verify author identity signature before applying. - // payload.author is the engagement-diff sender; the - // post's real author lives in storage. - let post_author = match storage.get_post(post_id) { - Ok(Some(p)) => p.author, - _ => continue, - }; - if !crate::fof::verify_fof_revocation( - &post_author, post_id, revoked_pub_x, - *revoked_at_ms, *reason_code, author_sig, - ) { - continue; - } - // Apply: record + cascade-delete stored comments. - let _ = crate::fof::apply_fof_revocation_locally( - &storage, post_id, revoked_pub_x, - *revoked_at_ms, *reason_code, author_sig, - ); - } - BlobHeaderDiffOp::FoFAccessGrant { - post_id, new_pub_x, new_wrap_slot, granted_at_ms, author_sig, - } => { - let post_author = match storage.get_post(post_id) { - Ok(Some(p)) => p.author, - _ => continue, - }; - if !crate::fof::verify_fof_access_grant( - &post_author, post_id, new_pub_x, new_wrap_slot, - *granted_at_ms, author_sig, - ) { - continue; - } - let _ = crate::fof::apply_fof_access_grant_locally( - &storage, post_id, new_pub_x, new_wrap_slot, - ); - } - BlobHeaderDiffOp::FoFKeyBurn { - post_id, slot_index, new_pub_x, new_wrap_slot, burned_at_ms, author_sig, - } => { - let post_author = match storage.get_post(post_id) { - Ok(Some(p)) => p.author, - _ => continue, - }; - if !crate::fof::verify_fof_key_burn( - &post_author, post_id, *slot_index, new_pub_x, new_wrap_slot, - *burned_at_ms, author_sig, - ) { - continue; - } - let _ = crate::fof::apply_fof_key_burn_locally( - &storage, post_id, *slot_index, new_pub_x, new_wrap_slot, - *burned_at_ms, - ); - } - BlobHeaderDiffOp::ThreadSplit { new_post_id } => { - let _ = storage.store_thread_meta(&crate::types::ThreadMeta { - post_id: *new_post_id, - parent_post_id: payload.post_id, - }); - } - BlobHeaderDiffOp::WriteReceiptSlot { post_id, slot_index, data } => { - // Store encrypted bytes directly — no decryption needed on relay nodes - if let Ok(Some((json, _ts))) = storage.get_blob_header(post_id) { - if let Ok(mut header) = serde_json::from_str::(&json) { - let idx = *slot_index as usize; - while header.receipt_slots.len() <= idx { - header.receipt_slots.push(vec![0u8; 64]); // padding - } - header.receipt_slots[idx] = data.clone(); - let now_ms = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_millis() as u64) - .unwrap_or(0); - header.updated_at = now_ms; - if let Ok(new_json) = serde_json::to_string(&header) { - let _ = storage.store_blob_header(post_id, &header.author, &new_json, now_ms); - } - } - } - } - BlobHeaderDiffOp::WriteCommentSlot { post_id, slot_index, data } => { - if let Ok(Some((json, _ts))) = storage.get_blob_header(post_id) { - if let Ok(mut header) = serde_json::from_str::(&json) { - let idx = *slot_index as usize; - while header.comment_slots.len() <= idx { - header.comment_slots.push(vec![0u8; 256]); - } - header.comment_slots[idx] = data.clone(); - let now_ms = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_millis() as u64) - .unwrap_or(0); - header.updated_at = now_ms; - if let Ok(new_json) = serde_json::to_string(&header) { - let _ = storage.store_blob_header(post_id, &header.author, &new_json, now_ms); - } - } - } - } - BlobHeaderDiffOp::AddCommentSlots { post_id, count: _, slots } => { - if let Ok(Some((json, _ts))) = storage.get_blob_header(post_id) { - if let Ok(mut header) = serde_json::from_str::(&json) { - for slot in slots { - header.comment_slots.push(slot.clone()); - } - let now_ms = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_millis() as u64) - .unwrap_or(0); - header.updated_at = now_ms; - if let Ok(new_json) = serde_json::to_string(&header) { - let _ = storage.store_blob_header(post_id, &header.author, &new_json, now_ms); - } - } - } - } - BlobHeaderDiffOp::Unknown => {} // future ops — silently skip + }); + header.reactions = reactions; + header.comments = comments; + header.policy = policy; + header.updated_at = payload.timestamp_ms; + // Look up actual post author (don't trust payload.author) + let actual_author = storage.get_post(&payload.post_id) + .ok().flatten() + .map(|p| p.author) + .unwrap_or(payload.author); // fallback if post not stored yet + header.author = actual_author; + if let Ok(json) = serde_json::to_string(&header) { + let _ = storage.store_blob_header(&payload.post_id, &actual_author, &json, payload.timestamp_ms); } + // Phase 4: Update last_engagement_ms when engagement arrives via diff + let _ = storage.update_post_last_engagement(&payload.post_id, payload.timestamp_ms); } + novel + }; - // Rebuild blob header JSON from current DB state so pull-based sync gets fresh data. - // Use _with_tombstones so tombstones propagate through the pull path. - let reactions = storage.get_reactions_with_tombstones(&payload.post_id).unwrap_or_default(); - let comments = storage.get_comments_with_tombstones(&payload.post_id).unwrap_or_default(); - let policy = storage.get_comment_policy(&payload.post_id).ok().flatten().unwrap_or_default(); - let (existing_header_json, _) = storage.get_blob_header(&payload.post_id) - .ok() - .flatten() - .unwrap_or((String::new(), 0)); - let mut header: crate::types::BlobHeader = serde_json::from_str(&existing_header_json).unwrap_or_else(|_| { - crate::types::BlobHeader { - post_id: payload.post_id, - author: payload.author, - reactions: vec![], - comments: vec![], - policy: crate::types::CommentPolicy::default(), - updated_at: 0, - thread_splits: vec![], - receipt_slots: vec![], - comment_slots: vec![], - prior_author: None, - } - }); - header.reactions = reactions; - header.comments = comments; - header.policy = policy; - header.updated_at = payload.timestamp_ms; - // Look up actual post author (don't trust payload.author) - let actual_author = storage.get_post(&payload.post_id) - .ok().flatten() - .map(|p| p.author) - .unwrap_or(payload.author); // fallback if post not stored yet - header.author = actual_author; - if let Ok(json) = serde_json::to_string(&header) { - let _ = storage.store_blob_header(&payload.post_id, &actual_author, &json, payload.timestamp_ms); - } - // Phase 4: Update last_engagement_ms when engagement arrives via diff - let _ = storage.update_post_last_engagement(&payload.post_id, payload.timestamp_ms); + // Nothing changed here ⇒ nothing to tell anyone. This is the + // termination condition that makes the flood quiescent. + if novel_ops.is_empty() { + return; } // Re-propagate to all file holders (flat set, max 5). Exclude sender. @@ -6447,7 +6250,17 @@ impl ConnectionManager { } } if !targets.is_empty() { - let payload_clone = payload.clone(); + // v0.8 (D): the outbound push is BUILT FROM WHAT CHANGED HERE — + // never a verbatim forward of what arrived. A coalesced diff of + // 9 known ops + 1 novel op relays exactly the one op, so the + // message shrinks along each hop instead of re-amplifying the + // whole batch at every holder in the cluster. + let payload_clone = BlobHeaderDiffPayload { + post_id: payload.post_id, + author: payload.author, + ops: novel_ops, + timestamp_ms: payload.timestamp_ms, + }; tokio::spawn(async move { // Send to up to 10 concurrently, then batch the rest use tokio::task::JoinSet; @@ -9345,6 +9158,497 @@ pub fn ingest_header_comments( stored } +/// v0.8 (D) THE NOVELTY GATE — apply an incoming `BlobHeaderDiff`'s ops to +/// local storage and return **only the ops that actually changed local +/// state**. The caller re-propagates exactly this list, and sends nothing +/// at all when it comes back empty. +/// +/// Why it has this shape (round 10 ruling: "if I receive non-novel updates +/// that's old updates sloshing around — I shouldn't repeat or else we'll +/// have a feedback loop we do NOT want"): +/// +/// * **State change, not message identity.** A seen-set of message +/// hashes cannot work: coalescing (hot-post backpressure merges local +/// activity with relayed activity into one push) means no two pushes +/// are ever byte-identical, so hash dedup fails by construction. The +/// only stable question is "did my store move?". +/// * **Per-op, not per-message.** A coalesced diff of 9 already-known +/// ops + 1 new one must relay ONE op. So the outbound push is +/// assembled from what CHANGED here, never forwarded verbatim from +/// what ARRIVED — each op below is admitted only on its own storage +/// apply reporting `true`. +/// * **Tombstones count even when their target is absent.** Recording +/// the tombstone IS the state change (see `Storage::delete_comment` +/// and `fof::apply_fof_revocation_locally`); otherwise a delete that +/// outruns its comment dies at the first node that has not yet seen +/// the comment, and the content lives on behind it. +/// +/// With this gate the protocol is ordinary rumour-mongering with feedback +/// termination: a node stops spreading a rumour as soon as it is no longer +/// news to that node, so a dense holder cluster (registry post, greeting- +/// enabled bios — exactly the open-slot posts where anyone can generate +/// activity) quiesces instead of echoing. +/// +/// Ops that are deliberately IGNORED on receive (`EditComment`, +/// `SetPolicy`, `Unknown`) can never be novel — they change nothing, so +/// they also stop travelling here. That is intended: an op this build +/// refuses to apply is an op it has no business amplifying. +pub fn apply_diff_ops( + storage: &crate::storage::Storage, + payload: &BlobHeaderDiffPayload, + sender: NodeId, + policy: &crate::types::CommentPolicy, + followers_set: &HashSet, + now: u64, +) -> Vec { + use crate::types::BlobHeaderDiffOp; + + // v0.8 (D): bootstrap the header row BEFORE any op is applied, and + // independently of novelty. The slot writers below need an existing + // `blob_headers` row to write into; the full header rebuild that used to + // create one for them now runs only when something was novel, so a diff + // carrying nothing but slot ops (which is exactly what the encrypted + // private-comment channel sends — see `node::add_encrypted_comment`) + // would otherwise deadlock forever: no row ⇒ nothing applies ⇒ nothing + // novel ⇒ no rebuild ⇒ still no row. Bounded to posts we actually hold, + // like every other row this path can create. + if payload.ops.iter().any(|op| matches!( + op, + BlobHeaderDiffOp::WriteReceiptSlot { .. } + | BlobHeaderDiffOp::WriteCommentSlot { .. } + | BlobHeaderDiffOp::AddCommentSlots { .. } + )) && storage.get_blob_header(&payload.post_id).ok().flatten().is_none() { + if let Ok(Some(post)) = storage.get_post(&payload.post_id) { + let header = crate::types::BlobHeader { + post_id: payload.post_id, + author: post.author, + reactions: vec![], + comments: vec![], + policy: crate::types::CommentPolicy::default(), + updated_at: 0, + thread_splits: vec![], + receipt_slots: vec![], + comment_slots: vec![], + prior_author: None, + }; + if let Ok(json) = serde_json::to_string(&header) { + let _ = storage.store_blob_header(&payload.post_id, &post.author, &json, now); + } + } + } + + let mut novel: Vec = Vec::new(); + for op in &payload.ops { + match op { + BlobHeaderDiffOp::AddReaction(reaction) => { + // Envelope binding (see the DeleteComment arm): the + // signature below is verified against `payload.post_id` + // while `store_reaction` files the row under + // `reaction.post_id`. Letting those differ would file a + // reaction that verified for post A against post B. + if reaction.post_id != payload.post_id { + continue; + } + if policy.blocklist.contains(&reaction.reactor) { + continue; + } + if let crate::types::ReactPermission::None = policy.allow_reacts { + continue; + } + // Verify signature (skip if empty for backward compat with old nodes) + if !reaction.signature.is_empty() && !crate::crypto::verify_reaction_signature( + &reaction.reactor, + &payload.post_id, + &reaction.emoji, + reaction.timestamp_ms, + &reaction.signature, + ) { + continue; // Skip forged reactions + } + if storage.store_reaction(reaction).unwrap_or(false) { + novel.push(op.clone()); + } + } + BlobHeaderDiffOp::RemoveReaction { reactor, emoji, post_id } => { + // Envelope binding, same rule as everywhere else here: a + // diff about post A may not tombstone rows on post B. + if *post_id != payload.post_id { + continue; + } + // DELIBERATE ASYMMETRY WITH `DeleteComment` — read before + // "fixing" it. Requirement (c) (a tombstone whose target is + // absent still counts as a state change, so the retraction + // outruns its content) is implemented for comment deletes + // but NOT here, for three reasons that are specific to + // reactions: + // 1. `RemoveReaction` carries no timestamp. The reactions + // row is keyed (reactor, post_id, emoji) and ordered by + // `timestamp_ms`, and `store_reaction`'s upsert keeps + // whichever side is STRICTLY NEWER. A placeholder + // inserted here could only guess a timestamp, so the + // late-arriving `AddReaction` would win and resurrect + // the reaction anyway. The comment placeholder works + // precisely because `DeleteComment` carries the exact + // `(author, post_id, timestamp_ms)` primary key. + // 2. Removals are not self-certifying. `delete_comment_ + // authorized` verifies a signature by the comment + // author; the guard below compares a NETWORK-class + // sender against a POSTING-class reactor, or against + // the attacker-controlled `payload.author` — so it + // authenticates nothing, and a placeholder write here + // would be a free, unbounded row vector keyed on an + // attacker-chosen (reactor, emoji) pair, with `emoji` + // being arbitrary-length TEXT. + // 3. The reactions table has no `expires_at` column, so + // unlike the comment placeholder such a row could not + // self-clean via the expiry sweep. + // The real limiter today is the guard below, which also + // keeps removals effectively single-hop. The follow-up that + // makes this symmetric is a SIGNED `RemoveReaction` carrying + // the reaction's timestamp (mirroring `delete_comment_ + // authorized`); the placeholder is only worth adding on top + // of that, with the same per-post cap and held-post bound as + // `Storage::record_absent_comment_tombstone`. + if *reactor == sender || sender == payload.author { + if storage.remove_reaction(reactor, post_id, emoji).unwrap_or(false) { + novel.push(op.clone()); + } + } + } + BlobHeaderDiffOp::AddComment(comment) => { + // v0.8 (A3): the single shared accept gate — + // signature (digest v2 incl. expiry), TTL sanity, + // policy, FoF four-check gated on + // post.fof_gating (not the policy enum), + // open-slot size buckets + greeting cap, + // registry entry validation + newest-wins. + // Same gate runs on both pull-path merges. + let parent = storage.get_post(&payload.post_id).ok().flatten(); + if accept_incoming_comment( + storage, + &payload.post_id, + parent.as_ref(), + policy, + followers_set, + comment, + now, + ) { + // Registry newest-wins pruning runs only after + // a SUCCESSFUL store, so a store error can't + // leave the persona with no entry (the gate + // itself is side-effect free). + // + // v0.8 (D): `store_comment` now reports whether the + // row moved. Passing the gate is NOT novelty — a + // holder re-sent the same valid comment we already + // hold passes the gate every time. + if storage.store_comment(comment).unwrap_or(false) { + novel.push(op.clone()); + if comment.post_id == crate::registry::REGISTRY_POST_ID { + let _ = storage.prune_older_registry_entries( + &comment.post_id, + &comment.author, + comment.timestamp_ms, + ); + } + } + } + } + BlobHeaderDiffOp::EditComment { .. } => { + // v0.8: remote edits are IGNORED. The old arm + // trusted the attacker-controlled `payload.author` + // (`sender == payload.author` is trivially forged) + // and rewrote stored content without any signature + // — and post-A1 a network-id sender can never + // legitimately match a posting-id author anyway. + // Edits = the author re-sends AddComment with the + // same (author, post_id, timestamp_ms) key and a + // fresh v2 signature; the upsert replaces the row. + } + BlobHeaderDiffOp::DeleteComment { author, post_id, timestamp_ms, signature } => { + // v0.8 (A3): self-certifying delete ONLY — the + // comment author's signature verifies from the op + // alone (works on registry holders that never met + // the persona). The old parent-post-author sender + // override compared against attacker-controlled + // `payload.author` (forgeable), and could never + // fire legitimately anyway (sender is a NETWORK + // id, post authors are POSTING ids). Post-author + // moderation returns later as a SIGNED override; + // bulk moderation = the RevocationEntry off-switch. + // + // v0.8 (D): the tombstone is recorded even when the comment + // itself has never been seen here, and that counts as a + // change — so a delete racing ahead of its own comment keeps + // travelling (requirement (c)). + // + // ENVELOPE BINDING applies to the whole arm, same as + // `accept_incoming_comment` step 0: a diff about post A may + // not file rows against post B. Both senders in this tree + // already set them equal. + // + // The two writes underneath are then bounded DIFFERENTLY, + // and the split matters: + // * Tombstoning a row we already hold has no extra bound — + // it can only move a row that is already on disk. It + // must NOT be gated on holding the parent post: comments + // are routinely stored without it (`accept_incoming_ + // comment` takes `parent_post: Option<&Post>` and only + // refuses slot-claiming comments when it is absent), so + // gating here would leave a deleted comment live forever + // on exactly those nodes while they keep relaying the + // content and swallow the retraction. + // * Recording an ABSENT-target placeholder is a row + // conjured from nothing, so it additionally requires + // that we hold the parent post — a post we do not hold + // is one we never re-serve — on top of the per-post cap + // and bounded expiry inside + // `Storage::record_absent_comment_tombstone`. The + // signature proves only that the op's own author signed + // it, so fresh keypairs × arbitrary timestamps are free. + if *post_id == payload.post_id + && delete_comment_authorized(author, post_id, *timestamp_ms, signature) + { + let tombstoned = storage + .tombstone_comment_if_present(author, post_id, *timestamp_ms) + .unwrap_or(false); + let changed = tombstoned + || (storage.get_post(post_id).ok().flatten().is_some() + && storage + .record_absent_comment_tombstone(author, post_id, *timestamp_ms) + .unwrap_or(false)); + if changed { + novel.push(op.clone()); + } + } + } + BlobHeaderDiffOp::SetPolicy(_) => { + // v0.8: remote policy writes are IGNORED. The old + // `sender == payload.author` check compared against + // an attacker-controlled field, and A3's accept + // gate consumes the stored policy as its FIRST + // drop condition — one forged SetPolicy(None) + // against REGISTRY_POST_ID would poison this + // holder into rejecting ALL future registrations. + // Policy rows are written only by the author's own + // device (node.set_comment_policy / + // persist_gated_post_author_state); a signed + // policy-change op can reintroduce remote writes. + } + BlobHeaderDiffOp::FoFRevocation { + post_id, revoked_pub_x, revoked_at_ms, reason_code, author_sig, + } => { + // Verify author identity signature before applying. + // payload.author is the engagement-diff sender; the + // post's real author lives in storage. + // + // This `continue` is a VERIFICATION PREREQUISITE, not a + // novelty decision: the op carries no author id, so without + // the stored post there is no key to check `author_sig` + // against. It is also why requirement (c) reaches less far + // for revocations than for comment deletes — a node holding + // no copy of the post drops the revocation instead of + // recording and relaying it. Carrying the post author in the + // op would fix that, and is a wire change. See + // `fof::RevocationApplied`. + let post_author = match storage.get_post(post_id) { + Ok(Some(p)) => p.author, + _ => continue, + }; + if !crate::fof::verify_fof_revocation( + &post_author, post_id, revoked_pub_x, + *revoked_at_ms, *reason_code, author_sig, + ) { + continue; + } + // Apply: record + cascade-delete stored comments. + let applied = crate::fof::apply_fof_revocation_locally( + storage, post_id, revoked_pub_x, + *revoked_at_ms, *reason_code, author_sig, + ); + if applied.map(|a| a.changed()).unwrap_or(false) { + novel.push(op.clone()); + } + } + BlobHeaderDiffOp::FoFAccessGrant { + post_id, new_pub_x, new_wrap_slot, granted_at_ms, author_sig, + } => { + let post_author = match storage.get_post(post_id) { + Ok(Some(p)) => p.author, + _ => continue, + }; + if !crate::fof::verify_fof_access_grant( + &post_author, post_id, new_pub_x, new_wrap_slot, + *granted_at_ms, author_sig, + ) { + continue; + } + // Already returns "appended?" — false on a duplicate + // grant and on a grant for an already-revoked pub_x. + if crate::fof::apply_fof_access_grant_locally( + storage, post_id, new_pub_x, new_wrap_slot, + ).unwrap_or(false) { + novel.push(op.clone()); + } + } + BlobHeaderDiffOp::FoFKeyBurn { + post_id, slot_index, new_pub_x, new_wrap_slot, burned_at_ms, author_sig, + } => { + let post_author = match storage.get_post(post_id) { + Ok(Some(p)) => p.author, + _ => continue, + }; + if !crate::fof::verify_fof_key_burn( + &post_author, post_id, *slot_index, new_pub_x, new_wrap_slot, + *burned_at_ms, author_sig, + ) { + continue; + } + // Already returns "replaced?" — false on a replay of an + // older-or-equal burn at this slot (the monotonic guard). + if crate::fof::apply_fof_key_burn_locally( + storage, post_id, *slot_index, new_pub_x, new_wrap_slot, + *burned_at_ms, + ).unwrap_or(false) { + novel.push(op.clone()); + } + } + BlobHeaderDiffOp::ThreadSplit { new_post_id } => { + if storage.store_thread_meta(&crate::types::ThreadMeta { + post_id: *new_post_id, + parent_post_id: payload.post_id, + }).unwrap_or(false) { + novel.push(op.clone()); + } + } + BlobHeaderDiffOp::WriteReceiptSlot { post_id, slot_index, data } => { + // ENVELOPE BINDING (same rule as the DeleteComment arm): + // `write_header_slot` fetches and rewrites the stored header + // of whatever post the OP names, with no signature check of + // any kind, so without this a diff about post A could + // scribble on the header we hold for any other post B — and + // the novelty gate would then relay that scribble onward as + // news (fresh random slot bytes are novel every time). + // In-tree senders already set the two equal, so honest + // traffic is unaffected. Note this bounds the TARGET only: + // slot writes are still unauthenticated (any peer may write + // any slot of a post we hold), which is a separate follow-up + // — the gate deduplicates identical bytes but does nothing + // against an attacker who varies them. + if *post_id != payload.post_id { + continue; + } + // Store encrypted bytes directly — no decryption needed on relay nodes + if write_header_slot(storage, post_id, *slot_index, data, SlotKind::Receipt) { + novel.push(op.clone()); + } + } + BlobHeaderDiffOp::WriteCommentSlot { post_id, slot_index, data } => { + // Envelope binding — see WriteReceiptSlot above. + if *post_id != payload.post_id { + continue; + } + if write_header_slot(storage, post_id, *slot_index, data, SlotKind::Comment) { + novel.push(op.clone()); + } + } + BlobHeaderDiffOp::AddCommentSlots { post_id, count: _, slots } => { + // Envelope binding — see WriteReceiptSlot above. + if *post_id != payload.post_id { + continue; + } + // v0.8 (D): append is now idempotent on slot BYTES. Without + // that, a re-delivered AddCommentSlots grew the header + // forever AND looked novel forever — an unbounded + // amplification loop on exactly the dense clusters this + // gate exists to quieten. Only the genuinely-new slots are + // appended, and only those are relayed onward. + let appended = append_comment_slots(storage, post_id, slots); + if !appended.is_empty() { + novel.push(BlobHeaderDiffOp::AddCommentSlots { + post_id: *post_id, + count: appended.len() as u32, + slots: appended, + }); + } + } + BlobHeaderDiffOp::Unknown => {} // future ops — silently skip + } + } + novel +} + +/// Which fixed-size slot vector on a `BlobHeader` a write targets. +#[derive(Clone, Copy, PartialEq, Eq)] +enum SlotKind { Receipt, Comment } + +/// Write one header slot, returning `true` only if the bytes actually +/// changed (a re-delivered write of identical bytes is not news). +fn write_header_slot( + storage: &crate::storage::Storage, + post_id: &crate::types::PostId, + slot_index: u32, + data: &[u8], + kind: SlotKind, +) -> bool { + let Ok(Some((json, _ts))) = storage.get_blob_header(post_id) else { return false; }; + let Ok(mut header) = serde_json::from_str::(&json) else { return false; }; + let idx = slot_index as usize; + let (slots, pad) = match kind { + SlotKind::Receipt => (&mut header.receipt_slots, 64usize), + SlotKind::Comment => (&mut header.comment_slots, 256usize), + }; + if slots.get(idx).map(|s| s.as_slice()) == Some(data) { + return false; // identical bytes already present + } + while slots.len() <= idx { + slots.push(vec![0u8; pad]); // padding + } + slots[idx] = data.to_vec(); + let ts = now_ms(); + header.updated_at = ts; + let author = header.author; + match serde_json::to_string(&header) { + Ok(new_json) => storage.store_blob_header(post_id, &author, &new_json, ts).is_ok(), + Err(_) => false, + } +} + +/// Append comment slots the header does not already carry. Returns the +/// slots that were genuinely appended (empty = nothing changed). +fn append_comment_slots( + storage: &crate::storage::Storage, + post_id: &crate::types::PostId, + slots: &[Vec], +) -> Vec> { + let Ok(Some((json, _ts))) = storage.get_blob_header(post_id) else { return Vec::new(); }; + let Ok(mut header) = serde_json::from_str::(&json) else { return Vec::new(); }; + let mut appended: Vec> = Vec::new(); + for slot in slots { + if header.comment_slots.iter().any(|s| s == slot) { + continue; + } + header.comment_slots.push(slot.clone()); + appended.push(slot.clone()); + } + if appended.is_empty() { + return appended; + } + let ts = now_ms(); + header.updated_at = ts; + let author = header.author; + match serde_json::to_string(&header) { + Ok(new_json) => { + if storage.store_blob_header(post_id, &author, &new_json, ts).is_ok() { + appended + } else { + Vec::new() + } + } + Err(_) => Vec::new(), + } +} + #[cfg(test)] mod accept_gate_tests { //! v0.8 (A3) T9: the accept-gate matrix, exercised BOTH through the @@ -9393,6 +9697,21 @@ mod accept_gate_tests { seed_byte: u8, max_comments: Option, comment_ttl: Option, + ) -> (Storage, PostId, Post) { + setup_greeting_bio_spec(seed_byte, comment_ttl, move |_s, _id| { + crate::fof::OpenSlotSpec::new(OpenSlotKind::Greeting, 1024) + .with_limit(max_comments) + }) + } + + /// As above, but the open-slot spec is derived from LIVE STORAGE at + /// build time. Lets a test go through `node::greeting_open_slot_spec` + /// — the same function the real bio publish uses — instead of handing + /// the limit in directly. + fn setup_greeting_bio_spec( + seed_byte: u8, + comment_ttl: Option, + spec_from: impl Fn(&Storage, &NodeId) -> crate::fof::OpenSlotSpec, ) -> (Storage, PostId, Post) { let s = temp_storage(); let (alice_id, alice_seed) = make_persona(seed_byte); @@ -9409,8 +9728,7 @@ mod accept_gate_tests { let built = crate::fof::build_fof_comment_gating( &s, &alice_id, - Some(crate::fof::OpenSlotSpec::new(OpenSlotKind::Greeting, 1024) - .with_limit(max_comments)), + Some(spec_from(&s, &alice_id)), ).unwrap().expect("gating built"); let post = Post { author: alice_id, @@ -10006,6 +10324,84 @@ mod accept_gate_tests { assert!(!gate_via_pull(&s, &post_id, &post.author, &over), "…and on the pull path"); } + /// v0.8: the greeting cap the APP writes must survive all the way to a + /// holder's accept decision. This walks the real path end to end — + /// the `greetings_max.` setting the Profiles lightbox (and + /// the `set_greetings_max` Tauri command / `greetings-max` CLI + /// command) writes → `node::greeting_open_slot_spec`, which the bio + /// republish reads → the SIGNED `OpenSlotDecl` inside the bio post → + /// enforcement on a holder that has only ever seen the post. + /// + /// The republish is the load-bearing half: the cap lives inside the + /// signed post, so writing the setting without republishing would + /// leave holders enforcing the old value indefinitely. + #[test] + fn greetings_max_setting_round_trips_to_holder_enforcement() { + let (s, post_id, post) = setup_greeting_bio_spec(116, None, |s, id| { + // Exactly what the app writes. + s.set_setting(&crate::node::greetings_max_setting_key(id), "3").unwrap(); + crate::node::greeting_open_slot_spec(s, id) + }); + + // It reached the signed declaration every holder enforces. + let decl = post.fof_gating.as_ref().unwrap().open_slot.as_ref().unwrap(); + assert_eq!(decl.max_comments, Some(3), "the cap is in the signed OpenSlotDecl"); + let slot_index = decl.slot_index; + + // And a holder enforces it — on both ingest paths. + let t = now(); + for i in 0..3u64 { + let c = make_greeting(&post, &post_id, 117 + i as u8, t + i, t + 40 * 24 * 3600 * 1000); + assert!(gate(&s, Some(&post), &c), "under the author's declared cap"); + s.store_comment(&c).unwrap(); + } + assert_eq!(s.count_unexpired_open_slot_comments(&post_id, slot_index).unwrap(), 3); + + let over = make_greeting(&post, &post_id, 125, t + 3, t + 40 * 24 * 3600 * 1000); + assert!(!gate(&s, Some(&post), &over), "cap from the setting enforced (diff)"); + assert!(!gate_via_pull(&s, &post_id, &post.author, &over), "…and on the pull path"); + } + + /// Blank/0 in the app's field means "unset" — the holder default, not + /// refusal. (Refusal is the structural case: `greetings_open = 0` + /// publishes a bio with no open slot at all.) + #[test] + fn blank_greetings_max_means_holder_default_not_refusal() { + let (_s, _post_id, post) = setup_greeting_bio_spec(126, None, |s, id| { + s.set_setting(&crate::node::greetings_max_setting_key(id), "").unwrap(); + crate::node::greeting_open_slot_spec(s, id) + }); + let decl = post.fof_gating.as_ref().unwrap().open_slot.as_ref().unwrap(); + assert_eq!(decl.max_comments, None, "unset — holders apply their own default"); + assert_eq!( + crate::comment_ttl::open_slot_limit( + decl, + crate::comment_ttl::holder_default_open_slot_limit(decl.kind), + ), + MAX_GREETINGS_PER_BIO, + ); + } + + /// The clamp to [`MAX_GREETINGS_PER_BIO`] lives in ONE place — + /// `node::greetings_max_setting`, the single read every writer funnels + /// through (the `set_greetings_max` Tauri/CLI command, and the Profiles + /// lightbox, which writes the setting directly so its `set_profile` + /// carries the change in one republish). The UI's own `min(n, 64)` is + /// presentational: a raw setting written past the ceiling must still + /// publish a declaration no holder would refuse. + #[test] + fn over_ceiling_greetings_max_is_clamped_before_it_is_signed() { + let (_s, _post_id, post) = setup_greeting_bio_spec(127, None, |s, id| { + s.set_setting(&crate::node::greetings_max_setting_key(id), "5000").unwrap(); + crate::node::greeting_open_slot_spec(s, id) + }); + let decl = post.fof_gating.as_ref().unwrap().open_slot.as_ref().unwrap(); + assert_eq!( + decl.max_comments, Some(MAX_GREETINGS_PER_BIO as u32), + "clamped at the source, not left for holders to reject", + ); + } + /// An author cannot RAISE the ceiling past the holder's own default: /// the storage being spent is the holder's. #[test] @@ -11036,3 +11432,550 @@ mod convection_tests { assert!(s.list_pool_anchors(16).unwrap().is_empty()); } } + +#[cfg(test)] +mod novelty_gate_tests { + //! v0.8 (D) T-D1: the diff re-propagation NOVELTY GATE. + //! + //! Round 10 ruling: "If I receive non-novel updates that's old updates + //! sloshing around. I shouldn't repeat or else we'll have a feedback + //! loop we do NOT want." Before this gate, `handle_blob_header_diff` + //! re-propagated every received diff to its file holders with + //! sender-exclusion as the only guard, so a dense holder cluster — + //! precisely what the registry post and greeting-enabled bios create — + //! had no termination condition at all. + //! + //! These tests pin the four properties that decide whether the gate + //! actually holds: state-change (not message identity), per-op (not + //! per-message), tombstones-count-when-the-target-is-absent, and + //! silence when nothing moved. + + use super::apply_diff_ops; + use crate::protocol::BlobHeaderDiffPayload; + use crate::storage::Storage; + use crate::types::{ + BlobHeaderDiffOp, CommentPolicy, InlineComment, NodeId, Post, PostId, + PostVisibility, Reaction, VisibilityIntent, + }; + use ed25519_dalek::SigningKey; + use std::collections::HashSet; + + fn temp_storage() -> Storage { + Storage::open(":memory:").unwrap() + } + + fn make_persona(seed_byte: u8) -> (NodeId, [u8; 32]) { + let mut seed = [0u8; 32]; + seed[0] = seed_byte; + let sk = SigningKey::from_bytes(&seed); + (*sk.verifying_key().as_bytes(), seed) + } + + fn now() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis() as u64 + } + + /// A stored public post to hang engagement on, plus its author. + fn public_post(seed_byte: u8) -> (Storage, PostId, NodeId) { + let s = temp_storage(); + let (author_id, _) = make_persona(seed_byte); + let post = Post { + author: author_id, + content: "hello".into(), + attachments: vec![], + timestamp_ms: 3000, + fof_gating: None, + supersedes_post_id: None, + comment_ttl: None, + }; + let post_id = crate::content::compute_post_id(&post); + s.store_post_with_intent( + &post_id, &post, &PostVisibility::Public, &VisibilityIntent::Public, + ).unwrap(); + (s, post_id, author_id) + } + + fn react_op(post_id: &PostId, seed_byte: u8, emoji: &str, ts: u64) -> BlobHeaderDiffOp { + let (reactor, seed) = make_persona(seed_byte); + BlobHeaderDiffOp::AddReaction(Reaction { + reactor, + emoji: emoji.into(), + post_id: *post_id, + timestamp_ms: ts, + encrypted_payload: None, + deleted_at: None, + signature: crate::crypto::sign_reaction(&seed, &reactor, post_id, emoji, ts), + }) + } + + /// A signed public comment + the matching self-certifying delete op. + fn comment_and_delete( + post_id: &PostId, + seed_byte: u8, + ts: u64, + ) -> (InlineComment, BlobHeaderDiffOp) { + comment_and_delete_expiring(post_id, seed_byte, ts, 0) + } + + /// As above with an explicit expiry. A node that does NOT hold the + /// parent post cannot read its retention policy, so `CommentTtlRule:: + /// UnknownParent` refuses the `0` never-expires sentinel there — + /// permanence is never granted on evidence we cannot read. + fn comment_and_delete_expiring( + post_id: &PostId, + seed_byte: u8, + ts: u64, + expires_at_ms: u64, + ) -> (InlineComment, BlobHeaderDiffOp) { + let (author, seed) = make_persona(seed_byte); + let content = "nice post"; + let comment = InlineComment { + author, + post_id: *post_id, + content: content.into(), + timestamp_ms: ts, + signature: crate::crypto::sign_comment( + &seed, &author, post_id, content, ts, None, expires_at_ms, + ), + deleted_at: None, + ref_post_id: None, + pub_x_index: None, + group_sig: None, + encrypted_payload: None, + expires_at_ms, + }; + let del = BlobHeaderDiffOp::DeleteComment { + author, + post_id: *post_id, + timestamp_ms: ts, + signature: crate::crypto::sign_comment_delete(&seed, &author, post_id, ts), + }; + (comment, del) + } + + /// Run a diff through the gate exactly as `handle_blob_header_diff` + /// does, and return the ops it would re-propagate. + fn relayed( + s: &Storage, + post_id: &PostId, + author: &NodeId, + ops: Vec, + ) -> Vec { + let payload = BlobHeaderDiffPayload { + post_id: *post_id, + author: *author, + ops, + timestamp_ms: now(), + }; + let sender = make_persona(240).0; + apply_diff_ops( + s, + &payload, + sender, + &CommentPolicy::default(), + &HashSet::new(), + now(), + ) + } + + /// THE headline property: a diff whose every op we already know + /// produces NO outbound push. Without it, each duplicate receipt in a + /// holder cluster spawns a fresh round of sends to every other holder, + /// which spawns more — no termination condition. + #[test] + fn duplicate_diff_produces_no_outbound_push() { + let (s, post_id, author) = public_post(30); + let t = now(); + let ops = vec![ + react_op(&post_id, 31, "👍", t), + react_op(&post_id, 32, "🎉", t + 1), + react_op(&post_id, 33, "🔥", t + 2), + ]; + + let first = relayed(&s, &post_id, &author, ops.clone()); + assert_eq!(first.len(), 3, "all three are news the first time"); + + let second = relayed(&s, &post_id, &author, ops.clone()); + assert!(second.is_empty(), "second receipt of the same state is not news"); + + // …and it stays quiet however many times the cluster echoes it. + for _ in 0..5 { + assert!(relayed(&s, &post_id, &author, ops.clone()).is_empty()); + } + } + + /// Per-op, not per-message: 3 known ops + 1 novel op relays ONE op. + /// The push is assembled from what changed locally, so the message + /// shrinks along each hop instead of re-amplifying the whole batch. + #[test] + fn mixed_diff_propagates_only_the_novel_op() { + let (s, post_id, author) = public_post(34); + let t = now(); + let known = vec![ + react_op(&post_id, 35, "👍", t), + react_op(&post_id, 36, "🎉", t + 1), + react_op(&post_id, 37, "🔥", t + 2), + ]; + assert_eq!(relayed(&s, &post_id, &author, known.clone()).len(), 3); + + let novel_op = react_op(&post_id, 38, "🤖", t + 3); + let mut coalesced = known.clone(); + coalesced.push(novel_op.clone()); + + let out = relayed(&s, &post_id, &author, coalesced); + assert_eq!(out.len(), 1, "only the one op that moved local state"); + assert_eq!(out[0], novel_op); + } + + /// A message-hash seen-set would pass the duplicate test above and + /// still fail here: the coalesced message is byte-different from + /// anything seen before, so hash dedup would relay all four ops. The + /// gate must be defined over STATE, which is what this asserts. + #[test] + fn novelty_is_state_change_not_message_identity() { + let (s, post_id, author) = public_post(39); + let t = now(); + let a = react_op(&post_id, 40, "👍", t); + let b = react_op(&post_id, 41, "🎉", t + 1); + + assert_eq!(relayed(&s, &post_id, &author, vec![a.clone()]).len(), 1); + assert_eq!(relayed(&s, &post_id, &author, vec![b.clone()]).len(), 1); + + // Same two ops, now arriving coalesced into one never-before-seen + // message. Nothing about our store moves ⇒ nothing goes out. + let out = relayed(&s, &post_id, &author, vec![a, b]); + assert!(out.is_empty(), "a novel MESSAGE carrying no novel STATE is silent"); + } + + /// A tombstone whose target we have never seen is still news: + /// recording the tombstone IS the state change. Otherwise a delete + /// dies at the first node that has not yet received the comment. + #[test] + fn tombstone_for_absent_target_is_novel() { + let (s, post_id, author) = public_post(42); + let (comment, delete_op) = comment_and_delete(&post_id, 43, now()); + + // The comment is NOT stored — this node has never seen it. + assert!(s.get_comments(&post_id).unwrap().is_empty()); + + let out = relayed(&s, &post_id, &author, vec![delete_op.clone()]); + assert_eq!(out.len(), 1, "the delete is recorded, so it keeps travelling"); + assert_eq!(out[0], delete_op); + + // Recorded means recorded: a second copy is no longer news. + assert!( + relayed(&s, &post_id, &author, vec![delete_op.clone()]).is_empty(), + "a re-delivered tombstone terminates like anything else", + ); + + // The tombstone is inert on the wire and in the UI. + assert!(s.get_comments(&post_id).unwrap().is_empty()); + let _ = comment; + } + + /// The out-of-order case end to end: the delete arrives first, is + /// relayed onward, and then the comment it kills shows up. The + /// comment must NOT come back to life, and must not be relayed as + /// though it were new content. + #[test] + fn delete_arriving_before_its_comment_reaches_the_next_hop() { + let (s, post_id, author) = public_post(44); + let t = now(); + let (comment, delete_op) = comment_and_delete(&post_id, 45, t); + + // 1. Delete first — novel, so the next hop hears about it. + let out = relayed(&s, &post_id, &author, vec![delete_op.clone()]); + assert_eq!(out, vec![delete_op.clone()], "delete relayed despite the absent target"); + + // 2. The comment finally arrives. It passes the accept gate (it is + // a perfectly valid signed public comment) but must land dead. + let add = BlobHeaderDiffOp::AddComment(comment.clone()); + let _ = relayed(&s, &post_id, &author, vec![add]); + assert!( + s.get_comments(&post_id).unwrap().is_empty(), + "the comment does not resurrect behind its own delete", + ); + + // 3. The tombstone survived the upsert that filled in the content. + let rows = s.get_comments_with_tombstones(&post_id).unwrap(); + assert_eq!(rows.len(), 1); + assert!(rows[0].deleted_at.is_some(), "still tombstoned"); + + // 4. And the delete is still not re-relayed on a later duplicate. + assert!(relayed(&s, &post_id, &author, vec![delete_op]).is_empty()); + } + + /// The absent-target tombstone write is bounded, or it becomes a free + /// write amplifier: a signature proves only that its own author signed + /// it, so anyone with a keypair can mint deletes for arbitrary + /// (post_id, timestamp) pairs. Neither an off-envelope target nor a + /// post we do not hold may create a row — or be relayed. + #[test] + fn absent_target_tombstones_are_bounded() { + let (s, post_id, author) = public_post(53); + + // (a) Off-envelope: a diff about THIS post carrying a delete aimed + // at a different post files nothing. + let other_post_id: PostId = [7u8; 32]; + let (_, off_envelope) = comment_and_delete(&other_post_id, 54, now()); + assert!(relayed(&s, &post_id, &author, vec![off_envelope]).is_empty()); + assert!(s.get_comments_with_tombstones(&other_post_id).unwrap().is_empty()); + + // (b) A post we do not hold: no rows, nothing relayed. (Same + // storage, a post_id that was never stored.) + let unheld: PostId = [8u8; 32]; + let (_, unheld_delete) = comment_and_delete(&unheld, 55, now()); + assert!(relayed(&s, &unheld, &author, vec![unheld_delete]).is_empty()); + assert!(s.get_comments_with_tombstones(&unheld).unwrap().is_empty()); + + // (c) The legitimate case still works: held post, matching envelope. + let (_, good) = comment_and_delete(&post_id, 56, now()); + assert_eq!(relayed(&s, &post_id, &author, vec![good.clone()]), vec![good]); + } + + /// A comment we already hold passes the accept gate every single time + /// it is re-sent — passing the gate is NOT novelty. Only the store + /// actually moving is. + #[test] + fn re_sent_known_comment_passes_the_gate_but_is_not_relayed() { + let (s, post_id, author) = public_post(46); + let (comment, _) = comment_and_delete(&post_id, 47, now()); + let add = BlobHeaderDiffOp::AddComment(comment.clone()); + + assert_eq!(relayed(&s, &post_id, &author, vec![add.clone()]).len(), 1); + assert_eq!(s.get_comments(&post_id).unwrap().len(), 1); + + assert!( + relayed(&s, &post_id, &author, vec![add.clone()]).is_empty(), + "the gate still accepts it; the store does not move; nothing is relayed", + ); + // Still exactly one row — the re-delivery was a true no-op. + assert_eq!(s.get_comments(&post_id).unwrap().len(), 1); + } + + /// Ops this build deliberately refuses to APPLY (remote edits, remote + /// policy writes, forward-compat unknowns) must also stop travelling. + /// Amplifying an op we will not act on is pure loop fuel. + #[test] + fn ops_we_refuse_to_apply_are_never_relayed() { + let (s, post_id, author) = public_post(48); + let (commenter, _) = make_persona(49); + let out = relayed(&s, &post_id, &author, vec![ + BlobHeaderDiffOp::EditComment { + author: commenter, + post_id, + timestamp_ms: now(), + new_content: "rewritten".into(), + }, + BlobHeaderDiffOp::SetPolicy(CommentPolicy::default()), + BlobHeaderDiffOp::Unknown, + ]); + assert!(out.is_empty()); + } + + /// A forged reaction is dropped by the signature check, so it is + /// neither stored nor relayed — the gate does not become a laundering + /// path for content that failed verification. + #[test] + fn rejected_ops_are_not_relayed() { + let (s, post_id, author) = public_post(50); + let t = now(); + let mut forged = react_op(&post_id, 51, "👍", t); + if let BlobHeaderDiffOp::AddReaction(r) = &mut forged { + r.emoji = "💀".into(); // signature now covers the wrong emoji + } + assert!(relayed(&s, &post_id, &author, vec![forged]).is_empty()); + assert!(s.get_reactions(&post_id).unwrap().is_empty()); + } + + /// `AddCommentSlots` used to append unconditionally: a re-delivered op + /// grew the header forever AND looked novel forever — unbounded + /// amplification on exactly the dense clusters this gate exists to + /// quieten. Appends are now idempotent on slot bytes. + #[test] + fn repeated_comment_slot_append_is_idempotent_and_silent() { + let (s, post_id, author) = public_post(52); + s.store_blob_header( + &post_id, + &author, + &serde_json::to_string(&crate::types::BlobHeader { + post_id, + author, + reactions: vec![], + comments: vec![], + policy: CommentPolicy::default(), + updated_at: 1, + thread_splits: vec![], + receipt_slots: vec![], + comment_slots: vec![], + prior_author: None, + }).unwrap(), + 1, + ).unwrap(); + + let op = BlobHeaderDiffOp::AddCommentSlots { + post_id, + count: 2, + slots: vec![vec![7u8; 32], vec![9u8; 32]], + }; + assert_eq!(relayed(&s, &post_id, &author, vec![op.clone()]).len(), 1); + assert!(relayed(&s, &post_id, &author, vec![op.clone()]).is_empty()); + + let (json, _) = s.get_blob_header(&post_id).unwrap().unwrap(); + let header: crate::types::BlobHeader = serde_json::from_str(&json).unwrap(); + assert_eq!(header.comment_slots.len(), 2, "no unbounded growth"); + } + + /// Comments are routinely held WITHOUT their parent post + /// (`accept_incoming_comment` takes `parent_post: Option<&Post>` and + /// only refuses slot-claiming comments when it is absent) — steady + /// state for a CDN holder, and a guaranteed race window while a post + /// sync is in flight. On such a node a signed delete must still + /// tombstone the comment AND keep travelling. Gating the whole arm on + /// "we hold the post" would drop a delete whose target is right there, + /// which is strictly worse than the absent-target case the placeholder + /// was added for: content spreads, the retraction does not. + #[test] + fn delete_tombstones_comment_on_a_node_without_the_parent_post() { + let s = temp_storage(); + let post_id: PostId = [11u8; 32]; + let (author, _) = make_persona(60); // envelope author; no post stored + let t = now(); + // Bounded TTL: with the parent post unheld, `CommentTtlRule:: + // UnknownParent` refuses the never-expires sentinel. + let (comment, delete_op) = + comment_and_delete_expiring(&post_id, 61, t, t + 30 * 24 * 3600 * 1000); + + // No `posts` row at all — this node holds the comment only. + assert!(s.get_post(&post_id).unwrap().is_none()); + let add = BlobHeaderDiffOp::AddComment(comment.clone()); + assert_eq!(relayed(&s, &post_id, &author, vec![add]).len(), 1); + assert_eq!(s.get_comments(&post_id).unwrap().len(), 1, "comment held without its post"); + + // The delete lands: tombstoned locally AND relayed onward. + let out = relayed(&s, &post_id, &author, vec![delete_op.clone()]); + assert_eq!(out, vec![delete_op.clone()], "the retraction keeps travelling"); + assert!(s.get_comments(&post_id).unwrap().is_empty(), "tombstoned locally"); + + // Still terminates: a second copy moves nothing. + assert!(relayed(&s, &post_id, &author, vec![delete_op]).is_empty()); + + // …and no placeholder was invented for a post we do not hold: the + // only row is the real comment, now carrying its tombstone. + let rows = s.get_comments_with_tombstones(&post_id).unwrap(); + assert_eq!(rows.len(), 1); + assert!(rows[0].deleted_at.is_some()); + } + + /// The absent-target placeholder is the one row an unknown peer can + /// conjure from nothing, and its signature proves only that its own + /// author signed it — so fresh keypairs and arbitrary timestamps are + /// free. Unbounded, each forged op would be novel exactly once per + /// node, hence stored AND relayed to five holders, who relay to five: + /// the feedback loop this gate exists to kill, reached through the + /// gate's own novelty signal. It must be capped in rows and in relays. + #[test] + fn forged_deletes_from_fresh_keypairs_are_capped() { + let (s, post_id, author) = public_post(57); + let cap = crate::storage::MAX_ORPHAN_COMMENT_TOMBSTONES_PER_POST as usize; + + let mut relays = 0usize; + for seed in 1..=(cap as u64 + 40) { + // A fresh keypair AND a fresh timestamp for every op — nothing + // an attacker has to work for. + let (_, forged) = comment_and_delete(&post_id, (seed % 250 + 1) as u8, 10_000 + seed); + relays += relayed(&s, &post_id, &author, vec![forged]).len(); + } + + assert_eq!(relays, cap, "past the cap, nothing is relayed"); + + // Capped rows are also invisible to everything we publish: they + // never enter the header we serve on a pull… + assert!( + s.get_comments_with_tombstones(&post_id).unwrap().is_empty(), + "placeholders stay out of the served header", + ); + // …and they self-clean rather than pinning disk forever. The sweep + // count doubles as the row count: every placeholder carries a + // bounded `expires_at`, and nothing else was stored here. + let far = now() + crate::comment_ttl::MAX_COMMENT_TTL_MS + 1; + assert_eq!( + s.expire_comments(far).unwrap(), cap, + "exactly `cap` placeholder rows exist, and the expiry sweep reclaims them", + ); + } + + /// A diff carrying ONLY slot ops is the encrypted private-comment + /// channel (`node::add_encrypted_comment` emits exactly + /// `AddCommentSlots`/`WriteCommentSlot`). On a holder with no + /// `blob_headers` row yet, the slot writers have nothing to write into + /// — and since the full header rebuild now runs only when something + /// was novel, a naive gate deadlocks: no row ⇒ nothing applies ⇒ + /// nothing novel ⇒ no rebuild ⇒ still no row, forever. The bootstrap + /// must therefore be independent of novelty. + #[test] + fn slot_only_diff_bootstraps_a_missing_header_row() { + let (s, post_id, author) = public_post(58); + assert!(s.get_blob_header(&post_id).unwrap().is_none(), "no header row yet"); + + let op = BlobHeaderDiffOp::AddCommentSlots { + post_id, + count: 1, + slots: vec![vec![3u8; 32]], + }; + assert_eq!(relayed(&s, &post_id, &author, vec![op.clone()]).len(), 1, "applied and relayed"); + + let (json, _) = s.get_blob_header(&post_id).unwrap().unwrap(); + let header: crate::types::BlobHeader = serde_json::from_str(&json).unwrap(); + assert_eq!(header.comment_slots, vec![vec![3u8; 32]]); + + // Same for a positional write, and it still terminates. + let w = BlobHeaderDiffOp::WriteCommentSlot { post_id, slot_index: 0, data: vec![4u8; 32] }; + assert_eq!(relayed(&s, &post_id, &author, vec![w.clone()]).len(), 1); + assert!(relayed(&s, &post_id, &author, vec![w]).is_empty()); + } + + /// Slot ops carry their own `post_id`, and `write_header_slot` rewrites + /// the stored header of whatever post it names with no signature check + /// of any kind. Without envelope binding, a diff about post A could + /// scribble on the header we hold for post B — and the novelty gate + /// would relay that scribble as news, since fresh random slot bytes are + /// novel every time. + #[test] + fn slot_ops_cannot_write_across_the_envelope() { + let (s, post_id, author) = public_post(59); + let other: PostId = [12u8; 32]; + s.store_blob_header( + &other, + &author, + &serde_json::to_string(&crate::types::BlobHeader { + post_id: other, + author, + reactions: vec![], + comments: vec![], + policy: CommentPolicy::default(), + updated_at: 1, + thread_splits: vec![], + receipt_slots: vec![], + comment_slots: vec![], + prior_author: None, + }).unwrap(), + 1, + ).unwrap(); + + // Envelope = post_id, ops aimed at `other`. + let out = relayed(&s, &post_id, &author, vec![ + BlobHeaderDiffOp::WriteCommentSlot { post_id: other, slot_index: 0, data: vec![5u8; 32] }, + BlobHeaderDiffOp::WriteReceiptSlot { post_id: other, slot_index: 0, data: vec![6u8; 32] }, + BlobHeaderDiffOp::AddCommentSlots { post_id: other, count: 1, slots: vec![vec![7u8; 32]] }, + ]); + assert!(out.is_empty(), "cross-post slot writes are neither applied nor relayed"); + + let (json, _) = s.get_blob_header(&other).unwrap().unwrap(); + let header: crate::types::BlobHeader = serde_json::from_str(&json).unwrap(); + assert!(header.comment_slots.is_empty() && header.receipt_slots.is_empty()); + } +} diff --git a/crates/core/src/fof.rs b/crates/core/src/fof.rs index 39eed2a..1ddfe35 100644 --- a/crates/core/src/fof.rs +++ b/crates/core/src/fof.rs @@ -1031,9 +1031,40 @@ pub fn apply_fof_access_grant_locally( Ok(appended) } +/// Outcome of applying a revocation locally. +/// +/// v0.8 (D): `recorded` is the NOVELTY signal for the diff gate — it is +/// true only the first time this `(post_id, revoked_pub_x)` pair lands +/// here, so a duplicate delivery stops travelling. It distinguishes a +/// first delivery from a duplicate on a node that HOLDS the post but has +/// not yet seen any comment signed under the revoked pub_x (where +/// `deleted` is 0 and the recording is the only state change). +/// +/// Reach boundary, stated plainly because it is easy to assume otherwise: +/// this does NOT extend revocations through nodes that hold no copy of the +/// post. The diff path (`connection::apply_diff_ops`) must read the post +/// author out of the stored post to verify the author signature — the op +/// carries no author id — so a node without the post drops the op before +/// calling this. Making requirement (c) hold for revocations too would +/// mean carrying the post author (or its key) in the op itself, i.e. a +/// wire change; tracked as a follow-up if revocation reach matters. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RevocationApplied { + /// The revocation row was newly inserted (not a duplicate delivery). + pub recorded: bool, + /// Locally-stored comments cascade-deleted under the revoked pub_x. + pub deleted: usize, +} + +impl RevocationApplied { + /// Did this application change local state in any observable way? + pub fn changed(&self) -> bool { + self.recorded || self.deleted > 0 + } +} + /// Apply a verified revocation to local storage + cascade delete /// already-stored comments. Idempotent on `(post_id, revoked_pub_x)`. -/// Returns the count of comments deleted. /// /// Must only be called after `verify_fof_revocation` returns true. /// The caller (CDN receive path) is responsible for that gate. @@ -1044,20 +1075,26 @@ pub fn apply_fof_revocation_locally( revoked_at_ms: u64, reason_code: u8, author_sig: &[u8], -) -> Result { - storage.add_fof_revocation(post_id, revoked_pub_x, revoked_at_ms, reason_code, author_sig)?; +) -> Result { + let recorded = storage.add_fof_revocation( + post_id, revoked_pub_x, revoked_at_ms, reason_code, author_sig, + )?; // Resolve pub_x -> pub_x_index via the post's pub_post_set, then // cascade-delete locally-stored comments matching that index. - let Some(post) = storage.get_post(post_id)? else { return Ok(0); }; - let Some(gating) = post.fof_gating.as_ref() else { return Ok(0); }; + let Some(post) = storage.get_post(post_id)? else { + return Ok(RevocationApplied { recorded, deleted: 0 }); + }; + let Some(gating) = post.fof_gating.as_ref() else { + return Ok(RevocationApplied { recorded, deleted: 0 }); + }; let mut deleted = 0; for (idx, pub_x) in gating.pub_post_set.iter().enumerate() { if pub_x == revoked_pub_x { deleted += storage.delete_fof_comments_by_pub_x_index(post_id, idx as u32)?; } } - Ok(deleted) + Ok(RevocationApplied { recorded, deleted }) } #[cfg(test)] @@ -1387,21 +1424,27 @@ mod tests { let sig = sign_fof_revocation(&alice_seed, &post_id, &bob_pub_x, revoked_at, 0); assert!(verify_fof_revocation(&alice_id, &post_id, &bob_pub_x, revoked_at, 0, &sig)); - let deleted = apply_fof_revocation_locally( + let applied = apply_fof_revocation_locally( &s, &post_id, &bob_pub_x, revoked_at, 0, &sig, ).unwrap(); - assert_eq!(deleted, 1, "Bob's comment retroactively deleted"); + assert_eq!(applied.deleted, 1, "Bob's comment retroactively deleted"); + assert!(applied.recorded, "revocation newly recorded"); + assert!(applied.changed(), "first application is novel"); assert!(s.get_comments(&post_id).unwrap().is_empty(), "no live comments remain on the post"); // Verify revocation is recorded for future CDN-verify lookups. assert!(s.is_fof_pub_x_revoked(&post_id, &bob_pub_x).unwrap()); - // Idempotent: re-apply is a no-op (returns 0 because comment already gone). - let re_deleted = apply_fof_revocation_locally( + // Idempotent: re-apply is a no-op — nothing recorded, nothing + // deleted, so `changed()` is false and the v0.8 (D) novelty gate + // refuses to re-propagate it. + let re_applied = apply_fof_revocation_locally( &s, &post_id, &bob_pub_x, revoked_at, 0, &sig, ).unwrap(); - assert_eq!(re_deleted, 0); + assert_eq!(re_applied.deleted, 0); + assert!(!re_applied.recorded); + assert!(!re_applied.changed(), "duplicate revocation is not novel"); } /// Access-grant roundtrip: Alice publishes a Mode 2 FoF post, then diff --git a/crates/core/src/node.rs b/crates/core/src/node.rs index d8a529e..30695ee 100644 --- a/crates/core/src/node.rs +++ b/crates/core/src/node.rs @@ -129,11 +129,18 @@ fn greetings_open_setting(storage: &crate::storage::Storage, posting_id: &NodeId /// (`MAX_GREETINGS_PER_BIO`). The value is baked into the bio post's /// `OpenSlotDecl` at publish time, so every holder enforces it — the /// author cannot change it after the fact without republishing the bio. -/// No UI yet; the mechanism and plumbing are here for it. +/// Reachable from the app: Settings → Profiles → "Max live greetings" +/// (Tauri `set_greetings_max` / `get_greetings_max`), and `greetings-max` +/// in the CLI. pub fn greetings_max_setting_key(posting_id: &NodeId) -> String { format!("greetings_max.{}", hex::encode(posting_id)) } +/// THE single source of truth for the declared greeting cap. Every writer +/// — `Node::set_greetings_max` (Tauri + CLI), and the Profiles lightbox, +/// which writes the setting directly so one `set_profile` republish +/// carries it — funnels through this read, so the clamp lives here and +/// nowhere else. fn greetings_max_setting(storage: &crate::storage::Storage, posting_id: &NodeId) -> Option { storage .get_setting(&greetings_max_setting_key(posting_id)) @@ -143,10 +150,18 @@ fn greetings_max_setting(storage: &crate::storage::Storage, posting_id: &NodeId) // 0 is not "refuse" — refusal is `greetings_open = 0`, which // publishes a bio with no open slot at all. .filter(|n| *n > 0) + // Authors may LOWER the holder ceiling, never raise it (the storage + // being spent is the holder's). `comment_ttl::open_slot_limit` + // re-clamps holder-side regardless — this keeps us from publishing a + // signed number no holder would honour. + .map(|n| n.min(crate::connection::MAX_GREETINGS_PER_BIO as u32)) } /// Build the bio's Greeting open-slot spec from the persona's settings. -fn greeting_open_slot_spec( +/// `pub(crate)` so the holder-enforcement tests can walk the real path +/// (setting → spec → signed `OpenSlotDecl` → accept gate) rather than +/// hand-constructing the limit. +pub(crate) fn greeting_open_slot_spec( storage: &crate::storage::Storage, posting_id: &NodeId, ) -> crate::fof::OpenSlotSpec { @@ -6360,6 +6375,14 @@ impl Node { /// the bio is republished. Writing the setting alone (e.g. through /// the generic `set_setting` command) would have no observable /// effect until some unrelated republish happened to pick it up. + /// + /// This method is the CLI/API entry point (`greetings-max`, and the + /// Tauri command of the same name) and republishes on its own. The app + /// deliberately does NOT call it: the Profiles lightbox writes the + /// `greetings_max.` setting directly and lets its following + /// `set_profile` carry the change, so saving a profile is ONE + /// republish instead of two. Both routes converge on + /// `greetings_max_setting`, which owns the clamp. pub async fn set_greetings_max( &self, posting_id: &NodeId, diff --git a/crates/core/src/storage.rs b/crates/core/src/storage.rs index 8916c90..d302c6a 100644 --- a/crates/core/src/storage.rs +++ b/crates/core/src/storage.rs @@ -122,6 +122,24 @@ const MIN_MIGRATABLE_VERSION: u32 = 1; /// latch; this is what bounds it in time. const ANCHOR_ENRICH_MAX_AGE_MS: i64 = 24 * 60 * 60 * 1000; // 24h +/// v0.8 (D): per-post ceiling on ABSENT-TARGET comment tombstones — the +/// placeholder rows `record_absent_comment_tombstone` writes for a delete +/// that outran its own comment. +/// +/// That write is the one row an unknown peer can conjure from nothing on +/// the diff path (a `DeleteComment` op is self-certifying: its signature +/// proves only that its own author signed it, so fresh keypairs and +/// arbitrary timestamps are free). Without a cap, one attacker turns into +/// unbounded rows on every node in a post's holder cluster, each insert +/// reporting "novel" and being relayed onward — the exact feedback loop +/// the novelty gate exists to kill, reached through the gate's own signal. +/// +/// Sized to match `connection::MAX_GREETINGS_PER_BIO`: on the open-slot +/// posts where anyone may legitimately comment (registry, greeting-enabled +/// bios) the live comment population is capped there too, so an honest +/// burst of deletes cannot exhaust this budget. +pub const MAX_ORPHAN_COMMENT_TOMBSTONES_PER_POST: u64 = 64; + // ---- v0.8 §layers size budget for the uniques pools ---- // // design.html §layers publishes N2 <= 400 and N3 <= 8,000 as the design @@ -3879,8 +3897,17 @@ impl Storage { // origin_local = 0: comments that reached us from the network. // Ours are filtered at the store, not here, so nobody has to // remember the rule at each of the four local authoring sites. - let mut stmt = self.conn - .prepare("SELECT DISTINCT author FROM comments WHERE origin_local = 0")?; + // + // v0.8 (D): `deleted_at IS NULL` keeps tombstones out. We hold no + // content for a deleted comment, so announcing its author claims + // help we cannot give — and for the absent-target placeholders + // (`record_absent_comment_tombstone`) the author ID is chosen by + // whoever signed the delete, which would let a forger publish + // arbitrary IDs through our announce. + let mut stmt = self.conn.prepare( + "SELECT DISTINCT author FROM comments + WHERE origin_local = 0 AND deleted_at IS NULL", + )?; let mut rows = stmt.query([])?; while let Some(row) = rows.next()? { if let Ok(nid) = blob_to_nodeid(row.get(0)?) { @@ -5861,8 +5888,8 @@ impl Storage { revoked_at_ms: u64, reason_code: u8, author_sig: &[u8], - ) -> anyhow::Result<()> { - self.conn.execute( + ) -> anyhow::Result { + let inserted = self.conn.execute( "INSERT OR IGNORE INTO fof_revocations (post_id, revoked_pub_x, revoked_at_ms, reason_code, author_sig) VALUES (?1, ?2, ?3, ?4, ?5)", @@ -5874,7 +5901,17 @@ impl Storage { author_sig, ], )?; - Ok(()) + // v0.8 (D): `true` = newly recorded (the OR IGNORE path reports 0). + // Recording the revocation is a state change in its own right, even + // on a holder that has not yet seen any comment under the revoked + // pub_x — that is the novelty signal the diff gate consumes. + // + // Note the reach limit this does NOT lift: the diff path + // (`connection::apply_diff_ops`) reads the post author out of the + // stored post to verify the author signature, so a node that holds + // no copy of the post drops the op before ever reaching here. See + // `fof::RevocationApplied`. + Ok(inserted > 0) } /// FoF Layer 2: delete locally-stored comments on a post whose @@ -6042,7 +6079,29 @@ impl Storage { /// Store a reaction (upsert by reactor+post_id+emoji). /// Tombstone-aware: incoming reaction wins only if its timestamp is newer. - pub fn store_reaction(&self, reaction: &Reaction) -> anyhow::Result<()> { + /// + /// v0.8 (D): returns `true` iff this call actually CHANGED local state — + /// the novelty signal the diff re-propagation gate is built from (see + /// `connection::apply_diff_ops`). The `ON CONFLICT` clause below writes + /// only when `excluded.timestamp_ms > timestamp_ms`, so the pre-read + /// below decides it exactly: no row (insert) or a strictly newer + /// timestamp (update) — anything else is a no-op we must not re-spread. + /// `execute()`'s row count cannot answer this: SQLite reports 1 for a + /// conflicting upsert even when every CASE arm keeps the old value. + pub fn store_reaction(&self, reaction: &Reaction) -> anyhow::Result { + let existing_ts: Option = self.conn.query_row( + "SELECT timestamp_ms FROM reactions WHERE reactor = ?1 AND post_id = ?2 AND emoji = ?3", + params![ + reaction.reactor.as_slice(), + reaction.post_id.as_slice(), + reaction.emoji, + ], + |row| row.get(0), + ).ok(); + let changed = match existing_ts { + None => true, + Some(ts) => (reaction.timestamp_ms as i64) > ts, + }; self.conn.execute( "INSERT INTO reactions (reactor, post_id, emoji, timestamp_ms, encrypted_payload, deleted_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6) @@ -6059,16 +6118,21 @@ impl Storage { reaction.deleted_at.map(|v| v as i64), ], )?; - Ok(()) + Ok(changed) } /// Tombstone a reaction (soft-delete by setting deleted_at). - pub fn remove_reaction(&self, reactor: &NodeId, post_id: &PostId, emoji: &str) -> anyhow::Result<()> { - self.conn.execute( - "UPDATE reactions SET deleted_at = ?4 WHERE reactor = ?1 AND post_id = ?2 AND emoji = ?3", + /// + /// v0.8 (D): returns `true` iff a LIVE reaction was tombstoned by this + /// call. The `deleted_at IS NULL` guard makes the second delivery of the + /// same removal report "no change", which terminates re-propagation. + pub fn remove_reaction(&self, reactor: &NodeId, post_id: &PostId, emoji: &str) -> anyhow::Result { + let updated = self.conn.execute( + "UPDATE reactions SET deleted_at = ?4 + WHERE reactor = ?1 AND post_id = ?2 AND emoji = ?3 AND deleted_at IS NULL", params![reactor.as_slice(), post_id.as_slice(), emoji, now_ms()], )?; - Ok(()) + Ok(updated > 0) } /// Get live (non-tombstoned) reactions for a post. Used for UI display. @@ -6175,7 +6239,18 @@ impl Storage { /// Store a comment. Tombstone-aware upsert: if the incoming comment carries a /// deleted_at tombstone, store it so the tombstone propagates. - pub fn store_comment(&self, comment: &InlineComment) -> anyhow::Result<()> { + /// + /// v0.8 (D): returns `true` iff the row's observable content actually + /// CHANGED (insert, or an upsert that moved at least one column). The + /// `ON CONFLICT` clause below is a lattice of CASE/COALESCE arms, so no + /// closed-form predicate over the incoming comment can decide this — + /// hence the before/after fingerprint. This is the novelty signal the + /// diff re-propagation gate consumes; a re-delivered comment we already + /// hold must report `false` so we stop spreading it. + pub fn store_comment(&self, comment: &InlineComment) -> anyhow::Result { + let before = self.comment_row_fingerprint( + &comment.author, &comment.post_id, comment.timestamp_ms, + ); self.conn.execute( "INSERT INTO comments (author, post_id, content, timestamp_ms, signature, deleted_at, @@ -6212,7 +6287,39 @@ impl Storage { if comment.expires_at_ms > 0 { Some(comment.expires_at_ms as i64) } else { None }, ], )?; - Ok(()) + let after = self.comment_row_fingerprint( + &comment.author, &comment.post_id, comment.timestamp_ms, + ); + Ok(before != after) + } + + /// Every column of a comment row that a peer can observe, as one + /// comparable tuple. `None` = the row does not exist. Used only to + /// decide "did that write change anything?" — see `store_comment`. + /// `origin_local` is deliberately excluded: it is a purely local flag + /// and `store_own_comment` sets it after the store. + #[allow(clippy::type_complexity)] + fn comment_row_fingerprint( + &self, + author: &NodeId, + post_id: &PostId, + timestamp_ms: u64, + ) -> Option<( + String, Option, Vec, Option>, + Option, Option>, Option>, Option, + )> { + self.conn.query_row( + "SELECT content, deleted_at, signature, ref_post_id, + pub_x_index, group_sig, encrypted_payload, expires_at + FROM comments WHERE author = ?1 AND post_id = ?2 AND timestamp_ms = ?3", + params![author.as_slice(), post_id.as_slice(), timestamp_ms as i64], + |row| { + Ok(( + row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?, + row.get(4)?, row.get(5)?, row.get(6)?, row.get(7)?, + )) + }, + ).ok() } /// Store a comment WE authored. Identical to `store_comment` except it @@ -6243,15 +6350,123 @@ impl Storage { Ok(updated > 0) } - /// Tombstone a comment (soft-delete by setting deleted_at). - pub fn delete_comment(&self, author: &NodeId, post_id: &PostId, timestamp_ms: u64) -> anyhow::Result { + /// Tombstone a comment row we ACTUALLY HOLD. Returns `true` iff a live + /// row was tombstoned by this call (the `deleted_at IS NULL` guard makes + /// the second delivery of the same delete report "no change", which + /// terminates re-propagation). + /// + /// v0.8 (D): this half carries no bound of its own and needs none — it + /// can only ever move a row that is already on disk, so it is safe to + /// run on any node that passed `connection::delete_comment_authorized`, + /// including one that does not hold the parent post. Comments are + /// routinely stored without their parent post (`accept_incoming_comment` + /// takes `parent_post: Option<&Post>`), and refusing to tombstone them + /// would leave a deleted comment live locally forever AND swallow the + /// retraction while still relaying the content. + pub fn tombstone_comment_if_present( + &self, + author: &NodeId, + post_id: &PostId, + timestamp_ms: u64, + ) -> anyhow::Result { let updated = self.conn.execute( - "UPDATE comments SET deleted_at = ?4 WHERE author = ?1 AND post_id = ?2 AND timestamp_ms = ?3", + "UPDATE comments SET deleted_at = ?4 + WHERE author = ?1 AND post_id = ?2 AND timestamp_ms = ?3 AND deleted_at IS NULL", params![author.as_slice(), post_id.as_slice(), timestamp_ms as i64, now_ms()], )?; Ok(updated > 0) } + /// Record a tombstone for a comment we have NEVER SEEN (a delete that + /// outran its own comment), as a bare placeholder row: empty content, + /// empty signature, `deleted_at` set. + /// + /// Load-bearing for two separate reasons: + /// * Propagation: a delete that outruns its comment must still count + /// as a state change here, or the novelty gate stops it dead and it + /// never reaches the next hop. + /// * Correctness: without the placeholder, the comment arriving after + /// its own delete would be stored live and resurrect forever. With + /// it, `store_comment`'s upsert fills in content/signature while + /// `deleted_at = CASE WHEN excluded.deleted_at IS NOT NULL THEN + /// excluded.deleted_at ELSE deleted_at END` preserves the tombstone. + /// The `(author, post_id, timestamp_ms)` primary key is exactly what + /// the `DeleteComment` op carries, so the placeholder lands on the + /// precise row the late comment will occupy. + /// + /// THIS IS THE ONLY WRITE ON THE DIFF PATH AN UNKNOWN PEER CAN CREATE + /// FROM NOTHING, so it is bounded three ways: + /// * Caller-side: `apply_diff_ops` binds the op to the diff envelope + /// and requires that we hold the parent post — a post we do not hold + /// is one we never re-serve, so its orphan tombstones are not ours + /// to remember. (Tombstoning a comment we DO hold has no such bound; + /// that is `tombstone_comment_if_present`.) + /// * CARDINALITY, here: `delete_comment_authorized` proves only that + /// whoever signed the op signed it, so fresh keypairs × arbitrary + /// timestamps are free to an attacker. At most + /// [`MAX_ORPHAN_COMMENT_TOMBSTONES_PER_POST`] placeholders may exist + /// per post; past that this returns `false`, so the forged op is + /// neither stored nor relayed. + /// * LIFETIME, here: the row gets `expires_at = now + + /// MAX_COMMENT_TTL_MS` so the ordinary `expire_comments` sweep + /// reclaims it. The ceiling (rather than the parent post's shorter + /// window) is deliberate: `accept_incoming_comment` refuses any + /// comment whose `expires_at_ms` exceeds `now + MAX_COMMENT_TTL_MS`, + /// and the never-expires class (`expires_at_ms == 0`) has to be + /// covered too, so no real comment can outlive its own placeholder. + /// + /// The placeholder is also kept out of everything we publish: + /// `get_comments_with_tombstones` (the served-header source) and the + /// uniques announce both filter it out, so it can neither bloat the + /// header nor advertise attacker-chosen author IDs as reachable here. + pub fn record_absent_comment_tombstone( + &self, + author: &NodeId, + post_id: &PostId, + timestamp_ms: u64, + ) -> anyhow::Result { + let orphans: i64 = self.conn.query_row( + "SELECT COUNT(*) FROM comments + WHERE post_id = ?1 AND length(signature) = 0 AND deleted_at IS NOT NULL", + params![post_id.as_slice()], + |row| row.get(0), + )?; + if orphans as u64 >= MAX_ORPHAN_COMMENT_TOMBSTONES_PER_POST { + return Ok(false); + } + let now = now_ms(); + let inserted = self.conn.execute( + "INSERT OR IGNORE INTO comments + (author, post_id, content, timestamp_ms, signature, deleted_at, expires_at) + VALUES (?1, ?2, '', ?3, X'', ?4, ?5)", + params![ + author.as_slice(), + post_id.as_slice(), + timestamp_ms as i64, + now, + now.saturating_add(crate::comment_ttl::MAX_COMMENT_TTL_MS as i64), + ], + )?; + Ok(inserted > 0) + } + + /// Tombstone a comment, recording an absent-target placeholder when we + /// have never seen the comment itself. Returns `true` iff this call + /// RECORDED a tombstone that was not already there — the novelty signal + /// the diff re-propagation gate consumes. + /// + /// Callers MUST have authorised the delete first + /// (`connection::delete_comment_authorized`, or local ownership), and — + /// because of the placeholder half — must hold the parent post. Callers + /// that do not hold it want `tombstone_comment_if_present` instead. + pub fn delete_comment(&self, author: &NodeId, post_id: &PostId, timestamp_ms: u64) -> anyhow::Result { + if self.tombstone_comment_if_present(author, post_id, timestamp_ms)? { + return Ok(true); + } + // Either already tombstoned (no change) or never seen (record it). + self.record_absent_comment_tombstone(author, post_id, timestamp_ms) + } + /// Get live (non-tombstoned, unexpired) comments for a post. Used for /// UI display. The expiry filter is belt-and-suspenders between /// `expire_comments` sweeps. @@ -6311,11 +6526,20 @@ impl Storage { /// encrypted_payload) + expires_at — without them, FoF/greeting /// comments served via full-header sync would lose their group_sig /// and be dropped by the receive gate. + /// + /// v0.8 (D): `length(signature) > 0` excludes the absent-target + /// placeholder rows written by `record_absent_comment_tombstone`. They + /// are a purely local record that a delete passed through, carry no + /// content and no signature, and every pulling peer would drop them at + /// the accept gate anyway — serving them would only let a forger inflate + /// the header we hand out for a post. Once the real comment arrives its + /// upsert fills in the signature, and the (still tombstoned) row starts + /// being served normally. pub fn get_comments_with_tombstones(&self, post_id: &PostId) -> anyhow::Result> { let mut stmt = self.conn.prepare( "SELECT author, post_id, content, timestamp_ms, signature, deleted_at, ref_post_id, pub_x_index, group_sig, encrypted_payload, expires_at - FROM comments WHERE post_id = ?1 + FROM comments WHERE post_id = ?1 AND length(signature) > 0 AND (expires_at IS NULL OR expires_at = 0 OR expires_at > ?2) ORDER BY timestamp_ms ASC" )?; @@ -6727,13 +6951,16 @@ impl Storage { // --- Engagement: thread metadata --- /// Store a thread split link (child → parent). - pub fn store_thread_meta(&self, meta: &ThreadMeta) -> anyhow::Result<()> { - self.conn.execute( + /// v0.8 (D): returns `true` iff the link was newly inserted (the + /// `DO NOTHING` conflict path reports 0 rows) — the novelty signal for + /// the `ThreadSplit` diff op. + pub fn store_thread_meta(&self, meta: &ThreadMeta) -> anyhow::Result { + let inserted = self.conn.execute( "INSERT INTO thread_meta (post_id, parent_post_id) VALUES (?1, ?2) ON CONFLICT DO NOTHING", params![meta.post_id.as_slice(), meta.parent_post_id.as_slice()], )?; - Ok(()) + Ok(inserted > 0) } /// Get all child posts for a parent (thread splits). diff --git a/crates/tauri-app/gen/android/app/src/main/java/com/itsgoin/app/MainActivity.kt b/crates/tauri-app/gen/android/app/src/main/java/com/itsgoin/app/MainActivity.kt index 72f3913..f74ba2e 100644 --- a/crates/tauri-app/gen/android/app/src/main/java/com/itsgoin/app/MainActivity.kt +++ b/crates/tauri-app/gen/android/app/src/main/java/com/itsgoin/app/MainActivity.kt @@ -21,6 +21,10 @@ class MainActivity : TauriActivity() { } } + // Genuine launch — clear any prior "user quit" flag so the service is + // allowed to run (and to resume via START_STICKY) again. + NodeService.setUserQuit(this, false) + // Start foreground service to keep connections alive in background val serviceIntent = Intent(this, NodeService::class.java) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { diff --git a/crates/tauri-app/gen/android/app/src/main/java/com/itsgoin/app/NodeService.kt b/crates/tauri-app/gen/android/app/src/main/java/com/itsgoin/app/NodeService.kt index 0112936..0a31bb9 100644 --- a/crates/tauri-app/gen/android/app/src/main/java/com/itsgoin/app/NodeService.kt +++ b/crates/tauri-app/gen/android/app/src/main/java/com/itsgoin/app/NodeService.kt @@ -18,6 +18,28 @@ class NodeService : Service() { const val CHANNEL_ID = "itsgoin_node" const val NOTIFICATION_ID = 1 + // Survives process death, unlike any in-memory flag. START_STICKY + // means Android resurrects this service when its process dies — + // desirable when the SYSTEM kills us in the background, wrong when + // the USER explicitly quit. stopService() is asynchronous, so a + // fast app.exit(0) can kill the process before the stop is + // processed, and the resurrection races ahead of it. This flag is + // how a restarted service learns the quit already happened. + private const val PREFS = "itsgoin_service" + private const val KEY_USER_QUIT = "user_quit" + + @JvmStatic + fun setUserQuit(context: Context, quit: Boolean) { + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + .edit() + .putBoolean(KEY_USER_QUIT, quit) + .commit() // synchronous — the process may die moments from now + } + + private fun userQuit(context: Context): Boolean = + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + .getBoolean(KEY_USER_QUIT, false) + // Called via JNI from Rust when the user taps the in-app close // button. Foreground services survive Activity exit by design // (keeps connections alive when backgrounded). When the user @@ -25,6 +47,9 @@ class NodeService : Service() { // service in addition to ending the Activity. @JvmStatic fun stopFromNative(context: Context) { + // Record the intent to quit BEFORE asking the service to stop, + // so a sticky restart that beats us to it still sees the flag. + setUserQuit(context, true) val intent = Intent(context, NodeService::class.java) context.stopService(intent) } @@ -54,6 +79,16 @@ class NodeService : Service() { } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + // A null intent means Android resurrected us under START_STICKY + // rather than MainActivity starting us. If the user had quit, honour + // that: stop immediately and do not come back. MainActivity clears + // the flag whenever the app is genuinely launched, so a system-kill + // restart (the case START_STICKY exists for) still resumes. + if (intent == null && userQuit(this)) { + stopForeground(STOP_FOREGROUND_REMOVE) + stopSelf() + return START_NOT_STICKY + } return START_STICKY } diff --git a/crates/tauri-app/src/lib.rs b/crates/tauri-app/src/lib.rs index a6440b5..7238091 100644 --- a/crates/tauri-app/src/lib.rs +++ b/crates/tauri-app/src/lib.rs @@ -1161,7 +1161,16 @@ async fn exit_app(app: tauri::AppHandle) { // explicitly hits the in-app close button, also stop the service // so we actually free the device's network/wakelock. #[cfg(target_os = "android")] - itsgoin_core::android_wifi::stop_node_service(); + { + itsgoin_core::android_wifi::stop_node_service(); + // stopService() is asynchronous: it posts to ActivityManager and the + // service's onDestroy runs afterwards on the main thread. Exiting + // immediately kills the process mid-flight, which Android treats as + // "foreground service died" and restarts under START_STICKY. Give the + // clean path a moment to win; NodeService's persisted user-quit flag + // is the backstop for when it doesn't. + tokio::time::sleep(std::time::Duration::from_millis(400)).await; + } app.exit(0); } @@ -2006,6 +2015,34 @@ async fn get_greetings_open( node.get_greetings_open(&posting_id).await.map_err(|e| e.to_string()) } +/// Ruling #6: author-declared cap on live stranger greetings for this +/// persona's bio. `None`/0 = the holder default; refusal is the separate +/// structural case (`set_greetings_open(false)`). +/// +/// Republishes the bio, because the cap lives inside the bio post's SIGNED +/// `OpenSlotDecl` — writing the setting alone would never reach a holder. +#[tauri::command] +async fn set_greetings_max( + state: State<'_, AppNode>, + posting_id_hex: String, + max_comments: Option, +) -> Result<(), String> { + let node = get_node(&state).await; + let posting_id = parse_node_id(&posting_id_hex)?; + node.set_greetings_max(&posting_id, max_comments).await.map_err(|e| e.to_string()) +} + +/// Current author-declared greeting cap (`None` = holder default). +#[tauri::command] +async fn get_greetings_max( + state: State<'_, AppNode>, + posting_id_hex: String, +) -> Result, String> { + let node = get_node(&state).await; + let posting_id = parse_node_id(&posting_id_hex)?; + node.get_greetings_max(&posting_id).await.map_err(|e| e.to_string()) +} + /// Open a URL in the user's default system browser. /// Desktop: spawns the platform opener (xdg-open / open / cmd start). /// Only https:// URLs are accepted to avoid being a generic command exec. @@ -3737,6 +3774,8 @@ pub fn run() { dismiss_greeting, set_greetings_open, get_greetings_open, + set_greetings_max, + get_greetings_max, ]) .build(tauri::generate_context!()) .expect("error while building tauri application") diff --git a/frontend/app.js b/frontend/app.js index 88a74ca..a798ae6 100644 --- a/frontend/app.js +++ b/frontend/app.js @@ -3450,10 +3450,15 @@ $('#profile-lightbox-btn').addEventListener('click', () => {
Not listed
-