Compare commits

..

No commits in common. "8d29cb918e113b9d6929314f569ded5865465b7d" and "3232796d4d30af8583ed5ca0d7699ab6ef5445d4" have entirely different histories.

8 changed files with 297 additions and 1647 deletions

File diff suppressed because it is too large Load diff

View file

@ -1031,40 +1031,9 @@ pub fn apply_fof_access_grant_locally(
Ok(appended) 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 /// Apply a verified revocation to local storage + cascade delete
/// already-stored comments. Idempotent on `(post_id, revoked_pub_x)`. /// 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. /// Must only be called after `verify_fof_revocation` returns true.
/// The caller (CDN receive path) is responsible for that gate. /// The caller (CDN receive path) is responsible for that gate.
@ -1075,26 +1044,20 @@ pub fn apply_fof_revocation_locally(
revoked_at_ms: u64, revoked_at_ms: u64,
reason_code: u8, reason_code: u8,
author_sig: &[u8], author_sig: &[u8],
) -> Result<RevocationApplied> { ) -> Result<usize> {
let recorded = storage.add_fof_revocation( storage.add_fof_revocation(post_id, revoked_pub_x, revoked_at_ms, reason_code, author_sig)?;
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 // Resolve pub_x -> pub_x_index via the post's pub_post_set, then
// cascade-delete locally-stored comments matching that index. // cascade-delete locally-stored comments matching that index.
let Some(post) = storage.get_post(post_id)? else { let Some(post) = storage.get_post(post_id)? else { return Ok(0); };
return Ok(RevocationApplied { recorded, deleted: 0 }); let Some(gating) = post.fof_gating.as_ref() else { return Ok(0); };
};
let Some(gating) = post.fof_gating.as_ref() else {
return Ok(RevocationApplied { recorded, deleted: 0 });
};
let mut deleted = 0; let mut deleted = 0;
for (idx, pub_x) in gating.pub_post_set.iter().enumerate() { for (idx, pub_x) in gating.pub_post_set.iter().enumerate() {
if pub_x == revoked_pub_x { if pub_x == revoked_pub_x {
deleted += storage.delete_fof_comments_by_pub_x_index(post_id, idx as u32)?; deleted += storage.delete_fof_comments_by_pub_x_index(post_id, idx as u32)?;
} }
} }
Ok(RevocationApplied { recorded, deleted }) Ok(deleted)
} }
#[cfg(test)] #[cfg(test)]
@ -1424,27 +1387,21 @@ mod tests {
let sig = sign_fof_revocation(&alice_seed, &post_id, &bob_pub_x, revoked_at, 0); 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)); assert!(verify_fof_revocation(&alice_id, &post_id, &bob_pub_x, revoked_at, 0, &sig));
let applied = apply_fof_revocation_locally( let deleted = apply_fof_revocation_locally(
&s, &post_id, &bob_pub_x, revoked_at, 0, &sig, &s, &post_id, &bob_pub_x, revoked_at, 0, &sig,
).unwrap(); ).unwrap();
assert_eq!(applied.deleted, 1, "Bob's comment retroactively deleted"); assert_eq!(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(), assert!(s.get_comments(&post_id).unwrap().is_empty(),
"no live comments remain on the post"); "no live comments remain on the post");
// Verify revocation is recorded for future CDN-verify lookups. // Verify revocation is recorded for future CDN-verify lookups.
assert!(s.is_fof_pub_x_revoked(&post_id, &bob_pub_x).unwrap()); assert!(s.is_fof_pub_x_revoked(&post_id, &bob_pub_x).unwrap());
// Idempotent: re-apply is a no-op — nothing recorded, nothing // Idempotent: re-apply is a no-op (returns 0 because comment already gone).
// deleted, so `changed()` is false and the v0.8 (D) novelty gate let re_deleted = apply_fof_revocation_locally(
// refuses to re-propagate it.
let re_applied = apply_fof_revocation_locally(
&s, &post_id, &bob_pub_x, revoked_at, 0, &sig, &s, &post_id, &bob_pub_x, revoked_at, 0, &sig,
).unwrap(); ).unwrap();
assert_eq!(re_applied.deleted, 0); assert_eq!(re_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 /// Access-grant roundtrip: Alice publishes a Mode 2 FoF post, then

View file

@ -129,18 +129,11 @@ fn greetings_open_setting(storage: &crate::storage::Storage, posting_id: &NodeId
/// (`MAX_GREETINGS_PER_BIO`). The value is baked into the bio post's /// (`MAX_GREETINGS_PER_BIO`). The value is baked into the bio post's
/// `OpenSlotDecl` at publish time, so every holder enforces it — the /// `OpenSlotDecl` at publish time, so every holder enforces it — the
/// author cannot change it after the fact without republishing the bio. /// author cannot change it after the fact without republishing the bio.
/// Reachable from the app: Settings → Profiles → "Max live greetings" /// No UI yet; the mechanism and plumbing are here for it.
/// (Tauri `set_greetings_max` / `get_greetings_max`), and `greetings-max`
/// in the CLI.
pub fn greetings_max_setting_key(posting_id: &NodeId) -> String { pub fn greetings_max_setting_key(posting_id: &NodeId) -> String {
format!("greetings_max.{}", hex::encode(posting_id)) 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<u32> { fn greetings_max_setting(storage: &crate::storage::Storage, posting_id: &NodeId) -> Option<u32> {
storage storage
.get_setting(&greetings_max_setting_key(posting_id)) .get_setting(&greetings_max_setting_key(posting_id))
@ -150,18 +143,10 @@ fn greetings_max_setting(storage: &crate::storage::Storage, posting_id: &NodeId)
// 0 is not "refuse" — refusal is `greetings_open = 0`, which // 0 is not "refuse" — refusal is `greetings_open = 0`, which
// publishes a bio with no open slot at all. // publishes a bio with no open slot at all.
.filter(|n| *n > 0) .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. /// Build the bio's Greeting open-slot spec from the persona's settings.
/// `pub(crate)` so the holder-enforcement tests can walk the real path fn greeting_open_slot_spec(
/// (setting → spec → signed `OpenSlotDecl` → accept gate) rather than
/// hand-constructing the limit.
pub(crate) fn greeting_open_slot_spec(
storage: &crate::storage::Storage, storage: &crate::storage::Storage,
posting_id: &NodeId, posting_id: &NodeId,
) -> crate::fof::OpenSlotSpec { ) -> crate::fof::OpenSlotSpec {
@ -6375,14 +6360,6 @@ impl Node {
/// the bio is republished. Writing the setting alone (e.g. through /// the bio is republished. Writing the setting alone (e.g. through
/// the generic `set_setting` command) would have no observable /// the generic `set_setting` command) would have no observable
/// effect until some unrelated republish happened to pick it up. /// 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.<persona>` 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( pub async fn set_greetings_max(
&self, &self,
posting_id: &NodeId, posting_id: &NodeId,

View file

@ -122,24 +122,6 @@ const MIN_MIGRATABLE_VERSION: u32 = 1;
/// latch; this is what bounds it in time. /// latch; this is what bounds it in time.
const ANCHOR_ENRICH_MAX_AGE_MS: i64 = 24 * 60 * 60 * 1000; // 24h 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 ---- // ---- v0.8 §layers size budget for the uniques pools ----
// //
// design.html §layers publishes N2 <= 400 and N3 <= 8,000 as the design // design.html §layers publishes N2 <= 400 and N3 <= 8,000 as the design
@ -3897,17 +3879,8 @@ impl Storage {
// origin_local = 0: comments that reached us from the network. // origin_local = 0: comments that reached us from the network.
// Ours are filtered at the store, not here, so nobody has to // Ours are filtered at the store, not here, so nobody has to
// remember the rule at each of the four local authoring sites. // remember the rule at each of the four local authoring sites.
// let mut stmt = self.conn
// v0.8 (D): `deleted_at IS NULL` keeps tombstones out. We hold no .prepare("SELECT DISTINCT author FROM comments WHERE origin_local = 0")?;
// 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([])?; let mut rows = stmt.query([])?;
while let Some(row) = rows.next()? { while let Some(row) = rows.next()? {
if let Ok(nid) = blob_to_nodeid(row.get(0)?) { if let Ok(nid) = blob_to_nodeid(row.get(0)?) {
@ -5888,8 +5861,8 @@ impl Storage {
revoked_at_ms: u64, revoked_at_ms: u64,
reason_code: u8, reason_code: u8,
author_sig: &[u8], author_sig: &[u8],
) -> anyhow::Result<bool> { ) -> anyhow::Result<()> {
let inserted = self.conn.execute( self.conn.execute(
"INSERT OR IGNORE INTO fof_revocations "INSERT OR IGNORE INTO fof_revocations
(post_id, revoked_pub_x, revoked_at_ms, reason_code, author_sig) (post_id, revoked_pub_x, revoked_at_ms, reason_code, author_sig)
VALUES (?1, ?2, ?3, ?4, ?5)", VALUES (?1, ?2, ?3, ?4, ?5)",
@ -5901,17 +5874,7 @@ impl Storage {
author_sig, author_sig,
], ],
)?; )?;
// v0.8 (D): `true` = newly recorded (the OR IGNORE path reports 0). Ok(())
// 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 /// FoF Layer 2: delete locally-stored comments on a post whose
@ -6079,29 +6042,7 @@ impl Storage {
/// Store a reaction (upsert by reactor+post_id+emoji). /// Store a reaction (upsert by reactor+post_id+emoji).
/// Tombstone-aware: incoming reaction wins only if its timestamp is newer. /// 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<bool> {
let existing_ts: Option<i64> = 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( self.conn.execute(
"INSERT INTO reactions (reactor, post_id, emoji, timestamp_ms, encrypted_payload, deleted_at) "INSERT INTO reactions (reactor, post_id, emoji, timestamp_ms, encrypted_payload, deleted_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6) VALUES (?1, ?2, ?3, ?4, ?5, ?6)
@ -6118,21 +6059,16 @@ impl Storage {
reaction.deleted_at.map(|v| v as i64), reaction.deleted_at.map(|v| v as i64),
], ],
)?; )?;
Ok(changed) Ok(())
} }
/// Tombstone a reaction (soft-delete by setting deleted_at). /// Tombstone a reaction (soft-delete by setting deleted_at).
/// pub fn remove_reaction(&self, reactor: &NodeId, post_id: &PostId, emoji: &str) -> anyhow::Result<()> {
/// v0.8 (D): returns `true` iff a LIVE reaction was tombstoned by this self.conn.execute(
/// call. The `deleted_at IS NULL` guard makes the second delivery of the "UPDATE reactions SET deleted_at = ?4 WHERE reactor = ?1 AND post_id = ?2 AND emoji = ?3",
/// same removal report "no change", which terminates re-propagation.
pub fn remove_reaction(&self, reactor: &NodeId, post_id: &PostId, emoji: &str) -> anyhow::Result<bool> {
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()], params![reactor.as_slice(), post_id.as_slice(), emoji, now_ms()],
)?; )?;
Ok(updated > 0) Ok(())
} }
/// Get live (non-tombstoned) reactions for a post. Used for UI display. /// Get live (non-tombstoned) reactions for a post. Used for UI display.
@ -6239,18 +6175,7 @@ impl Storage {
/// Store a comment. Tombstone-aware upsert: if the incoming comment carries a /// Store a comment. Tombstone-aware upsert: if the incoming comment carries a
/// deleted_at tombstone, store it so the tombstone propagates. /// 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<bool> {
let before = self.comment_row_fingerprint(
&comment.author, &comment.post_id, comment.timestamp_ms,
);
self.conn.execute( self.conn.execute(
"INSERT INTO comments "INSERT INTO comments
(author, post_id, content, timestamp_ms, signature, deleted_at, (author, post_id, content, timestamp_ms, signature, deleted_at,
@ -6287,39 +6212,7 @@ impl Storage {
if comment.expires_at_ms > 0 { Some(comment.expires_at_ms as i64) } else { None }, if comment.expires_at_ms > 0 { Some(comment.expires_at_ms as i64) } else { None },
], ],
)?; )?;
let after = self.comment_row_fingerprint( Ok(())
&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<i64>, Vec<u8>, Option<Vec<u8>>,
Option<i64>, Option<Vec<u8>>, Option<Vec<u8>>, Option<i64>,
)> {
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 /// Store a comment WE authored. Identical to `store_comment` except it
@ -6350,123 +6243,15 @@ impl Storage {
Ok(updated > 0) Ok(updated > 0)
} }
/// Tombstone a comment row we ACTUALLY HOLD. Returns `true` iff a live /// Tombstone a comment (soft-delete by setting deleted_at).
/// row was tombstoned by this call (the `deleted_at IS NULL` guard makes pub fn delete_comment(&self, author: &NodeId, post_id: &PostId, timestamp_ms: u64) -> anyhow::Result<bool> {
/// 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<bool> {
let updated = self.conn.execute( let updated = self.conn.execute(
"UPDATE comments SET deleted_at = ?4 "UPDATE comments SET deleted_at = ?4 WHERE author = ?1 AND post_id = ?2 AND timestamp_ms = ?3",
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()], params![author.as_slice(), post_id.as_slice(), timestamp_ms as i64, now_ms()],
)?; )?;
Ok(updated > 0) 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<bool> {
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<bool> {
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 /// Get live (non-tombstoned, unexpired) comments for a post. Used for
/// UI display. The expiry filter is belt-and-suspenders between /// UI display. The expiry filter is belt-and-suspenders between
/// `expire_comments` sweeps. /// `expire_comments` sweeps.
@ -6526,20 +6311,11 @@ impl Storage {
/// encrypted_payload) + expires_at — without them, FoF/greeting /// encrypted_payload) + expires_at — without them, FoF/greeting
/// comments served via full-header sync would lose their group_sig /// comments served via full-header sync would lose their group_sig
/// and be dropped by the receive gate. /// 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<Vec<InlineComment>> { pub fn get_comments_with_tombstones(&self, post_id: &PostId) -> anyhow::Result<Vec<InlineComment>> {
let mut stmt = self.conn.prepare( let mut stmt = self.conn.prepare(
"SELECT author, post_id, content, timestamp_ms, signature, deleted_at, ref_post_id, "SELECT author, post_id, content, timestamp_ms, signature, deleted_at, ref_post_id,
pub_x_index, group_sig, encrypted_payload, expires_at pub_x_index, group_sig, encrypted_payload, expires_at
FROM comments WHERE post_id = ?1 AND length(signature) > 0 FROM comments WHERE post_id = ?1
AND (expires_at IS NULL OR expires_at = 0 OR expires_at > ?2) AND (expires_at IS NULL OR expires_at = 0 OR expires_at > ?2)
ORDER BY timestamp_ms ASC" ORDER BY timestamp_ms ASC"
)?; )?;
@ -6951,16 +6727,13 @@ impl Storage {
// --- Engagement: thread metadata --- // --- Engagement: thread metadata ---
/// Store a thread split link (child → parent). /// Store a thread split link (child → parent).
/// v0.8 (D): returns `true` iff the link was newly inserted (the pub fn store_thread_meta(&self, meta: &ThreadMeta) -> anyhow::Result<()> {
/// `DO NOTHING` conflict path reports 0 rows) — the novelty signal for self.conn.execute(
/// the `ThreadSplit` diff op.
pub fn store_thread_meta(&self, meta: &ThreadMeta) -> anyhow::Result<bool> {
let inserted = self.conn.execute(
"INSERT INTO thread_meta (post_id, parent_post_id) VALUES (?1, ?2) "INSERT INTO thread_meta (post_id, parent_post_id) VALUES (?1, ?2)
ON CONFLICT DO NOTHING", ON CONFLICT DO NOTHING",
params![meta.post_id.as_slice(), meta.parent_post_id.as_slice()], params![meta.post_id.as_slice(), meta.parent_post_id.as_slice()],
)?; )?;
Ok(inserted > 0) Ok(())
} }
/// Get all child posts for a parent (thread splits). /// Get all child posts for a parent (thread splits).

View file

@ -21,10 +21,6 @@ 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 // Start foreground service to keep connections alive in background
val serviceIntent = Intent(this, NodeService::class.java) val serviceIntent = Intent(this, NodeService::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

View file

@ -18,28 +18,6 @@ class NodeService : Service() {
const val CHANNEL_ID = "itsgoin_node" const val CHANNEL_ID = "itsgoin_node"
const val NOTIFICATION_ID = 1 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 // Called via JNI from Rust when the user taps the in-app close
// button. Foreground services survive Activity exit by design // button. Foreground services survive Activity exit by design
// (keeps connections alive when backgrounded). When the user // (keeps connections alive when backgrounded). When the user
@ -47,9 +25,6 @@ class NodeService : Service() {
// service in addition to ending the Activity. // service in addition to ending the Activity.
@JvmStatic @JvmStatic
fun stopFromNative(context: Context) { 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) val intent = Intent(context, NodeService::class.java)
context.stopService(intent) context.stopService(intent)
} }
@ -79,16 +54,6 @@ class NodeService : Service() {
} }
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { 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 return START_STICKY
} }

View file

@ -1161,16 +1161,7 @@ async fn exit_app(app: tauri::AppHandle) {
// explicitly hits the in-app close button, also stop the service // explicitly hits the in-app close button, also stop the service
// so we actually free the device's network/wakelock. // so we actually free the device's network/wakelock.
#[cfg(target_os = "android")] #[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); app.exit(0);
} }
@ -2015,34 +2006,6 @@ async fn get_greetings_open(
node.get_greetings_open(&posting_id).await.map_err(|e| e.to_string()) 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<u32>,
) -> 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<Option<u32>, 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. /// Open a URL in the user's default system browser.
/// Desktop: spawns the platform opener (xdg-open / open / cmd start). /// Desktop: spawns the platform opener (xdg-open / open / cmd start).
/// Only https:// URLs are accepted to avoid being a generic command exec. /// Only https:// URLs are accepted to avoid being a generic command exec.
@ -3774,8 +3737,6 @@ pub fn run() {
dismiss_greeting, dismiss_greeting,
set_greetings_open, set_greetings_open,
get_greetings_open, get_greetings_open,
set_greetings_max,
get_greetings_max,
]) ])
.build(tauri::generate_context!()) .build(tauri::generate_context!())
.expect("error while building tauri application") .expect("error while building tauri application")

View file

@ -3450,15 +3450,10 @@ $('#profile-lightbox-btn').addEventListener('click', () => {
</label> </label>
<input id="lb-registry-keywords" type="text" placeholder="Keywords, comma-separated (up to 8)" maxlength="280" style="width:100%;margin-bottom:0.25rem" /> <input id="lb-registry-keywords" type="text" placeholder="Keywords, comma-separated (up to 8)" maxlength="280" style="width:100%;margin-bottom:0.25rem" />
<div id="lb-registry-status" class="empty-hint" style="font-size:0.72rem;margin-bottom:0.5rem">Not listed</div> <div id="lb-registry-status" class="empty-hint" style="font-size:0.72rem;margin-bottom:0.5rem">Not listed</div>
<label class="checkbox-label" style="margin:0.5rem 0 0.25rem;display:block;font-size:0.8rem"> <label class="checkbox-label" style="margin:0.5rem 0;display:block;font-size:0.8rem">
<input type="checkbox" id="lb-greetings-open" checked /> <input type="checkbox" id="lb-greetings-open" checked />
Accept greetings (sealed hellos from people outside your circles) Accept greetings (sealed hellos from people outside your circles)
</label> </label>
<div style="display:flex;align-items:center;gap:0.5rem;margin-bottom:0.25rem">
<label for="lb-greetings-max" style="font-size:0.8rem;color:#888;flex:1">Max live greetings</label>
<input id="lb-greetings-max" type="number" min="1" max="64" placeholder="64" style="width:5rem" />
</div>
<div class="empty-hint" style="font-size:0.72rem;margin-bottom:0.5rem">Blank = the default of 64. The people holding your bio enforce this limit.</div>
<div style="display:flex;gap:0.5rem;justify-content:center;margin-top:0.75rem"> <div style="display:flex;gap:0.5rem;justify-content:center;margin-top:0.75rem">
<button class="btn btn-primary btn-sm" id="lb-profile-save">Save</button> <button class="btn btn-primary btn-sm" id="lb-profile-save">Save</button>
</div> </div>
@ -3479,12 +3474,7 @@ $('#profile-lightbox-btn').addEventListener('click', () => {
// and auto-renew silently continuing. // and auto-renew silently continuing.
let _lbWasListed = false; let _lbWasListed = false;
const _lbSaveBtn = overlay.querySelector('#lb-profile-save'); const _lbSaveBtn = overlay.querySelector('#lb-profile-save');
const _lbGreetMax = overlay.querySelector('#lb-greetings-max');
_lbSaveBtn.disabled = true; _lbSaveBtn.disabled = true;
// Disabled alongside Save: the prefill below assigns into this field, so
// leaving it editable lets a fast typist have their value silently
// overwritten when the async read lands.
if (_lbGreetMax) _lbGreetMax.disabled = true;
(async () => { (async () => {
try { try {
const personaId = await getDefaultPersonaId(); const personaId = await getDefaultPersonaId();
@ -3506,15 +3496,8 @@ $('#profile-lightbox-btn').addEventListener('click', () => {
const greetCheck = overlay.querySelector('#lb-greetings-open'); const greetCheck = overlay.querySelector('#lb-greetings-open');
if (greetCheck) greetCheck.checked = !!open; if (greetCheck) greetCheck.checked = !!open;
} catch (_) {} } catch (_) {}
try {
// Ruling #6: author-declared greeting cap. Blank input =
// unset = the holder default, so leave it empty on null.
const max = await invoke('get_greetings_max', { postingIdHex: personaId });
if (_lbGreetMax && max) _lbGreetMax.value = String(max);
} catch (_) {}
} finally { } finally {
_lbSaveBtn.disabled = false; _lbSaveBtn.disabled = false;
if (_lbGreetMax) _lbGreetMax.disabled = false;
} }
})(); })();
_lbSaveBtn.addEventListener('click', async () => { _lbSaveBtn.addEventListener('click', async () => {
@ -3533,25 +3516,6 @@ $('#profile-lightbox-btn').addEventListener('click', () => {
throw new Error('could not resolve your persona — profile not saved, please try again'); throw new Error('could not resolve your persona — profile not saved, please try again');
} }
await invoke('set_setting', { key: 'greetings_open.' + personaId, value: greetOpen ? '1' : '0' }); await invoke('set_setting', { key: 'greetings_open.' + personaId, value: greetOpen ? '1' : '0' });
// Ruling #6: the greeting cap ships inside the bio's SIGNED
// OpenSlotDecl, so it only reaches holders on a republish.
// Written the same way and for the same reason as the consent
// flag above — before set_profile, so ONE republish carries
// both. This is DELIBERATE, not an oversight: the
// `set_greetings_max` Tauri command exists and republishes on
// its own, which is right for CLI/API callers but would cost a
// second republish here. Do not "fix" it into a direct call.
// Blank/0 = unset = the holder default.
const greetMaxRaw = _lbGreetMax.value.trim();
const greetMaxNum = parseInt(greetMaxRaw, 10);
// The 64 is presentational only — `node::greetings_max_setting`
// owns the real clamp (to connection::MAX_GREETINGS_PER_BIO) for
// every writer, and holders re-clamp again via
// comment_ttl::open_slot_limit.
const greetMax = (greetMaxRaw && Number.isFinite(greetMaxNum) && greetMaxNum > 0)
? String(Math.min(greetMaxNum, 64))
: '';
await invoke('set_setting', { key: 'greetings_max.' + personaId, value: greetMax });
await invoke('set_profile', { name, bio }); await invoke('set_profile', { name, bio });
const visible = overlay.querySelector('#lb-public-visible').checked; const visible = overlay.querySelector('#lb-public-visible').checked;
await invoke('set_public_visible', { visible }); await invoke('set_public_visible', { visible });