Skip to main content

vector_core/community/
service.rs

1//! Orchestration that ties the Community send/delete primitives to persistence,
2//! with multi-account safety. This is the layer Tauri commands are thin wrappers
3//! over: it publishes a message AND retains its ephemeral key (so the sender can
4//! later delete it), and deletes by loading that retained key back.
5//!
6//! Every method is `SessionGuard`-gated: a `swap_session` can happen at any await
7//! point, and persisting an ephemeral secret (or reading one) must never cross into
8//! the wrong account's DB.
9
10use nostr_sdk::prelude::{Event, EventId, JsonUtil, Keys, Tag, ToBech32};
11
12use super::invite::CommunityInvite;
13use super::public_invite::{
14    self, build_public_invite_event, locator_hex, parse_public_invite_event, PublicInviteBundle,
15};
16use super::send::{delete_own_message, publish_signed_message};
17use super::transport::{Query, Transport};
18use super::{Channel, Community};
19use crate::state::SessionGuard;
20use crate::stored_event::event_kind;
21
22/// The active signer for authority actions (bunker support): the live client's signer — which covers a
23/// NIP-46 bunker — falling back to the local vault keys when there is no client OR the client has no
24/// signer attached (local accounts, headless/CLI paths, and tests). Every keyless control edition +
25/// moderation hide signs through this, so a bunker account can create AND administer a community. (The
26/// REKEY path is the one exception — its blob locator needs a raw ECDH the signer can't expose, so it
27/// still requires a local key; the ban/privatize flows fail-fast for bunker accounts.)
28async fn active_signer() -> Result<std::sync::Arc<dyn nostr_sdk::prelude::NostrSigner>, String> {
29    if let Some(client) = crate::state::nostr_client() {
30        if let Ok(s) = client.signer().await {
31            return Ok(s);
32        }
33    }
34    let keys = crate::state::MY_SECRET_KEY.to_keys().ok_or("no signer available (no client and no local key)")?;
35    Ok(std::sync::Arc::new(keys))
36}
37
38/// Max communities a device may hold locally. The synced Community List is a single NIP-44 event
39/// (65 KB plaintext); past the cap even the slimmed list can't encrypt, so a NEW join/create is
40/// rejected above it (the user leaves one to make room).
41pub const MAX_COMMUNITIES: usize = 50;
42
43/// Reject a NEW join/create when already at [`MAX_COMMUNITIES`] local memberships. Counts the synced
44/// Community List (the thing that overflows). Re-accepting a community already held is exempt — the
45/// caller checks membership before calling this.
46fn enforce_community_cap() -> Result<(), String> {
47    let held = super::list::load_local_list().entries.len();
48    if held >= MAX_COMMUNITIES {
49        return Err(format!(
50            "You've reached the limit of {} communities. Leave one to join another.",
51            MAX_COMMUNITIES
52        ));
53    }
54    Ok(())
55}
56
57/// Create a brand-new Community end-to-end: mint keys + the default channel, persist
58/// it locally, and publish its GroupRoot + ChannelMetadata to the Community's relays.
59/// Returns the created Community. (The caller then runs the subscription refresh so it
60/// starts receiving.)
61pub async fn create_community<T: Transport + ?Sized>(
62    transport: &T,
63    name: &str,
64    default_channel_name: &str,
65    relays: Vec<String>,
66) -> Result<Community, String> {
67    let session = SessionGuard::capture();
68    enforce_community_cap()?;
69    let mut community = Community::create(name, default_channel_name, relays);
70    // Owner attestation — MANDATORY: a community cannot exist without the root that anchors its
71    // authority graph. It binds the community id to the creator's identity, signed by the owner's identity
72    // signer. The proven owner is later DERIVED by verifying this, never an unverified claim. Sign via the
73    // local vault when present (local accounts + tests), else the
74    // active client's signer (bunker / NIP-46). No signer at all → creation fails, by design.
75    let owner_pk = crate::state::my_public_key().ok_or("cannot create a community without an identity")?;
76    let unsigned = super::owner::build_owner_attestation_unsigned(owner_pk, &community.id.to_hex());
77    // Use the local vault ONLY if it actually holds the active identity's key — else a stale/mismatched
78    // local secret would sign the attestation as the WRONG owner (or break verification). On mismatch,
79    // fall through to the client signer, which is the authority that produced `my_public_key()`.
80    let attestation = if let Some(keys) = crate::state::MY_SECRET_KEY.to_keys().filter(|k| k.public_key() == owner_pk) {
81        unsigned.sign_with_keys(&keys).map_err(|e| format!("sign owner attestation: {e}"))?
82    } else if let Some(client) = crate::state::nostr_client() {
83        let signer = client.signer().await.map_err(|e| format!("no signer for owner attestation: {e}"))?;
84        unsigned.sign(&signer).await.map_err(|e| format!("sign owner attestation: {e}"))?
85    } else {
86        return Err("cannot create a community without an identity signer (the owner attestation is mandatory)".to_string());
87    };
88    community.owner_attestation = Some(attestation.as_json());
89    // Minting + the DB write straddle the (above) signer round-trip, so re-check before persist.
90    if !session.is_valid() {
91        return Err("account changed during community creation".to_string());
92    }
93    // CREATION is the deliberate exception to publish-first: we save locally BEFORE publishing because
94    // (a) no peers exist yet, so there is no shared view to diverge from, and (b) the keys are
95    // fresh-random — losing them (e.g. by rolling back on a publish hiccup) would orphan the community
96    // irrecoverably. A failed publish leaves a local community the owner can re-publish
97    // (`republish_community_metadata`), not a cross-member divergence.
98    crate::db::community::save_community(&community)?;
99
100    // The owner signs every genesis edition with their REAL identity (keyless control plane) via the
101    // active signer — local vault OR a NIP-46 bunker.
102    let signer = active_signer().await?;
103    let cid = community.id.to_hex();
104    let created = std::time::SystemTime::now()
105        .duration_since(std::time::UNIX_EPOCH)
106        .map(|d| d.as_secs())
107        .unwrap_or(0);
108
109    // The genesis control plane: GroupRoot (vsk=0) + each channel's display metadata (vsk=2) + the
110    // auto Admin role (vsk=1), all real-npub 3308 editions signed by the owner. The Admin role is
111    // DATA, not a hardcoded flag (Mod/custom roles are additive later); the owner takes no grant (owner
112    // = implicit position 0, never a Role). Build + collect each (entity_hex, self_hash) head, publish
113    // each, and only AFTER every publish succeeds record the heads — so a mid-create publish failure
114    // never leaves heads for a partially-published genesis (which would make a later base rotation's
115    // re-anchor coverage gate trip forever on an entity the relay never received).
116    let admin = super::roles::Role::admin(crate::simd::hex::bytes_to_hex_32(&super::random_32()));
117    let root_meta = super::metadata::CommunityMetadata::of(&community);
118    let root_inner = super::roster::build_community_root_edition_unsigned(owner_pk, &community.id, &root_meta, 1, None, created, None)?
119        .sign(&signer).await.map_err(|e| format!("sign genesis group-root: {e}"))?;
120    let role_inner = super::roster::build_role_edition_unsigned(owner_pk, &admin, 1, None, created, None)?
121        .sign(&signer).await.map_err(|e| format!("sign genesis admin-role: {e}"))?;
122    // (entity_hex, self_hash, inner_id-for-display-entities). The GroupRoot + channels record their
123    // inner_id so a same-version genesis fork resolves by the deterministic tiebreak; the role doesn't
124    // converge (authority record), so it carries None.
125    let mut heads: Vec<(String, [u8; 32], Option<[u8; 32]>)> = vec![
126        (cid.clone(), super::version::edition_hash(&community.id.0, 1, None, root_inner.content.as_bytes()), Some(root_inner.id.to_bytes())),
127        (admin.role_id.clone(), super::version::edition_hash(&crate::simd::hex::hex_to_bytes_32(&admin.role_id), 1, None, role_inner.content.as_bytes()), None),
128    ];
129    let mut to_publish: Vec<Event> = vec![
130        super::roster::seal_control_edition(&Keys::generate(), &root_inner, &community.server_root_key, &community.id, community.server_root_epoch)?,
131        super::roster::seal_control_edition(&Keys::generate(), &role_inner, &community.server_root_key, &community.id, community.server_root_epoch)?,
132    ];
133    for channel in &community.channels {
134        let meta = super::metadata::ChannelMetadata { name: channel.name.clone() };
135        let inner = super::roster::build_channel_metadata_edition_unsigned(owner_pk, &channel.id, &meta, 1, None, created, None)?
136            .sign(&signer).await.map_err(|e| format!("sign genesis channel-metadata: {e}"))?;
137        heads.push((channel.id.to_hex(), super::version::edition_hash(&channel.id.0, 1, None, inner.content.as_bytes()), Some(inner.id.to_bytes())));
138        to_publish.push(super::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, community.server_root_epoch)?);
139    }
140    // Publish the genesis editions durably: each returns once a relay ACKs (the laggards thread in the
141    // background) and throws if NO relay accepts within the confirm window — so a dead relay set fails the
142    // create loudly instead of recording heads for editions that never reached the network.
143    for outer in &to_publish {
144        transport.publish_durable(outer, &community.relays).await?;
145    }
146    // Every edition reached at least one relay — now record each head + cache the Admin role (gated on the
147    // session still being ours, so a mid-publish account swap doesn't write into the wrong account).
148    if session.is_valid() {
149        for (entity_hex, hash, inner_id) in &heads {
150            let _ = match inner_id {
151                Some(id) => crate::db::community::set_edition_head_with_id(&cid, entity_hex, 1, hash, id),
152                None => crate::db::community::set_edition_head(&cid, entity_hex, 1, hash),
153            };
154        }
155        let roster = super::roles::CommunityRoles { roles: vec![admin], grants: Vec::new() };
156        let _ = crate::db::community::set_community_roles(&cid, &roster, created as i64);
157    }
158    Ok(community)
159}
160
161/// Publish a Community message and retain its ephemeral key in the account DB so the
162/// sender can delete it later. Returns the published outer event.
163pub async fn send_message<T: Transport + ?Sized>(
164    transport: &T,
165    community: &Community,
166    channel: &Channel,
167    author: &Keys,
168    content: &str,
169    ms: u64,
170) -> Result<Event, String> {
171    let session = SessionGuard::capture();
172    // Build + sign the inner explicitly so we know the message_id (the deletion key) up
173    // front, then publish via the signed path. Identical wire output to the old
174    // publish_message route.
175    let inner = super::envelope::build_inner_event(author.public_key(), &channel.id, channel.epoch, content, ms, None)
176        .sign_with_keys(author)
177        .map_err(|e| e.to_string())?;
178    let (outer, ephemeral) = publish_signed_message(transport, community, channel, &inner, false).await?;
179    // The publish straddled network I/O; bail before writing to the (possibly
180    // swapped) account DB.
181    if !session.is_valid() {
182        return Err("account changed during send; not persisting message key".to_string());
183    }
184    crate::db::community::store_message_key(&inner.id.to_hex(), &outer.id.to_hex(), &ephemeral, &community.relays)?;
185    Ok(outer)
186}
187
188/// Publish a message whose inner authorship event was signed externally (via the active
189/// signer — local OR bunker) and retain its ephemeral key. Use this from the command
190/// layer where `client.signer()` is available; it gives bunker accounts send parity with
191/// DMs. (Local-only callers/tests can use [`send_message`].)
192pub async fn send_signed_message<T: Transport + ?Sized>(
193    transport: &T,
194    community: &Community,
195    channel: &Channel,
196    inner: &Event,
197) -> Result<Event, String> {
198    let session = SessionGuard::capture();
199    let (outer, ephemeral) = publish_signed_message(transport, community, channel, inner, false).await?;
200    if !session.is_valid() {
201        return Err("account changed during send; not persisting message key".to_string());
202    }
203    crate::db::community::store_message_key(&inner.id.to_hex(), &outer.id.to_hex(), &ephemeral, &community.relays)?;
204    Ok(outer)
205}
206
207/// Announce presence (join/leave) into a channel: a kind-3306 inner signed by the active identity,
208/// published under a fresh ephemeral outer. Content is `"leave"`, plain `"join"`, or — for a join via a
209/// public invite — a small JSON `{"by":"<inviter npub>","l":"<label>"}` carrying attribution (which
210/// link/source brought this member; members-only). Client best-practice (not enforced); no deletion key
211/// retained. Callers treat failure as non-fatal. `attribution` = `Some((inviter_npub, label))` on an
212/// invite-join, else `None`.
213/// Build + sign a presence (3306) inner event WITHOUT publishing. Lets the caller record the local
214/// system event first (memory→DB, like an outgoing message) and publish in the background — the relay
215/// echo then dedups by this inner's id. `inner.id` is the system-event dedup key.
216pub async fn build_presence(
217    channel: &Channel,
218    joined: bool,
219    attribution: Option<(String, Option<String>)>,
220) -> Result<nostr_sdk::Event, String> {
221    let author_pk = crate::state::my_public_key().ok_or("not logged in")?;
222    let ms = std::time::SystemTime::now()
223        .duration_since(std::time::UNIX_EPOCH)
224        .map(|d| d.as_millis() as u64)
225        .unwrap_or(0);
226    let content = match (joined, attribution) {
227        (false, _) => "leave".to_string(),
228        (true, Some((by, label))) => serde_json::json!({ "by": by, "l": label }).to_string(),
229        (true, None) => "join".to_string(),
230    };
231    let unsigned = super::envelope::build_inner_typed(
232        author_pk, &channel.id, channel.epoch, event_kind::COMMUNITY_PRESENCE, &content, ms, None, &[],
233    );
234    let signer = active_signer().await?;
235    unsigned.sign(&signer).await.map_err(|e| format!("Failed to sign presence: {e}"))
236}
237
238/// Publish a pre-built presence inner (from [`build_presence`]) to the channel's recipient set.
239pub async fn publish_presence_event<T: Transport + ?Sized>(
240    transport: &T,
241    community: &Community,
242    channel: &Channel,
243    inner: &nostr_sdk::Event,
244) -> Result<(), String> {
245    let _ = publish_signed_message(transport, community, channel, inner, true).await?;
246    Ok(())
247}
248
249pub async fn publish_presence<T: Transport + ?Sized>(
250    transport: &T,
251    community: &Community,
252    channel: &Channel,
253    joined: bool,
254    attribution: Option<(String, Option<String>)>,
255) -> Result<(), String> {
256    let inner = build_presence(channel, joined, attribution).await?;
257    publish_presence_event(transport, community, channel, &inner).await
258}
259
260/// Publish a WebXDC realtime peer signal (3310) into a channel: an advertisement of the local
261/// Iroh node for a Mini App session (`node_addr` = Some) or a peer-left (`node_addr` = None).
262/// The Community-transport twin of the NIP-17 peer-advertisement/peer-left DM rumors — signed
263/// by the member's real identity (a member can't forge another player's presence), sealed under
264/// the channel epoch key like presence. Callers treat failure as non-fatal (a missed ad only
265/// delays discovery; the next re-advertise covers it).
266pub async fn publish_webxdc_signal<T: Transport + ?Sized>(
267    transport: &T,
268    community: &Community,
269    channel: &Channel,
270    topic_id: &str,
271    node_addr: Option<&str>,
272) -> Result<(), String> {
273    let author_pk = crate::state::my_public_key().ok_or("not logged in")?;
274    let ms = std::time::SystemTime::now()
275        .duration_since(std::time::UNIX_EPOCH)
276        .map(|d| d.as_millis() as u64)
277        .unwrap_or(0);
278    let content = crate::webxdc::peer_signal_content(topic_id, node_addr);
279    let unsigned = super::envelope::build_inner_typed(
280        author_pk, &channel.id, channel.epoch, event_kind::COMMUNITY_WEBXDC, &content, ms, None, &[],
281    );
282    let signer = active_signer().await?;
283    let inner = unsigned.sign(&signer).await.map_err(|e| format!("Failed to sign webxdc signal: {e}"))?;
284    let _ = publish_signed_message(transport, community, channel, &inner, true).await?;
285    Ok(())
286}
287
288/// Publish a typing indicator (3311) into a channel: an inner "typing" event signed by the member,
289/// sealed under the channel epoch key like presence. The Community-transport twin of the NIP-17
290/// typing rumor. Ephemeral — never persisted/folded; the latency-sensitive single-attempt path
291/// (`durable = false`), and callers treat failure as non-fatal (a dropped keystroke ping is harmless;
292/// the next one ~every few seconds covers it).
293pub async fn publish_typing_signal<T: Transport + ?Sized>(
294    transport: &T,
295    community: &Community,
296    channel: &Channel,
297) -> Result<(), String> {
298    let author_pk = crate::state::my_public_key().ok_or("not logged in")?;
299    let ms = std::time::SystemTime::now()
300        .duration_since(std::time::UNIX_EPOCH)
301        .map(|d| d.as_millis() as u64)
302        .unwrap_or(0);
303    let unsigned = super::envelope::build_inner_typed(
304        author_pk, &channel.id, channel.epoch, event_kind::COMMUNITY_TYPING, "typing", ms, None, &[],
305    );
306    let signer = active_signer().await?;
307    let inner = unsigned.sign(&signer).await.map_err(|e| format!("Failed to sign typing signal: {e}"))?;
308    let _ = publish_signed_message(transport, community, channel, &inner, false).await?;
309    Ok(())
310}
311
312/// Persist an inbound WebXDC peer signal as a kind-30078 event row — the SAME shape the DM
313/// peer-advertisement handler writes (content `peer-advertisement`/`peer-left`, `reference_id`
314/// = topic, `webxdc-topic`/`webxdc-node-addr` tags) — so the miniapp layer's
315/// `get_active_peer_advertisements` (latest-per-npub, left-tombstone-aware) reads both
316/// transports identically. This is what lets a member who closed Vector mid-session rediscover
317/// the active players on reopen. Idempotent via `event_exists`.
318pub async fn persist_webxdc_signal(
319    channel_hex: &str,
320    npub: &str,
321    topic_id: &str,
322    node_addr: Option<&str>,
323    event_id: &str,
324    created_at: u64,
325) {
326    if crate::db::events::event_exists(event_id).unwrap_or(true) {
327        return;
328    }
329    // Sender-claimed timestamp: clamp into the near future so a forged far-future ad
330    // can't outrank every later genuine peer-left in the latest-per-npub read.
331    let now_secs = std::time::SystemTime::now()
332        .duration_since(std::time::UNIX_EPOCH)
333        .unwrap_or_default()
334        .as_secs();
335    let created_at = created_at.min(now_secs + 300);
336    let Ok(chat_id) = crate::db::id_cache::get_or_create_chat_id(channel_hex) else { return };
337    let mut tags = vec![
338        vec!["webxdc-topic".to_string(), topic_id.to_string()],
339        vec!["d".to_string(), "vector-webxdc-peer".to_string()],
340    ];
341    if let Some(addr) = node_addr {
342        tags.push(vec!["webxdc-node-addr".to_string(), addr.to_string()]);
343    }
344    let event = crate::stored_event::StoredEvent {
345        id: event_id.to_string(),
346        kind: crate::stored_event::event_kind::APPLICATION_SPECIFIC,
347        chat_id,
348        user_id: None,
349        content: if node_addr.is_some() { "peer-advertisement" } else { "peer-left" }.to_string(),
350        tags,
351        reference_id: Some(topic_id.to_string()),
352        created_at,
353        received_at: std::time::SystemTime::now()
354            .duration_since(std::time::UNIX_EPOCH)
355            .unwrap_or_default()
356            .as_millis() as u64,
357        mine: false,
358        pending: false,
359        failed: false,
360        wrapper_event_id: None,
361        npub: Some(npub.to_string()),
362        preview_metadata: None,
363    };
364    if let Err(e) = crate::db::events::save_event(&event).await {
365        crate::log_warn!("[community] failed to persist webxdc peer signal: {e}");
366    }
367}
368
369/// Publish a cooperative kick (3309) of `target_hex` into `channel`: a real-npub-signed inner directive
370/// (content = the target's hex pubkey) carrying the actor's `vac` authority citation. NOT a rekey and NOT
371/// folded — the kicked client self-removes on receipt (drops the community keys + wipes local chat data);
372/// peers drop the target from their observed member list. The actor must hold `KICK` and strictly outrank
373/// the target (the owner is never a valid target); this is the sender-side half of the rule peers
374/// re-verify on receipt. For a malicious target that ignores the kick, escalate to a BAN.
375/// Signs via the active client signer, so a bunker (NIP-46) identity works without exposing the secret.
376/// On removal (kick/ban), strip the target's roles so their authority doesn't dangle — a removed admin
377/// would otherwise silently regain @admin on re-add, and the roster would keep listing a non-member as an
378/// admin. Best-effort: a no-op if the target holds no role; a SKIP (logged) if the remover lacks
379/// `MANAGE_ROLES`/outrank for any held role (a future mid-tier remover) — the kick/ban still neutralizes
380/// them, and leaving the grant beats a partial strip. Publishes the full revoke (empty grant) when
381/// authorized for EVERY held role.
382async fn strip_member_roles_on_removal<T: Transport + ?Sized>(
383    transport: &T,
384    community: &Community,
385    member_hex: &str,
386) {
387    let cid = community.id.to_hex();
388    let roster = match crate::db::community::get_community_roles(&cid) {
389        Ok(r) => r,
390        Err(_) => return,
391    };
392    let held: Vec<String> = roster
393        .grants
394        .iter()
395        .find(|g| g.member == member_hex)
396        .map(|g| g.role_ids.clone())
397        .unwrap_or_default();
398    if held.is_empty() {
399        return; // plain member — no authority to strip
400    }
401    for role_id in &held {
402        if caller_can_manage_role(community, &roster, role_id, member_hex).is_err() {
403            crate::log_warn!(
404                "removal: not authorized to revoke role {role_id} of {member_hex}; leaving the grant (kick/ban still neutralizes)"
405            );
406            return;
407        }
408    }
409    if let Err(e) = set_member_grant(transport, community, member_hex, Vec::new()).await {
410        crate::log_warn!("removal: role-strip publish failed for {member_hex}: {e}");
411    }
412}
413
414pub async fn publish_kick<T: Transport + ?Sized>(
415    transport: &T,
416    community: &Community,
417    channel: &Channel,
418    target_hex: &str,
419) -> Result<String, String> {
420    let author_pk = crate::state::my_public_key().ok_or("not logged in")?;
421    let me = author_pk.to_hex();
422    let cid = community.id.to_hex();
423    // hierarchy gate: hold KICK + strictly outrank the target (owner is never a valid target). Mirror
424    // of publish_banlist's gate; peers re-verify the same rule against their floor-protected roster.
425    {
426        let owner = proven_owner_hex(community);
427        let roster = crate::db::community::get_community_roles(&cid).unwrap_or_default();
428        if !roster.can_act_on_member(&me, owner.as_deref(), target_hex, super::roles::Permissions::KICK) {
429            return Err("you can't kick a member who outranks you (or the owner)".to_string());
430        }
431    }
432    let ms = std::time::SystemTime::now()
433        .duration_since(std::time::UNIX_EPOCH)
434        .map(|d| d.as_millis() as u64)
435        .unwrap_or(0);
436    // pinned authority: a non-owner kicker cites the grant that authorizes them (owner cites nothing).
437    let citation = authority_citation(community, &me);
438    let extra: Vec<nostr_sdk::prelude::Tag> = citation.iter().map(|c| c.to_tag()).collect();
439    let unsigned = super::envelope::build_inner_full(
440        author_pk, &channel.id, channel.epoch, event_kind::COMMUNITY_KICK, target_hex, ms, None, &[], &extra,
441    );
442    let signer = active_signer().await?;
443    let inner = unsigned.sign(&signer).await.map_err(|e| format!("Failed to sign kick: {e}"))?;
444    publish_signed_message(transport, community, channel, &inner, true).await?;
445    // Removal strips authority: revoke the kicked member's roles too (best-effort) so a kicked admin
446    // doesn't rejoin (fresh invite) silently still admin, and no non-member lingers in the roster.
447    strip_member_roles_on_removal(transport, community, target_hex).await;
448    // Return the inner id so the caller can record a local "Member Left" that dedups with the relay echo.
449    Ok(inner.id.to_hex())
450}
451
452
453/// Replace the Community banlist and publish it as a real-npub-signed 3308 EDITION (vsk=4) at the
454/// community-scoped banlist locator (keyless; foldable + re-anchorable). `banned_hex`
455/// is the full new list (latest-wins). The actor's inner signature IS the authority proof; every member
456/// re-verifies it held `BAN` against the authorized roster on receipt. Publish FIRST, then
457/// persist locally on success — a failed publish must not leave us enforcing a ban no one else sees.
458pub async fn publish_banlist<T: Transport + ?Sized>(
459    transport: &T,
460    community: &Community,
461    banned_hex: &[String],
462) -> Result<(), String> {
463    let session = SessionGuard::capture();
464    let cid = community.id.to_hex();
465    // Keyless model: sign with the actor's own identity via the active signer (local vault OR a NIP-46
466    // bunker). `author` is the active pubkey; `signer` signs the unsigned edition below.
467    let signer = active_signer().await?;
468    let actor_pk = crate::state::my_public_key().ok_or("no local identity to sign the banlist edition")?;
469    // hierarchy gate: the actor must hold BAN and strictly outrank every member in the DELTA
470    // both those being ADDED (ban) and those being REMOVED (unban). Gating only additions would let a
471    // low-ranked admin undo a superior's ban or wholesale-clear the list. The owner is never a valid
472    // target. This is the sender-side half of the rule peers re-verify on receipt.
473    {
474        let me = actor_pk.to_hex();
475        let owner = proven_owner_hex(community);
476        let roster = crate::db::community::get_community_roles(&cid).unwrap_or_default();
477        let current: std::collections::HashSet<String> =
478            crate::db::community::get_community_banlist(&cid).unwrap_or_default().into_iter().collect();
479        let next: std::collections::HashSet<&str> = banned_hex.iter().map(|s| s.as_str()).collect();
480        let added = banned_hex.iter().filter(|n| !current.contains(n.as_str()));
481        let removed = current.iter().filter(|n| !next.contains(n.as_str()));
482        for target in added.chain(removed) {
483            if !roster.can_act_on_member(&me, owner.as_deref(), target, super::roles::Permissions::BAN) {
484                return Err("you can't ban or unban a member who outranks you (or the owner)".to_string());
485            }
486        }
487    }
488    // Fail-fast (bunker boundary): a newly-banned member in a PRIVATE community must be READ-CUT (a
489    // base rekey), and a rekey needs a RAW local key — its blob locator is an ECDH a NIP-46 bunker can't
490    // expose. Refuse BEFORE publishing anything, so we never half-apply (publish a ban we then can't
491    // enforce, leaving a "banned but still readable" member). Covers a pending prior cut too. A community
492    // admin who holds a local key can carry out the ban. (Public bans + unbans don't rekey → allowed.)
493    {
494        let prev: std::collections::HashSet<String> =
495            crate::db::community::get_community_banlist(&cid).unwrap_or_default().into_iter().collect();
496        let adds = banned_hex.iter().any(|n| !prev.contains(n.as_str()));
497        let cut_needed = (adds || crate::db::community::get_read_cut_pending(&cid)?) && !is_public(community)?;
498        if cut_needed && crate::state::MY_SECRET_KEY.to_keys().is_none() {
499            return Err("Banning someone from a private community cuts their read access, which needs a key rotation your account can't perform: it signs remotely (a NIP-46 bunker), and a rotation requires a local key. Ask a community admin who holds a local key to carry out the ban.".to_string());
500        }
501    }
502    // Next version in the banlist's own chain (single community-wide entity at the banlist locator).
503    let entity_id = super::derive::banlist_locator(&community.id);
504    let entity_hex = crate::simd::hex::bytes_to_hex_32(&entity_id);
505    let (version, prev_hash) = match crate::db::community::get_edition_head(&cid, &entity_hex)? {
506        Some((v, h)) => (v + 1, Some(h)),
507        None => (1, None),
508    };
509    let created_at = std::time::SystemTime::now()
510        .duration_since(std::time::UNIX_EPOCH)
511        .map(|d| d.as_secs())
512        .unwrap_or(0);
513    // pinned authority: a non-owner banner cites the grant edition that authorizes them, so peers
514    // resolve the ban against that exact grant version (not their live roster). The owner cites nothing.
515    let citation = authority_citation(community, &actor_pk.to_hex());
516    let unsigned = super::roster::build_banlist_edition_unsigned(actor_pk, &community.id, banned_hex, version, prev_hash.as_ref(), created_at, citation.as_ref())?;
517    let inner = unsigned.sign(&signer).await.map_err(|e| format!("sign banlist edition: {e}"))?;
518    let outer = super::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, community.server_root_epoch)?;
519    let self_hash = super::version::edition_hash(&entity_id, version, prev_hash.as_ref(), inner.content.as_bytes());
520
521    // Did this ban ADD anyone (vs the list we held)? Captured BEFORE the persist below so we can decide
522    // whether to cut read access. Unbans (removals) never rekey.
523    let newly_added: Vec<String> = {
524        let prev: std::collections::HashSet<String> =
525            crate::db::community::get_community_banlist(&cid).unwrap_or_default().into_iter().collect();
526        banned_hex.iter().filter(|n| !prev.contains(n.as_str())).cloned().collect()
527    };
528    let newly_banned = !newly_added.is_empty();
529
530    // Publish FIRST — advancing the head before a fallible publish would leave a phantom head (the next
531    // edition cites an unpublished predecessor → fold quarantines it forever). Re-check the session after
532    // the await: it may have straddled an account swap, and persisting then would write the wrong account.
533    transport.publish_durable(&outer, &community.relays).await?;
534    if session.is_valid() {
535        crate::db::community::set_community_banlist(&cid, banned_hex, created_at as i64)?;
536        crate::db::community::set_edition_head(&cid, &entity_hex, version, &self_hash)?;
537    }
538
539    // Removal strips authority: revoke the roles of every NEWLY-banned member so their grant doesn't dangle
540    // — a banned admin would otherwise silently regain @admin on unban, and the roster would keep listing a
541    // removed member as admin. Best-effort, and BEFORE the read-cut so its re-anchor carries the revoked
542    // (empty) grant forward.
543    if session.is_valid() {
544        for member_hex in &newly_added {
545            strip_member_roles_on_removal(transport, community, member_hex).await;
546        }
547    }
548
549    // rekey-on-removal: in a PRIVATE community, a newly-banned member must also lose READ access, so
550    // re-seal the base to the surviving observed participants (`community_member_activity` excludes the
551    // banlist, so the just-banned member is dropped). A PUBLIC community does NOT rotate the base
552    // (anti-memberlist: no recipient set to wrap to, and a banned member could re-enter via a link
553    // anyway) — there the banlist alone suppresses them, and the UI must say "blocked," not "removed."
554    // Runs after the banlist is persisted (so the observed set already excludes the banned).
555    //
556    // rekey-on-removal read-cut. Re-seal if this ban ADDED someone, OR a prior re-seal is still
557    // pending (`read_cut_pending`) — the latter decouples recovery from the add-delta (which the durable
558    // banlist persist consumes), so a re-seal that failed on a previous ban is RETRIED here even when this
559    // call adds no one. Mark pending BEFORE the attempt (durable intent) and clear ONLY on success: a
560    // failure (total relay outage / re-anchor-withhold / mid-ban swap) leaves the flag set, so the next
561    // ban OR a community sync ([`retry_pending_read_cut`]) re-attempts it — no "blocked but not read-cut"
562    // member survives a transient failure. The re-seal publish is itself durable (×30 per relay).
563    let need_cut = (newly_banned || crate::db::community::get_read_cut_pending(&cid)?)
564        && session.is_valid()
565        && !is_public(community)?;
566    if need_cut {
567        // `newly_banned` is a fresh exclusion delta → force a base epoch past the removal; otherwise this is
568        // a resume of an interrupted prior cut → keep its in-flight target.
569        run_read_cut(transport, community, newly_banned).await?;
570    }
571    Ok(())
572}
573
574/// Is the local user in this community's (folded, cached) banlist? Drives BAN self-removal: a
575/// banned member tears down locally (drop the community keys + wipe local chat data) exactly like a kick,
576/// but CANNOT rejoin — re-detecting the ban on any later sync re-removes them, and admins can't invite a
577/// banned npub. Reads the cached banlist, so refresh it via [`fetch_and_apply_banlist`] first for an
578/// authoritative (realtime or boot) check.
579pub fn am_i_banned(community: &Community) -> bool {
580    let me = match crate::state::my_public_key() {
581        Some(p) => p.to_hex(),
582        None => return false,
583    };
584    crate::db::community::get_community_banlist(&community.id.to_hex())
585        .unwrap_or_default()
586        .iter()
587        .any(|b| b == &me)
588}
589
590/// Retry an outstanding PRIVATE-community read-cut re-seal, if one is pending. Called from the sync
591/// path so a re-seal that failed during a ban (e.g. a relay outage) AUTO-RECOVERS on the owner's next
592/// community sync — no manual re-ban needed. No-op if nothing is pending. If the community has since gone
593/// PUBLIC the read-cut is moot (anti-memberlist: a Public ban doesn't rotate the base), so the stale flag
594/// is cleared. Best-effort + idempotent; the re-seal authority (BAN) is enforced by `rotate_server_root`.
595pub async fn retry_pending_read_cut<T: Transport + ?Sized>(
596    transport: &T,
597    community: &Community,
598) -> Result<(), String> {
599    let cid = community.id.to_hex();
600    if !crate::db::community::get_read_cut_pending(&cid)? {
601        return Ok(());
602    }
603    if is_public(community)? {
604        crate::db::community::set_read_cut_pending(&cid, false)?; // moot in Public mode
605        return Ok(());
606    }
607    // Reload so the re-seal rotates from the FRESHEST root/epoch — the caller's `community` struct may
608    // predate a recent rotation, and rotating from a stale root would address the rekey under the wrong
609    // prior-root pseudonym. Pure resume (`fresh = false`): keep the in-flight target so an interrupted cut
610    // finishes without forcing an extra base rotation.
611    let fresh = crate::db::community::load_community(&community.id)?.ok_or("community no longer present")?;
612    run_read_cut(transport, &fresh, false).await
613}
614
615/// Fetch the Community's control plane and apply the folded banlist locally. The banlist is a 3308
616/// edition at the community-scoped banlist locator; the folded head is applied only if its signer held
617/// `BAN` in the authorized roster (the keyless authority gate) and it is strictly newer than the
618/// banlist edition we hold (refuse-downgrade by version). No authorized edition → local unchanged.
619/// ONE REQ for the entire control plane: fetch every kind-3308 edition at the control pseudonym(s) and
620/// fold the full roster (banlist + roles + invite-links + metadata) in a single pass. The per-slice
621/// `fetch_and_apply_*` functions and `fetch_and_apply_control` share this, so a sync/join/boot folds ONCE
622/// instead of issuing four identical REQs. Fetches at the CURRENT server-root epoch (re-anchoring keeps
623/// the complete plane reachable there); `z_tags` is a Vec so the addressing can extend if ever needed.
624async fn fetch_control_folded<T: Transport + ?Sized>(
625    transport: &T,
626    community: &Community,
627) -> Result<super::roster::FoldedRoster, String> {
628    // The control plane lives at the CURRENT server-root epoch — a rotation re-anchors it there, and all
629    // live publishes (grants/banlist/metadata/invite-links) seal at the same epoch. Fetch exactly that one
630    // (NOT a 0..=epoch range — a post-rotation joiner can't derive prior-epoch pseudonyms; the re-anchor
631    // guarantees the complete current plane is reachable here).
632    let z_tags = vec![super::roster::control_pseudonym(&community.server_root_key, &community.id, community.server_root_epoch)];
633    // The fold is fail-closed on version-chain gaps; the live transport unions all relays
634    // (a single fast-but-partial relay would otherwise gap-quarantine the head and wedge
635    // this seat on a stale plane forever).
636    let query = Query { kinds: vec![event_kind::COMMUNITY_CONTROL], z_tags, ..Default::default() };
637    let raw = transport.fetch(&query, &community.relays).await?;
638    // Bound the AEAD work too (fold_roster re-caps the verify/fold): a relay
639    // flooding the coordinate must not buy unbounded decrypt attempts.
640    let inner_editions: Vec<Event> = raw
641        .iter()
642        .take(super::roster::MAX_CONTROL_EDITIONS)
643        .filter_map(|ev| super::roster::open_control_edition(ev, &community.server_root_key).ok())
644        .collect();
645    // VALID (opened) editions, NOT raw.len() — the admin-write isolation signal must mean "a relay served
646    // our actual control plane," so a relay returning only junk/unopenable events at the coordinate doesn't
647    // count as a response. (Floors still guard against stale/rollback; this just stops content-withholding
648    // from masquerading as connectivity.)
649    let fetched = inner_editions.len();
650    // Fold from the persisted per-entity floors (refuse-downgrade) so a withholding relay can't roll
651    // an entity's chain back to a since-revoked version. EPOCH-PRIMARY: seed only the floors recorded
652    // at the CURRENT epoch — a head from a PRIOR epoch belongs to a superseded founding, so that entity
653    // folds fresh from the new epoch's v1 genesis (which anchors cleanly at floor 0; not Policy-B, since a
654    // compacted genesis carries no prev_hash). Within the current epoch, refuse-downgrade + floor anchoring hold.
655    let current_epoch = community.server_root_epoch.0;
656    let floors: std::collections::HashMap<String, (u64, [u8; 32])> =
657        crate::db::community::get_all_edition_heads_epoched(&community.id.to_hex())?
658            .into_iter()
659            .filter(|(_, (epoch, _, _))| *epoch == current_epoch)
660            .map(|(entity, (_epoch, version, hash))| (entity, (version, hash)))
661            .collect();
662    let mut folded = super::roster::fold_roster(&inner_editions, &community.id, &floors);
663    folded.fetched = fetched; // openable editions the relays served (isolation signal for admin-write guards)
664    Ok(folded)
665}
666
667/// Fetch the control plane ONCE and apply every slice — banlist, roles, invite links, metadata — from a
668/// single REQ + single fold. Sync/join/boot call THIS instead of the four `fetch_and_apply_*` in sequence
669/// (which was four identical REQs). Banlist is applied first so a caller's subsequent `am_i_banned` sees the
670/// freshest list. Each slice is best-effort; one failing doesn't abort the rest. (Solo callers that need a
671/// single slice — e.g. revoke refreshing invite links — still use the individual `fetch_and_apply_*`.)
672pub async fn fetch_and_apply_control<T: Transport + ?Sized>(
673    transport: &T,
674    community: &Community,
675) -> Result<usize, String> {
676    let session = SessionGuard::capture();
677    let cid = community.id.to_hex();
678    // binary seal: once dissolved, the control fold STOPS advancing — no further editions apply (the
679    // inbound message path likewise drops everything). Cheap flag check before any fetch.
680    if crate::db::community::get_community_dissolved(&cid)? {
681        return Ok(0);
682    }
683    let folded = fetch_control_folded(transport, community).await?;
684    if !session.is_valid() {
685        return Err("account changed during control fetch".to_string());
686    }
687    // tombstone: if a GroupDissolved edition at the locator was signed by the PROVEN owner (derived
688    // via the deed at fold time, never a cached field), SEAL the community and stop. Fail-closed: an
689    // unreadable deed (no proven owner) or a non-owner signer is REJECTED — we stay in the prior state,
690    // never death-by-default. THIS fold pass IS the "one bounded final drain": the banlist/roles/
691    // metadata applied below are the last accepted control; subsequent syncs see the flag and drop.
692    // Detect an owner tombstone via EITHER the rotation-stable coordinate probe (the cross-epoch path: a
693    // post-rotation joiner only derives a later root + never fetches the publish-epoch control_pseudonym,
694    // but always derives `dissolved_pseudonym`) OR the control-plane fold (the current-epoch fast path).
695    // Owner derived from the deed at fold time; fail-closed (no proven owner / non-owner signer ⇒ rejected).
696    if let Some(owner) = proven_owner_hex(community) {
697        let by_fold = folded.dissolved_by.iter().any(|s| s.to_hex() == owner);
698        let by_probe = !by_fold && dissolved_tombstone_present(transport, community, &owner).await;
699        if by_fold || by_probe {
700            // This fold pass IS the "one bounded final drain": apply the last accepted control, then
701            // seal. Subsequent syncs short-circuit on the flag above and drop everything.
702            let _ = fetch_and_apply_banlist_inner(transport, community, Some(folded.clone())).await;
703            let _ = fetch_and_apply_roles_inner(transport, community, Some(folded.clone())).await;
704            let _ = fetch_and_apply_invite_links_inner(transport, community, Some(folded.clone())).await;
705            let _ = fetch_and_apply_metadata_inner(transport, community, Some(folded.clone())).await;
706            if session.is_valid() {
707                crate::db::community::set_community_dissolved(&cid)?;
708                // Notify the UI to re-render the dead community live (lock composer + end divider). Emitting
709                // from the single seal point covers EVERY caller — sync, boot, realtime refresh — not just the
710                // realtime path. Fires once: the short-circuit above skips it on every subsequent fetch.
711                crate::emit_event("community_refreshed", &serde_json::json!({ "community_id": cid }));
712            }
713            return Ok(folded.fetched);
714        }
715    }
716    // Openable control editions this single fetch served — the caller's "≥1 relay returned our actual plane"
717    // isolation signal (no separate probe fetch needed).
718    let fetched = folded.fetched;
719    let _ = fetch_and_apply_banlist_inner(transport, community, Some(folded.clone())).await;
720    let _ = fetch_and_apply_roles_inner(transport, community, Some(folded.clone())).await;
721    let _ = fetch_and_apply_invite_links_inner(transport, community, Some(folded.clone())).await;
722    let _ = fetch_and_apply_metadata_inner(transport, community, Some(folded)).await;
723    Ok(fetched)
724}
725
726pub async fn fetch_and_apply_banlist<T: Transport + ?Sized>(
727    transport: &T,
728    community: &Community,
729) -> Result<Vec<String>, String> {
730    fetch_and_apply_banlist_inner(transport, community, None).await
731}
732
733async fn fetch_and_apply_banlist_inner<T: Transport + ?Sized>(
734    transport: &T,
735    community: &Community,
736    prefolded: Option<super::roster::FoldedRoster>,
737) -> Result<Vec<String>, String> {
738    let session = SessionGuard::capture();
739    let cid = community.id.to_hex();
740    let folded = match prefolded {
741        Some(f) => f,
742        None => fetch_control_folded(transport, community).await?,
743    };
744    // Authority: the banlist signer must hold BAN in the AUTHORIZED roster (delegation-chain filtered),
745    // not merely be validly-signed. A demoted/never-authorized signer's banlist is dropped.
746    let owner = proven_owner_hex(community);
747    let authorized = super::roster::authorize_delegation(&folded, owner.as_deref());
748    if !session.is_valid() {
749        return Err("account changed during banlist fetch".to_string());
750    }
751    if let (Some(author), Some(head)) = (folded.banlist_author, &folded.banlist_head) {
752        // Authority is per-target, not just the BAN bit: the signer must strictly OUTRANK every member
753        // in the delta between the list we hold and the folded list (both newly-banned and newly-unbanned)
754        // — the same check the sender ran. A bit-only check would let a low-ranked BAN-holder ban or
755        // unban a peer/superior (or the owner). Owner is never a valid target (folds out of can_act_on_member).
756        let author_hex = author.to_hex();
757        let held: std::collections::HashSet<String> =
758            crate::db::community::get_community_banlist(&cid)?.into_iter().collect();
759        let next: std::collections::HashSet<&str> = folded.banned.iter().map(|s| s.as_str()).collect();
760        let added = folded.banned.iter().filter(|n| !held.contains(n.as_str()));
761        let removed = held.iter().filter(|n| !next.contains(n.as_str()));
762        // version-pinned authority: the banner's edition cites the grant that authorizes them; we
763        // apply only if we have folded that grant to AT LEAST the cited version (a complete, un-forked
764        // view — else fail closed, never act on a partial authority view). The per-target outrank below
765        // is then resolved against the CURRENT authorized roster, so a since-demoted banner is dropped
766        // there (refuse-superseded). Owner cites nothing and is supreme.
767        let citation = folded.banlist_head.as_ref().and_then(|h| h.citation.as_ref());
768        let banner_grant_hex = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(&community.id, &author.to_bytes()));
769        let pinned = super::roster::authority_citation_satisfied(&folded.heads, owner.as_deref(), &author_hex, &banner_grant_hex, citation);
770        let authed = pinned
771            && added.chain(removed).all(|target| {
772                authorized.can_act_on_member(&author_hex, owner.as_deref(), target, super::roles::Permissions::BAN)
773            });
774        let held_version = crate::db::community::get_edition_head(&cid, &head.entity_hex)?.map(|(v, _)| v).unwrap_or(0);
775        if authed && head.version > held_version {
776            crate::db::community::set_community_banlist(&cid, &folded.banned, head.version as i64)?;
777            crate::db::community::set_edition_head(&cid, &head.entity_hex, head.version, &head.self_hash)?;
778            return Ok(folded.banned);
779        }
780    }
781    // Nothing newer/authorized applied — report the banlist we still hold, not an empty list.
782    crate::db::community::get_community_banlist(&cid)
783}
784
785/// Set a member's complete role set (owner/admin authority) and publish their per-member
786/// Grant event (vsk=3). Empty `role_ids` revokes all of that member's roles. Persists the updated
787/// local graph BEFORE the publish await (so our own client reflects it immediately and the write
788/// lands in the captured account); the relay echo dedups.
789pub async fn set_member_grant<T: Transport + ?Sized>(
790    transport: &T,
791    community: &Community,
792    member_hex: &str,
793    role_ids: Vec<String>,
794) -> Result<(), String> {
795    let session = SessionGuard::capture();
796    // Keyless model: the grant is a real-npub-signed edition. Sign
797    // with the actor's own identity via the active signer (local vault OR a NIP-46 bunker).
798    let signer = active_signer().await?;
799    let actor_pk = crate::state::my_public_key().ok_or("no local identity to sign the grant edition")?;
800    let cid = community.id.to_hex();
801    let grant = super::roles::MemberGrant { member: member_hex.to_string(), role_ids };
802
803    // Next version in this member's grant chain. The entity coordinate is the member's grant locator,
804    // so the head tracks per-member; v+1 cites the held head's self_hash (genesis v1 if none).
805    let member_bytes = crate::simd::hex::hex_to_bytes_32(member_hex);
806    let entity_id = super::derive::grant_locator(&community.id, &member_bytes);
807    let entity_hex = crate::simd::hex::bytes_to_hex_32(&entity_id);
808    let (version, prev_hash) = match crate::db::community::get_edition_head(&cid, &entity_hex)? {
809        Some((v, h)) => (v + 1, Some(h)),
810        None => (1, None),
811    };
812    let created_at = std::time::SystemTime::now()
813        .duration_since(std::time::UNIX_EPOCH)
814        .map(|d| d.as_secs())
815        .unwrap_or(0);
816
817    // Build (real-npub signed inner) + seal under the server-root for the wire. The grant authoring
818    // gate (`caller_can_manage_role`) runs in the grant_role/revoke_role callers; this is the encoder.
819    // pinned authority: a delegated admin granting a lower member cites the grant that authorizes
820    // them, so the delegation chain is verifiable at that version. The owner cites nothing (supreme).
821    // (Owner-only granting is the MVP norm, so this is usually `None` — but emitting it now keeps the
822    // immutable wire data complete for the delegation-chain verifier, rather than baking in a gap.)
823    let citation = authority_citation(community, &actor_pk.to_hex());
824    let unsigned = super::roster::build_grant_edition_unsigned(actor_pk, &community.id, &grant, version, prev_hash.as_ref(), created_at, citation.as_ref())?;
825    let inner = unsigned.sign(&signer).await.map_err(|e| format!("sign grant edition: {e}"))?;
826    let outer = super::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, community.server_root_epoch)?;
827    // The new head's self_hash = a hash over the EXACT content bytes the inner committed to (not a
828    // re-serialization), so the stored head matches the published edition and the next edition's
829    // prev_hash cites it correctly.
830    let self_hash = super::version::edition_hash(&entity_id, version, prev_hash.as_ref(), inner.content.as_bytes());
831
832    let is_full_revoke = grant.role_ids.is_empty();
833    // Compute the advanced local state in memory (cheap; no DB write yet).
834    let mut roster = crate::db::community::get_community_roles(&cid)?;
835    roster.grants.retain(|g| g.member != member_hex);
836    if !grant.role_ids.is_empty() {
837        roster.grants.push(grant);
838    }
839
840    // Publish FIRST, then persist the advanced head + roster only on success. Advancing the head
841    // before a fallible publish would leave a phantom head: a failed publish means the next edition
842    // cites an unpublished predecessor, which every fold quarantines as a gap forever. Re-check the
843    // session after the await — it may have straddled an account swap, and persisting then would
844    // write into the wrong account (the edition published under the captured one).
845    transport.publish_durable(&outer, &community.relays).await?;
846    if session.is_valid() {
847        crate::db::community::set_community_roles(&cid, &roster, created_at as i64)?;
848        crate::db::community::set_edition_head(&cid, &entity_hex, version, &self_hash)?;
849    }
850
851    // Revoke-time re-assert (publish-time authority — "Concord Convergence"): a demotion drops the
852    // member's authority, so the author-aware fold would orphan any authority-gated entity the member
853    // currently HEADS. Re-publish those heads as the actor (the `republish_*` helpers gate on the actor's
854    // own permission), so the member's validly-published content survives for EVERY client — fresh joiners
855    // included — and a post-demotion forgery can't win. Skip-if-not-head: only entities the member actually
856    // heads are re-asserted (the common case publishes nothing). Best-effort + per-entity publish-then-
857    // persist inside the helpers (W2). MVP: full revoke only (`role_ids` empty); partial demote is a follow-on.
858    if is_full_revoke && session.is_valid() {
859        if let Ok(folded) = fetch_control_folded(transport, community).await {
860            if session.is_valid() {
861                let current = crate::db::community::load_community(&community.id)?.unwrap_or_else(|| community.clone());
862                if folded.root_author.map(|a| a.to_hex()).as_deref() == Some(member_hex) {
863                    if let Some(meta) = &folded.root_meta {
864                        let mut c = current.clone();
865                        c.name = meta.name.clone();
866                        c.description = meta.description.clone();
867                        c.icon = meta.icon.clone();
868                        c.banner = meta.banner.clone();
869                        let _ = republish_community_metadata(transport, &c).await;
870                    }
871                }
872                for cm in &folded.channel_meta {
873                    if cm.author.to_hex() == member_hex
874                        && current.channels.iter().any(|ch| ch.id.0 == cm.channel_id)
875                    {
876                        let _ = republish_channel_metadata(
877                            transport, &current, &crate::community::ChannelId(cm.channel_id), &cm.meta.name,
878                        ).await;
879                    }
880                }
881            }
882        }
883    }
884    Ok(())
885}
886
887/// True iff the local user is the PROVEN owner of this community — derived by verifying the owner
888/// attestation against `my_public_key()` (keyless: the owner is the npub that signed the attestation
889/// binding this community_id). The check honest clients use to gate
890/// owner-only actions (mint invites, set images) and to render the owner crown.
891pub fn is_proven_owner(community: &Community) -> bool {
892    match crate::state::my_public_key() {
893        Some(me) => proven_owner_hex(community).as_deref() == Some(me.to_hex().as_str()),
894        None => false,
895    }
896}
897
898/// True iff the local user may manage roles — i.e. holds the `MANAGE_ROLES` permission.
899/// Permission-based, NOT a hardcoded owner check: the owner is simply the uppermost role and holds
900/// every permission; any member granted a role carrying `MANAGE_ROLES` qualifies just the same.
901pub fn caller_can_manage_roles(community: &Community) -> bool {
902    let me = match crate::state::my_public_key() {
903        Some(p) => p,
904        None => return false,
905    };
906    let cid = community.id.to_hex();
907    let is_owner = community
908        .owner_attestation
909        .as_ref()
910        .and_then(|a| super::owner::verify_owner_attestation(a, &cid))
911        .map(|pk| pk == me)
912        .unwrap_or(false);
913    if is_owner {
914        return true; // the uppermost role holds all permissions
915    }
916    crate::db::community::get_community_roles(&cid)
917        .unwrap_or_default()
918        .has_permission(&me.to_hex(), super::roles::Permissions::MANAGE_ROLES)
919}
920
921/// Does the local user hold `permission` in this community? The generalized [`caller_can_manage_roles`]:
922/// owner = supreme (every bit), otherwise the union of their granted roles' bits (the role engine).
923/// Drives both the capability report and the producer-side authority gates — no hardcoded owner check.
924pub fn caller_has_permission(community: &Community, permission: u64) -> bool {
925    let me = match crate::state::my_public_key() {
926        Some(p) => p,
927        None => return false,
928    };
929    crate::db::community::get_community_roles(&community.id.to_hex())
930        .unwrap_or_default()
931        .is_authorized(&me.to_hex(), proven_owner_hex(community).as_deref(), permission)
932}
933
934/// Can the local caller grant/revoke `role_id` — i.e. do they hold `MANAGE_ROLES` AND outrank that role's
935/// position? The crown's gate, expressed as the POSITION rule (NOT an owner check): the owner is just
936/// position 0, so in the single-@admin-role MVP this resolves to "owner only" because the @admin role sits
937/// directly below position 0 — but it generalizes to any role hierarchy. `false` if the role is unknown.
938pub fn caller_can_manage_role_id(community: &Community, role_id: &str) -> bool {
939    let me = match crate::state::my_public_key() {
940        Some(p) => p.to_hex(),
941        None => return false,
942    };
943    let roster = crate::db::community::get_community_roles(&community.id.to_hex()).unwrap_or_default();
944    let position = match roster.role(role_id) {
945        Some(r) => r.position,
946        None => return false,
947    };
948    roster.can_manage_position(&me, proven_owner_hex(community).as_deref(), position)
949}
950
951/// The local user's effective management capabilities in a community, resolved purely by the role engine
952/// (positions + permission bits; the owner is just the role at position 0 — NOTHING is owner-hardcoded).
953/// The frontend gates each management affordance on the matching bit, so an admin whose role carries a
954/// permission gets the exact same affordance as the owner.
955#[derive(Debug, Clone, Default, serde::Serialize)]
956pub struct CommunityCapabilities {
957    pub manage_metadata: bool,
958    pub manage_channels: bool,
959    pub create_invite: bool,
960    pub kick: bool,
961    pub ban: bool,
962    pub manage_messages: bool,
963    pub manage_roles: bool,
964}
965
966pub fn caller_capabilities(community: &Community) -> CommunityCapabilities {
967    use super::roles::Permissions as P;
968    let me_hex = match crate::state::my_public_key() {
969        Some(p) => p.to_hex(),
970        None => return CommunityCapabilities::default(),
971    };
972    let owner = proven_owner_hex(community);
973    let roster = crate::db::community::get_community_roles(&community.id.to_hex()).unwrap_or_default();
974    let has = |bit: u64| roster.is_authorized(&me_hex, owner.as_deref(), bit);
975    CommunityCapabilities {
976        manage_metadata: has(P::MANAGE_METADATA),
977        manage_channels: has(P::MANAGE_CHANNELS),
978        create_invite: has(P::CREATE_INVITE),
979        kick: has(P::KICK),
980        ban: has(P::BAN),
981        manage_messages: has(P::MANAGE_MESSAGES),
982        manage_roles: has(P::MANAGE_ROLES),
983    }
984}
985
986/// The pinned authority citation the local user attaches to a control action — points at their
987/// OWN authorizing Grant edition (stable community-scoped coordinate + its current head version/hash),
988/// so every verifier resolves the action's authority against that exact point instead of their own
989/// possibly-lagging-or-ahead live roster. `None` when the local user is the proven owner (supreme —
990/// owner actions cite nothing) or has no grant head to cite (an unauthorized actor — the send-side
991/// authority gate refuses them before a citation would matter). See
992/// [`super::roster::authority_citation_satisfied`] for the verifier side.
993fn authority_citation(community: &Community, actor_hex: &str) -> Option<super::edition::AuthorityCitation> {
994    if proven_owner_hex(community).as_deref() == Some(actor_hex) {
995        return None;
996    }
997    let cid = community.id.to_hex();
998    let actor_bytes = crate::simd::hex::hex_to_bytes_32(actor_hex);
999    let entity_id = super::derive::grant_locator(&community.id, &actor_bytes);
1000    let entity_hex = crate::simd::hex::bytes_to_hex_32(&entity_id);
1001    crate::db::community::get_edition_head(&cid, &entity_hex)
1002        .ok()
1003        .flatten()
1004        .map(|(version, edition_hash)| super::edition::AuthorityCitation { entity_id, version, edition_hash })
1005}
1006
1007/// The proven owner's pubkey (hex), or `None` on an unproven community (no attestation / fails to
1008/// verify). The owner is DERIVED by verifying the attestation, never a bare claim.
1009fn proven_owner_hex(community: &Community) -> Option<String> {
1010    let cid = community.id.to_hex();
1011    community
1012        .owner_attestation
1013        .as_ref()
1014        .and_then(|a| super::owner::verify_owner_attestation(a, &cid))
1015        .map(|pk| pk.to_hex())
1016}
1017
1018/// Can `actor_hex` moderation-hide a message authored by `author_hex` in this community? True iff
1019/// the actor holds MANAGE_MESSAGES and strictly outranks the author (the owner is unhideable). This
1020/// is the SINGLE source of truth for moderation authority — both the publish gate
1021/// (`publish_owner_hide`) and the UI affordance (`get_message_delete_options`) call it, so the
1022/// button shown can never disagree with what the publish will actually allow.
1023pub fn can_moderation_hide(community: &Community, actor_hex: &str, author_hex: &str) -> bool {
1024    // Normalize both identities to hex first. Callers pass a message's stored npub, which Concord
1025    // persists as BECH32 (`opened.author.to_bech32()`), whereas the owner (`proven_owner_hex`) and the
1026    // roster grants are keyed by lowercase HEX. A raw bech32 author matched NEITHER — it skipped
1027    // owner-protection (`owner_hex == target_hex` is hex≠bech32) AND missed the roster position lookup
1028    // (defaulting to u32::MAX, the lowest rank), so an admin wrongly "outranked" and could hide the
1029    // owner. The enforcing `apply_delete` path avoids this by normalizing the same way (PublicKey::parse).
1030    let to_hex = |s: &str| nostr_sdk::PublicKey::parse(s).map(|pk| pk.to_hex()).unwrap_or_else(|_| s.to_string());
1031    let actor = to_hex(actor_hex);
1032    let author = to_hex(author_hex);
1033    let owner = proven_owner_hex(community);
1034    let roster = crate::db::community::get_community_roles(&community.id.to_hex()).unwrap_or_default();
1035    roster.can_act_on_member(&actor, owner.as_deref(), &author, super::roles::Permissions::MANAGE_MESSAGES)
1036}
1037
1038/// Rekey-plane authority with §6 banlist precedence: a positive authority
1039/// lookup can never honor a banned identity. The banlist and the grant-revoke
1040/// are SEPARATE editions a withholding relay can split — without this, a
1041/// since-banned admin whose revoke is withheld still ranks for rotations,
1042/// letting them race their own removal with a re-founding. Read failure
1043/// degrades to "not banned" (the roster gate still fails closed on its own
1044/// read failure); the owner is exempt (supreme, never a valid ban target).
1045fn rotator_is_authorized(
1046    cid: &str,
1047    roster: &super::roles::CommunityRoles,
1048    owner_hex: Option<&str>,
1049    rotator_hex: &str,
1050    permission: u64,
1051) -> bool {
1052    if owner_hex != Some(rotator_hex)
1053        && crate::db::community::get_community_banlist(cid)
1054            .unwrap_or_default()
1055            .iter()
1056            .any(|b| b == rotator_hex)
1057    {
1058        return false;
1059    }
1060    roster.is_authorized(rotator_hex, owner_hex, permission)
1061}
1062
1063/// escalation defense for an authoring action — may the local caller grant/revoke `role_id` on
1064/// `member_hex`? The caller must strictly outrank BOTH the role being changed AND the target member
1065/// (so they can't grant a role at/above their own rank, nor touch a superior member). The owner is
1066/// supreme. Returns a frontend-displayable error if refused. Peers re-run the same predicate on
1067/// receipt (Phase 2) — this is the local half of the same rule.
1068fn caller_can_manage_role(
1069    community: &Community,
1070    roster: &super::roles::CommunityRoles,
1071    role_id: &str,
1072    member_hex: &str,
1073) -> Result<(), String> {
1074    let me = crate::state::my_public_key().ok_or("no active identity")?.to_hex();
1075    let owner = proven_owner_hex(community);
1076    let owner_ref = owner.as_deref();
1077    let role = roster.role(role_id).ok_or("no such role")?;
1078    if !roster.can_manage_position(&me, owner_ref, role.position) {
1079        return Err("you can only manage roles below your own".to_string());
1080    }
1081    if !roster.can_manage_member(&me, owner_ref, member_hex) {
1082        return Err("you can't manage a member who outranks you".to_string());
1083    }
1084    Ok(())
1085}
1086
1087/// Grant `member` a role (requires the `MANAGE_ROLES` permission). Publishes the per-member Grant
1088/// event. The member already holds read keys from membership; the roster entry adds write authority,
1089/// exercised by signing their own control actions, which peers verify against the roster.
1090pub async fn grant_role<T: Transport + ?Sized>(
1091    transport: &T,
1092    community: &Community,
1093    member: nostr_sdk::prelude::PublicKey,
1094    role_id: &str,
1095) -> Result<(), String> {
1096    let cid = community.id.to_hex();
1097    let member_hex = member.to_hex();
1098    let roster = crate::db::community::get_community_roles(&cid)?;
1099    caller_can_manage_role(community, &roster, role_id, &member_hex)?;
1100    // The member's new full role set = existing + this role (deduped).
1101    let mut role_ids: Vec<String> = roster
1102        .grants
1103        .iter()
1104        .find(|g| g.member == member_hex)
1105        .map(|g| g.role_ids.clone())
1106        .unwrap_or_default();
1107    if !role_ids.iter().any(|r| r == role_id) {
1108        role_ids.push(role_id.to_string());
1109    }
1110
1111    // Keyless model: granting a role delivers NO secret. Authority is the grantee's npub being in
1112    // the roster at that rank — they exercise it by signing their own actions, which peers verify
1113    // against the roster.
1114    set_member_grant(transport, community, &member_hex, role_ids).await
1115}
1116
1117/// Revoke a role from `member` (owner/admin authority) — instant *logical* (the role record is
1118/// dropped, so the grant-set check stops honoring their actions). The *physical* lockout
1119/// (channel rekey per) is a later step; this only edits the grant. In the MVP a role is permission
1120/// bits, NOT a channel read key (channels aren't role-gated), so a revoke needs NO rekey and a bunker
1121/// account can do it freely. WHEN role-gated channels ship, the rekey-on-revoke path must adopt the same
1122/// bunker fail-fast guard as `publish_banlist`/`revoke_public_invite` (a rekey needs a raw local key).
1123pub async fn revoke_role<T: Transport + ?Sized>(
1124    transport: &T,
1125    community: &Community,
1126    member: nostr_sdk::prelude::PublicKey,
1127    role_id: &str,
1128) -> Result<(), String> {
1129    let cid = community.id.to_hex();
1130    let member_hex = member.to_hex();
1131    let roster = crate::db::community::get_community_roles(&cid)?;
1132    caller_can_manage_role(community, &roster, role_id, &member_hex)?;
1133    let role_ids: Vec<String> = roster
1134        .grants
1135        .iter()
1136        .find(|g| g.member == member_hex)
1137        .map(|g| g.role_ids.iter().filter(|r| r.as_str() != role_id).cloned().collect())
1138        .unwrap_or_default();
1139    set_member_grant(transport, community, &member_hex, role_ids).await
1140}
1141
1142/// Fetch the Community's role graph (real-npub control editions, kind 3308) and fold it into the
1143/// local roster. Fetches by the **server-root pseudonym** (not by author — the outer is
1144/// ephemeral), opens each edition under the server-root key, and folds: verify authorship, bind
1145/// entity↔content, version-fold, quarantine gaps. Advances each entity's monotonic head (the
1146/// per-entity refuse-downgrade floor) and refreshes the roster cache. Returns the folded roster.
1147pub async fn fetch_and_apply_roles<T: Transport + ?Sized>(
1148    transport: &T,
1149    community: &Community,
1150) -> Result<super::roles::CommunityRoles, String> {
1151    fetch_and_apply_roles_inner(transport, community, None).await
1152}
1153
1154async fn fetch_and_apply_roles_inner<T: Transport + ?Sized>(
1155    transport: &T,
1156    community: &Community,
1157    prefolded: Option<super::roster::FoldedRoster>,
1158) -> Result<super::roles::CommunityRoles, String> {
1159    let session = SessionGuard::capture();
1160    let cid = community.id.to_hex();
1161    let folded = match prefolded {
1162        Some(f) => f,
1163        None => fetch_control_folded(transport, community).await?,
1164    };
1165
1166    if !session.is_valid() {
1167        return Err("account changed during roles fetch".to_string());
1168    }
1169    // NOTE: `folded.gapped_entities` is not consumed yet — the fold is fail-closed by construction
1170    // (gapped heads are never folded into `folded.roles`), so it's safe in the single-writer MVP. Once
1171    // multi-writer + rotation ship, this must suspend any cached entry whose entity is now gapped.
1172    // Advance each entity's head MONOTONICALLY — the per-entity rollback defense (a withholding relay
1173    // serving only old editions can't lower a head; our own publish's echo is a no-op). The roster
1174    // CACHE is a derived view refreshed from the fold; a withholding relay can transiently shrink it,
1175    // but it self-heals on the next quorum fetch and the send side reads the (monotonic) heads, not
1176    // the cache. (`roles_at` is vestigial under the per-entity model — the heads are the floor now.)
1177    for head in &folded.heads {
1178        crate::db::community::set_edition_head(&cid, &head.entity_hex, head.version, &head.self_hash)?;
1179    }
1180    // Don't let an empty/withheld fetch wipe a populated roster cache: only refresh it when the fold
1181    // actually produced editions. The heads above already advanced monotonically (the real floor);
1182    // the cache is a derived view, so on an empty fold we return what we still hold. (Full per-entity
1183    // merge so a PARTIAL fetch can't shrink the cache either is the quorum/completeness work, G1.)
1184    if folded.heads.is_empty() {
1185        return crate::db::community::get_community_roles(&cid);
1186    }
1187    // Authorize: keep only entries whose SIGNER was allowed (delegation chain to the owner).
1188    // A validly-signed+bound-but-unauthorized edition (e.g. a self-signed Admin grant) is dropped here,
1189    // never cached as authority. Owner resolved from the (verified) attestation; unproven → empty.
1190    let authorized = super::roster::authorize_delegation(&folded, proven_owner_hex(community).as_deref());
1191    crate::db::community::set_community_roles(&cid, &authorized, 0)?;
1192    Ok(authorized)
1193}
1194
1195/// Moderation-hide: publish a 3305 delete for another member's message, signed by the actor's
1196/// REAL npub (keyless). Authority is the inner signature, re-verified
1197/// by every member against the owner-rooted roster (MANAGE_MESSAGES + a strict outrank of the
1198/// target's author). Permanent (the tombstone can't be un-published).
1199pub async fn publish_owner_hide<T: Transport + ?Sized>(
1200    transport: &T,
1201    community: &Community,
1202    channel: &Channel,
1203    target_message_id: &str,
1204) -> Result<(), String> {
1205    // hierarchy gate (keyless): I must hold MANAGE_MESSAGES and strictly outrank the target
1206    // message's author — the owner, outranked by no one, can never be hidden. Resolve the author from
1207    // local state (you can only moderate a message you can see). A granted
1208    // MANAGE_MESSAGES member can moderate. Peers RE-verify this against my real-npub inner sig + roster.
1209    let signer = active_signer().await?;
1210    let me_pk = crate::state::my_public_key().ok_or("no local identity to sign the hide")?;
1211    let me = me_pk.to_hex();
1212    {
1213        let target_author = {
1214            let st = crate::state::STATE.lock().await;
1215            st.find_message(target_message_id).and_then(|(_, m)| m.npub)
1216        };
1217        let author = target_author
1218            .ok_or("can't resolve the target message's author to authorize the hide")?;
1219        if !can_moderation_hide(community, &me, &author) {
1220            return Err("you can't hide a message from a member who outranks you (or the owner)".to_string());
1221        }
1222    }
1223    let ms = std::time::SystemTime::now()
1224        .duration_since(std::time::UNIX_EPOCH)
1225        .map(|d| d.as_millis() as u64)
1226        .unwrap_or(0);
1227    // Keyless moderation-hide: a 3305 delete signed by MY REAL npub. The inner signature IS the
1228    // authority proof — every member re-verifies it against
1229    // the roster, so authority is member-visible + non-repudiable, not anonymized.
1230    // pinned authority: a non-owner hider cites the grant that authorizes them, carried as a `vac`
1231    // tag on the inner so peers resolve the hide against that grant version (the owner cites nothing).
1232    let citation = authority_citation(community, &me);
1233    let extra: Vec<Tag> = citation.iter().map(|c| c.to_tag()).collect();
1234    let inner = super::envelope::build_inner_full(
1235        me_pk, &channel.id, channel.epoch,
1236        event_kind::COMMUNITY_DELETE, "", ms, Some(target_message_id), &[], &extra,
1237    )
1238    .sign(&signer)
1239    .await
1240    .map_err(|e| format!("sign hide: {e}"))?;
1241    let _ = publish_signed_message(transport, community, channel, &inner, true).await?;
1242    Ok(())
1243}
1244
1245/// Delete a message the local user previously sent, by its INNER message id (what the UI
1246/// holds). Loads the retained ephemeral key + the outer event id it points at, then
1247/// NIP-09-deletes that outer event. Errors if no key is retained (not ours, or already
1248/// deleted).
1249pub async fn delete_message<T: Transport + ?Sized>(
1250    transport: &T,
1251    message_id: &str,
1252) -> Result<(), String> {
1253    let session = SessionGuard::capture();
1254    if !session.is_valid() {
1255        return Err("account changed; aborting delete".to_string());
1256    }
1257    // PEEK the key (don't consume it yet): the NIP-09 publish below is fallible, and the
1258    // key is single-use — consuming it before a failed publish would leave the message
1259    // permanently undeletable. Remove it only after the deletion actually goes out.
1260    let (ephemeral, outer_event_id_hex, relays) = match crate::db::community::get_message_key(message_id)? {
1261        Some(v) => v,
1262        None => {
1263            return Err("no retained key for this message (not yours, or already deleted)".to_string())
1264        }
1265    };
1266    let id = EventId::from_hex(&outer_event_id_hex).map_err(|e| e.to_string())?;
1267    delete_own_message(transport, &relays, &ephemeral, id).await?;
1268    // Published — now it's safe to consume the key.
1269    crate::db::community::delete_message_key(message_id)?;
1270    Ok(())
1271}
1272
1273/// Accept a parked invite and persist the member-view Community (the user-consented
1274/// half of the carrier — the inbound handler only *parks* invites; this is reached
1275/// from an explicit accept command). Guards against id-collision overwrites:
1276///
1277/// - if we already OWN a Community with this id, refuse (a member-view save would clobber
1278///   our owner state);
1279/// - if we already hold it as a member under a DIFFERENT server root, refuse —
1280/// `community_id` is unauthenticated random bytes, so a hostile bundle reusing
1281///   a known id must not be able to swap out our channel keys / authority / relays.
1282///
1283/// `SessionGuard`-gated: the accept may straddle a relay-fetch in the caller, and the
1284/// save must land in the account that consented.
1285pub fn accept_invite(invite: &CommunityInvite) -> Result<Community, String> {
1286    let session = SessionGuard::capture();
1287    let community = super::invite::accept_invite(invite)?; // validates caps + decodes keys
1288
1289    match crate::db::community::load_community(&community.id)? {
1290        // Already a member: a re-accept doesn't grow the list, so it's exempt from the cap.
1291        Some(existing) => {
1292            if is_proven_owner(&existing) {
1293                return Err("you already own this Community".to_string());
1294            }
1295            // A known community id arriving with a DIFFERENT base key is a different community wearing
1296            // the same id (collision / hijack) — reject rather than overwrite. The server-root key is
1297            // the community's core secret, so it's the keyless authority anchor.
1298            if existing.server_root_key.as_bytes() != community.server_root_key.as_bytes() {
1299                return Err(
1300                    "invite reuses a known Community id under a different authority — rejected"
1301                        .to_string(),
1302                );
1303            }
1304        }
1305        // New membership — reject if we're already at the local community cap.
1306        None => enforce_community_cap()?,
1307    }
1308
1309    if !session.is_valid() {
1310        return Err("account changed during invite accept".to_string());
1311    }
1312    crate::db::community::save_community(&community)?;
1313    Ok(community)
1314}
1315
1316/// Warm a community's primary-channel first page into the RAM preload cache BEFORE the user joins,
1317/// so accepting opens a populated chat instead of paying the join sync. RAM-only and side-effect-
1318/// free: builds the member view from the bundle WITHOUT persisting (nothing is stored for a
1319/// community the user may decline), fetches one page, and stashes it keyed by community id (the
1320/// fetch also warms the relay connection). Best-effort — any failure just leaves Join to sync
1321/// normally. Spawn this behind a `SessionGuard`; promotion on Join re-validates freshness.
1322pub async fn preload_community(invite: &super::invite::CommunityInvite) {
1323    let Ok(community) = super::invite::accept_invite(invite) else { return };
1324    let Some(channel) = community.channels.first() else { return };
1325    let cid = community.id.to_hex();
1326    // Mark in-flight FIRST so a Join that races the fetch adopts it instead of double-fetching.
1327    crate::community::cache::begin_preload(&cid);
1328    let transport = super::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
1329    // Newest page, no `since` (first warm). 50 mirrors the GUI page limit.
1330    match super::send::fetch_channel_page(&transport, &community, channel, None, None, 50).await {
1331        Ok(page) if !page.is_empty() => crate::community::cache::finish_preload(&cid, page),
1332        // Empty page or fetch error → drop the in-flight marker so an adopter falls back at once.
1333        _ => crate::community::cache::abort_preload(&cid),
1334    }
1335
1336    // Warming this invite added its (≤5, capped) relays to the pool. If it never becomes a join
1337    // within the preload window, shed them — an unsolicited or declined invite must not park relays
1338    // in the pool forever (#297). A genuine Join re-warms them via its subscription, so this is safe.
1339    let prune_relays = community.relays.clone();
1340    let prune_id = community.id;
1341    let guard = crate::state::SessionGuard::capture();
1342    tokio::spawn(async move {
1343        tokio::time::sleep(crate::community::cache::PRELOAD_TTL).await;
1344        if !guard.is_valid() {
1345            return;
1346        }
1347        // Joined within the window? Its relays are legitimate now (and its preload entry was already
1348        // taken on accept) — leave them.
1349        if matches!(crate::db::community::load_community(&prune_id), Ok(Some(_))) {
1350            return;
1351        }
1352        // Drop any lingering warm entry, then shed the relays no joined community needs.
1353        crate::community::cache::abort_preload(&prune_id.to_hex());
1354        super::transport::prune_unneeded_community_relays(&prune_relays).await;
1355    });
1356}
1357
1358/// Persist edited Community display metadata and republish the GroupRoot as a real-npub 3308 edition
1359/// (vsk=0) so other members + re-anchoring pick it up. Keyless authority: the actor must hold
1360/// `MANAGE_METADATA` (the owner holds every permission). The caller mutates `community` (name /
1361/// description / icon / banner) first; this gates, saves it, then publishes the next edition version.
1362pub async fn republish_community_metadata<T: Transport + ?Sized>(
1363    transport: &T,
1364    community: &Community,
1365) -> Result<(), String> {
1366    let session = SessionGuard::capture();
1367    let cid = community.id.to_hex();
1368    let signer = active_signer().await?;
1369    let actor_pk = crate::state::my_public_key().ok_or("no local identity to sign the metadata edition")?;
1370    let owner = proven_owner_hex(community);
1371    let roster = crate::db::community::get_community_roles(&cid).unwrap_or_default();
1372    if !roster.is_authorized(&actor_pk.to_hex(), owner.as_deref(), super::roles::Permissions::MANAGE_METADATA) {
1373        return Err("only a member with manage-metadata authority can edit the community".to_string());
1374    }
1375    // Publish-FIRST, then persist content + head on success (now that `fetch_and_apply_metadata` is a
1376    // live consumer, metadata is relay-authoritative: a failed publish must not leave us showing an edit
1377    // no member can see, and advancing the head before a fallible publish would phantom-head it — the
1378    // successor cites an unpublished predecessor → the fold quarantines the chain forever).
1379    let (version, prev_hash) = match crate::db::community::get_edition_head(&cid, &cid)? {
1380        Some((v, h)) => (v + 1, Some(h)),
1381        None => (1, None),
1382    };
1383    let created = std::time::SystemTime::now()
1384        .duration_since(std::time::UNIX_EPOCH)
1385        .map(|d| d.as_secs())
1386        .unwrap_or(0);
1387    let meta = super::metadata::CommunityMetadata::of(community);
1388    // authority citation — the actor's "role badge" (the grant they act under), emitted by EVERY other
1389    // control producer. Owner cites nothing (supreme). The metadata consumer doesn't version-pin on it (a
1390    // metadata edit is cosmetic + self-healing, unlike an access-cutting ban), but emitting it keeps the
1391    // immutable wire data complete rather than baking in a gap.
1392    let citation = authority_citation(community, &actor_pk.to_hex());
1393    let unsigned = super::roster::build_community_root_edition_unsigned(actor_pk, &community.id, &meta, version, prev_hash.as_ref(), created, citation.as_ref())?;
1394    let inner = unsigned.sign(&signer).await.map_err(|e| format!("sign community-root edition: {e}"))?;
1395    let outer = super::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, community.server_root_epoch)?;
1396    transport.publish_durable(&outer, &community.relays).await?;
1397    if session.is_valid() {
1398        crate::db::community::save_community(community)?;
1399        let h = super::version::edition_hash(&community.id.0, version, prev_hash.as_ref(), inner.content.as_bytes());
1400        // Record OUR own edition's inner_id so a peer's same-version fork can't displace it unless that
1401        // peer genuinely wins the deterministic tiebreak (lower inner id), per converge_edition_head.
1402        crate::db::community::set_edition_head_with_id(&cid, &cid, version, &h, &inner.id.to_bytes())?;
1403    }
1404    Ok(())
1405}
1406
1407/// Rename a channel and republish its ChannelMetadata as a real-npub 3308 edition (vsk=2) so
1408/// members fold it via [`fetch_and_apply_metadata`]. Keyless authority: the actor must hold
1409/// `MANAGE_CHANNELS` (channel edits are a channel-management action; the owner holds every permission).
1410/// `channel_id` must be one of `community`'s channels. Publish-FIRST then persist on success (relay-
1411/// authoritative, phantom-head-safe — same contract as the community GroupRoot).
1412pub async fn republish_channel_metadata<T: Transport + ?Sized>(
1413    transport: &T,
1414    community: &Community,
1415    channel_id: &crate::community::ChannelId,
1416    new_name: &str,
1417) -> Result<(), String> {
1418    let session = SessionGuard::capture();
1419    let cid = community.id.to_hex();
1420    let ch_hex = channel_id.to_hex();
1421    if !community.channels.iter().any(|c| &c.id == channel_id) {
1422        return Err("no such channel in this community".to_string());
1423    }
1424    let signer = active_signer().await?;
1425    let actor_pk = crate::state::my_public_key().ok_or("no local identity to sign the channel metadata edition")?;
1426    let owner = proven_owner_hex(community);
1427    let roster = crate::db::community::get_community_roles(&cid).unwrap_or_default();
1428    if !roster.is_authorized(&actor_pk.to_hex(), owner.as_deref(), super::roles::Permissions::MANAGE_CHANNELS) {
1429        return Err("only a member with manage-channels authority can rename a channel".to_string());
1430    }
1431    let (version, prev_hash) = match crate::db::community::get_edition_head(&cid, &ch_hex)? {
1432        Some((v, h)) => (v + 1, Some(h)),
1433        None => (1, None),
1434    };
1435    let created = std::time::SystemTime::now()
1436        .duration_since(std::time::UNIX_EPOCH)
1437        .map(|d| d.as_secs())
1438        .unwrap_or(0);
1439    let meta = super::metadata::ChannelMetadata { name: new_name.to_string() };
1440    // authority citation — same "role badge" the community-root + grant/ban producers emit (owner cites
1441    // nothing). Consumer doesn't version-pin metadata, but the wire data stays complete.
1442    let citation = authority_citation(community, &actor_pk.to_hex());
1443    let unsigned = super::roster::build_channel_metadata_edition_unsigned(actor_pk, channel_id, &meta, version, prev_hash.as_ref(), created, citation.as_ref())?;
1444    let inner = unsigned.sign(&signer).await.map_err(|e| format!("sign channel-metadata edition: {e}"))?;
1445    let outer = super::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, community.server_root_epoch)?;
1446    transport.publish_durable(&outer, &community.relays).await?;
1447    if session.is_valid() {
1448        let mut current = crate::db::community::load_community(&community.id)?.ok_or("community no longer present")?;
1449        if let Some(ch) = current.channels.iter_mut().find(|c| &c.id == channel_id) {
1450            ch.name = new_name.to_string();
1451        }
1452        crate::db::community::save_community(&current)?;
1453        let h = super::version::edition_hash(&channel_id.0, version, prev_hash.as_ref(), inner.content.as_bytes());
1454        crate::db::community::set_edition_head_with_id(&cid, &ch_hex, version, &h, &inner.id.to_bytes())?;
1455    }
1456    Ok(())
1457}
1458
1459// ============================================================================
1460// Public (link) invites
1461// ============================================================================
1462
1463/// Mint a public invite link for a Community the local user owns: snapshot its preview,
1464/// build + publish the token-encrypted bundle to the Community relays, retain the token
1465/// locally (for list/revoke), and return `(hex token, shareable URL)`.
1466///
1467/// Owner-only: the bundle grants the @everyone base (server-root) key, and minting the
1468/// canonical link is an owner action. `SessionGuard`-gated around the token persist.
1469/// A short, human-typable label for an unlabeled invite link. Crockford-ish base32 (no 0/1/I/O)
1470/// so it's unambiguous to read and share aloud; 6 chars ≈ 1B combinations (collision-improbable).
1471fn generate_invite_label() -> String {
1472    use rand::Rng;
1473    const ALPHABET: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1474    let mut rng = rand::thread_rng();
1475    (0..6).map(|_| ALPHABET[rng.gen_range(0..ALPHABET.len())] as char).collect()
1476}
1477
1478pub async fn create_public_invite<T: Transport + ?Sized>(
1479    transport: &T,
1480    community: &Community,
1481    expires_at: Option<u64>,
1482    label: Option<String>,
1483) -> Result<(String, String), String> {
1484    if !caller_has_permission(community, super::roles::Permissions::CREATE_INVITE) {
1485        return Err("you need the create-invite permission to mint a public invite".to_string());
1486    }
1487    let session = SessionGuard::capture();
1488
1489    // Every link gets a label: use the one provided, else mint a random 6-char handle. A stable label
1490    // makes the link identifiable in the UI and keys per-link join attribution off (creator, label),
1491    // so it must be unique among THIS creator's links (else two links share a join bucket).
1492    let existing = crate::db::community::list_public_invites(&community.id.to_hex()).unwrap_or_default();
1493    let label_taken = |cand: &str| {
1494        existing.iter().any(|r| r.label.as_deref().map(|e| e.eq_ignore_ascii_case(cand)).unwrap_or(false))
1495    };
1496    let label = match label {
1497        Some(l) if !l.trim().is_empty() => {
1498            let l = l.trim().to_string();
1499            if label_taken(&l) {
1500                return Err(format!("You already have an invite link labeled \u{201c}{l}\u{201d}. Pick a different label."));
1501            }
1502            Some(l)
1503        }
1504        // Random handle — regenerate on the (astronomically unlikely) collision.
1505        _ => {
1506            let mut l = generate_invite_label();
1507            while label_taken(&l) {
1508                l = generate_invite_label();
1509            }
1510            Some(l)
1511        }
1512    };
1513
1514    // Attribution (metrics): stamp the bundle with who minted it (my npub) + the creator's label, so
1515    // a joiner's Presence can announce "invited by me via <label>".
1516    let creator_npub = crate::state::my_public_key().and_then(|pk| pk.to_bech32().ok());
1517    let token = public_invite::new_token();
1518    let event = build_public_invite_event(community, &token, expires_at, creator_npub, label.clone()).map_err(|e| e.to_string())?;
1519    transport.publish_durable(&event, &community.relays).await?;
1520
1521    // Published — retain the token so the owner can list + revoke. Bail if the account
1522    // swapped across the publish await.
1523    if !session.is_valid() {
1524        return Err("account changed during public invite creation".to_string());
1525    }
1526    let token_hex = crate::simd::hex::bytes_to_hex_32(&token);
1527    let url = public_invite::encode_invite_url(&community.relays, &token);
1528    crate::db::community::save_public_invite(
1529        &token_hex,
1530        &community.id.to_hex(),
1531        &url,
1532        expires_at.map(|e| e as i64),
1533        label.as_deref(),
1534    )?;
1535    // Record the token in the self-encrypted Invite List so our other devices can see + copy + revoke this
1536    // link (the local token store is device-only). Sibling to the Community List, debounced republish.
1537    super::invite_list::add_invite(super::invite_list::InviteEntry {
1538        token: token_hex.clone(),
1539        community_id: community.id.to_hex(),
1540        url: url.clone(),
1541        label: label.clone(),
1542        created_at: std::time::SystemTime::now()
1543            .duration_since(std::time::UNIX_EPOCH)
1544            .map(|d| d.as_secs())
1545            .unwrap_or(0),
1546        expires_at,
1547    });
1548    // Publish MY updated invite-link set so every member's computed mode flips to Public — the link
1549    // now exists in the signed, foldable per-creator source of truth, not just my local token store.
1550    republish_my_invite_links(transport, community).await?;
1551    Ok((token_hex, url))
1552}
1553
1554/// Read-only freshen for an invite preview: build the bundle's ephemeral community, fold the live
1555/// control plane, and return the LATEST authorized display metadata — never the bundle's mint-time
1556/// snapshot (which goes stale the moment metadata is edited; mirrors the website preview). No DB
1557/// floors and no persistence: the previewer isn't a member, so there is no local state to anchor.
1558/// Any failure falls back to the snapshot so a flaky relay can't blank the preview.
1559pub async fn latest_invite_preview<T: Transport + ?Sized>(
1560    transport: &T,
1561    bundle: &public_invite::PublicInviteBundle,
1562) -> public_invite::PublicInvitePreview {
1563    let snapshot = bundle.preview.clone();
1564    let Ok(community) = super::invite::accept_invite(&bundle.join) else {
1565        return snapshot;
1566    };
1567    let Ok(folded) = fetch_control_folded(transport, &community).await else {
1568        return snapshot;
1569    };
1570    let owner = proven_owner_hex(&community);
1571    let authorized = super::roster::authorize_delegation(&folded, owner.as_deref());
1572    match folded.root_candidates.iter().find(|c| {
1573        authorized.is_authorized(&c.author.to_hex(), owner.as_deref(), super::roles::Permissions::MANAGE_METADATA)
1574    }) {
1575        Some(c) => public_invite::PublicInvitePreview {
1576            name: c.meta.name.clone(),
1577            description: c.meta.description.clone(),
1578            icon: c.meta.icon.clone(),
1579        },
1580        None => snapshot,
1581    }
1582}
1583
1584/// Fetch + decrypt the bundle for a public-invite token from the given bootstrap relays.
1585/// Queries the addressable coordinate (`d` = token locator, author = token signer) and
1586/// verifies the signer, so an impostor squatting the locator is rejected.
1587pub async fn fetch_public_invite<T: Transport + ?Sized>(
1588    transport: &T,
1589    relays: &[String],
1590    token: &[u8; 32],
1591) -> Result<PublicInviteBundle, String> {
1592    // Query by coordinate (kind + locator d-tag) only — do NOT rely on the relay to
1593    // honor an authors filter. A hostile relay can pile junk events at the same locator
1594    // (signed by other keys, possibly with a newer created_at to shadow the real one).
1595    let query = Query {
1596        kinds: vec![event_kind::APPLICATION_SPECIFIC],
1597        d_tags: vec![locator_hex(token)],
1598        ..Default::default()
1599    };
1600    let events = transport.fetch(&query, relays).await?;
1601    // Resolve by the NEWEST token-signed event at the coordinate (replaceable-event semantics), skipping any
1602    // impostor/junk (parse enforces author == token signer). A revocation tombstone is unforgeable, so a
1603    // `Revoked` verdict on ANY relay is authoritative — and it WINS ties with a bundle (fail-safe: a
1604    // deliberate revoke beats a same-second bundle), defeating the mixed-relay race where one relay kept the
1605    // stale live bundle. A genuinely re-created link (a bundle STRICTLY newer than the tombstone) still wins.
1606    let (mut bundle_at, mut bundle, mut revoked_at) = (0u64, None, None::<u64>);
1607    for ev in &events {
1608        match parse_public_invite_event(ev, token) {
1609            Ok(b) => if bundle.is_none() || ev.created_at.as_secs() > bundle_at {
1610                bundle_at = ev.created_at.as_secs();
1611                bundle = Some(b);
1612            },
1613            Err(super::public_invite::PublicInviteError::Revoked) => {
1614                let at = ev.created_at.as_secs();
1615                if revoked_at.map_or(true, |r| at > r) { revoked_at = Some(at); }
1616            }
1617            Err(_) => {} // impostor / junk / undecryptable — ignore
1618        }
1619    }
1620    match (bundle, revoked_at) {
1621        (Some(b), Some(r)) if bundle_at > r => Ok(b), // a re-created bundle strictly newer than the tombstone
1622        (_, Some(_)) => Err("this invite was revoked".to_string()),
1623        (Some(b), None) => Ok(b),
1624        (None, None) => Err("no public invite found at that link (revoked, never posted, or shadowed)".to_string()),
1625    }
1626}
1627
1628/// Accept a fetched public-invite bundle: reject if expired, join via the guarded
1629/// member-save (caps + id-collision checks), then patch in the preview's display
1630/// metadata (description/icon) so the new member sees them immediately.
1631pub fn accept_public_invite(bundle: &PublicInviteBundle, now_secs: u64) -> Result<Community, String> {
1632    if bundle.is_expired(now_secs) {
1633        return Err("this invite link has expired".to_string());
1634    }
1635    let mut community = accept_invite(&bundle.join)?;
1636    // accept_invite leaves display metadata None; the public bundle carries a preview,
1637    // so populate it (and re-save) for an immediately-rich member view.
1638    if bundle.preview.description.is_some() || bundle.preview.icon.is_some() {
1639        community.description = bundle.preview.description.clone();
1640        community.icon = bundle.preview.icon.clone();
1641        crate::db::community::save_community(&community)?;
1642    }
1643    Ok(community)
1644}
1645
1646/// Revoke a public invite: NIP-09-delete the bundle event (by its addressable coordinate, signed by the
1647/// token-derived key we re-derive from the retained token), forget the token locally, and republish the
1648/// invite-link registry so the mode tracks reality. **If this was the LAST link, the community goes
1649/// Private → it is re-founded (privatize): the base key is rotated to the observed-participants set,
1650/// sealing out link-joined lurkers who never spoke.** Creator-only: you can only retire YOUR OWN
1651/// links (the token is held only by its creator); the privatize rekey is `BAN`-gated + needs a local key.
1652pub async fn revoke_public_invite<T: Transport + ?Sized>(
1653    transport: &T,
1654    community: &Community,
1655    token: &[u8; 32],
1656) -> Result<(), String> {
1657    let session = SessionGuard::capture();
1658    let cid = community.id.to_hex();
1659    let token_hex = crate::simd::hex::bytes_to_hex_32(token);
1660    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
1661    // Idempotent no-op if we don't hold the token: either it's already retired (re-revoke) or it's not
1662    // ours — creator-only, the token is held only by its creator. Nothing to do, never a double-rotate.
1663    if !crate::db::community::list_public_invites(&cid)?.iter().any(|r| r.token == token_hex) {
1664        return Ok(());
1665    }
1666    let my_locators_before: Vec<String> = crate::db::community::list_public_invites(&cid)?
1667        .iter()
1668        .filter(|r| r.expires_at.map_or(true, |e| (e as u64) > now))
1669        .map(|r| public_invite::locator_hex(&crate::simd::hex::hex_to_bytes_32(&r.token)))
1670        .collect();
1671    // B1 fix: refresh the aggregate from relays FIRST, so the privatize decision sees OTHER creators'
1672    // live links (a stale/scroll-back-only cache would wrongly read empty and rekey a still-Public
1673    // community out from under another creator). Best-effort; on failure we fall back to the cache.
1674    let _ = fetch_and_apply_invite_links(transport, community).await;
1675    if !session.is_valid() {
1676        return Err("account changed during invite revoke".to_string());
1677    }
1678    // Will retiring this link empty the AGGREGATE (this creator's remaining ∪ every other creator's)?
1679    // Others' locators = the freshly-folded aggregate minus mine (locators are per-token-unique). Only
1680    // then does it privatize → re-found rekey. Fail-fast (bunker): the rekey needs a RAW local key
1681    // (the blob locator is an ECDH a NIP-46 bunker can't expose) — refuse BEFORE publishing so we never
1682    // half-apply (flip to Private over a live base key). A community admin with a local key privatizes.
1683    let this_locator = public_invite::locator_hex(token);
1684    let cached_aggregate: std::collections::BTreeSet<String> =
1685        crate::db::community::get_community_invite_registry(&cid)?.into_iter().collect();
1686    let my_before: std::collections::BTreeSet<String> = my_locators_before.iter().cloned().collect();
1687    let others: std::collections::BTreeSet<String> = cached_aggregate.difference(&my_before).cloned().collect();
1688    let my_after: std::collections::BTreeSet<String> =
1689        my_before.iter().filter(|l| **l != this_locator).cloned().collect();
1690    let would_empty_aggregate = others.is_empty() && my_after.is_empty();
1691    if would_empty_aggregate && crate::state::MY_SECRET_KEY.to_keys().is_none() {
1692        return Err("Revoking this last invite link makes the community private, which re-keys it so link-joined lurkers lose access. Your account signs remotely (a NIP-46 bunker) and can't perform that rotation. Ask a community admin who holds a local key to privatize the community.".to_string());
1693    }
1694    // Revoke the bundle by OVERWRITING it with an empty, token-signed revocation tombstone (vsk=9) at its
1695    // coordinate. The bundle is a replaceable event (kind 30078), and relays honor replaceable-event
1696    // REPLACEMENT near-universally — far more reliably than NIP-09 `a`-tag (coordinate) deletions, which
1697    // many relays silently ignore (live-confirmed: 2 of 3 relays kept the bundle after a coordinate delete,
1698    // but all 3 replaced it with the tombstone). So the tombstone alone reliably kills the live bundle on
1699    // every relay AND leaves an explicit marker the preview page reads as "revoked". A NIP-09 delete is not
1700    // just redundant but counterproductive: on a relay that honors it, a same-second delete can drop the
1701    // tombstone too, leaving the coordinate empty and losing the revoked marker. (Not the access cut — the
1702    // rekey below is.) Best-effort so a publish hiccup can't block the rekey; publish_durable retries.
1703    if let Ok(tombstone) = public_invite::build_public_invite_tombstone(token) {
1704        let _ = transport.publish_durable(&tombstone, &community.relays).await;
1705    }
1706    // Re-check the session straddling the publish await before any per-account DB write (B2).
1707    if !session.is_valid() {
1708        return Err("account changed during invite revoke".to_string());
1709    }
1710    crate::db::community::delete_public_invite(&token_hex)?;
1711    // Tombstone it in the self-encrypted Invite List so our other devices drop the link too (and a stale
1712    // device can't resurrect it). Terminal: a token is never re-minted.
1713    super::invite_list::revoke_invite(&token_hex, &cid);
1714    // Republish MY (reduced) link set so the mode reflects the removal, then set the recomputed aggregate.
1715    republish_my_invite_links(transport, community).await?;
1716    if session.is_valid() {
1717        let aggregate_after: Vec<String> = others.union(&my_after).cloned().collect();
1718        crate::db::community::set_community_invite_registry(&cid, &aggregate_after)?;
1719    }
1720    if would_empty_aggregate {
1721        // Aggregate empty → a genuine Public→Private transition → re-found (re-seal base to observed).
1722        // Durable (read_cut_pending): a failed privatize re-seal is resumed on the next ban or sync, like a
1723        // ban read-cut — not silently dropped, which would leave it half-private.
1724        run_read_cut(transport, community, true).await?;
1725    }
1726    Ok(())
1727}
1728
1729/// owner dissolution ("Delete Community") — publish the terminal GroupDissolved tombstone, then seal
1730/// locally. The owner's ONLY honest exit (a bare leave would orphan the chain root). Order (defense in
1731/// depth): (a) authority — the caller MUST be the proven owner (a BAN admin is NOT enough — ending the
1732/// community for everyone is the owner's call alone); (b) publish the tombstone at `dissolved_locator`
1733/// FIRST and require it to LAND (must-succeed durable publish — a failed tombstone after a link-retire is a
1734/// stuck half-state); (c) THEN best-effort retire all of the owner's OWN public invite-link editions on a
1735/// path that emits NO 3303 rekey and NO epoch bump (dissolution rotates nothing — there is no future
1736/// content to protect); (d) set the local seal. Irreversible.
1737/// Probe the ROTATION-STABLE dissolved coordinate for a tombstone signed by `owner_hex`. The
1738/// cross-epoch discovery path: it fetches `dissolved_pseudonym` (community-id-derived, epoch-free) and
1739/// opens under the community-id envelope key, so a client holding ANY epoch root finds it. Best-effort
1740/// (a relay miss ⇒ false; the next sync re-probes). The caller has already derived + verified the owner.
1741async fn dissolved_tombstone_present<T: Transport + ?Sized>(transport: &T, community: &Community, owner_hex: &str) -> bool {
1742    let z = super::derive::dissolved_pseudonym(&community.id);
1743    let q = Query { kinds: vec![event_kind::COMMUNITY_CONTROL], z_tags: vec![z], ..Default::default() };
1744    for ev in transport.fetch(&q, &community.relays).await.unwrap_or_default() {
1745        if super::roster::dissolved_tombstone_signer(&ev, &community.id).map(|s| s.to_hex()) == Some(owner_hex.to_string()) {
1746            return true;
1747        }
1748    }
1749    false
1750}
1751
1752pub async fn dissolve_community<T: Transport + ?Sized>(
1753    transport: &T,
1754    community: &Community,
1755) -> Result<(), String> {
1756    let session = SessionGuard::capture();
1757    let cid = community.id.to_hex();
1758
1759    // (a) Authority: owner-only, derived from the deed (never a cached claim). Stricter than re-founding.
1760    if !is_proven_owner(community) {
1761        return Err("only the community owner can dissolve (delete) the community".to_string());
1762    }
1763    let signer = active_signer().await?;
1764    let actor_pk = crate::state::my_public_key().ok_or("no local identity to sign the dissolution")?;
1765
1766    // (b) Tombstone FIRST, must-succeed. The marker is the whole mechanism; build it chain-free (vsk=10,
1767    // fixed v1, no prev-hash) and seal under the CURRENT server root for the wire (re-anchoring keeps the
1768    // plane reachable there). A durable publish that fails returns Err so we never half-apply.
1769    let created_at = std::time::SystemTime::now()
1770        .duration_since(std::time::UNIX_EPOCH)
1771        .map(|d| d.as_secs())
1772        .unwrap_or(0);
1773    let unsigned = super::roster::build_group_dissolved_edition_unsigned(actor_pk, &community.id, created_at);
1774    let inner = unsigned.sign(&signer).await.map_err(|e| format!("sign dissolution tombstone: {e}"))?;
1775    // Publish at the ROTATION-STABLE coordinate — the load-bearing path: a community-id-keyed
1776    // envelope at `dissolved_pseudonym`, found + openable by any client at any epoch, so a concurrent
1777    // re-founding can't strand the tombstone at an old epoch and let post-rotation joiners see a live group.
1778    let stable = super::roster::seal_dissolved_edition(&Keys::generate(), &inner, &community.id)?;
1779    transport.publish_durable(&stable, &community.relays).await?;
1780    // Also publish at the current `control_pseudonym` (a current-epoch fast path so members fold it in their
1781    // normal control fetch without the extra probe). Best-effort — the stable publish above is the guarantee.
1782    if let Ok(outer) = super::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, community.server_root_epoch) {
1783        let _ = transport.publish_durable(&outer, &community.relays).await;
1784    }
1785    if !session.is_valid() {
1786        return Err("account changed during dissolution".to_string());
1787    }
1788
1789    // (c) Best-effort retire the owner's OWN public invite-link editions WITHOUT the privatize re-founding
1790    // path: publish an empty per-creator link set (NO 3303 rekey, NO epoch bump — that rekey lives only in
1791    // `revoke_public_invite`) and tombstone+delete each owned token. A failure here is harmless (the
1792    // tombstone above already ends the community + an honest joiner refuses the stable-locator-dissolved
1793    // group). Skipped if we lack CREATE_INVITE (no links to retire).
1794    if caller_has_permission(community, super::roles::Permissions::CREATE_INVITE) {
1795        let _ = publish_my_invite_links(transport, community, &[]).await;
1796        if let Ok(records) = crate::db::community::list_public_invites(&cid) {
1797            for r in records {
1798                let token = crate::simd::hex::hex_to_bytes_32(&r.token);
1799                if let Ok(tombstone) = public_invite::build_public_invite_tombstone(&token) {
1800                    let _ = transport.publish_durable(&tombstone, &community.relays).await;
1801                }
1802                let _ = crate::db::community::delete_public_invite(&r.token);
1803            }
1804        }
1805    }
1806
1807    // (d) Seal locally — permanent. Re-check the session straddling the awaits before the per-account write.
1808    if !session.is_valid() {
1809        return Err("account changed during dissolution".to_string());
1810    }
1811    crate::db::community::set_community_dissolved(&cid)?;
1812    Ok(())
1813}
1814
1815/// Publish the LOCAL user's OWN invite-link set as a `CREATE_INVITE`-gated vsk=8 control edition at
1816/// their per-creator coordinate — one of the per-creator lists members fold into the aggregate active-set.
1817/// `my_locators` is the FULL new set of THIS creator's active link locators (hex; the token in the URL is
1818/// the secret, never listed). Publish FIRST, then advance the head + merge into the cached aggregate on
1819/// success (relay-authoritative + phantom-head rule). A creator manages only their own list — no
1820/// `MANAGE_INVITES`. Carries the actor's `vac` citation so a non-owner creator's authority is verifiable.
1821pub async fn publish_my_invite_links<T: Transport + ?Sized>(
1822    transport: &T,
1823    community: &Community,
1824    my_locators: &[String],
1825) -> Result<(), String> {
1826    let session = SessionGuard::capture();
1827    if !caller_has_permission(community, super::roles::Permissions::CREATE_INVITE) {
1828        return Err("you need the create-invite permission to publish invite links".to_string());
1829    }
1830    let cid = community.id.to_hex();
1831    let signer = active_signer().await?;
1832    let actor_pk = crate::state::my_public_key().ok_or("no local identity to sign the invite links")?;
1833    let entity_id = super::derive::invite_links_locator(&community.id, &actor_pk.to_bytes());
1834    let entity_hex = crate::simd::hex::bytes_to_hex_32(&entity_id);
1835    let (version, prev_hash) = match crate::db::community::get_edition_head(&cid, &entity_hex)? {
1836        Some((v, h)) => (v + 1, Some(h)),
1837        None => (1, None),
1838    };
1839    let created_at = std::time::SystemTime::now()
1840        .duration_since(std::time::UNIX_EPOCH)
1841        .map(|d| d.as_secs())
1842        .unwrap_or(0);
1843    // pinned authority: a non-owner creator cites the grant that authorizes them (owner cites nothing).
1844    let citation = authority_citation(community, &actor_pk.to_hex());
1845    let unsigned = super::roster::build_invite_links_edition_unsigned(actor_pk, &community.id, my_locators, version, prev_hash.as_ref(), created_at, citation.as_ref())?;
1846    let inner = unsigned.sign(&signer).await.map_err(|e| format!("sign invite-links edition: {e}"))?;
1847    let outer = super::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, community.server_root_epoch)?;
1848    let self_hash = super::version::edition_hash(&entity_id, version, prev_hash.as_ref(), inner.content.as_bytes());
1849    transport.publish_durable(&outer, &community.relays).await?;
1850    if session.is_valid() {
1851        crate::db::community::set_edition_head(&cid, &entity_hex, version, &self_hash)?;
1852        // Optimistically merge MY locators into the cached aggregate so `is_public` is right immediately;
1853        // the next `fetch_and_apply_invite_links` recomputes the authoritative union across all creators.
1854        let mut agg: std::collections::BTreeSet<String> =
1855            crate::db::community::get_community_invite_registry(&cid)?.into_iter().collect();
1856        agg.extend(my_locators.iter().cloned());
1857        crate::db::community::set_community_invite_registry(&cid, &agg.into_iter().collect::<Vec<_>>())?;
1858        crate::db::community::upsert_invite_link_set(&cid, &actor_pk.to_hex(), my_locators)?;
1859    }
1860    Ok(())
1861}
1862
1863/// Fetch the control plane and apply the folded invite-link AGGREGATE locally: UNION the locators of
1864/// every per-creator vsk=8 edition whose `creator` held `CREATE_INVITE` in the AUTHORIZED roster (the
1865/// keyless gate, same shape as the banlist's BAN check), advancing each authorized creator's head
1866/// (refuse-downgrade). The union is the source of truth for the Public/Private mode (`is_public`) + the
1867/// metrics — NOT join-gating (joining is envelope-only). Returns the aggregate set (empty = Private).
1868pub async fn fetch_and_apply_invite_links<T: Transport + ?Sized>(
1869    transport: &T,
1870    community: &Community,
1871) -> Result<Vec<String>, String> {
1872    fetch_and_apply_invite_links_inner(transport, community, None).await
1873}
1874
1875async fn fetch_and_apply_invite_links_inner<T: Transport + ?Sized>(
1876    transport: &T,
1877    community: &Community,
1878    prefolded: Option<super::roster::FoldedRoster>,
1879) -> Result<Vec<String>, String> {
1880    let session = SessionGuard::capture();
1881    let cid = community.id.to_hex();
1882    let folded = match prefolded {
1883        Some(f) => f,
1884        None => fetch_control_folded(transport, community).await?,
1885    };
1886    if !session.is_valid() {
1887        return Err("account changed during invite-links fetch".to_string());
1888    }
1889    let owner = proven_owner_hex(community);
1890    let authorized = super::roster::authorize_delegation(&folded, owner.as_deref());
1891    let mut aggregate: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
1892    // Per-creator sets (attribution) for the "X has N active invite links" UI.
1893    let mut per_creator: Vec<crate::db::community::InviteLinkSetRow> = Vec::new();
1894    for set in &folded.invite_link_sets {
1895        // authority: only a creator who held CREATE_INVITE counts. A self-minted list from an
1896        // unpermissioned member is dropped (the inner sig proves authorship, not authority).
1897        if !authorized.is_authorized(&set.creator.to_hex(), owner.as_deref(), super::roles::Permissions::CREATE_INVITE) {
1898            continue;
1899        }
1900        let held = crate::db::community::get_edition_head(&cid, &set.head.entity_hex)?.map(|(v, _)| v).unwrap_or(0);
1901        if set.head.version > held {
1902            crate::db::community::set_edition_head(&cid, &set.head.entity_hex, set.head.version, &set.head.self_hash)?;
1903        }
1904        aggregate.extend(set.locators.iter().cloned());
1905        per_creator.push(crate::db::community::InviteLinkSetRow {
1906            creator_hex: set.creator.to_hex(),
1907            locators: set.locators.clone(),
1908        });
1909    }
1910    let aggregate: Vec<String> = aggregate.into_iter().collect();
1911    crate::db::community::set_community_invite_registry(&cid, &aggregate)?;
1912    crate::db::community::replace_invite_link_sets(&cid, &per_creator)?;
1913    Ok(aggregate)
1914}
1915
1916/// Fetch the Community's control plane and apply folded METADATA edits locally: the GroupRoot
1917/// (vsk=0 — community name/description/icon/banner) and each ChannelMetadata (vsk=2 — channel name). An
1918/// edition applies only if its signer held `MANAGE_METADATA` in the AUTHORIZED roster (the keyless 
1919/// gate, same as the producer) AND is strictly newer than the head we hold (refuse-downgrade by version).
1920/// Identity/transport fields (`server_root_key`, `relays`, `owner_attestation`) are NEVER taken from a
1921/// metadata edit — a manage-metadata admin edits DISPLAY, not the community's identity. Best-effort:
1922/// returns `Ok` even when nothing applied. This is what makes an owner/admin's edit sync to every member.
1923pub async fn fetch_and_apply_metadata<T: Transport + ?Sized>(
1924    transport: &T,
1925    community: &Community,
1926) -> Result<(), String> {
1927    fetch_and_apply_metadata_inner(transport, community, None).await
1928}
1929
1930async fn fetch_and_apply_metadata_inner<T: Transport + ?Sized>(
1931    transport: &T,
1932    community: &Community,
1933    prefolded: Option<super::roster::FoldedRoster>,
1934) -> Result<(), String> {
1935    let session = SessionGuard::capture();
1936    let cid = community.id.to_hex();
1937    let folded = match prefolded {
1938        Some(f) => f,
1939        None => fetch_control_folded(transport, community).await?,
1940    };
1941    if !session.is_valid() {
1942        return Err("account changed during metadata fetch".to_string());
1943    }
1944    let owner = proven_owner_hex(community);
1945    let authorized = super::roster::authorize_delegation(&folded, owner.as_deref());
1946    // Community display = MANAGE_METADATA; channel display = MANAGE_CHANNELS (— channel edits are a
1947    // channel-management action, matching `build_channel_metadata_edition`'s contract).
1948    let manage = super::roles::Permissions::MANAGE_METADATA;
1949    let manage_channels = super::roles::Permissions::MANAGE_CHANNELS;
1950
1951    // Apply onto the freshest local state (the caller's struct may predate other syncs). `save_community`
1952    // UPSERTs the community row, so `created_at` (the kick join-anchor) and the banlist are preserved.
1953    let mut current = match crate::db::community::load_community(&community.id)? {
1954        Some(c) => c,
1955        None => return Ok(()),
1956    };
1957    let mut dirty = false;
1958    // (entity_hex, version, self_hash, inner_id, is_converge) of each edition applied — written AFTER a
1959    // successful save. `is_converge` routes a same-version fork-resolution to converge_edition_head; a
1960    // strictly-higher version is a plain advance.
1961    let mut head_updates: Vec<(String, u64, [u8; 32], [u8; 32], bool)> = Vec::new();
1962
1963    // Decide whether a folded display head should apply, and how. A strictly-higher version ADVANCES the
1964    // refuse-downgrade floor. An equal version with a DIFFERENT, lower-inner-id edition CONVERGES a
1965    // concurrent fork: two authorized editors editing from the same base both produce v+1, and every
1966    // client must adopt the same deterministic winner (lowest inner edition id). Mirrors
1967    // converge_edition_head's SQL (a NULL/None held id is "always replaceable") so we never apply a
1968    // display edit the head write would then refuse. `Some(is_converge)` → apply; `None` → keep the floor.
1969    let decide = |entity_hex: &str, head: &super::roster::EntityHead| -> Result<Option<bool>, String> {
1970        let held = crate::db::community::get_edition_head(&cid, entity_hex)?;
1971        let held_v = held.map(|(v, _)| v).unwrap_or(0);
1972        if head.version > held_v {
1973            return Ok(Some(false)); // advance
1974        }
1975        if head.version == held_v && held.map(|(_, h)| h) != Some(head.self_hash) {
1976            let held_id = crate::db::community::get_edition_head_inner_id(&cid, entity_hex)?;
1977            if held_id.is_none() || Some(head.inner_id) < held_id {
1978                return Ok(Some(true)); // converge to the lower-inner-id authorized winner
1979            }
1980        }
1981        Ok(None)
1982    };
1983
1984    // Author-aware descending scan (/ B1b): the candidates are sorted (version desc, inner-id asc), so
1985    // the first whose author CURRENTLY holds MANAGE_METADATA is both the highest-version AND (within a
1986    // version) the deterministic tiebreak winner. Skips a demoted author's editions, incl. a same-version
1987    // forgery. No authorized candidate → keep the floor.
1988    if let Some(c) = folded.root_candidates.iter()
1989        .find(|c| authorized.is_authorized(&c.author.to_hex(), owner.as_deref(), manage))
1990    {
1991        let head = &c.head;
1992        if let Some(is_converge) = decide(&head.entity_hex, head)? {
1993            let meta = &c.meta;
1994            // Apply only the editable display fields.
1995            // `meta.owner_attestation` is DELIBERATELY NOT applied: the owner is the deed, anchored from
1996            // the invite/founding. Letting an editable field redefine it = a one-edit takeover, so
1997            // ownership is NON-TRANSFERABLE for the MVP. (Transfer — and eventually owner quorums — will
1998            // be a deliberate owner-signed action, never a metadata side-effect.)
1999            // `meta.relays` is also dropped for now (silently following an embedded relay list is a
2000            // herding/partition vector). Relay migration is likewise deferred to a first-class,
2001            // permissioned, ADDITIVE (union-not-replace) action.
2002            current.name = meta.name.clone();
2003            current.description = meta.description.clone();
2004            current.icon = meta.icon.clone();
2005            current.banner = meta.banner.clone();
2006            dirty = true;
2007            head_updates.push((head.entity_hex.clone(), head.version, head.self_hash, head.inner_id, is_converge));
2008        }
2009    }
2010    // Channels mirror GroupRoot: per channel, an author-aware descending scan over its candidates (sorted
2011    // version desc, inner-id asc) → the highest whose author CURRENTLY holds MANAGE_CHANNELS, then decide()
2012    // advance/converge. A concurrent same-version rename converges to the same deterministic winner on every
2013    // client; a demoted author's edition (incl. a same-version forgery) is skipped. Candidates arrive grouped
2014    // + sorted per channel, so the first authorized per channel is the winner.
2015    let mut resolved_channels: std::collections::HashSet<[u8; 32]> = std::collections::HashSet::new();
2016    for cm in &folded.channel_candidates {
2017        if resolved_channels.contains(&cm.channel_id) {
2018            continue; // this channel already resolved (its candidates are contiguous + sorted)
2019        }
2020        if !authorized.is_authorized(&cm.author.to_hex(), owner.as_deref(), manage_channels) {
2021            continue; // skip a demoted author; keep scanning lower candidates for this channel
2022        }
2023        resolved_channels.insert(cm.channel_id);
2024        let Some(is_converge) = decide(&cm.head.entity_hex, &cm.head)? else { continue };
2025        if let Some(ch) = current.channels.iter_mut().find(|c| c.id.0 == cm.channel_id) {
2026            ch.name = cm.meta.name.clone();
2027            dirty = true;
2028            head_updates.push((cm.head.entity_hex.clone(), cm.head.version, cm.head.self_hash, cm.head.inner_id, is_converge));
2029        }
2030    }
2031
2032    if dirty && session.is_valid() {
2033        crate::db::community::save_community(&current)?;
2034        // Persist heads in the SAME save block so a subsequent re-assert/edit chains prev_hash from the
2035        // converged head, not a stale one (else the fork regenerates at the next version).
2036        for (entity_hex, version, self_hash, inner_id, is_converge) in &head_updates {
2037            if *is_converge {
2038                crate::db::community::converge_edition_head(&cid, entity_hex, *version, self_hash, inner_id)?;
2039            } else {
2040                crate::db::community::set_edition_head_with_id(&cid, entity_hex, *version, self_hash, inner_id)?;
2041            }
2042        }
2043    }
2044    Ok(())
2045}
2046
2047/// The computed Public/Private mode: a community is PUBLIC iff the folded per-creator invite-link
2048/// aggregate has ≥1 active locator, else PRIVATE. Every member computes the same value from the folded
2049/// editions, which is what lets it drive rekey-on-removal consistently (Private removals rekey the base
2050/// to the roster; Public ones don't — anti-memberlist). Reads the cached aggregate, which is only as
2051/// fresh as the last successful latest-page sync ([`fetch_and_apply_invite_links`], wired best-effort
2052/// into the sync path) — a member who only scrolled back, or whose sync failed, can hold a stale mode
2053/// (which is why `revoke_public_invite` refreshes the aggregate before deciding to privatize).
2054pub fn is_public(community: &Community) -> Result<bool, String> {
2055    Ok(!crate::db::community::get_community_invite_registry(&community.id.to_hex())?.is_empty())
2056}
2057
2058/// Recompute the LOCAL user's OWN invite-link set from their currently-retained public-invite tokens and
2059/// publish it (per-creator), so every member's computed Public/Private mode tracks reality. Returns
2060/// this creator's new active link-locator set (empty = they hold no links). Expired links are dropped —
2061/// they can't be joined, so they don't keep a community Public.
2062async fn republish_my_invite_links<T: Transport + ?Sized>(
2063    transport: &T,
2064    community: &Community,
2065) -> Result<Vec<String>, String> {
2066    let cid = community.id.to_hex();
2067    let now = std::time::SystemTime::now()
2068        .duration_since(std::time::UNIX_EPOCH)
2069        .map(|d| d.as_secs())
2070        .unwrap_or(0);
2071    let locators: Vec<String> = crate::db::community::list_public_invites(&cid)?
2072        .iter()
2073        .filter(|r| r.expires_at.map_or(true, |e| (e as u64) > now))
2074        .map(|r| public_invite::locator_hex(&crate::simd::hex::hex_to_bytes_32(&r.token)))
2075        .collect();
2076    publish_my_invite_links(transport, community, &locators).await?;
2077    Ok(locators)
2078}
2079
2080/// Fetch + INGEST the channel append-plane across ALL held epochs (messages + presence) into the local
2081/// store. The retain set for a rekey is computed from this store (`community_member_activity`), and the
2082/// no-role chatters live ONLY here — not in the control plane — so a privatize/ban must observe it first or
2083/// it would shed anyone the re-founder hasn't already synced. Best-effort per channel; uses the multi-epoch
2084/// fetch so activity under any retained epoch counts. `SessionGuard`-gated across the fetches.
2085async fn observe_channel_activity<T: Transport + ?Sized>(
2086    transport: &T,
2087    community: &Community,
2088) -> Result<(), String> {
2089    let session = SessionGuard::capture();
2090    let my_pk = crate::state::my_public_key().ok_or("no local identity to observe channel activity")?;
2091    for channel in &community.channels {
2092        let events = super::send::fetch_channel_events(transport, community, channel)
2093            .await
2094            .unwrap_or_default();
2095        if !session.is_valid() {
2096            return Err("account changed during activity observation".to_string());
2097        }
2098        let outcomes = {
2099            let mut st = crate::state::STATE.lock().await;
2100            super::inbound::process_channel_batch(&mut st, &events, channel, &my_pk)
2101        };
2102        let ch_hex = channel.id.to_hex();
2103        for o in &outcomes {
2104            match o {
2105                super::inbound::IncomingEvent::NewMessage(m)
2106                | super::inbound::IncomingEvent::Updated { message: m, .. } => {
2107                    let _ = crate::db::events::save_message(&ch_hex, m).await;
2108                }
2109                super::inbound::IncomingEvent::Presence { npub, joined, event_id, created_at, invited_by, invited_label } => {
2110                    let et = if *joined {
2111                        crate::stored_event::SystemEventType::MemberJoined
2112                    } else {
2113                        crate::stored_event::SystemEventType::MemberLeft
2114                    };
2115                    let note = invited_by.as_ref().map(|by| match invited_label {
2116                        Some(l) if !l.is_empty() => format!("{by}|{l}"),
2117                        _ => by.clone(),
2118                    });
2119                    let _ = crate::db::events::save_system_event_at(event_id, &ch_hex, et, npub, note.as_deref(), *created_at, invited_by.as_deref(), invited_label.as_deref()).await;
2120                }
2121                super::inbound::IncomingEvent::WebxdcPeer { npub, topic_id, node_addr, event_id, created_at } => {
2122                    persist_webxdc_signal(&ch_hex, npub, topic_id, node_addr.as_deref(), event_id, *created_at).await;
2123                }
2124                _ => {}
2125            }
2126        }
2127    }
2128    Ok(())
2129}
2130
2131/// FRESHEN-BEFORE-WRITE guard for an administrative write (rekey / ban / kick / grant / revoke / metadata):
2132/// hop any base rotation + fold the LATEST control plane from ALL relays + (for a rekey) ingest channel
2133/// activity, so the write acts on the freshest reachable truth — not just a stale local view. The
2134/// demonstrated bug this fixes: privatizing before observing a member's activity wrongly cut them.
2135///
2136/// BEST-EFFORT, not hard-fail: the refuse-downgrade FLOORS already prevent the write from acting on
2137/// rolled-back state (the fold can't apply below what we hold), so blocking when relays are unreachable
2138/// would only forbid legitimate admin actions during an outage (e.g. you couldn't ban anyone). The one
2139/// hard stop is REMOVAL — if an authorized base rotation has cut us, we must not be writing at all.
2140/// Returns the refreshed community.
2141pub async fn sync_before_admin_write<T: Transport + ?Sized>(
2142    transport: &T,
2143    community: &Community,
2144    observe_activity: bool,
2145) -> Result<Community, String> {
2146    // Hop any base rotation we missed; abort only if it REMOVED us (we shouldn't be writing then).
2147    if catch_up_server_root(transport, community).await?.removed {
2148        return Err("you have been removed from this community".to_string());
2149    }
2150    let community = crate::db::community::load_community(&community.id)?
2151        .ok_or("community gone during admin sync")?;
2152    let cid = community.id.to_hex();
2153    // ONE fresh control fetch+fold from all relays, applied (banlist/roles/metadata/invites) so the roster +
2154    // floors the write reads are as current as the relays can make them; its raw event count doubles as the
2155    // isolation signal (no separate probe). Floors guard against stale/rolled-back data, so we DON'T block on
2156    // "can't confirm latest" — only on true ISOLATION: if we KNOW a control plane exists (we hold edition
2157    // heads) but NO relay returned ANY control event, an admin decision made blind (and unpublishable) must
2158    // not happen. A community with no published plane (no local heads) has nothing to confirm → proceed.
2159    let responded = fetch_and_apply_control(transport, &community).await.map(|n| n > 0).unwrap_or(false);
2160    let hold_local_heads = !crate::db::community::get_all_edition_heads_epoched(&cid)?.is_empty();
2161    if hold_local_heads && !responded {
2162        return Err("can't reach any relay to confirm this community's current state — administrative actions are blocked while offline (try again when connected)".to_string());
2163    }
2164    let community = crate::db::community::load_community(&community.id)?
2165        .ok_or("community gone during admin sync")?;
2166    // For a rekey, ingest channel activity so the retain set sees no-role chatters too (they live only in
2167    // the message/presence history, not the control plane).
2168    if observe_activity {
2169        let _ = observe_channel_activity(transport, &community).await;
2170    }
2171    crate::db::community::load_community(&community.id)?.ok_or("community gone during admin sync".to_string())
2172}
2173
2174/// Drive a read-cut (re-founding) to completion, DURABLY. Sets `read_cut_pending` as the intent BEFORE
2175/// the work and clears it only on full success — so a transient failure (relay outage, power cut, mid-cut
2176/// account swap) leaves it pending, and the next ban OR a community sync ([`retry_pending_read_cut`])
2177/// resumes EXACTLY where it stopped (no double base rotation, channels picked up where they left off).
2178///
2179/// `fresh` distinguishes a NEW exclusion delta (a ban add / a privatize transition) from a pure RESUME: a
2180/// fresh delta bumps `read_cut_target_epoch` to `base + 1` so the base MUST rotate past it (excluding the
2181/// newly-removed member) and every channel is re-cut; a resume keeps the in-flight target so an interrupted
2182/// cut finishes without forcing an extra base rotation.
2183async fn run_read_cut<T: Transport + ?Sized>(
2184    transport: &T,
2185    community: &Community,
2186    fresh: bool,
2187) -> Result<(), String> {
2188    let cid = community.id.to_hex();
2189    let session = SessionGuard::capture();
2190    if fresh {
2191        // Compute the target from the FRESHEST base epoch in the DB (the passed struct may predate a recent
2192        // rotation), so a fresh exclusion always lands at an epoch strictly past the current root.
2193        let base = crate::db::community::load_community(&community.id)?
2194            .map(|c| c.server_root_epoch.0)
2195            .unwrap_or(community.server_root_epoch.0);
2196        crate::db::community::set_read_cut_target_epoch(&cid, base.saturating_add(1))?;
2197    }
2198    crate::db::community::set_read_cut_pending(&cid, true)?;
2199    reseal_base_to_observed(transport, community).await?;
2200    if session.is_valid() {
2201        crate::db::community::set_read_cut_pending(&cid, false)?;
2202    }
2203    Ok(())
2204}
2205
2206/// Re-seal the base / server-root key to the current OBSERVED-PARTICIPANTS set
2207/// (`community_member_activity` — everyone who posted, reacted, or announced a join, minus those who
2208/// left or were banned). The shared read-cut behind two actions: PRIVATIZE (revoking the last link →
2209/// re-found, sealing link-joined lurkers) and REKEY-ON-REMOVAL (a ban in a Private community →
2210/// forward-exclude the banned member, who is absent from the observed set because the banlist filters
2211/// them out). The re-keyer (here, the owner) is always included (`rotate_server_root` adds its own self).
2212/// Honest joiners are observable because they emit a `join` Presence on accept, so a removed member
2213/// is the only one shed. `rotate_server_root` re-anchors the control plane (incl. the current banlist +
2214/// the registry head) under the new epoch, so post-rotation peers read complete authority state.
2215async fn reseal_base_to_observed<T: Transport + ?Sized>(
2216    transport: &T,
2217    community: &Community,
2218) -> Result<(), String> {
2219    let session = SessionGuard::capture();
2220    let cid = community.id.to_hex();
2221    // BLOCK-UNTIL-SYNCED: fold the latest control plane + ingest channel activity from ALL relays BEFORE
2222    // computing the retain set, so it reflects current truth (roster ∪ presence ∪ activity), not a stale
2223    // local view. The demonstrated bug: privatizing before observing a member's posts cut them. Fails closed
2224    // if no relay confirms our head — better to abort the rekey than shed real members on a partial view.
2225    let community = &sync_before_admin_write(transport, community, true).await?;
2226    // `community_member_activity` returns npubs in the events table's BECH32 form (`npub1...`), so parse
2227    // with `PublicKey::parse` (bech32 OR hex) — `from_hex` would reject every one, emptying the set and
2228    // sealing the community down to the owner alone (the re-founding inverted).
2229    let participants: Vec<nostr_sdk::PublicKey> = crate::db::community::community_member_activity(&cid)?
2230        .into_iter()
2231        .filter_map(|(npub, _)| nostr_sdk::PublicKey::parse(&npub).ok())
2232        .collect();
2233    // RESUMABLE re-founding (durable across interruption — outage, power cut, mass relay failure mid-cut).
2234    // A re-founding rotates the base THEN each channel key; a naive retry would re-run BOTH from scratch
2235    // (a second base epoch + full control-plane re-anchor, and re-rotation of channels already done).
2236    //
2237    // `target` = the base epoch THIS pending cut must reach (set durably when the cut was triggered). The
2238    // base is rotated ONLY while the OBSERVABLE base epoch is below it — so a crash AFTER the base advanced
2239    // but BEFORE any flag write never double-rotates (the decision reads the real epoch, not a separate
2240    // flag that could be out of step). `rotate_server_root` reuses its archived root + recomputes the epoch
2241    // from the DB head, so even a retry of the base itself is idempotent (no same-epoch fork).
2242    let target = crate::db::community::get_read_cut_target_epoch(&cid)?;
2243    if community.server_root_epoch.0 < target {
2244        rotate_server_root(transport, community, &participants).await?;
2245        if !session.is_valid() {
2246            return Err("account changed during re-founding".to_string());
2247        }
2248    }
2249    // O2: the base rotation cuts the control plane + @everyone, but channel MESSAGES are sealed under
2250    // per-channel keys — so a removed member who held a channel key would keep reading NEW messages.
2251    // Rotate every channel key to the retained set. Reload first so we see the freshest per-channel rekey
2252    // progress + the new base epoch. (SessionGuard: a mid-rotation account swap must not reload/rotate
2253    // against the wrong account's pool.)
2254    let community = crate::db::community::load_community(&community.id)?
2255        .ok_or("community gone after base rotation")?;
2256    let cut_epoch = community.server_root_epoch.0;
2257    // / A-B2 fix: envelope + address each channel rekey under the PRIOR (pre-rotation) root, NOT the new
2258    // one — mirroring the base rekey. Concurrent re-founders each mint their OWN new root; base convergence
2259    // adopts ONE and the losers DROP theirs, so a channel rekey sealed under the new root becomes unreadable
2260    // to any loser (the live-proven channel fork). The prior root is the shared key EVERY retained member
2261    // still holds through the convergence, so all can open + apply the channel rekey and converge.
2262    let prior_root = crate::db::community::held_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, cut_epoch.saturating_sub(1))?
2263        .unwrap_or(*community.server_root_key.as_bytes()); // epoch 0 (no prior) → current root (no fork risk)
2264    for channel in &community.channels {
2265        let ch_hex = channel.id.to_hex();
2266        // Skip channels already rotated for this read-cut — a retry resumes exactly where it stopped, so
2267        // each pass makes monotonic forward progress (no re-publishing rekeys for finished channels).
2268        if crate::db::community::channel_rekeyed_at_server_epoch(&cid, &ch_hex)? >= cut_epoch {
2269            continue;
2270        }
2271        rotate_channel(transport, &community, &channel.id, &participants, &prior_root).await?;
2272        if !session.is_valid() {
2273            return Err("account changed during re-founding".to_string());
2274        }
2275        crate::db::community::mark_channel_rekeyed_at_server_epoch(&cid, &ch_hex, cut_epoch)?;
2276    }
2277    Ok(())
2278}
2279
2280/// The result of applying a received channel Rekey (3303).
2281#[derive(Debug, PartialEq, Eq)]
2282pub enum RekeyOutcome {
2283    /// The new key was recovered + committed. `head_advanced` is true if it became the channel's
2284    /// current epoch (a catch-up of an OLDER epoch archives the key but leaves the head, so `false`).
2285    Applied { head_advanced: bool },
2286    /// No blob at my recipient locator — I'm not in this rotation's recipient set (a non-member of the
2287    /// channel, or the member this removal deliberately excluded). Expected, NOT an error.
2288    NotARecipient,
2289}
2290
2291/// Apply a received, already-opened channel Rekey ([`super::rekey::open_rekey_event`]) for `community`.
2292///
2293/// Verifies the rotator's authority (`MANAGE_CHANNELS`) against the current roster (owner supreme,
2294///), checks chain continuity against the held prior-epoch key (fork detection — when held),
2295/// finds + opens MY per-recipient blob, and commits the new key via `advance_channel_epoch` (the
2296/// atomic archive+head write). `SessionGuard`-gated: the caller's fetch can straddle an account swap,
2297/// so the DB write is re-validated immediately before it. Does NOT fetch — the catch-up fetch loop is
2298/// a later layer. (Scope-pinned + version-pinned authority — evaluating the rotator's rank at the
2299/// roster version the rekey cites, under block-until-synced — is deferred; server-root rotation has
2300/// its own apply, deferred.)
2301pub fn apply_channel_rekey(
2302    community: &Community,
2303    parsed: &super::rekey::ParsedRekey,
2304) -> Result<RekeyOutcome, String> {
2305    // Fully synchronous (no `.await`), so a session swap can't preempt between the MY_SECRET_KEY read
2306    // and the DB write — one captured guard + one re-check before the write suffices. If a remote
2307    // signer (bunker) open path ever adds an await here, MY_SECRET_KEY must be re-read after it.
2308    let session = SessionGuard::capture();
2309
2310    // Scope must be a channel of THIS community (server-root rotation is a separate, deferred path).
2311    let channel_id = match parsed.scope {
2312        super::derive::RekeyScope::Channel(c) => c,
2313        super::derive::RekeyScope::ServerRoot => {
2314            return Err("server-root rotation uses apply_server_root_rekey, not the channel path".to_string())
2315        }
2316    };
2317    if !community.channels.iter().any(|c| c.id == channel_id) {
2318        return Err("rekey targets a channel not in this community".to_string());
2319    }
2320    let cid = community.id.to_hex();
2321    let channel_hex = channel_id.to_hex();
2322
2323    // Authority: the rotator must hold MANAGE_CHANNELS per the current roster; the owner is
2324    // supreme. Reject an unauthorized rotation rather than fail open.
2325    // TODO(scope): is_authorized unions MANAGE_CHANNELS across ALL the rotator's roles regardless of
2326    // RoleScope — once channel-scoped roles become grantable, gate on the scope covering THIS channel,
2327    // else a Channel(other)-scoped grant would wrongly authorize rotating this one. MVP roles are all
2328    // Server-scoped, so the hole is currently unreachable.
2329    let owner = proven_owner_hex(community);
2330    let roster = crate::db::community::get_community_roles(&cid).unwrap_or_else(|e| {
2331        // A DB hiccup degrades (fail-closed) to owner-only authorization; surface it so the resulting
2332        // "lacks MANAGE_CHANNELS" rejection isn't mistaken for a real authority problem.
2333        crate::log_warn!("rekey apply: roster read failed ({e}); authorizing owner only");
2334        Default::default()
2335    });
2336    if !roster.is_authorized(
2337        &parsed.rotator.to_hex(),
2338        owner.as_deref(),
2339        super::roles::Permissions::MANAGE_CHANNELS,
2340    ) {
2341        return Err("rekey rotator lacks MANAGE_CHANNELS authority".to_string());
2342    }
2343
2344    // Chain continuity — relaxed for FORK-CONVERGENCE: if I hold the prior-epoch key this rekey cites
2345    // and its commitment matches, great (the normal contiguous case). If it MISMATCHES, I'm on a LOSING
2346    // FORK of the prior epoch (e.g. a concurrent re-founding I lost) while this rekey extends the WINNING
2347    // fork. It is NOT a foreign chain: the rotator is already authority-verified above (holds MANAGE_CHANNELS)
2348    // and the ECDH blob below proves it's addressed to ME. So ADOPT it — converge forward onto the authorized
2349    // chain — rather than reject and strand myself on the dead fork forever. (Authority + recipient are the
2350    // real gates; the commitment is continuity, which must yield to convergence. Replays of OLD epochs can't
2351    // reach here: the forward walk only fetches epochs past my head.) My divergent prior-epoch key stays as
2352    // local history; going forward I'm on the converged key.
2353    if let Some(prev_key) = crate::db::community::held_epoch_key(&cid, &channel_hex, parsed.prev_epoch.0)? {
2354        if super::rekey::epoch_key_commitment(parsed.prev_epoch, &prev_key) != parsed.prev_key_commitment {
2355            crate::log_warn!(
2356                "channel rekey to epoch {} cites a prior-epoch key I don't hold (I'm on a losing fork of epoch {}) — converging forward onto the authorized chain",
2357                parsed.new_epoch.0, parsed.prev_epoch.0
2358            );
2359        }
2360    }
2361
2362    // Find + open MY blob (compute my own recipient locator, no trial-decryption).
2363    let my_keys = crate::state::MY_SECRET_KEY
2364        .to_keys()
2365        .ok_or("no local identity to open the rekey blob")?;
2366    let secret = super::rekey::rekey_pairwise_secret(my_keys.secret_key(), &parsed.rotator)?;
2367    let my_locator = super::derive::recipient_pseudonym(&secret, parsed.scope, parsed.new_epoch).to_hex();
2368    let mine = match parsed.blobs.iter().find(|b| b.locator == my_locator) {
2369        Some(b) => b,
2370        None => return Ok(RekeyOutcome::NotARecipient),
2371    };
2372    let new_key =
2373        super::rekey::open_rekey_blob(my_keys.secret_key(), &parsed.rotator, parsed.scope, parsed.new_epoch, mine)?;
2374
2375    // Commit (N2 dual-write). Re-validate the session straddling the caller's fetch before writing.
2376    if !session.is_valid() {
2377        return Err("session changed during rekey apply".to_string());
2378    }
2379    let head_advanced =
2380        crate::db::community::advance_channel_epoch(&cid, &channel_hex, parsed.new_epoch.0, &new_key)?;
2381    Ok(RekeyOutcome::Applied { head_advanced })
2382}
2383
2384/// Mint the new key for a rotation, OR reuse the one a prior (failed-mid-publish) attempt already minted
2385/// and archived for this `(scope, epoch)`. Reuse is the FORK-SAFETY crux of splitting: a rotation's key
2386/// is minted ONCE and persisted to the epoch-key archive BEFORE publishing, so a retry re-publishes the
2387/// SAME key across all chunks — never a second random root for the same epoch (which would split
2388/// recipients onto incompatible keys). Returns the (zeroized) key.
2389fn mint_or_reuse_rotation_key(cid: &str, scope_id: &str, epoch: u64) -> Result<zeroize::Zeroizing<[u8; 32]>, String> {
2390    if let Some(k) = crate::db::community::held_epoch_key(cid, scope_id, epoch)? {
2391        return Ok(zeroize::Zeroizing::new(k));
2392    }
2393    let k = zeroize::Zeroizing::new(super::random_32());
2394    crate::db::community::store_epoch_key(cid, scope_id, epoch, &k)?;
2395    Ok(k)
2396}
2397
2398/// Publish a rotation's per-recipient blobs as one OR MORE 3303 events, SPLIT into chunks of
2399/// `MAX_REKEY_BLOBS` so each stays under the relay size limit (e.g. 200 recipients → a 120-blob event
2400/// + an 80-blob event). All chunks share the SAME address (the builder derives it from scope/epoch, not
2401/// the blobs) and carry the SAME new key, so a recipient finds + recovers their key from whichever chunk
2402/// holds their blob. Each chunk is published durably; FAIL-FAST if a chunk reaches no relay (the caller
2403/// leaves its head unadvanced; because the key is persisted + reused on retry, re-publishing carries the
2404/// SAME key → no same-epoch fork).
2405async fn publish_rekey_chunked<T, F>(
2406    transport: &T,
2407    relays: &[String],
2408    blobs: &[super::rekey::RekeyBlob],
2409    build: F,
2410) -> Result<(), String>
2411where
2412    T: Transport + ?Sized,
2413    F: Fn(&[super::rekey::RekeyBlob]) -> Result<Event, String>,
2414{
2415    if blobs.is_empty() {
2416        return Err("rekey has no recipients".to_string());
2417    }
2418    for chunk in blobs.chunks(super::rekey::MAX_REKEY_BLOBS) {
2419        let event = build(chunk)?;
2420        transport.publish_durable(&event, relays).await?;
2421    }
2422    Ok(())
2423}
2424
2425/// Rotate a channel's key (a channel rekey): mint a fresh-random key for `current_epoch + 1`,
2426/// deliver it to `recipients` as one self-proving 3303 event (epoch + every recipient blob + the
2427/// prior-epoch commitment + my real-npub authority sig, all in one — the design tenet), publish it,
2428/// then advance MY local epoch. Returns the new epoch.
2429///
2430/// The caller supplies the recipient set (the recipient-set policy — "everyone who stays" — is a
2431/// separate layer); I am always added (so my other devices recover the key). I must hold
2432/// `MANAGE_CHANNELS`. **Publish FIRST, advance my head only after a successful publish** — moving my
2433/// head to an epoch no peer received would strand me. (A post-publish session swap leaves peers ahead
2434/// of my local head, which self-heals: the rekey is server-root-addressed, so I re-derive my own key
2435/// on the next fetch.) `SessionGuard`-gated across the publish await.
2436pub async fn rotate_channel<T: Transport + ?Sized>(
2437    transport: &T,
2438    community: &Community,
2439    channel_id: &super::ChannelId,
2440    recipients: &[nostr_sdk::PublicKey],
2441    // the server root this rekey is ENVELOPED + ADDRESSED under. A standalone channel removal passes the
2442    // CURRENT root. A re-founding (base rotation) passes the PRIOR (pre-rotation) root — exactly like the
2443    // base rekey (`base_rekey_pseudonym(prior_root, …)`) — so every RETAINED member can still open it after
2444    // the base converges to ONE winning root (the losers dropped their own new root). Sealing under the new
2445    // root instead would strand any base-fork loser on an unreadable channel rekey.
2446    envelope_root: &[u8; 32],
2447) -> Result<u64, String> {
2448    let session = SessionGuard::capture();
2449    let cid = community.id.to_hex();
2450
2451    // Authority: I must hold MANAGE_CHANNELS (owner supreme). A rekey needs the RAW local key
2452    // (the blob locator is a ConversationKey ECDH, which NIP-46 can't expose) — so a bunker account can
2453    // administer via editions but not rekey. Fails clearly here rather than silently.
2454    let my_keys = crate::state::MY_SECRET_KEY.to_keys().ok_or("a key rotation requires a local key (bunker/NIP-46 accounts can't rekey)")?;
2455    let owner = proven_owner_hex(community);
2456    let roster = crate::db::community::get_community_roles(&cid).unwrap_or_default();
2457    if !roster.is_authorized(&my_keys.public_key().to_hex(), owner.as_deref(), super::roles::Permissions::MANAGE_CHANNELS) {
2458        return Err("not authorized to rotate this channel (no MANAGE_CHANNELS)".to_string());
2459    }
2460
2461    // Current epoch + key (the chain link we extend). `channel.key` is the head key, kept in lockstep
2462    // with the archived prev_epoch key by `advance_channel_epoch`, so the commitment computed here
2463    // matches what the apply side verifies against `held_epoch_key(prev_epoch)`.
2464    let channel = community
2465        .channels
2466        .iter()
2467        .find(|c| &c.id == channel_id)
2468        .ok_or("channel not found in community")?;
2469    let prev_epoch = channel.epoch;
2470    let new_epoch = super::Epoch(prev_epoch.0.checked_add(1).ok_or("channel epoch overflow")?);
2471    let prev_commit = super::rekey::epoch_key_commitment(prev_epoch, channel.key.as_bytes());
2472    // The fresh channel key — minted ONCE + archived, reused on a retry (fork-safety, see
2473    // `mint_or_reuse_rotation_key`). Zeroized on drop.
2474    let new_key = mint_or_reuse_rotation_key(&cid, &channel_id.to_hex(), new_epoch.0)?;
2475
2476    // Recipient set = the supplied stayers ∪ me (deduped), each wrapped a per-recipient blob. Published
2477    // SPLIT across ≤MAX_REKEY_BLOBS-blob events so a large channel rotates in multiple 64KB-safe
2478    // events at one address; a recipient recovers from whichever chunk holds their blob.
2479    let mut seen = std::collections::HashSet::new();
2480    let mut blobs = Vec::new();
2481    for pk in recipients.iter().chain(std::iter::once(&my_keys.public_key())) {
2482        if !seen.insert(pk.to_hex()) {
2483            continue;
2484        }
2485        blobs.push(super::rekey::build_rekey_blob(
2486            my_keys.secret_key(), pk, super::derive::RekeyScope::Channel(*channel_id), new_epoch, &new_key,
2487        )?);
2488    }
2489
2490    // Publish FIRST (all chunks) — only advance my own head once peers can actually receive the new key.
2491    publish_rekey_chunked(transport, &community.relays, &blobs, |chunk| {
2492        super::rekey::build_channel_rekey_event(
2493            &Keys::generate(), &my_keys, envelope_root, channel_id,
2494            new_epoch, prev_epoch, &prev_commit, chunk,
2495        )
2496    })
2497    .await?;
2498    if !session.is_valid() {
2499        return Err("session changed during channel rotation".to_string());
2500    }
2501    crate::db::community::advance_channel_epoch(&cid, &channel_id.to_hex(), new_epoch.0, &new_key)?;
2502    Ok(new_epoch.0)
2503}
2504
2505/// Emit a privatize/rekey progress step to the UI (no-op on headless clients via the unregistered emitter).
2506/// `pct` is OVERALL progress 0-100 across the whole rotation; `label` is layman-facing. The frontend renders
2507/// a determinate ring + this label in an unclosable modal so the user is guided through the multi-second op.
2508fn emit_rekey_progress(label: &str, pct: u8) {
2509    crate::emit_event("community_rekey_progress", &serde_json::json!({ "label": label, "pct": pct }));
2510}
2511
2512/// Rotate the SERVER ROOT (a base rotation — the Private-removal / re-founding read-cut), the
2513/// complete orchestration: mint a fresh-random new root for `current_base_epoch + 1`, deliver it to
2514/// `recipients` as one self-proving server-root rekey (enveloped under the PRIOR root, addressed by
2515/// `base_rekey_pseudonym`), **re-anchor the control plane under the new epoch**, and only then
2516/// advance MY base head. Returns the new base epoch.
2517///
2518/// I am always added to the recipient set (multi-device). I must hold `BAN` (server-wide rotation
2519/// authority; owner supreme). The ordering is the safety contract: publish the base rekey → re-anchor →
2520/// advance head, with the **head-advance gated on a successful, count-complete re-anchor** — so a
2521/// post-rotation joiner who holds only the new root always reaches current authority, and a withholding
2522/// relay can't advance us over a thinned control plane. The recipient-set policy ("who stays") is still
2523/// the caller's (privatize/removal flow, #7/#8). `pub(crate)` — exposed only inside the crate until that
2524/// flow wraps it. Re-anchor carries the whole 3308 control plane (roles, grants, banlist, GroupRoot,
2525/// channel metadata) — every authority + display entity is preserved across a base rotation.
2526// Called by the privatize re-founding flow (`privatize_reseal`); also exercised directly by tests.
2527pub(crate) async fn rotate_server_root<T: Transport + ?Sized>(
2528    transport: &T,
2529    community: &Community,
2530    recipients: &[nostr_sdk::PublicKey],
2531) -> Result<u64, String> {
2532    let session = SessionGuard::capture();
2533    let cid = community.id.to_hex();
2534
2535    // a re-founding cannot cross a tombstone. A dissolved community never rotates the base again.
2536    if crate::db::community::get_community_dissolved(&cid)? {
2537        return Err("community is dissolved; it cannot be re-founded".to_string());
2538    }
2539
2540    // Authority: I must hold BAN (server-wide rotation; owner supreme). Re-founding re-WRAPS each entity
2541    // head verbatim (never re-authors), so an HONEST re-founder of any rank preserves everything: grants keep
2542    // their original granter and the owner deed rides along untouched (ownership is unstealable — the deed is
2543    // owner-signed and verified from the invite bundle, never from the snapshot).
2544    // KNOWN MVP LIMITATION (audited, accepted): a MALICIOUS non-owner admin (modified client) can OMIT a peer
2545    // admin's grant from the snapshot to demote them — a privilege escalation, since epoch-primary floors drop
2546    // the prior-epoch floors so followers can't detect the omission. Accepted because admins are owner-
2547    // appointed/trusted and the owner recovers (re-grant the peer + remove the bad admin); it can't steal
2548    // ownership or leak data. The bulletproof fix (verifiable removal: followers reject a snapshot that drops
2549    // a member the re-founder doesn't outrank) is deferred. Needs the RAW local key (ECDH), so no bunker.
2550    let my_keys = crate::state::MY_SECRET_KEY.to_keys().ok_or("a base rotation (privatize / private-ban read-cut) requires a local key (bunker/NIP-46 accounts can't rekey)")?;
2551    let owner = proven_owner_hex(community);
2552    let roster = crate::db::community::get_community_roles(&cid).unwrap_or_default();
2553    if !roster.is_authorized(&my_keys.public_key().to_hex(), owner.as_deref(), super::roles::Permissions::BAN) {
2554        return Err("not authorized to rotate the server root (no BAN)".to_string());
2555    }
2556
2557    // Derive prev_epoch / prev_commit / the rekey ENVELOPE root from the FRESHEST base state, never a
2558    // possibly-stale caller struct: addressing a rotation under a root that's already been superseded (e.g.
2559    // a re-founder re-rotating from a pre-convergence in-memory struct) lands it at a pseudonym converged
2560    // members never query → a base re-fork with no past-epoch heal to recover it. Reload first (mirrors
2561    // run_read_cut's freshest-epoch read); all downstream uses (envelope, re-anchor fetch) then agree.
2562    let fresh = crate::db::community::load_community(&community.id)?
2563        .ok_or("community gone before base rotation")?;
2564    let community = &fresh;
2565    let prev_epoch = community.server_root_epoch;
2566    let new_epoch = super::Epoch(prev_epoch.0.checked_add(1).ok_or("server-root epoch overflow")?);
2567    // Commit to the PRIOR root (the chain link the apply side verifies against `held_epoch_key(prev)`).
2568    let prev_commit = super::rekey::epoch_key_commitment(prev_epoch, community.server_root_key.as_bytes());
2569    // The fresh server root — minted ONCE + archived, reused on a retry (fork-safety). Zeroized on drop.
2570    let new_root = mint_or_reuse_rotation_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, new_epoch.0)?;
2571    emit_rekey_progress("Rerolling community keys...", 5);
2572
2573    // ACQUIRE-BEFORE-COMMIT: do EVERY fetch the re-founding needs BEFORE publishing anything. The only
2574    // mid-rekey fetch is the re-anchor (the current control plane → re-wrapped under the new epoch); its
2575    // coverage gate (a head not fetchable) is exactly what stranded a published base rekey when it ran AFTER
2576    // the publish. Fetch + seal it now, so a transient miss aborts the whole re-founding with ZERO published
2577    // state. Only the publishes below need retry logic. The sealed editions are sent in the commit phase.
2578    let sealed = prepare_reanchor_control_plane(transport, community, &new_root, new_epoch).await?;
2579    if !session.is_valid() {
2580        return Err("session changed during re-founding acquire".to_string());
2581    }
2582
2583    let total_recipients = (recipients.len() + 1).max(1); // recipients + me (multi-device)
2584    let mut seen = std::collections::HashSet::new();
2585    let mut blobs = Vec::new();
2586    for pk in recipients.iter().chain(std::iter::once(&my_keys.public_key())) {
2587        if !seen.insert(pk.to_hex()) {
2588            continue;
2589        }
2590        blobs.push(super::rekey::build_rekey_blob(
2591            my_keys.secret_key(), pk, super::derive::RekeyScope::ServerRoot, new_epoch, &new_root,
2592        )?);
2593        emit_rekey_progress(
2594            &format!("Preparing keys for members ({}/{})...", blobs.len(), total_recipients),
2595            (5 + 35 * blobs.len() / total_recipients) as u8,
2596        );
2597    }
2598
2599    // COMMIT phase (publishes only — all fetching is done above). Publish the base rekey (delivers the new
2600    // root to recipients), SPLIT across ≤MAX_REKEY_BLOBS-blob events so a large recipient set rotates
2601    // in multiple 64KB-safe events at one address.
2602    emit_rekey_progress("Sending keys to members...", 42);
2603    publish_rekey_chunked(transport, &community.relays, &blobs, |chunk| {
2604        super::rekey::build_server_root_rekey_event(
2605            &Keys::generate(), &my_keys, community.server_root_key.as_bytes(), &community.id,
2606            new_epoch, prev_epoch, &prev_commit, chunk,
2607        )
2608    })
2609    .await?;
2610
2611    // RE-FOUND BY COMPACTION: publish the pre-sealed snapshot (the current folded state re-wrapped as
2612    // editions under the new epoch) so a post-rotation joiner reaches the new root with reachable authority.
2613    // Gate the head-advance on EVERY edition landing (O(entities), tiny): a single un-ACKed edition aborts,
2614    // head-not-advanced is the safe side. A failed publish leaves the base rekey on relays while our head
2615    // stays put; a retry REUSES the archived root via `mint_or_reuse_rotation_key`, recomputing `new_epoch`
2616    // from the DB head — no same-epoch fork, idempotent re-publish. (The fetch can no longer fail here: the
2617    // snapshot was acquired up front, so this commit phase is publish-retry territory only.)
2618    let snapshot = publish_reanchor_snapshot(transport, &community.relays, sealed).await?;
2619    if snapshot.iter().any(|e| !e.published) {
2620        return Err(
2621            "re-founding aborted: a snapshot edition did not land (rate-limited / unreachable relay?); base head NOT advanced".to_string()
2622        );
2623    }
2624    if !session.is_valid() {
2625        return Err("session changed during server-root rotation".to_string());
2626    }
2627    emit_rekey_progress("Finalizing...", 98);
2628    // Only now commit: the new root is on relays AND the compacted plane is reachable at the new epoch.
2629    crate::db::community::advance_server_root_epoch(&cid, new_epoch.0, &new_root)?;
2630    // Record our carried heads at the (now-committed) new epoch so a subsequent edit chains from them, not
2631    // the abandoned old-epoch chain. The head is re-wrapped VERBATIM, so its version is preserved; epoch is
2632    // primary, so it supersedes the prior epoch's head regardless of version.
2633    for e in &snapshot {
2634        crate::db::community::set_edition_head_with_id(&cid, &e.entity_hex, e.version, &e.self_hash, &e.inner_id)?;
2635    }
2636    Ok(new_epoch.0)
2637}
2638
2639/// Re-anchor the control plane after a base rotation: re-post the current control HEADS under the NEW
2640/// epoch's server-root pseudonym, so a post-rotation joiner (who holds only the new root) reaches current
2641/// authority with the one control-plane query they can make. Returns the per-entity snapshot it published.
2642///
2643/// **Re-WRAP, not re-sign.** Each edition's inner is the original real-npub-signed event — its signature,
2644/// version, and (community-scoped, rotation-stable) `entity_id` are all preserved; only the outer envelope
2645/// is fresh (new-root encryption + new-epoch `control_pseudonym` + ephemeral signer). Anyone can re-wrap
2646/// because the inner signature is what verifies — so the owner deed (carried inside the GroupRoot head) and
2647/// every grant's original granter survive untouched, which is what lets any BAN-holder re-found without
2648/// re-authoring or demoting anyone.
2649///
2650/// **COMPACTION: re-posts only the per-entity HEAD, not the whole `v1..vN` chain.** Cost is O(entities),
2651/// not O(history) — the fix for the original full-chain re-anchor, which failed once relays dropped old
2652/// editions or rate-limited the burst. The head is carried VERBATIM (keeps its real version number), so at
2653/// the new epoch its `prev_hash` dangles; that's fine because epoch-primary floors put a following member
2654/// in BOOTSTRAP mode for the new epoch (floor 0), where `fold_roster` surfaces the head via `bootstrap_head`
2655/// (Policy B) + the authority gate — no contiguous `v1..vN` is needed. (The old chain stays orphaned at the
2656/// prior epoch.) Only the freshest editions (the heads) need to be fetchable, sidestepping the dropped-old-
2657/// version wall.
2658///
2659/// **SCOPE: every tracked control entity** (GroupRoot, ChannelMetadata, roles, grants, the banlist) — built
2660/// from `get_all_edition_heads_epoched` and matched to its fetched raw edition; a head we can't fetch ABORTS
2661/// the rotation (better than stranding members on a thinned plane).
2662///
2663/// PRECONDITION: call this while `community` still holds the CURRENT (pre-rotation) root/epoch — it
2664/// fetches the current plane and re-posts under the new one. Running it after the head advanced would
2665/// fetch the (empty) new-epoch plane and re-anchor nothing.
2666///
2667/// `pub(crate)` + part of the base-rotation orchestration (#4e-2 sequences rekey → re-anchor → advance,
2668/// gating the head-advance on a successful re-anchor); `SessionGuard`-gated across the fetch + each
2669/// publish (publish-only — no local DB write, so a mid-loop swap is not a cross-account hazard).
2670// Reached in production via `rotate_server_root` (the privatize re-founding path); also tested directly.
2671/// One re-wrapped entity head in a re-founding snapshot: its coordinate + (version, self_hash, inner_id)
2672/// of the head carried forward (for recording at the new epoch), and whether its publish landed.
2673pub(crate) struct SnapshotEntry {
2674    pub entity_hex: String,
2675    pub version: u64,
2676    pub self_hash: [u8; 32],
2677    pub inner_id: [u8; 32],
2678    pub published: bool,
2679}
2680
2681/// ACQUIRE half of the re-anchor (acquire-before-commit): fetch the current control plane and re-wrap every
2682/// entity head under the new root/epoch — but publish NOTHING. Returns the sealed editions ready to send.
2683/// The coverage gate (a head not fetchable ABORTS) lives here, so it trips BEFORE any rekey is published —
2684/// a transient fetch miss then aborts the whole re-founding with ZERO published state (clean retry), instead
2685/// of stranding a published base rekey with a half-anchored plane. See `rotate_server_root` for the ordering.
2686pub(crate) async fn prepare_reanchor_control_plane<T: Transport + ?Sized>(
2687    transport: &T,
2688    community: &Community,
2689    new_root: &[u8; 32],
2690    new_epoch: super::Epoch,
2691) -> Result<Vec<(Event, SnapshotEntry)>, String> {
2692    let session = SessionGuard::capture();
2693    let cid = community.id.to_hex();
2694
2695    // RE-FOUND BY COMPACTION: re-wrap each entity's CURRENT HEAD verbatim under the new epoch — ONE
2696    // edition per entity, not the O(history) chain. "Re-wrap, not re-sign": the inner real-npub signature
2697    // (and the owner deed riding inside the GroupRoot content) are carried UNCHANGED, so every grant keeps
2698    // its ORIGINAL granter and authority re-derives identically at the new epoch. That's what lets ANY
2699    // BAN-holder re-found without demoting peer admins or touching ownership — the re-founder only re-keys
2700    // + re-addresses, never re-authors. Only the HEADS are needed (the freshest, most-retained editions),
2701    // so this sidesteps the unfetchable-old-version wall that broke the full-history re-anchor.
2702    let z = super::roster::control_pseudonym(&community.server_root_key, &community.id, community.server_root_epoch);
2703    let query = Query { kinds: vec![event_kind::COMMUNITY_CONTROL], z_tags: vec![z], ..Default::default() };
2704    let outers = transport.fetch(&query, &community.relays).await?;
2705    if !session.is_valid() {
2706        return Err("session changed during re-founding fetch".to_string());
2707    }
2708    // self_hash → (raw inner edition opened under the CURRENT root, its inner_id).
2709    let mut by_hash: std::collections::HashMap<[u8; 32], (Event, [u8; 32])> = std::collections::HashMap::new();
2710    for outer in &outers {
2711        if let Ok(inner) = super::roster::open_control_edition(outer, &community.server_root_key) {
2712            if let Ok(parsed) = super::edition::parse_edition_inner(&inner) {
2713                by_hash.insert(parsed.self_hash, (inner, parsed.inner_id));
2714            }
2715        }
2716    }
2717
2718    // Each entity's CURRENT head (the floors recorded at the current epoch) → re-wrap that exact edition
2719    // verbatim under the new root/epoch. A head we can't fetch ABORTS (better than stranding members on a
2720    // plane missing an entity); heads are the freshest editions, so the relay union almost always has them.
2721    let new_root_key = super::ServerRootKey(*new_root);
2722    let mut sealed: Vec<(Event, SnapshotEntry)> = Vec::new();
2723    for (entity_hex, (epoch, version, self_hash)) in crate::db::community::get_all_edition_heads_epoched(&cid)? {
2724        if epoch != community.server_root_epoch.0 {
2725            continue; // only the current founding's heads (a stale prior-epoch head is already superseded)
2726        }
2727        let (inner, inner_id) = by_hash.get(&self_hash).ok_or_else(|| {
2728            format!("re-founding aborted: head edition for entity {entity_hex} (v{version}) not fetchable — aborting so no member is stranded")
2729        })?;
2730        let outer = super::roster::seal_control_edition(&Keys::generate(), inner, &new_root_key, &community.id, new_epoch)?;
2731        sealed.push((outer, SnapshotEntry { entity_hex, version, self_hash, inner_id: *inner_id, published: false }));
2732    }
2733    Ok(sealed)
2734}
2735
2736/// COMMIT half of the re-anchor: publish the (already-fetched + sealed) snapshot editions. Publishing only —
2737/// no fetch — so the caller's acquire phase guarantees there's nothing left that could fail-to-fetch here.
2738/// Each `published` flag reports whether that edition landed; the caller gates the head-advance on all true.
2739pub(crate) async fn publish_reanchor_snapshot<T: Transport + ?Sized>(
2740    transport: &T,
2741    relays: &[String],
2742    sealed: Vec<(Event, SnapshotEntry)>,
2743) -> Result<Vec<SnapshotEntry>, String> {
2744    // Publish THROTTLED (a bounded window, not an all-at-once burst) so the snapshot survives rate-limited
2745    // relays — the 0/N stall that the old concurrent re-anchor hit. Volume is O(entities), so this is small.
2746    use futures_util::stream::StreamExt;
2747    let total = sealed.len().max(1);
2748    let done = std::sync::atomic::AtomicUsize::new(0);
2749    let done_ref = &done;
2750    emit_rekey_progress(&format!("Re-founding community (0/{total})..."), 50);
2751    let out: Vec<SnapshotEntry> = futures_util::stream::iter(sealed.into_iter().map(|(ev, mut entry)| async move {
2752        entry.published = transport.publish_durable(&ev, relays).await.is_ok();
2753        let n = done_ref.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
2754        emit_rekey_progress(&format!("Re-founding community ({n}/{total})..."), (50 + 45 * n / total) as u8);
2755        entry
2756    }))
2757    .buffer_unordered(4)
2758    .collect()
2759    .await;
2760    Ok(out)
2761}
2762
2763/// Re-anchor in one shot (fetch + seal + publish). Test-only convenience; production splits the two halves
2764/// (`prepare_*` then `publish_*`) so the fetch precedes any rekey publish (acquire-before-commit).
2765#[cfg(test)]
2766pub(crate) async fn reanchor_control_plane<T: Transport + ?Sized>(
2767    transport: &T,
2768    community: &Community,
2769    new_root: &[u8; 32],
2770    new_epoch: super::Epoch,
2771) -> Result<Vec<SnapshotEntry>, String> {
2772    let sealed = prepare_reanchor_control_plane(transport, community, new_root, new_epoch).await?;
2773    publish_reanchor_snapshot(transport, &community.relays, sealed).await
2774}
2775
2776/// Apply a received, already-opened SERVER-ROOT (base) Rekey for `community` — the base counterpart to
2777/// [`apply_channel_rekey`]. Verifies the rotator's server-wide rotation authority (`BAN`, "role-based,
2778/// not owner-only"), checks continuity against the held prior ROOT (when held), finds + opens MY
2779/// ServerRoot-scope blob, and commits the new root via the atomic base head+archive write. The new root
2780/// reaches me ONLY through my ECDH blob — if I was removed in this rotation I find no blob
2781/// (`NotARecipient`) and recover nothing. `SessionGuard`-gated; synchronous (one guard + the write
2782/// re-check suffice, same as `apply_channel_rekey`).
2783pub fn apply_server_root_rekey(
2784    community: &Community,
2785    parsed: &super::rekey::ParsedRekey,
2786) -> Result<RekeyOutcome, String> {
2787    let session = SessionGuard::capture();
2788
2789    // Scope must be the server root (a Channel rekey is the other path).
2790    if !matches!(parsed.scope, super::derive::RekeyScope::ServerRoot) {
2791        return Err("not a server-root rekey (channel rekeys use apply_channel_rekey)".to_string());
2792    }
2793    let cid = community.id.to_hex();
2794
2795    // a re-founding cannot cross a tombstone. Once dissolved, a base rekey is a "subsequent control
2796    // event" → refuse to advance the epoch (a rekey after a tombstone is invalid).
2797    if crate::db::community::get_community_dissolved(&cid)? {
2798        return Err("community is dissolved; base epoch cannot advance".to_string());
2799    }
2800
2801    // Authority: a server-wide rotation is gated on BAN (owner supreme). The deed-derived `owner` is
2802    // the chain root — a community whose deed is missing/stripped yields `owner = None`, so NO rotator
2803    // authorizes (a deedless re-founding is followed by no one). A roster-read failure degrades to
2804    // owner-only (fail-closed): a stale/unreadable roster only UNDER-authorizes a non-owner, never over-.
2805    // Version-pinned rotator authority (spec §6 rule 1) is deferred, as on the channel path; the
2806    // banlist-precedence gate + the heal's deauthorized-root abandonment are the implemented mitigations.
2807    let owner = proven_owner_hex(community);
2808    let roster = crate::db::community::get_community_roles(&cid).unwrap_or_else(|e| {
2809        crate::log_warn!("base rekey apply: roster read failed ({e}); authorizing owner only");
2810        Default::default()
2811    });
2812    if !rotator_is_authorized(&cid, &roster, owner.as_deref(), &parsed.rotator.to_hex(), super::roles::Permissions::BAN) {
2813        return Err("base rekey rotator lacks server-wide rotation authority (BAN)".to_string());
2814    }
2815
2816    // Chain continuity: if I hold the prior ROOT and its commitment mismatches, I'm on a LOSING fork of
2817    // that epoch (a concurrent re-founding I lost) while this rekey extends the WINNING fork. As with channel
2818    // rekeys, that is NOT a foreign chain — the rotator is authority-verified (BAN) above and the ECDH blob
2819    // below proves it's addressed to ME — so ADOPT it (converge forward / reorg onto the authorized chain)
2820    // rather than reject and strand myself on the dead fork, which would stall every later base rotation too.
2821    // Replays of OLD epochs can't reach here: the forward walk only fetches epochs past my head.
2822    if let Some(prev_root) =
2823        crate::db::community::held_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, parsed.prev_epoch.0)?
2824    {
2825        if super::rekey::epoch_key_commitment(parsed.prev_epoch, &prev_root) != parsed.prev_key_commitment {
2826            crate::log_warn!(
2827                "base rekey to epoch {} cites a prior-root I don't hold (I'm on a losing fork of epoch {}) — converging forward onto the authorized chain",
2828                parsed.new_epoch.0, parsed.prev_epoch.0
2829            );
2830        }
2831    }
2832
2833    // Find + open MY blob (ServerRoot scope).
2834    let my_keys = crate::state::MY_SECRET_KEY.to_keys().ok_or("no local identity to open the base rekey blob")?;
2835    let secret = super::rekey::rekey_pairwise_secret(my_keys.secret_key(), &parsed.rotator)?;
2836    let my_locator = super::derive::recipient_pseudonym(&secret, parsed.scope, parsed.new_epoch).to_hex();
2837    let mine = match parsed.blobs.iter().find(|b| b.locator == my_locator) {
2838        Some(b) => b,
2839        None => return Ok(RekeyOutcome::NotARecipient),
2840    };
2841    let new_root =
2842        super::rekey::open_rekey_blob(my_keys.secret_key(), &parsed.rotator, parsed.scope, parsed.new_epoch, mine)?;
2843
2844    if !session.is_valid() {
2845        return Err("session changed during base rekey apply".to_string());
2846    }
2847    let head_advanced = crate::db::community::advance_server_root_epoch(&cid, parsed.new_epoch.0, &new_root)?;
2848    Ok(RekeyOutcome::Applied { head_advanced })
2849}
2850
2851/// How many candidate epochs the catch-up scan derives + fetches per round. All rekey pseudonyms are
2852/// server-root-derived, so a member computes the whole window up front and fetches it in ONE batched
2853/// `#z` REQ (not a sequential walk). One round covers up to this many missed rotations.
2854const REKEY_CATCHUP_WINDOW: u64 = 64;
2855/// Backstop on catch-up rounds — bounds an endless slide (e.g. a relay fabricating contiguous rekeys).
2856/// At `REKEY_CATCHUP_WINDOW` epochs/round this still covers thousands of real rotations before bailing.
2857const MAX_REKEY_CATCHUP_ROUNDS: usize = 64;
2858
2859/// Converge a SET of held channel epochs to the deterministic LOWEST authorized key on the wire (the
2860/// concurrent-rekey tiebreak), in ONE batched fetch per held server root. Two MANAGE_CHANNELS holders can rotate an epoch
2861/// with different keys (a concurrent-rekey fork); both forked rekeys collide under the PRIOR (shared) server
2862/// root, so search every held root, peek the key each delivers to ME, and adopt the lowest. Heals the head,
2863/// any epoch reorged THIS sync, AND the recent window of held epochs — the last covers a member that reorged
2864/// its head under an EARLIER build (so the in-sync forked-epoch set was never populated) yet still sits on a
2865/// losing sibling at a past epoch whose messages would otherwise stay unreadable.
2866///
2867/// Converge DOWN only: a held epoch is re-keyed only to a sibling STRICTLY lower than the key it already
2868/// holds, so a flaky round that returns just the higher sibling can't re-fork a converged epoch. Epochs I do
2869/// NOT hold are left to the gap-fill / forward walk (recovery via `apply`, not a same-epoch swap).
2870async fn heal_channel_fork_epochs<T: Transport + ?Sized>(
2871    transport: &T,
2872    community: &Community,
2873    channel_id: &super::ChannelId,
2874    cid: &str,
2875    channel_hex: &str,
2876    epochs: &std::collections::BTreeSet<u64>,
2877    server_roots: &[[u8; 32]],
2878    session: &SessionGuard,
2879) -> Result<(), String> {
2880    if epochs.is_empty() {
2881        return Ok(());
2882    }
2883    let owner_hex = proven_owner_hex(community);
2884    let roster = crate::db::community::get_community_roles(cid).unwrap_or_default();
2885    // Batched fetch: every target epoch's rekey under each held root, ONE query per root (mirrors the
2886    // forward walk). Track the lowest key delivered to ME by an authorized rotator, per epoch.
2887    let mut winner: std::collections::BTreeMap<u64, [u8; 32]> = std::collections::BTreeMap::new();
2888    for sr in server_roots {
2889        let z_tags: Vec<String> = epochs
2890            .iter()
2891            .map(|e| super::derive::rekey_pseudonym(&super::ServerRootKey(*sr), channel_id, super::Epoch(*e)).to_hex())
2892            .collect();
2893        let q = Query { kinds: vec![event_kind::COMMUNITY_REKEY], z_tags, ..Default::default() };
2894        for ev in transport.fetch(&q, &community.relays).await.unwrap_or_default() {
2895            let Ok(p) = super::rekey::open_rekey_event(&ev, sr) else { continue };
2896            if !matches!(p.scope, super::derive::RekeyScope::Channel(c) if &c == channel_id) || !epochs.contains(&p.new_epoch.0) {
2897                continue;
2898            }
2899            if !rotator_is_authorized(cid, &roster, owner_hex.as_deref(), &p.rotator.to_hex(), super::roles::Permissions::MANAGE_CHANNELS) {
2900                continue;
2901            }
2902            let Some(key) = peek_my_channel_key(&p) else { continue }; // not a recipient of this candidate
2903            winner.entry(p.new_epoch.0).and_modify(|best| { if key < *best { *best = key; } }).or_insert(key);
2904        }
2905    }
2906    for (epoch, win_key) in winner {
2907        if !session.is_valid() {
2908            return Err("session changed during channel convergence".to_string());
2909        }
2910        // Only re-converge an epoch I ALREADY hold, and only DOWNWARD.
2911        // ACCEPTED MVP LIMITATION (GROUP_PROTOCOL.md): adoption checks blob-opens + authority, NOT that
2912        // the key decrypts extant messages — so a malicious MANAGE_CHANNELS holder can darken a settled past
2913        // epoch with a fresh lower key. Data-availability only, trusted-admin only; content-bind hardening deferred.
2914        if let Ok(Some(cur)) = crate::db::community::held_epoch_key(cid, channel_hex, epoch) {
2915            if win_key < cur {
2916                // `false` = the channel head moved off `epoch` between read and write (benign race); trace it
2917                // so a fork that keeps failing to converge is diagnosable in the field without changing flow.
2918                match crate::db::community::converge_channel_epoch(cid, channel_hex, epoch, &win_key) {
2919                    Ok(false) => crate::log_trace!("channel heal: converge of epoch {epoch} did not apply (head moved)"),
2920                    Err(e) => crate::log_trace!("channel heal: converge of epoch {epoch} errored: {e}"),
2921                    Ok(true) => {}
2922                }
2923            }
2924        }
2925    }
2926    Ok(())
2927}
2928
2929/// Catch a channel up to the latest epoch it is still a recipient of (windowed scan): fetch every
2930/// rekey published since our held epoch and apply the chain. Returns the channel's new current epoch.
2931/// Idempotent + cheap on the steady state (no new rotations → one empty-window fetch → returns the
2932/// held epoch). 3303s are addressed by the server-root-derived `rekey_pseudonym`, so this is a SEPARATE
2933/// fetch from the channel message plane (the exception).
2934///
2935/// **Removal is terminal.** Within a channel, the recipient set is forward-monotonic — once a member
2936/// is removed they are excluded from every later rotation, and re-addition is an out-of-band INVITE
2937/// that resets them to a fresh starter epoch (NOT something this scan discovers). So the walk stops at
2938/// the first `NotARecipient`: there is nothing legitimate past it for us. A *missing* intermediate
2939/// epoch (a relay-incomplete gap, where we ARE still a recipient on both sides) is logged and stepped
2940/// over (the hole stays unreadable until re-fetched from another relay), not treated as removal.
2941/// `SessionGuard`-gated; applies in ascending epoch order so each rekey's prior-key continuity check
2942/// sees the key its predecessor just archived.
2943pub async fn catch_up_channel_rekeys<T: Transport + ?Sized>(
2944    transport: &T,
2945    community: &Community,
2946    channel_id: &super::ChannelId,
2947) -> Result<u64, String> {
2948    let session = SessionGuard::capture();
2949    let server_root = community.server_root_key.as_bytes();
2950    let cid = community.id.to_hex();
2951    let channel_hex = channel_id.to_hex();
2952    // A channel rekey is addressed AND encrypted under whatever server root was current when it was
2953    // published — and the root itself ratchets on every base rotation. So derive + open the rekey window
2954    // under EVERY held server-root key, not just the current head: a channel rekey published under a prior
2955    // root is otherwise both unfindable (wrong pseudonym) and undecryptable, leaving permanent channel-key
2956    // gaps (and every message under those epochs stranded). We hold all prior roots in the epoch archive.
2957    let mut server_roots: Vec<[u8; 32]> = crate::db::community::held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX)
2958        .unwrap_or_default()
2959        .into_iter()
2960        .map(|(_, k)| k)
2961        .collect();
2962    if !server_roots.iter().any(|r| r == server_root) {
2963        server_roots.push(*server_root); // ensure the current root is covered even if the archive lags
2964    }
2965    let mut head = community
2966        .channels
2967        .iter()
2968        .find(|c| &c.id == channel_id)
2969        .ok_or("channel not found in community")?
2970        .epoch
2971        .0;
2972
2973    // Past epochs I reorged through (applied a rekey whose cited prior key I don't hold — I'm on a losing
2974    // fork there). The forward walk converges my HEAD, but a forked PAST epoch keeps the wrong sibling's key
2975    // and its messages stay unreadable. Collect them here and re-converge each to the lowest sibling below.
2976    let mut forked_epochs: std::collections::BTreeSet<u64> = std::collections::BTreeSet::new();
2977
2978    for _round in 0..MAX_REKEY_CATCHUP_ROUNDS {
2979        let window_top = head.saturating_add(REKEY_CATCHUP_WINDOW);
2980        // Derive + fetch the window under EACH held server root (a channel rekey lives under the root that
2981        // was current at its publish). Window × |held roots| is small and catch-up is rare; opening with
2982        // the SAME root that addressed each batch is unambiguous (a wrong root just fails the MAC).
2983        let mut parsed: Vec<super::rekey::ParsedRekey> = Vec::new();
2984        for sr in &server_roots {
2985            let z_tags: Vec<String> = (head.saturating_add(1)..=window_top)
2986                .map(|e| super::derive::rekey_pseudonym(&super::ServerRootKey(*sr), channel_id, super::Epoch(e)).to_hex())
2987                .collect();
2988            let query = Query { kinds: vec![event_kind::COMMUNITY_REKEY], z_tags, ..Default::default() };
2989            // Best-effort: a transient relay error on the forward-walk fetch must NOT abort the whole
2990            // catch-up (the caller ignores the Result), which would silently SKIP the current-head
2991            // convergence heal below — leaving a concurrent-rekey fork unhealed. Treat a failed fetch as
2992            // "no events here this round"; the next sync re-walks.
2993            for ev in transport.fetch(&query, &community.relays).await.unwrap_or_default() {
2994                if let Ok(p) = super::rekey::open_rekey_event(&ev, sr) {
2995                    if matches!(p.scope, super::derive::RekeyScope::Channel(c) if &c == channel_id) {
2996                        parsed.push(p);
2997                    }
2998                }
2999            }
3000        }
3001        if parsed.is_empty() {
3002            break; // no rekey exists past `head` under any held root
3003        }
3004        // Apply in ascending epoch order (so each rekey's prior-key continuity sees its predecessor's key).
3005        parsed.sort_by_key(|p| p.new_epoch.0);
3006        let max_found = parsed.last().map(|p| p.new_epoch.0).unwrap_or(head);
3007
3008        let head_before = head;
3009        let mut removed = false;
3010        // GROUP BY EPOCH: a rotation may be SPLIT across multiple chunk events at the same address.
3011        // For each epoch try every chunk — Applied if ANY chunk holds my blob; "removed" only if a VALID
3012        // chunk said NotARecipient and none Applied (a NotARecipient on one chunk just means my blob is
3013        // in another). All-errored at an epoch = a gap (skip), not a removal.
3014        let mut by_epoch: std::collections::BTreeMap<u64, Vec<&super::rekey::ParsedRekey>> = std::collections::BTreeMap::new();
3015        for p in &parsed {
3016            by_epoch.entry(p.new_epoch.0).or_default().push(p);
3017        }
3018        for (e, chunks) in by_epoch {
3019            if !session.is_valid() {
3020                return Err("session changed during rekey catch-up".to_string());
3021            }
3022            let mut applied = false;
3023            let mut saw_not_recipient = false;
3024            for p in &chunks {
3025                match apply_channel_rekey(community, p) {
3026                    Ok(RekeyOutcome::Applied { .. }) => {
3027                        applied = true;
3028                        break;
3029                    }
3030                    Ok(RekeyOutcome::NotARecipient) => saw_not_recipient = true,
3031                    Err(err) => crate::log_warn!("rekey catch-up: skipping epoch {e} chunk: {err}"),
3032                }
3033            }
3034            if applied {
3035                // Reorg detection: if this rekey continues from a prior epoch whose key I hold but whose
3036                // commitment mismatches, I just converged forward off a losing fork — that prior epoch is forked
3037                // and needs its own lowest-key heal (else its messages stay unreadable under the wrong sibling).
3038                // All chunks of one rotation carry IDENTICAL continuity fields (same prev_epoch + prev_commit —
3039                // they're the same rotation split across size-bounded events), so `first()` is representative.
3040                if let Some(p) = chunks.first() {
3041                    let pe = p.prev_epoch.0;
3042                    if let Ok(Some(prev_key)) = crate::db::community::held_epoch_key(&cid, &channel_hex, pe) {
3043                        if super::rekey::epoch_key_commitment(p.prev_epoch, &prev_key) != p.prev_key_commitment {
3044                            forked_epochs.insert(pe);
3045                        }
3046                    }
3047                }
3048                // A non-contiguous jump means intermediate epochs weren't recovered (a relay gap) —
3049                // surface the hole (that history stays unreadable until re-fetched).
3050                if e > head + 1 {
3051                    crate::log_warn!(
3052                        "rekey catch-up: channel epochs {}..={} not recovered (key gap; history unreadable until re-fetched)",
3053                        head + 1, e - 1
3054                    );
3055                }
3056                head = head.max(e);
3057            } else if saw_not_recipient {
3058                // A valid rotation at this epoch held no blob for me across ALL its chunks ⇒ I was removed
3059                // here. Forward-terminal (re-add is a fresh invite), so stop — nothing past it is ours.
3060                removed = true;
3061                break;
3062            }
3063            // else: all chunks at this epoch errored (gap/forged) — don't advance, don't remove.
3064        }
3065
3066        // Stop on removal (terminal), when a full round advanced nothing (only gaps/forged events — no
3067        // legit rekey for us here), or when the window wasn't saturated (we've reached the latest).
3068        if removed || head == head_before || max_found < window_top {
3069            break;
3070        }
3071    }
3072
3073    // BACKWARD gap-fill (heal): the forward walk above advances the HEAD and can leapfrog an epoch
3074    // whose rekey wasn't found (a prior catch-up that lacked the addressing root, or a relay miss). Those
3075    // holes are below `head`, so the forward window never revisits them — yet we're entitled to those
3076    // keys. Re-fetch each MISSING epoch's rekey under every held server root and apply it (archive-only:
3077    // `advance_channel_epoch` never regresses the head), so stranded history (messages under a skipped
3078    // epoch) becomes readable. Non-ratcheted keys make this pure random-access — no replay needed.
3079    let held: std::collections::HashSet<u64> = crate::db::community::held_epoch_keys(&cid, &channel_hex)
3080        .unwrap_or_default()
3081        .into_iter()
3082        .map(|(e, _)| e.0)
3083        .collect();
3084    let missing: Vec<u64> = (0..head).filter(|e| !held.contains(e)).collect();
3085    if !missing.is_empty() {
3086        for sr in &server_roots {
3087            if !session.is_valid() {
3088                return Err("session changed during rekey gap-fill".to_string());
3089            }
3090            let z_tags: Vec<String> = missing
3091                .iter()
3092                .map(|e| super::derive::rekey_pseudonym(&super::ServerRootKey(*sr), channel_id, super::Epoch(*e)).to_hex())
3093                .collect();
3094            let query = Query { kinds: vec![event_kind::COMMUNITY_REKEY], z_tags, ..Default::default() };
3095            // Best-effort (same rationale as the forward walk): a relay error on a gap-fill fetch must not
3096            // abort before the convergence heal.
3097            for ev in transport.fetch(&query, &community.relays).await.unwrap_or_default() {
3098                if let Ok(p) = super::rekey::open_rekey_event(&ev, sr) {
3099                    if matches!(p.scope, super::derive::RekeyScope::Channel(c) if &c == channel_id) {
3100                        let _ = apply_channel_rekey(community, &p); // archive-only for sub-head epochs
3101                    }
3102                }
3103            }
3104        }
3105    }
3106
3107    // CONCURRENT RE-FOUNDING HEAL: converge to the deterministic LOWEST authorized sibling at every epoch that
3108    // can be forked — the current HEAD (two MANAGE_CHANNELS holders rotated it concurrently with different
3109    // keys), every epoch I reorged through THIS sync, AND the recent window of held epochs. The window
3110    // pass heals a member that reorged its head under an EARLIER build (so `forked_epochs` was never populated
3111    // for it) yet still sits on a losing sibling at a past epoch — otherwise that epoch's messages stay
3112    // unreadable forever (the gap-fill skips it because a key IS held). One batched fetch per held root.
3113    if head > 0 && session.is_valid() {
3114        let lo = head.saturating_sub(REKEY_CATCHUP_WINDOW).max(1);
3115        let mut epochs: std::collections::BTreeSet<u64> = (lo..=head).collect();
3116        epochs.append(&mut forked_epochs);
3117        let _ = heal_channel_fork_epochs(transport, community, channel_id, &cid, &channel_hex, &epochs, &server_roots, &session).await;
3118    }
3119    Ok(head)
3120}
3121
3122/// Backstop on base-rotation walk steps (base rotations are rare, so this far exceeds any real chain;
3123/// it bounds a hostile/fabricated chain — which already fails at `apply_server_root_rekey` anyway).
3124const MAX_BASE_CATCHUP_STEPS: usize = 256;
3125
3126/// Catch the SERVER ROOT up to its latest epoch — a FORWARD WALK (the base has no stable key above
3127/// it, so `base_rekey_pseudonym` is keyed by the PRIOR root). Each step: derive the next base rekey's
3128/// address from the root I currently hold, fetch it, open it under that root, apply it (recovering the
3129/// NEXT root), and repeat. Returns the new base epoch. One step per base rotation — bounded, and base
3130/// rotations are rare. Stops on a removal (`NotARecipient` — re-add is a fresh invite, not this walk),
3131/// when no further base rekey exists, or when a rekey can't be applied (can't get the next root).
3132///
3133/// After this advances the base epoch, the caller MUST resync the control plane at the NEW epoch
3134/// (`control_pseudonym(new_root, …)`) before trusting authority — the re-anchoring guarantees the
3135/// current heads are reachable there (#4e). This fn only recovers the base keys + advances the head.
3136/// B2 helper: open MY ServerRoot blob in `parsed` WITHOUT committing, to learn which new root this rotation
3137/// would deliver me. Lets [`catch_up_server_root`] pick the canonical rotation among concurrent re-foundings
3138/// before applying any. `Ok(None)` = I'm not a recipient of this rotation (or it's not a base rekey).
3139fn peek_my_server_root(parsed: &super::rekey::ParsedRekey) -> Result<Option<[u8; 32]>, String> {
3140    if !matches!(parsed.scope, super::derive::RekeyScope::ServerRoot) {
3141        return Ok(None);
3142    }
3143    let my_keys = crate::state::MY_SECRET_KEY.to_keys().ok_or("no local key to open a base rekey blob")?;
3144    let secret = super::rekey::rekey_pairwise_secret(my_keys.secret_key(), &parsed.rotator)?;
3145    let my_locator = super::derive::recipient_pseudonym(&secret, parsed.scope, parsed.new_epoch).to_hex();
3146    let mine = match parsed.blobs.iter().find(|b| b.locator == my_locator) {
3147        Some(b) => b,
3148        None => return Ok(None),
3149    };
3150    super::rekey::open_rekey_blob(my_keys.secret_key(), &parsed.rotator, parsed.scope, parsed.new_epoch, mine).map(Some)
3151}
3152
3153/// Convergence helper: open MY Channel blob in `parsed` WITHOUT committing, to learn which new channel key this
3154/// rotation would deliver me. Lets the channel current-head heal pick a deterministic winner (lowest
3155/// delivered key) among concurrent same-epoch channel rotations. `None` = not a recipient / can't open.
3156fn peek_my_channel_key(parsed: &super::rekey::ParsedRekey) -> Option<[u8; 32]> {
3157    let my_keys = crate::state::MY_SECRET_KEY.to_keys()?;
3158    let secret = super::rekey::rekey_pairwise_secret(my_keys.secret_key(), &parsed.rotator).ok()?;
3159    let my_locator = super::derive::recipient_pseudonym(&secret, parsed.scope, parsed.new_epoch).to_hex();
3160    let mine = parsed.blobs.iter().find(|b| b.locator == my_locator)?;
3161    super::rekey::open_rekey_blob(my_keys.secret_key(), &parsed.rotator, parsed.scope, parsed.new_epoch, mine).ok()
3162}
3163
3164pub async fn catch_up_server_root<T: Transport + ?Sized>(
3165    transport: &T,
3166    community: &Community,
3167) -> Result<BaseCatchup, String> {
3168    let session = SessionGuard::capture();
3169    let cid = community.id.to_hex();
3170    let mut head = community.server_root_epoch.0;
3171    // Set true if the walk stops because an AUTHORIZED base rotation EXCLUDED us (read-cut / private ban):
3172    // we hold the prior root, opened the rotation, its rotator held BAN per the roster we hold, but no chunk
3173    // carried our blob. The caller treats this as removal and erases local community data (the cut member
3174    // can't read the new banlist to learn it the normal way, so this is the catch-all removal signal).
3175    let mut removed = false;
3176    // The root I currently hold at `head` — drives the next step's address (prior-root-keyed) + opens it.
3177    let mut current_root: [u8; 32] = *community.server_root_key.as_bytes();
3178
3179    for _step in 0..MAX_BASE_CATCHUP_STEPS {
3180        let next = match head.checked_add(1) {
3181            Some(n) => n,
3182            None => break,
3183        };
3184        let addr = super::derive::base_rekey_pseudonym(&super::ServerRootKey(current_root), &community.id, super::Epoch(next)).to_hex();
3185        let query = Query { kinds: vec![event_kind::COMMUNITY_REKEY], z_tags: vec![addr], ..Default::default() };
3186        let events = transport.fetch(&query, &community.relays).await?;
3187        if events.is_empty() {
3188            break; // no base rotation past `head`
3189        }
3190
3191        // Open under the root I hold; a base rotation at `next` may be SPLIT across chunk events at this
3192        // address, so collect ALL chunks for `next`.
3193        let chunks: Vec<super::rekey::ParsedRekey> = events
3194            .iter()
3195            .filter_map(|ev| super::rekey::open_rekey_event(ev, &current_root).ok())
3196            .filter(|p| matches!(p.scope, super::derive::RekeyScope::ServerRoot) && p.new_epoch.0 == next)
3197            .collect();
3198        if chunks.is_empty() {
3199            break; // nothing valid for `next` under the root we hold
3200        }
3201
3202        if !session.is_valid() {
3203            return Err("session changed during base rekey catch-up".to_string());
3204        }
3205
3206        // B2 — CONCURRENT RE-FOUNDING CONVERGENCE. There may be MORE than one rotation at `next` (two
3207        // BAN-holders re-founding at once, each delivering a DIFFERENT new root to the same observed set).
3208        // Every member must pick the SAME one or the community forks irrecoverably. Peek the root each
3209        // rotation would give me, then deterministically choose the LOWEST new-root bytes — convergent for
3210        // everyone who received both. (The root is the only member-computable rotation identity: the inner
3211        // event id of "my" chunk differs per member, since each member's blob sits in a different chunk, so
3212        // it can't be the tiebreak.) A member who only received the losing root heals on the next re-founding.
3213        //
3214        // AUTHORITY BEFORE THE TIEBREAK: only a BAN-holder's rotation is a candidate. A plain member
3215        // holds the prior root + can sign as rotator + build valid ECDH blobs, so without this gate they
3216        // could forge a byte-LOWER root that honest members would PICK as the winner and then fail to apply
3217        // (authority is also checked in apply) — stalling them at the prior epoch while others advance: a
3218        // permanent fork the heal can't recover. Gate here, before `min_by`, exactly like the current-head heal.
3219        let owner_hex = proven_owner_hex(community);
3220        let roster = crate::db::community::get_community_roles(&cid).unwrap_or_default();
3221        let mut candidates: Vec<(&super::rekey::ParsedRekey, [u8; 32])> = Vec::new();
3222        for parsed in &chunks {
3223            if !rotator_is_authorized(&cid, &roster, owner_hex.as_deref(), &parsed.rotator.to_hex(), super::roles::Permissions::BAN) {
3224                continue;
3225            }
3226            match peek_my_server_root(parsed) {
3227                Ok(Some(root)) => candidates.push((parsed, root)),
3228                Ok(None) => {}
3229                Err(err) => crate::log_warn!("base rekey catch-up: epoch {next} peek: {err}"),
3230            }
3231        }
3232        let applied = match candidates.into_iter().min_by(|a, b| a.1.cmp(&b.1)) {
3233            Some((parsed, _)) => match apply_server_root_rekey(community, parsed) {
3234                Ok(RekeyOutcome::Applied { .. }) => true,
3235                Ok(RekeyOutcome::NotARecipient) => false, // unreachable: peek already confirmed recipiency
3236                Err(err) => { crate::log_warn!("base rekey catch-up: epoch {next} apply: {err}"); false }
3237            },
3238            None => {
3239                // No chunk held my blob — I was excluded from this base rotation. If an AUTHORIZED rotator
3240                // (held BAN per the roster I STILL hold) performed it, this is a read-cut removing me →
3241                // signal removal so the caller erases. Verify authority so a non-BAN member who merely holds
3242                // the prior root can't forge an eviction event that tricks me into self-deleting.
3243                let owner = proven_owner_hex(community);
3244                let roster = crate::db::community::get_community_roles(&cid).unwrap_or_default();
3245                if chunks.iter().any(|p| rotator_is_authorized(&cid, &roster, owner.as_deref(), &p.rotator.to_hex(), super::roles::Permissions::BAN)) {
3246                    removed = true;
3247                }
3248                false // removed from the base (terminal) → stop the walk
3249            }
3250        };
3251        if !applied {
3252            break;
3253        }
3254        // Recover the just-archived new root to address the next step.
3255        match crate::db::community::held_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, next)? {
3256            Some(root) => {
3257                current_root = root;
3258                head = next;
3259            }
3260            None => {
3261                // Shouldn't happen — apply archives the root before returning Applied. If it ever does,
3262                // a DB-archive invariant broke; stop rather than loop on a stale root.
3263                crate::log_warn!("base rekey catch-up: epoch {next} applied but its root is not archived; halting walk");
3264                break;
3265            }
3266        }
3267    }
3268
3269    // CONCURRENT RE-FOUNDING HEAL (current-head convergence): the forward walk only tiebreaks at head+1, so
3270    // two BAN-holders who re-founded at the SAME epoch each end on their OWN root and never reconcile each
3271    // other (only bystanders advancing INTO the epoch do). Re-fetch THIS epoch's base rekeys — they're all
3272    // at the one address keyed by the PRIOR root we still hold — and if an AUTHORIZED sibling delivers a
3273    // LOWER root than the one we hold, switch to it (the same lowest-root rule), then re-fold the control
3274    // plane under the adopted root. Convergent for everyone: the lowest root is the deterministic winner.
3275    if head > 0 && !removed {
3276        if let Ok(Some(prior_root)) = crate::db::community::held_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, head - 1) {
3277            let addr = super::derive::base_rekey_pseudonym(&super::ServerRootKey(prior_root), &community.id, super::Epoch(head)).to_hex();
3278            let query = Query { kinds: vec![event_kind::COMMUNITY_REKEY], z_tags: vec![addr], ..Default::default() };
3279            let events = transport.fetch(&query, &community.relays).await.unwrap_or_default();
3280            let chunks: Vec<super::rekey::ParsedRekey> = events
3281                .iter()
3282                .filter_map(|ev| super::rekey::open_rekey_event(ev, &prior_root).ok())
3283                .filter(|p| matches!(p.scope, super::derive::RekeyScope::ServerRoot) && p.new_epoch.0 == head)
3284                .collect();
3285            let owner_hex = proven_owner_hex(community);
3286            let roster = crate::db::community::get_community_roles(&cid).unwrap_or_default();
3287            let mut best: Option<(&super::rekey::ParsedRekey, [u8; 32])> = None;
3288            for p in &chunks {
3289                // Only an AUTHORIZED re-founding (rotator held BAN, not banned) is a convergence
3290                // candidate — a non-BAN member who merely holds the prior root can't forge a lower
3291                // root to hijack the chain.
3292                if !rotator_is_authorized(&cid, &roster, owner_hex.as_deref(), &p.rotator.to_hex(), super::roles::Permissions::BAN) {
3293                    continue;
3294                }
3295                if let Ok(Some(root)) = peek_my_server_root(p) {
3296                    if best.as_ref().map_or(true, |(_, br)| root < *br) {
3297                        best = Some((p, root));
3298                    }
3299                }
3300            }
3301            // Authority dominates the down-only rule: if the root I currently hold is POSITIVELY
3302            // identified as a since-deauthorized rotation (its chunk is on the wire, delivers my
3303            // current root, and its rotator now fails the authority/banlist gate), abandon it for
3304            // the lowest AUTHORIZED sibling even when that sibling is byte-higher. Without this, a
3305            // banned admin who raced their own removal with a ground-low re-founding root keeps
3306            // every member who adopted it partitioned forever — the heal would refuse to climb back
3307            // to the owner's legitimate (higher) root. Positive identification only: when the
3308            // current root's chunk is absent (withheld), keep the strict down-only rule so a flaky
3309            // round can't re-fork a converged epoch.
3310            let current_deauthorized = chunks.iter().any(|p| {
3311                matches!(peek_my_server_root(p), Ok(Some(r)) if r == current_root)
3312                    && !rotator_is_authorized(&cid, &roster, owner_hex.as_deref(), &p.rotator.to_hex(), super::roles::Permissions::BAN)
3313            });
3314            if let Some((winner, win_root)) = best {
3315                let adopt = if current_deauthorized {
3316                    win_root != current_root
3317                } else {
3318                    win_root < current_root
3319                };
3320                if adopt {
3321                    if !session.is_valid() {
3322                        return Err("session changed during base convergence".to_string());
3323                    }
3324                    // Adopt the winner: apply archives its root (no head advance at the same epoch), then
3325                    // `converge_server_root_epoch` swaps the head root, then re-fold control under it.
3326                    if apply_server_root_rekey(community, winner).is_ok() {
3327                        match crate::db::community::converge_server_root_epoch(&cid, head, &win_root) {
3328                            Ok(false) => crate::log_trace!("base heal: converge of epoch {head} did not apply (head moved)"),
3329                            Err(e) => crate::log_trace!("base heal: converge of epoch {head} errored: {e}"),
3330                            Ok(true) => {}
3331                        }
3332                        current_root = win_root;
3333                        if let Ok(Some(fresh)) = crate::db::community::load_community(&community.id) {
3334                            let _ = fetch_and_apply_control(transport, &fresh).await;
3335                        }
3336                    }
3337                }
3338            }
3339        }
3340    }
3341    let _ = current_root; // may be unused if no further steps read it
3342    Ok(BaseCatchup { epoch: head, removed })
3343}
3344
3345/// Outcome of [`catch_up_server_root`]: the base epoch reached, and whether an AUTHORIZED base rotation
3346/// EXCLUDED us (a read-cut / private ban). `removed` is the catch-all "you've been removed" signal for a
3347/// cryptographically cut member who can no longer read the banlist to learn it the normal way.
3348#[derive(Debug, Clone, Copy)]
3349pub struct BaseCatchup {
3350    pub epoch: u64,
3351    pub removed: bool,
3352}
3353
3354#[cfg(test)]
3355mod tests {
3356    use super::*;
3357    use crate::community::send::fetch_channel_messages;
3358    use crate::community::transport::{memory::MemoryRelay, Query, Transport};
3359    use nostr_sdk::prelude::{EventBuilder, Kind};
3360
3361    /// A transport whose publish always fails (fetch returns nothing) — for testing that
3362    /// a failed deletion publish doesn't strand the single-use key.
3363    struct FailingRelay;
3364    #[async_trait::async_trait]
3365    impl Transport for FailingRelay {
3366        async fn publish(&self, _event: &Event, _relays: &[String]) -> Result<(), String> {
3367            Err("relay unreachable".to_string())
3368        }
3369        async fn publish_durable(&self, _event: &Event, _relays: &[String]) -> Result<(), String> {
3370            Err("relay unreachable".to_string())
3371        }
3372        async fn fetch(&self, _query: &Query, _relays: &[String]) -> Result<Vec<Event>, String> {
3373            Ok(Vec::new())
3374        }
3375    }
3376
3377    /// A relay that selectively fails REKEY (3303) publishes (toggleable), delegating everything else to
3378    /// an inner [`MemoryRelay`]. Lets a test make a re-seal's base rekey fail while the banlist edition
3379    /// still lands, then "fix" the relay and verify the read-cut retry recovers.
3380    struct RekeyFailingRelay {
3381        inner: MemoryRelay,
3382        fail_rekey: std::sync::atomic::AtomicBool,
3383    }
3384    impl RekeyFailingRelay {
3385        fn new() -> Self {
3386            Self { inner: MemoryRelay::new(), fail_rekey: std::sync::atomic::AtomicBool::new(true) }
3387        }
3388        fn allow_rekey(&self) {
3389            self.fail_rekey.store(false, std::sync::atomic::Ordering::Relaxed);
3390        }
3391        fn blocks(&self, event: &Event) -> bool {
3392            self.fail_rekey.load(std::sync::atomic::Ordering::Relaxed)
3393                && event.kind.as_u16() == crate::stored_event::event_kind::COMMUNITY_REKEY
3394        }
3395    }
3396    #[async_trait::async_trait]
3397    impl Transport for RekeyFailingRelay {
3398        async fn publish(&self, event: &Event, relays: &[String]) -> Result<(), String> {
3399            if self.blocks(event) { return Err("rekey relay down".to_string()); }
3400            self.inner.publish(event, relays).await
3401        }
3402        async fn publish_durable(&self, event: &Event, relays: &[String]) -> Result<(), String> {
3403            if self.blocks(event) { return Err("rekey relay down".to_string()); }
3404            self.inner.publish_durable(event, relays).await
3405        }
3406        async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
3407            self.inner.fetch(query, relays).await
3408        }
3409    }
3410
3411    static TEST_COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(5000);
3412
3413    fn make_test_npub(n: u32) -> String {
3414        const BECH32: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
3415        let mut payload = vec![b'q'; 58];
3416        let mut x = n as u64;
3417        let mut i = 58;
3418        while x > 0 && i > 0 {
3419            i -= 1;
3420            payload[i] = BECH32[(x as usize) % 32];
3421            x /= 32;
3422        }
3423        format!("npub1{}", std::str::from_utf8(&payload).unwrap())
3424    }
3425
3426    fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
3427        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
3428        crate::db::close_database();
3429        // Per-account row-id caches survive close_database; clear them so a stale entry from a prior
3430        // test's DB can't point into this fresh account's DB and FK-fail an insert.
3431        crate::db::clear_id_caches();
3432        let tmp = tempfile::tempdir().unwrap();
3433        let n = TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3434        let account = make_test_npub(n);
3435        std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
3436        crate::db::set_app_data_dir(tmp.path().to_path_buf());
3437        crate::db::set_current_account(account.clone()).unwrap();
3438        crate::db::init_database(&account).unwrap();
3439        // Clear any client a prior test installed — else `active_signer()` would prefer that stale
3440        // client's signer over this test's fresh local identity (cross-test contamination).
3441        let _ = crate::state::take_nostr_client();
3442        // A local owner identity so create_community can sign the (now mandatory) owner attestation.
3443        let owner = Keys::generate();
3444        crate::state::MY_SECRET_KEY.store_from_keys(&owner, &[]);
3445        crate::state::set_my_public_key(owner.public_key());
3446        (tmp, guard)
3447    }
3448
3449    #[test]
3450    fn community_cap_rejects_a_new_membership_at_the_limit() {
3451        let (_tmp, _guard) = init_test_db();
3452        let mk = |i: usize| {
3453            let id = format!("{:064x}", i);
3454            crate::community::list::CommunityListEntry {
3455                community_id: id.clone(),
3456                seed: crate::community::invite::CommunityInvite {
3457                    community_id: id,
3458                    name: String::new(),
3459                    server_root_key: String::new(),
3460                    server_root_epoch: 0,
3461                    relays: vec![],
3462                    channels: vec![],
3463                    owner_attestation: None,
3464                    icon: None,
3465                },
3466                current: None,
3467                added_at: 0,
3468            }
3469        };
3470        let mut list = crate::community::list::CommunityList::default();
3471        for i in 0..(MAX_COMMUNITIES - 1) {
3472            list.entries.push(mk(i));
3473        }
3474        crate::db::settings::set_sql_setting("community_list_json".to_string(), list.to_json()).unwrap();
3475        assert!(enforce_community_cap().is_ok(), "under the cap a new join is allowed");
3476
3477        list.entries.push(mk(MAX_COMMUNITIES - 1)); // now exactly MAX_COMMUNITIES
3478        crate::db::settings::set_sql_setting("community_list_json".to_string(), list.to_json()).unwrap();
3479        assert!(enforce_community_cap().is_err(), "at the cap a new join is rejected");
3480    }
3481
3482    // --- apply_channel_rekey (#3c) ---
3483
3484    /// Build + persist a member-view community whose proven owner is `owner` (attestation signed by
3485    /// them), archiving the genesis epoch-0 channel key + server root via save_community.
3486    fn saved_community_owned_by(owner: &Keys) -> Community {
3487        use nostr_sdk::JsonUtil;
3488        let mut community = Community::create("HQ", "general", vec!["r".into()]);
3489        let cid = community.id.to_hex();
3490        community.owner_attestation = Some(
3491            crate::community::owner::build_owner_attestation_unsigned(owner.public_key(), &cid)
3492                .sign_with_keys(owner)
3493                .unwrap()
3494                .as_json(),
3495        );
3496        crate::db::community::save_community(&community).unwrap();
3497        community
3498    }
3499
3500    /// An in-memory owner-attested Community signed by the SEEDED local identity (so `is_proven_owner`
3501    /// is true and owner-gated actions like `create_public_invite` pass). NOT saved to the DB — for
3502    /// tests where the same single DB later plays the joiner.
3503    fn attested_community(name: &str, channel: &str, relays: Vec<String>) -> Community {
3504        use nostr_sdk::JsonUtil;
3505        let owner = crate::state::MY_SECRET_KEY.to_keys().unwrap();
3506        let mut community = Community::create(name, channel, relays);
3507        community.owner_attestation = Some(
3508            crate::community::owner::build_owner_attestation_unsigned(owner.public_key(), &community.id.to_hex())
3509                .sign_with_keys(&owner).unwrap().as_json(),
3510        );
3511        community
3512    }
3513
3514    /// Set the local identity (the rekey recipient in these tests).
3515    fn become_local(me: &Keys) {
3516        crate::state::MY_SECRET_KEY.store_from_keys(me, &[]);
3517        crate::state::set_my_public_key(me.public_key());
3518    }
3519
3520    /// An owner-authored channel rekey to `new_epoch` carrying one blob for `recipient_pk`, citing the
3521    /// genesis epoch-0 key as `prev`. Returns the opened ParsedRekey ready for apply.
3522    fn owner_channel_rekey(
3523        owner: &Keys,
3524        community: &Community,
3525        recipient_pk: &nostr_sdk::PublicKey,
3526        new_epoch: u64,
3527        new_key: &[u8; 32],
3528    ) -> super::super::rekey::ParsedRekey {
3529        let chan = &community.channels[0];
3530        let scope = super::super::derive::RekeyScope::Channel(chan.id);
3531        let blob = super::super::rekey::build_rekey_blob(
3532            owner.secret_key(), recipient_pk, scope, crate::community::Epoch(new_epoch), new_key,
3533        )
3534        .unwrap();
3535        let commit = super::super::rekey::epoch_key_commitment(crate::community::Epoch(0), chan.key.as_bytes());
3536        let outer = super::super::rekey::build_channel_rekey_event(
3537            &Keys::generate(), owner, community.server_root_key.as_bytes(), &chan.id,
3538            crate::community::Epoch(new_epoch), crate::community::Epoch(0), &commit, &[blob],
3539        )
3540        .unwrap();
3541        super::super::rekey::open_rekey_event(&outer, community.server_root_key.as_bytes()).unwrap()
3542    }
3543
3544    /// Transport-unified outer dedup: a wire event we've already persisted (its outer id recorded as
3545    /// the inner's `wrapper_event_id`) is dropped BEFORE decryption on a re-fetch — the same contract
3546    /// DM gift-wraps get from the wrapper-id layer. This is what keeps a boot/catch-up sweep's re-fetch
3547    /// of the whole channel page from re-ingesting or re-emitting events we already hold.
3548    #[tokio::test]
3549    async fn outer_event_dedup_skips_an_already_persisted_wire_event() {
3550        let (_tmp, _guard) = init_test_db();
3551        let owner = Keys::generate();
3552        let me = Keys::generate();
3553        become_local(&me);
3554        let community = saved_community_owned_by(&owner);
3555        let channel = community.channels[0].clone();
3556        let chan_hex = channel.id.to_hex();
3557
3558        // A real wire event (stable outer id) authored by a keyholding member.
3559        let author = Keys::generate();
3560        let outer = crate::community::envelope::seal_message(
3561            &author, &channel.key, &channel.id, channel.epoch, "gm", 1000,
3562        ).unwrap();
3563        let outer_hex = outer.id.to_hex();
3564
3565        // First sight: ingests, and the inner records its OUTER wire id as the wrapper link.
3566        let mut state = crate::state::ChatState::new();
3567        let msg = match crate::community::inbound::process_incoming(&mut state, &outer, &channel, &me.public_key()) {
3568            Some(crate::community::inbound::IncomingEvent::NewMessage(m)) => m,
3569            _ => panic!("expected NewMessage from a fresh wire event"),
3570        };
3571        assert_eq!(msg.wrapper_event_id.as_deref(), Some(outer_hex.as_str()),
3572            "the inner must carry its outer wire id as wrapper_event_id");
3573
3574        // Persist exactly as the sweep does (writes wrapper_event_id into the events table).
3575        crate::db::events::save_message(&chan_hex, &msg).await.unwrap();
3576
3577        // Re-fetch / relay redelivery of the SAME wire event → dropped before decryption.
3578        let mut state2 = crate::state::ChatState::new();
3579        let second = crate::community::inbound::process_incoming(&mut state2, &outer, &channel, &me.public_key());
3580        assert!(second.is_none(), "an already-processed wire event must dedup before decryption");
3581    }
3582
3583    /// The dedup ledger is shared across transports, but NIP-77 negentropy must fingerprint ONLY the
3584    /// gift-wrap ('nip17') subset — a Concord wrapper in the DM reconciliation set would bloat and skew it.
3585    #[tokio::test]
3586    async fn ledger_is_shared_but_negentropy_stays_nip17_only() {
3587        let (_tmp, _guard) = init_test_db();
3588        let dm = [0xA1u8; 32];
3589        let concord = [0xC0u8; 32];
3590        crate::db::wrappers::save_processed_wrapper(&dm, 100, crate::db::wrappers::TRANSPORT_NIP17).unwrap();
3591        crate::db::wrappers::save_processed_wrapper(&concord, 200, crate::db::wrappers::TRANSPORT_CONCORD).unwrap();
3592
3593        // The dedup ledger sees BOTH transports.
3594        assert!(crate::db::wrappers::processed_wrapper_exists(&dm));
3595        assert!(crate::db::wrappers::processed_wrapper_exists(&concord));
3596
3597        // NIP-77 fingerprints only the gift-wrap subset — Concord never leaks into DM sync.
3598        let items = crate::db::wrappers::load_negentropy_items().unwrap();
3599        assert_eq!(items.len(), 1, "negentropy must exclude concord wrappers");
3600        assert_eq!(items[0].0.to_bytes(), dm);
3601    }
3602
3603    /// A non-message sub-kind (presence) has no inner row to carry a wrapper_event_id, so it records the
3604    /// outer id in the shared ledger at process time. A re-fetch then dedups it before decryption, just
3605    /// like a message — every sub-kind gets the same transport-level skip.
3606    #[tokio::test]
3607    async fn non_message_subkind_dedups_via_the_shared_ledger() {
3608        let (_tmp, _guard) = init_test_db();
3609        let owner = Keys::generate();
3610        let me = Keys::generate();
3611        become_local(&me);
3612        let community = saved_community_owned_by(&owner);
3613        let channel = community.channels[0].clone();
3614
3615        // A presence (3306) wire event from a member — a non-row sub-kind.
3616        let author = Keys::generate();
3617        let inner = super::super::envelope::build_inner_typed(
3618            author.public_key(), &channel.id, channel.epoch,
3619            crate::stored_event::event_kind::COMMUNITY_PRESENCE, "join", 5, None, &[],
3620        ).sign_with_keys(&author).unwrap();
3621        let outer = super::super::envelope::seal_with_signed_inner(
3622            &Keys::generate(), &inner, &channel.key, &channel.id, channel.epoch,
3623        ).unwrap();
3624
3625        // First sight: a Presence outcome, and the outer id is recorded in the ledger.
3626        let mut state = crate::state::ChatState::new();
3627        let first = crate::community::inbound::process_incoming(&mut state, &outer, &channel, &me.public_key());
3628        assert!(matches!(first, Some(crate::community::inbound::IncomingEvent::Presence { .. })),
3629            "expected a Presence outcome");
3630        assert!(crate::db::wrappers::processed_wrapper_exists(&outer.id.to_bytes()),
3631            "a non-message sub-kind must record its outer id in the shared ledger");
3632
3633        // Re-fetch of the same wire event → dropped before decryption.
3634        let second = crate::community::inbound::process_incoming(&mut crate::state::ChatState::new(), &outer, &channel, &me.public_key());
3635        assert!(second.is_none(), "a re-fetched presence must dedup via the shared ledger");
3636    }
3637
3638    #[test]
3639    fn apply_channel_rekey_recovers_and_advances_head() {
3640        let (_tmp, _guard) = init_test_db();
3641        let owner = Keys::generate(); // owner = rotator (supreme authority)
3642        let me = Keys::generate();
3643        become_local(&me);
3644        let community = saved_community_owned_by(&owner);
3645        let cid = community.id.to_hex();
3646        let chan_hex = community.channels[0].id.to_hex();
3647        let new_key = [0xCDu8; 32];
3648
3649        let parsed = owner_channel_rekey(&owner, &community, &me.public_key(), 1, &new_key);
3650        let outcome = apply_channel_rekey(&community, &parsed).unwrap();
3651        assert_eq!(outcome, RekeyOutcome::Applied { head_advanced: true });
3652
3653        // Archive holds the new epoch-1 key, and the channel head advanced to it (epoch + key).
3654        assert_eq!(crate::db::community::held_epoch_key(&cid, &chan_hex, 1).unwrap(), Some(new_key));
3655        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
3656        assert_eq!(reloaded.channels[0].epoch, crate::community::Epoch(1));
3657        assert_eq!(reloaded.channels[0].key.as_bytes(), &new_key);
3658        // The genesis epoch-0 key is RETAINED (cross-epoch history stays decryptable).
3659        assert!(crate::db::community::held_epoch_key(&cid, &chan_hex, 0).unwrap().is_some());
3660    }
3661
3662    #[test]
3663    fn apply_channel_rekey_accepts_matching_continuity() {
3664        // The happy continuity path: I HOLD the prior (genesis epoch-0) key and the rekey cites a
3665        // commitment over it → the fork-detection check passes and the rekey applies.
3666        let (_tmp, _guard) = init_test_db();
3667        let owner = Keys::generate();
3668        let me = Keys::generate();
3669        become_local(&me);
3670        let community = saved_community_owned_by(&owner);
3671        // owner_channel_rekey commits over the genesis epoch-0 key, which I hold (archived on save).
3672        let parsed = owner_channel_rekey(&owner, &community, &me.public_key(), 1, &[0x44u8; 32]);
3673        assert_eq!(
3674            apply_channel_rekey(&community, &parsed).unwrap(),
3675            RekeyOutcome::Applied { head_advanced: true },
3676            "a rekey whose prior-key commitment matches the held genesis key applies"
3677        );
3678    }
3679
3680    #[test]
3681    fn advance_channel_epoch_archives_when_no_head_row() {
3682        // A rekey for a channel with no community_channels head row: archive the key, don't fabricate
3683        // a head. (Exercises advance_channel_epoch's channel-row-absent branch directly.)
3684        let (_tmp, _guard) = init_test_db();
3685        let cid = "f".repeat(64);
3686        let orphan_channel = "a".repeat(64);
3687        let advanced = crate::db::community::advance_channel_epoch(&cid, &orphan_channel, 2, &[0x77u8; 32]).unwrap();
3688        assert!(!advanced, "no head row → head not advanced");
3689        assert_eq!(crate::db::community::held_epoch_key(&cid, &orphan_channel, 2).unwrap(), Some([0x77u8; 32]), "key still archived");
3690    }
3691
3692    #[tokio::test]
3693    async fn rotate_channel_publishes_recoverable_rekey_and_advances_own_head() {
3694        use crate::community::derive::{recipient_pseudonym, rekey_pseudonym};
3695        use crate::community::rekey::{open_rekey_blob, open_rekey_event, rekey_pairwise_secret};
3696        let (_tmp, _guard) = init_test_db();
3697        let owner = Keys::generate();
3698        become_local(&owner); // I am the owner (supreme authority to rotate)
3699        let community = saved_community_owned_by(&owner);
3700        let channel_id = community.channels[0].id;
3701        let member = Keys::generate(); // a stayer who must recover the new key
3702        let relay = MemoryRelay::new();
3703
3704        let new_epoch = rotate_channel(&relay, &community, &channel_id, &[member.public_key()], community.server_root_key.as_bytes())
3705            .await
3706            .expect("rotate");
3707        assert_eq!(new_epoch, 1);
3708
3709        // My own head advanced to the new epoch + a fresh key.
3710        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
3711        assert_eq!(reloaded.channels[0].epoch, crate::community::Epoch(1));
3712
3713        // The published rekey is found at the SERVER-ROOT-derived address (no channel key needed) and
3714        // opens under the server root.
3715        let addr = rekey_pseudonym(
3716            &crate::community::ServerRootKey(*community.server_root_key.as_bytes()),
3717            &channel_id, crate::community::Epoch(1),
3718        )
3719        .to_hex();
3720        let found = relay
3721            .fetch(&Query { kinds: vec![event_kind::COMMUNITY_REKEY], z_tags: vec![addr], ..Default::default() }, &community.relays)
3722            .await
3723            .unwrap();
3724        assert_eq!(found.len(), 1, "rekey addressable by its server-root pseudonym");
3725        let parsed = open_rekey_event(&found[0], community.server_root_key.as_bytes()).unwrap();
3726        assert_eq!(parsed.rotator, owner.public_key());
3727        assert_eq!(parsed.new_epoch, crate::community::Epoch(1));
3728        assert_eq!(parsed.prev_epoch, crate::community::Epoch(0));
3729        assert_eq!(parsed.blobs.len(), 2, "the member + me (multi-device) each get a blob");
3730
3731        // The member recovers a key, and it is EXACTLY the key my head advanced to (one source of truth).
3732        let secret = rekey_pairwise_secret(member.secret_key(), &parsed.rotator).unwrap();
3733        let loc = recipient_pseudonym(&secret, parsed.scope, parsed.new_epoch).to_hex();
3734        let mine = parsed.blobs.iter().find(|b| b.locator == loc).expect("member's blob present");
3735        let recovered = open_rekey_blob(member.secret_key(), &parsed.rotator, parsed.scope, parsed.new_epoch, mine).unwrap();
3736        assert_eq!(reloaded.channels[0].key.as_bytes(), &recovered, "member's recovered key == my advanced head key");
3737    }
3738
3739    #[tokio::test]
3740    async fn rotate_channel_failed_publish_leaves_head_unadvanced() {
3741        // The publish-before-advance invariant: if the publish fails, my local head must NOT move to an
3742        // epoch no peer received (else I'd be stranded talking to no one).
3743        let (_tmp, _guard) = init_test_db();
3744        let owner = Keys::generate();
3745        become_local(&owner);
3746        let community = saved_community_owned_by(&owner);
3747        let member = Keys::generate();
3748        let err = rotate_channel(&FailingRelay, &community, &community.channels[0].id, &[member.public_key()], community.server_root_key.as_bytes()).await;
3749        assert!(err.is_err(), "a failed publish must propagate, not silently advance");
3750        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
3751        assert_eq!(reloaded.channels[0].epoch, crate::community::Epoch(0), "head stays put on publish failure");
3752    }
3753
3754    /// Build a properly-chained run of channel rekeys (epoch 1..=n), each citing the prior epoch's key
3755    /// commitment (epoch 1 cites the genesis key), each carrying a blob for `recipient_pk`. Returns the
3756    /// events + the per-epoch keys. Does NOT touch the DB (so the recipient stays "behind" at epoch 0).
3757    fn build_rekey_chain(
3758        owner: &Keys, community: &Community, recipient_pk: &nostr_sdk::PublicKey, n: u64,
3759    ) -> (Vec<Event>, Vec<[u8; 32]>) {
3760        let chan = &community.channels[0];
3761        let scope = super::super::derive::RekeyScope::Channel(chan.id);
3762        let mut prev_key = *chan.key.as_bytes();
3763        let mut events = Vec::new();
3764        let mut keys = Vec::new();
3765        for e in 1..=n {
3766            let new_key = [e as u8; 32];
3767            let blob = super::super::rekey::build_rekey_blob(owner.secret_key(), recipient_pk, scope, crate::community::Epoch(e), &new_key).unwrap();
3768            let commit = super::super::rekey::epoch_key_commitment(crate::community::Epoch(e - 1), &prev_key);
3769            let ev = super::super::rekey::build_channel_rekey_event(
3770                &Keys::generate(), owner, community.server_root_key.as_bytes(), &chan.id,
3771                crate::community::Epoch(e), crate::community::Epoch(e - 1), &commit, &[blob],
3772            ).unwrap();
3773            events.push(ev);
3774            keys.push(new_key);
3775            prev_key = new_key;
3776        }
3777        (events, keys)
3778    }
3779
3780    #[tokio::test]
3781    async fn catch_up_steps_over_a_missing_epoch() {
3782        // W1: a relay-incomplete gap (epoch 2 absent). Catch-up applies 1, steps over the missing 2
3783        // (logged), applies 3 → head reaches the latest present epoch; epoch-2's key stays a hole.
3784        let (_tmp, _guard) = init_test_db();
3785        let owner = Keys::generate();
3786        let me = Keys::generate();
3787        become_local(&me);
3788        let community = saved_community_owned_by(&owner);
3789        let channel_id = community.channels[0].id;
3790        let cid = community.id.to_hex();
3791        let chan_hex = channel_id.to_hex();
3792
3793        let (events, keys) = build_rekey_chain(&owner, &community, &me.public_key(), 3);
3794        let relay = MemoryRelay::new();
3795        relay.inject(&events[0], &community.relays); // epoch 1
3796        relay.inject(&events[2], &community.relays); // epoch 3 — epoch 2 deliberately omitted
3797        let reached = catch_up_channel_rekeys(&relay, &community, &channel_id).await.unwrap();
3798
3799        assert_eq!(reached, 3, "head reaches the latest present epoch, stepping over the gap");
3800        assert_eq!(crate::db::community::held_epoch_key(&cid, &chan_hex, 1).unwrap(), Some(keys[0]));
3801        assert_eq!(crate::db::community::held_epoch_key(&cid, &chan_hex, 2).unwrap(), None, "missing epoch is a hole");
3802        assert_eq!(crate::db::community::held_epoch_key(&cid, &chan_hex, 3).unwrap(), Some(keys[2]));
3803    }
3804
3805    #[tokio::test]
3806    async fn catch_up_recovers_a_rekey_under_a_prior_server_root() {
3807        // A channel rekey is addressed + encrypted under whatever server root was current at publish, and
3808        // the root ratchets on every base rotation. After the base rotates 0→1, an epoch-1 channel rekey
3809        // published under root-0 must STILL be found + opened (we hold root-0 in the archive) — else its
3810        // key is lost. Cross-root catch-up.
3811        let (_tmp, _guard) = init_test_db();
3812        let owner = Keys::generate();
3813        let me = Keys::generate();
3814        become_local(&me);
3815        let root0_community = saved_community_owned_by(&owner);
3816        let cid = root0_community.id.to_hex();
3817        let channel_id = root0_community.channels[0].id;
3818        let chan_hex = channel_id.to_hex();
3819        let scope = super::super::derive::RekeyScope::Channel(channel_id);
3820        let genesis_key = *root0_community.channels[0].key.as_bytes();
3821
3822        // Base rotation 0→1; the member now holds BOTH roots (epoch 0 from save, epoch 1 from advance).
3823        let root1 = [0x99u8; 32];
3824        crate::db::community::advance_server_root_epoch(&cid, 1, &root1).unwrap();
3825        let community = crate::db::community::load_community(&root0_community.id).unwrap().unwrap();
3826        assert_eq!(community.server_root_epoch, crate::community::Epoch(1));
3827
3828        // Epoch-1 channel rekey under the PRIOR root (root-0); epoch-2 under the CURRENT root (root-1).
3829        let (k1, k2) = ([0x11u8; 32], [0x22u8; 32]);
3830        let blob1 = super::super::rekey::build_rekey_blob(owner.secret_key(), &me.public_key(), scope, crate::community::Epoch(1), &k1).unwrap();
3831        let commit0 = super::super::rekey::epoch_key_commitment(crate::community::Epoch(0), &genesis_key);
3832        let ev1 = super::super::rekey::build_channel_rekey_event(
3833            &Keys::generate(), &owner, root0_community.server_root_key.as_bytes(), &channel_id,
3834            crate::community::Epoch(1), crate::community::Epoch(0), &commit0, &[blob1]).unwrap();
3835        let blob2 = super::super::rekey::build_rekey_blob(owner.secret_key(), &me.public_key(), scope, crate::community::Epoch(2), &k2).unwrap();
3836        let commit1 = super::super::rekey::epoch_key_commitment(crate::community::Epoch(1), &k1);
3837        let ev2 = super::super::rekey::build_channel_rekey_event(
3838            &Keys::generate(), &owner, &root1, &channel_id,
3839            crate::community::Epoch(2), crate::community::Epoch(1), &commit1, &[blob2]).unwrap();
3840
3841        let relay = MemoryRelay::new();
3842        relay.inject(&ev1, &community.relays);
3843        relay.inject(&ev2, &community.relays);
3844
3845        let reached = catch_up_channel_rekeys(&relay, &community, &channel_id).await.unwrap();
3846        assert_eq!(reached, 2, "reached the latest channel epoch across the server-root rotation");
3847        assert_eq!(crate::db::community::held_epoch_key(&cid, &chan_hex, 1).unwrap(), Some(k1),
3848            "epoch-1 key recovered from a rekey under the PRIOR server root");
3849        assert_eq!(crate::db::community::held_epoch_key(&cid, &chan_hex, 2).unwrap(), Some(k2));
3850    }
3851
3852    #[tokio::test]
3853    async fn catch_up_backfills_a_sub_head_gap() {
3854        // An EXISTING hole below the head (an earlier catch-up leapfrogged epoch 1). The forward window
3855        // never revisits sub-head epochs, so the backward gap-fill must re-fetch + apply it.
3856        let (_tmp, _guard) = init_test_db();
3857        let owner = Keys::generate();
3858        let me = Keys::generate();
3859        become_local(&me);
3860        let community = saved_community_owned_by(&owner);
3861        let cid = community.id.to_hex();
3862        let channel_id = community.channels[0].id;
3863        let chan_hex = channel_id.to_hex();
3864        let scope = super::super::derive::RekeyScope::Channel(channel_id);
3865        let genesis_key = *community.channels[0].key.as_bytes();
3866
3867        // Pre-existing state: head already at epoch 2 (with its key), but epoch 1 is a HOLE.
3868        let k2 = [0x22u8; 32];
3869        crate::db::community::advance_channel_epoch(&cid, &chan_hex, 2, &k2).unwrap();
3870        assert_eq!(crate::db::community::held_epoch_key(&cid, &chan_hex, 1).unwrap(), None, "epoch 1 starts as a hole");
3871
3872        // Epoch-1's rekey is on relays (under the current root). The backward gap-fill should recover it.
3873        let k1 = [0x11u8; 32];
3874        let blob1 = super::super::rekey::build_rekey_blob(owner.secret_key(), &me.public_key(), scope, crate::community::Epoch(1), &k1).unwrap();
3875        let commit0 = super::super::rekey::epoch_key_commitment(crate::community::Epoch(0), &genesis_key);
3876        let ev1 = super::super::rekey::build_channel_rekey_event(
3877            &Keys::generate(), &owner, community.server_root_key.as_bytes(), &channel_id,
3878            crate::community::Epoch(1), crate::community::Epoch(0), &commit0, &[blob1]).unwrap();
3879        let relay = MemoryRelay::new();
3880        relay.inject(&ev1, &community.relays);
3881
3882        let community = crate::db::community::load_community(&community.id).unwrap().unwrap();
3883        let reached = catch_up_channel_rekeys(&relay, &community, &channel_id).await.unwrap();
3884        assert_eq!(reached, 2, "head unchanged (gap-fill never regresses it)");
3885        assert_eq!(crate::db::community::held_epoch_key(&cid, &chan_hex, 1).unwrap(), Some(k1),
3886            "the sub-head hole was backfilled");
3887    }
3888
3889    #[tokio::test]
3890    async fn catch_up_walks_a_chain_of_rotations_to_the_latest() {
3891        let (_tmp, _guard) = init_test_db();
3892        let owner = Keys::generate();
3893        let me = Keys::generate();
3894        become_local(&me); // I'm a member, behind at epoch 0
3895        let community = saved_community_owned_by(&owner);
3896        let channel_id = community.channels[0].id;
3897        let cid = community.id.to_hex();
3898        let chan_hex = channel_id.to_hex();
3899
3900        // 3 rotations happened while I was away; inject them onto the relay (unordered).
3901        let (events, keys) = build_rekey_chain(&owner, &community, &me.public_key(), 3);
3902        let relay = MemoryRelay::new();
3903        for ev in events.iter().rev() {
3904            relay.inject(ev, &community.relays);
3905        }
3906
3907        let reached = catch_up_channel_rekeys(&relay, &community, &channel_id).await.unwrap();
3908        assert_eq!(reached, 3, "caught up to the latest epoch");
3909        // Head advanced to 3 with epoch-3's key; ALL intervening epoch keys retained.
3910        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
3911        assert_eq!(reloaded.channels[0].epoch, crate::community::Epoch(3));
3912        assert_eq!(reloaded.channels[0].key.as_bytes(), &keys[2]);
3913        for (i, k) in keys.iter().enumerate() {
3914            assert_eq!(crate::db::community::held_epoch_key(&cid, &chan_hex, (i + 1) as u64).unwrap(), Some(*k));
3915        }
3916    }
3917
3918    #[tokio::test]
3919    async fn catch_up_slides_across_the_window_boundary() {
3920        // Exercises the multi-round slide arithmetic: 70 contiguous rotations (all for me) exceed the
3921        // 64-wide window, so catch-up must fetch window 1 (1..64), advance, then slide to window 2 and
3922        // reach 70 — proving the window math, not just a single-window apply.
3923        let (_tmp, _guard) = init_test_db();
3924        let owner = Keys::generate();
3925        let me = Keys::generate();
3926        become_local(&me);
3927        let community = saved_community_owned_by(&owner);
3928        let channel_id = community.channels[0].id;
3929        let cid = community.id.to_hex();
3930        let chan_hex = channel_id.to_hex();
3931
3932        let (events, keys) = build_rekey_chain(&owner, &community, &me.public_key(), 70);
3933        let relay = MemoryRelay::new();
3934        for ev in &events {
3935            relay.inject(ev, &community.relays);
3936        }
3937        let reached = catch_up_channel_rekeys(&relay, &community, &channel_id).await.unwrap();
3938        assert_eq!(reached, 70, "slid past the 64-epoch window boundary to the latest");
3939        assert_eq!(crate::db::community::held_epoch_key(&cid, &chan_hex, 70).unwrap(), Some(keys[69]));
3940        assert_eq!(crate::db::community::held_epoch_key(&cid, &chan_hex, 64).unwrap(), Some(keys[63]), "window-1 keys retained too");
3941    }
3942
3943    // --- catch_up_server_root (#4d) ---
3944
3945    /// A properly-chained run of base rekeys (epoch 1..=n), each enveloped under the PRIOR root and
3946    /// citing it, each carrying a ServerRoot blob for `recipient_pk`. Returns the events + per-epoch
3947    /// roots. Does NOT touch the DB (the recipient stays "behind" at base epoch 0).
3948    fn build_base_rekey_chain(
3949        owner: &Keys, community: &Community, recipient_pk: &nostr_sdk::PublicKey, n: u64,
3950    ) -> (Vec<Event>, Vec<[u8; 32]>) {
3951        let mut prior_root = *community.server_root_key.as_bytes();
3952        let mut events = Vec::new();
3953        let mut roots = Vec::new();
3954        for e in 1..=n {
3955            let new_root = [(e % 256) as u8; 32];
3956            let blob = super::super::rekey::build_rekey_blob(
3957                owner.secret_key(), recipient_pk, super::super::derive::RekeyScope::ServerRoot, crate::community::Epoch(e), &new_root,
3958            )
3959            .unwrap();
3960            let commit = super::super::rekey::epoch_key_commitment(crate::community::Epoch(e - 1), &prior_root);
3961            events.push(super::super::rekey::build_server_root_rekey_event(
3962                &Keys::generate(), owner, &prior_root, &community.id,
3963                crate::community::Epoch(e), crate::community::Epoch(e - 1), &commit, &[blob],
3964            ).unwrap());
3965            roots.push(new_root);
3966            prior_root = new_root;
3967        }
3968        (events, roots)
3969    }
3970
3971    #[tokio::test]
3972    async fn catch_up_server_root_walks_a_chain_of_base_rotations() {
3973        let (_tmp, _guard) = init_test_db();
3974        let owner = Keys::generate();
3975        let me = Keys::generate();
3976        become_local(&me);
3977        let community = saved_community_owned_by(&owner);
3978        let cid = community.id.to_hex();
3979
3980        let (events, roots) = build_base_rekey_chain(&owner, &community, &me.public_key(), 3);
3981        let relay = MemoryRelay::new();
3982        for ev in events.iter().rev() {
3983            relay.inject(ev, &community.relays);
3984        }
3985        let reached = catch_up_server_root(&relay, &community).await.unwrap();
3986        assert_eq!(reached.epoch, 3, "walked the base chain to the latest epoch");
3987        assert!(!reached.removed, "a normal catch-up is not a removal");
3988        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
3989        assert_eq!(reloaded.server_root_epoch, crate::community::Epoch(3));
3990        assert_eq!(reloaded.server_root_key.as_bytes(), &roots[2], "base head is the latest root");
3991        // All intervening roots retained (read old control/base history).
3992        for (i, r) in roots.iter().enumerate() {
3993            assert_eq!(crate::db::community::held_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, (i + 1) as u64).unwrap(), Some(*r));
3994        }
3995    }
3996
3997    #[tokio::test]
3998    async fn catch_up_recovers_from_a_split_base_rotation_second_chunk() {
3999        // SPLIT: a base rotation at epoch 1 is published as TWO chunk events at the SAME address; MY
4000        // blob is in the SECOND chunk. The walk must try both and recover from chunk 2 — the old
4001        // first-match logic would have hit chunk 1 (no blob for me), read it as removal, and stranded me.
4002        let (_tmp, _guard) = init_test_db();
4003        let owner = Keys::generate();
4004        let me = Keys::generate();
4005        become_local(&me);
4006        let community = saved_community_owned_by(&owner);
4007        let genesis = *community.server_root_key.as_bytes();
4008        let new_root = [0x5Au8; 32];
4009        let scope = super::super::derive::RekeyScope::ServerRoot;
4010        let commit = super::super::rekey::epoch_key_commitment(crate::community::Epoch(0), &genesis);
4011        let mk = |recipient: &nostr_sdk::PublicKey| {
4012            let blob = super::super::rekey::build_rekey_blob(owner.secret_key(), recipient, scope, crate::community::Epoch(1), &new_root).unwrap();
4013            super::super::rekey::build_server_root_rekey_event(
4014                &Keys::generate(), &owner, &genesis, &community.id,
4015                crate::community::Epoch(1), crate::community::Epoch(0), &commit, &[blob],
4016            ).unwrap()
4017        };
4018        let relay = MemoryRelay::new();
4019        relay.inject(&mk(&Keys::generate().public_key()), &community.relays); // chunk 1: NOT for me
4020        relay.inject(&mk(&me.public_key()), &community.relays); // chunk 2: my blob
4021
4022        let reached = catch_up_server_root(&relay, &community).await.unwrap();
4023        assert_eq!(reached.epoch, 1, "recovered the split rotation via the second chunk");
4024        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
4025        assert_eq!(reloaded.server_root_key.as_bytes(), &new_root, "recovered the new root from chunk 2");
4026    }
4027
4028    #[tokio::test]
4029    async fn catch_up_converges_concurrent_refoundings_on_the_lowest_root() {
4030        // B2: two BAN-holders re-found at the SAME epoch, each delivering a DIFFERENT new root to me. Every
4031        // member must pick the SAME canonical root or the community forks irrecoverably. The walk converges
4032        // on the LOWEST new-root bytes — deterministic for everyone — regardless of which arrived first.
4033        let (_tmp, _guard) = init_test_db();
4034        let owner = Keys::generate();
4035        let me = Keys::generate();
4036        become_local(&me);
4037        let community = saved_community_owned_by(&owner);
4038        let genesis = *community.server_root_key.as_bytes();
4039        let scope = super::super::derive::RekeyScope::ServerRoot;
4040        let commit = super::super::rekey::epoch_key_commitment(crate::community::Epoch(0), &genesis);
4041        let root_lo = [0x10u8; 32];
4042        let root_hi = [0xF0u8; 32]; // root_lo < root_hi bytewise
4043        let mk = |root: &[u8; 32]| {
4044            let blob = super::super::rekey::build_rekey_blob(owner.secret_key(), &me.public_key(), scope, crate::community::Epoch(1), root).unwrap();
4045            super::super::rekey::build_server_root_rekey_event(
4046                &Keys::generate(), &owner, &genesis, &community.id,
4047                crate::community::Epoch(1), crate::community::Epoch(0), &commit, &[blob],
4048            ).unwrap()
4049        };
4050        let relay = MemoryRelay::new();
4051        // Inject the HIGHER root FIRST — "first-arrived" logic would pick the wrong one without the tiebreak.
4052        relay.inject(&mk(&root_hi), &community.relays);
4053        relay.inject(&mk(&root_lo), &community.relays);
4054
4055        let reached = catch_up_server_root(&relay, &community).await.unwrap();
4056        assert_eq!(reached.epoch, 1, "advanced one epoch");
4057        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
4058        assert_eq!(reloaded.server_root_key.as_bytes(), &root_lo, "converged on the LOWEST root, not the first-arrived");
4059    }
4060
4061    #[tokio::test]
4062    async fn rotate_retry_reuses_the_archived_root_no_same_epoch_fork() {
4063        // FORK-SAFETY crux: a rotation whose publish fails archives the new root, and a RETRY reuses that
4064        // SAME root (never mints a fresh one for the same epoch — which would split recipients onto
4065        // incompatible keys). Fail the base rekey publish, capture the archived root, recover the relay,
4066        // retry, and assert the root is identical.
4067        let (_tmp, _guard) = init_test_db();
4068        let owner = Keys::generate();
4069        become_local(&owner);
4070        let community = saved_community_owned_by(&owner);
4071        let cid = community.id.to_hex();
4072        let relay = RekeyFailingRelay::new(); // base rekey (3303) publish fails
4073        let member = Keys::generate();
4074
4075        assert!(rotate_server_root(&relay, &community, &[member.public_key()]).await.is_err(), "the rekey publish fails");
4076        let k1 = crate::db::community::held_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 1).unwrap()
4077            .expect("the new root is archived before publishing (fork-safety)");
4078        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
4079        assert_eq!(reloaded.server_root_epoch, crate::community::Epoch(0), "head not advanced on a failed publish");
4080
4081        relay.allow_rekey();
4082        rotate_server_root(&relay, &reloaded, &[member.public_key()]).await.unwrap();
4083        let k2 = crate::db::community::held_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 1).unwrap().unwrap();
4084        assert_eq!(k1, k2, "the retry REUSES the archived root — no second root for epoch 1, no fork");
4085        let after = crate::db::community::load_community(&community.id).unwrap().unwrap();
4086        assert_eq!(after.server_root_epoch, crate::community::Epoch(1), "the retry completed the rotation");
4087        assert_eq!(after.server_root_key.as_bytes(), &k1, "the committed root is the one minted on attempt 1");
4088    }
4089
4090    #[tokio::test]
4091    async fn rotate_server_root_splits_a_large_recipient_set_into_multiple_events() {
4092        // A recipient set past MAX_REKEY_BLOBS publishes as MULTIPLE chunk events at one address.
4093        let (_tmp, _guard) = init_test_db();
4094        let owner = Keys::generate();
4095        become_local(&owner);
4096        let community = saved_community_owned_by(&owner);
4097        let genesis = *community.server_root_key.as_bytes();
4098        let relay = MemoryRelay::new();
4099        // MAX_REKEY_BLOBS recipients + the owner self-blob = MAX+1 blobs → exactly 2 chunks.
4100        let recipients: Vec<_> = (0..super::super::rekey::MAX_REKEY_BLOBS).map(|_| Keys::generate().public_key()).collect();
4101        rotate_server_root(&relay, &community, &recipients).await.unwrap();
4102        let addr = super::super::derive::base_rekey_pseudonym(&super::super::ServerRootKey(genesis), &community.id, crate::community::Epoch(1)).to_hex();
4103        let evs = relay
4104            .fetch(&Query { kinds: vec![event_kind::COMMUNITY_REKEY], z_tags: vec![addr], ..Default::default() }, &community.relays)
4105            .await
4106            .unwrap();
4107        assert_eq!(evs.len(), 2, "a >MAX_REKEY_BLOBS rotation splits into 2 events at one address");
4108    }
4109
4110    #[tokio::test]
4111    async fn catch_up_server_root_is_a_noop_with_no_rotations() {
4112        let (_tmp, _guard) = init_test_db();
4113        let owner = Keys::generate();
4114        let me = Keys::generate();
4115        become_local(&me);
4116        let community = saved_community_owned_by(&owner);
4117        let relay = MemoryRelay::new();
4118        assert_eq!(catch_up_server_root(&relay, &community).await.unwrap().epoch, 0, "no base rotations → stays at 0");
4119    }
4120
4121    #[tokio::test]
4122    async fn concurrent_refounders_converge_to_the_lowest_root() {
4123        // Two BAN-holders re-found at the SAME epoch with DIFFERENT roots → each ORIGINATOR ends on its own
4124        // root (the forward walk only tiebreaks at head+1). The current-head convergence reconciles them:
4125        // whoever holds the HIGHER root adopts the LOWER (deterministic winner). This is the exact case the
4126        // live dual-admin race broke — the bystander-only B2 test never covered the originators self-healing.
4127        let (_tmp, _guard) = init_test_db();
4128        let owner = Keys::generate();
4129        let me = Keys::generate();
4130        become_local(&me); // a member sitting on the LOSING (higher) root after my own concurrent re-founding
4131        let community = saved_community_owned_by(&owner);
4132        let cid = community.id.to_hex();
4133        let genesis_root = *community.server_root_key.as_bytes();
4134        let scope = super::super::derive::RekeyScope::ServerRoot;
4135
4136        // The OTHER originator's epoch-1 base rekey (root_lo, the winner) — carries a blob for ME, addressed
4137        // under the genesis (prior) root. Owner-authored, so it's authorized (supreme) regardless of roster.
4138        let root_lo = [0x10u8; 32];
4139        let root_hi = [0x99u8; 32]; // my own losing fork's root
4140        let commit0 = super::super::rekey::epoch_key_commitment(crate::community::Epoch(0), &genesis_root);
4141        let blob_lo = super::super::rekey::build_rekey_blob(owner.secret_key(), &me.public_key(), scope, crate::community::Epoch(1), &root_lo).unwrap();
4142        let ev_lo = super::super::rekey::build_server_root_rekey_event(
4143            &Keys::generate(), &owner, &genesis_root, &community.id, crate::community::Epoch(1), crate::community::Epoch(0), &commit0, &[blob_lo]).unwrap();
4144
4145        let relay = MemoryRelay::new();
4146        relay.inject(&ev_lo, &community.relays);
4147
4148        // I'm currently on the HIGHER root at epoch 1 (my own losing fork).
4149        crate::db::community::advance_server_root_epoch(&cid, 1, &root_hi).unwrap();
4150        let community = crate::db::community::load_community(&community.id).unwrap().unwrap();
4151        assert_eq!(community.server_root_key.as_bytes(), &root_hi, "start on the higher root");
4152
4153        let out = catch_up_server_root(&relay, &community).await.unwrap();
4154        assert_eq!(out.epoch, 1, "converged in place at the same epoch (not advanced)");
4155        assert!(!out.removed);
4156        let after = crate::db::community::load_community(&community.id).unwrap().unwrap();
4157        assert_eq!(after.server_root_key.as_bytes(), &root_lo, "originator converged to the lowest authorized root");
4158
4159        // Idempotent: a second pass holding the winner stays put (no flip back to the higher root).
4160        let _ = catch_up_server_root(&relay, &after).await.unwrap();
4161        assert_eq!(crate::db::community::load_community(&community.id).unwrap().unwrap().server_root_key.as_bytes(), &root_lo, "no flip-flop");
4162    }
4163
4164    #[tokio::test]
4165    async fn banned_rotators_rekey_is_not_a_convergence_candidate() {
4166        // §6 banlist precedence on the rekey plane: an admin who holds a (withheld-revoke) BAN grant
4167        // but sits on the SYNCED banlist must not be honored as a rotator — not by apply, not by the
4168        // forward walk, not by the heal. Here the banned admin's re-founding delivers a byte-LOWER
4169        // root than the one I hold; without the banlist gate the heal would adopt it.
4170        let (_tmp, _guard) = init_test_db();
4171        let owner = Keys::generate();
4172        let me = Keys::generate();
4173        let banned_admin = Keys::generate();
4174        become_local(&me);
4175        let community = saved_community_owned_by(&owner);
4176        let cid = community.id.to_hex();
4177        let genesis_root = *community.server_root_key.as_bytes();
4178        let scope = super::super::derive::RekeyScope::ServerRoot;
4179
4180        // The attacker still ranks in the roster (their grant-revoke is "withheld")...
4181        let role_id = "e".repeat(64);
4182        let roster = crate::community::roles::CommunityRoles {
4183            roles: vec![crate::community::roles::Role::admin(role_id.clone())],
4184            grants: vec![crate::community::roles::MemberGrant { member: banned_admin.public_key().to_hex(), role_ids: vec![role_id] }],
4185        };
4186        crate::db::community::set_community_roles(&cid, &roster, 1).unwrap();
4187        // ...but the banlist naming them DID sync. Banlist must dominate.
4188        crate::db::community::set_community_banlist(&cid, &[banned_admin.public_key().to_hex()], 2).unwrap();
4189
4190        // Banned admin's epoch-1 re-founding with a ground-low root, blob addressed to me.
4191        let root_evil = [0x01u8; 32];
4192        let commit0 = super::super::rekey::epoch_key_commitment(crate::community::Epoch(0), &genesis_root);
4193        let blob = super::super::rekey::build_rekey_blob(banned_admin.secret_key(), &me.public_key(), scope, crate::community::Epoch(1), &root_evil).unwrap();
4194        let ev = super::super::rekey::build_server_root_rekey_event(
4195            &Keys::generate(), &banned_admin, &genesis_root, &community.id, crate::community::Epoch(1), crate::community::Epoch(0), &commit0, &[blob]).unwrap();
4196        let relay = MemoryRelay::new();
4197        relay.inject(&ev, &community.relays);
4198
4199        // Forward walk: the banned rotation is the ONLY epoch-1 candidate → not adopted, not a
4200        // removal signal (a banned admin can't trick members into self-erasing either).
4201        let out = catch_up_server_root(&relay, &community).await.unwrap();
4202        assert_eq!(out.epoch, 0, "banned rotator's re-founding must not advance the base");
4203        assert!(!out.removed, "banned rotator's exclusion must not read as an authorized removal");
4204        let after = crate::db::community::load_community(&community.id).unwrap().unwrap();
4205        assert_eq!(after.server_root_key.as_bytes(), &genesis_root, "root unchanged");
4206
4207        // Direct apply refuses too.
4208        let parsed = super::super::rekey::open_rekey_event(&ev, &genesis_root).unwrap();
4209        assert!(apply_server_root_rekey(&community, &parsed).is_err(), "apply must refuse a banned rotator");
4210    }
4211
4212    #[tokio::test]
4213    async fn heal_abandons_a_deauthorized_root_for_the_authorized_higher_sibling() {
4214        // B1 (rekey-race fork): I adopted a since-BANNED admin's ground-low epoch-1 root before the
4215        // banlist reached me. Once the banlist syncs, the heal must abandon their root and climb UP
4216        // to the owner's legitimate (byte-higher) sibling — authority dominates the down-only rule.
4217        let (_tmp, _guard) = init_test_db();
4218        let owner = Keys::generate();
4219        let me = Keys::generate();
4220        let banned_admin = Keys::generate();
4221        become_local(&me);
4222        let community = saved_community_owned_by(&owner);
4223        let cid = community.id.to_hex();
4224        let genesis_root = *community.server_root_key.as_bytes();
4225        let scope = super::super::derive::RekeyScope::ServerRoot;
4226        let commit0 = super::super::rekey::epoch_key_commitment(crate::community::Epoch(0), &genesis_root);
4227
4228        // Both epoch-1 siblings on the wire, addressed under the shared genesis root:
4229        // the attacker's (ground-low) and the owner's (higher).
4230        let root_evil = [0x01u8; 32];
4231        let root_owner = [0x77u8; 32];
4232        let blob_evil = super::super::rekey::build_rekey_blob(banned_admin.secret_key(), &me.public_key(), scope, crate::community::Epoch(1), &root_evil).unwrap();
4233        let ev_evil = super::super::rekey::build_server_root_rekey_event(
4234            &Keys::generate(), &banned_admin, &genesis_root, &community.id, crate::community::Epoch(1), crate::community::Epoch(0), &commit0, &[blob_evil]).unwrap();
4235        let blob_owner = super::super::rekey::build_rekey_blob(owner.secret_key(), &me.public_key(), scope, crate::community::Epoch(1), &root_owner).unwrap();
4236        let ev_owner = super::super::rekey::build_server_root_rekey_event(
4237            &Keys::generate(), &owner, &genesis_root, &community.id, crate::community::Epoch(1), crate::community::Epoch(0), &commit0, &[blob_owner]).unwrap();
4238        let relay = MemoryRelay::new();
4239        relay.inject(&ev_evil, &community.relays);
4240        relay.inject(&ev_owner, &community.relays);
4241
4242        // I already adopted the attacker's root at epoch 1 (the race), and the ban has now synced.
4243        crate::db::community::advance_server_root_epoch(&cid, 1, &root_evil).unwrap();
4244        crate::db::community::set_community_banlist(&cid, &[banned_admin.public_key().to_hex()], 2).unwrap();
4245        let community = crate::db::community::load_community(&community.id).unwrap().unwrap();
4246        assert_eq!(community.server_root_key.as_bytes(), &root_evil, "start partitioned on the attacker's root");
4247
4248        let out = catch_up_server_root(&relay, &community).await.unwrap();
4249        assert_eq!(out.epoch, 1);
4250        assert!(!out.removed);
4251        let after = crate::db::community::load_community(&community.id).unwrap().unwrap();
4252        assert_eq!(after.server_root_key.as_bytes(), &root_owner,
4253            "heal must abandon the deauthorized root and adopt the owner's higher sibling");
4254
4255        // Stable: re-running keeps the owner's root (the attacker's lower root never wins again).
4256        let _ = catch_up_server_root(&relay, &after).await.unwrap();
4257        assert_eq!(crate::db::community::load_community(&community.id).unwrap().unwrap().server_root_key.as_bytes(), &root_owner, "no flap back to the banned root");
4258    }
4259
4260    #[tokio::test]
4261    async fn concurrent_channel_rekeyers_converge_to_the_lowest_key() {
4262        // Two MANAGE_CHANNELS holders rotate the SAME channel at the SAME epoch with DIFFERENT keys —
4263        // a true fork inside the propagation window. Both rekeys land at the same address under the (already
4264        // converged) server root, so relay order would otherwise decide last-write-wins. The current-head
4265        // heal must pick the LOWEST delivered key deterministically — every member computes the same winner.
4266        let (_tmp, _guard) = init_test_db();
4267        let owner = Keys::generate();
4268        let me = Keys::generate();
4269        become_local(&me); // a member sitting on the LOSING (higher) channel key after my own fork
4270        let community = saved_community_owned_by(&owner);
4271        let cid = community.id.to_hex();
4272        let channel_id = community.channels[0].id;
4273        let chan_hex = channel_id.to_hex();
4274        let scope = super::super::derive::RekeyScope::Channel(channel_id);
4275        let genesis_key = *community.channels[0].key.as_bytes();
4276        let root = *community.server_root_key.as_bytes();
4277        let commit0 = super::super::rekey::epoch_key_commitment(crate::community::Epoch(0), &genesis_key);
4278
4279        // Two owner-authorized epoch-1 channel rekeys, each carrying a blob for ME, both citing genesis.
4280        let key_lo = [0x10u8; 32];
4281        let key_hi = [0x99u8; 32];
4282        let blob_lo = super::super::rekey::build_rekey_blob(owner.secret_key(), &me.public_key(), scope, crate::community::Epoch(1), &key_lo).unwrap();
4283        let blob_hi = super::super::rekey::build_rekey_blob(owner.secret_key(), &me.public_key(), scope, crate::community::Epoch(1), &key_hi).unwrap();
4284        let ev_lo = super::super::rekey::build_channel_rekey_event(
4285            &Keys::generate(), &owner, &root, &channel_id, crate::community::Epoch(1), crate::community::Epoch(0), &commit0, &[blob_lo]).unwrap();
4286        let ev_hi = super::super::rekey::build_channel_rekey_event(
4287            &Keys::generate(), &owner, &root, &channel_id, crate::community::Epoch(1), crate::community::Epoch(0), &commit0, &[blob_hi]).unwrap();
4288
4289        let relay = MemoryRelay::new();
4290        relay.inject(&ev_hi, &community.relays); // inject the HIGHER first: naive relay-order would pick it
4291        relay.inject(&ev_lo, &community.relays);
4292
4293        // The two forked channel rekeys are addressed under the PRIOR
4294        // (shared) root they cite, not the current one. Advance the SERVER root so genesis becomes a prior
4295        // root — the heal must search EVERY held root to find them. A current-root-only fetch
4296        // missed both and never converged (the channel forked live while the base healed).
4297        crate::db::community::advance_server_root_epoch(&cid, 1, &[0x42u8; 32]).unwrap();
4298        // I'm currently on the HIGHER key at epoch 1 (my own losing fork).
4299        crate::db::community::advance_channel_epoch(&cid, &chan_hex, 1, &key_hi).unwrap();
4300        let community = crate::db::community::load_community(&community.id).unwrap().unwrap();
4301
4302        let reached = catch_up_channel_rekeys(&relay, &community, &channel_id).await.unwrap();
4303        assert_eq!(reached, 1, "converged in place at the same channel epoch");
4304        assert_eq!(crate::db::community::held_epoch_key(&cid, &chan_hex, 1).unwrap(), Some(key_lo),
4305            "adopted the lowest delivered key regardless of relay order");
4306
4307        // Idempotent: re-running holding the winner stays put (no flip back to the higher key).
4308        let after = crate::db::community::load_community(&community.id).unwrap().unwrap();
4309        let _ = catch_up_channel_rekeys(&relay, &after, &channel_id).await.unwrap();
4310        assert_eq!(crate::db::community::held_epoch_key(&cid, &chan_hex, 1).unwrap(), Some(key_lo), "no flip-flop");
4311    }
4312
4313    #[tokio::test]
4314    async fn concurrent_channel_rekeyers_converge_when_i_authored_the_losing_fork() {
4315        // FAITHFUL LIVE REPLICA of the dual-admin ban (the case the simpler test missed): TWO DISTINCT
4316        // authorized rotators (owner + a granted admin), and the LOCAL user IS one of them — I authored the
4317        // HIGHER (losing) channel rekey myself, the owner authored the lower. Both sit under the PRIOR shared
4318        // root, both deliver a blob to me. The heal must still converge ME down to the owner's lower key.
4319        let (_tmp, _guard) = init_test_db();
4320        let owner = Keys::generate();
4321        let me = Keys::generate(); // I am the ADMIN rotator (not a bystander) — mirrors the agent in the live test
4322        become_local(&me);
4323        let community = saved_community_owned_by(&owner);
4324        let cid = community.id.to_hex();
4325        let channel_id = community.channels[0].id;
4326        let chan_hex = channel_id.to_hex();
4327        let scope = super::super::derive::RekeyScope::Channel(channel_id);
4328        let genesis_key = *community.channels[0].key.as_bytes();
4329        let root = *community.server_root_key.as_bytes();
4330        let commit0 = super::super::rekey::epoch_key_commitment(crate::community::Epoch(0), &genesis_key);
4331
4332        // Grant ME (the admin) a role carrying MANAGE_CHANNELS, so MY OWN rekey is an authorized candidate
4333        // (owner is supreme regardless). Without this the heal would trivially pick the owner's; with it,
4334        // BOTH siblings are authorized — exactly the live ambiguity that must resolve to the lowest key.
4335        let role_id = "d".repeat(64);
4336        let roster = crate::community::roles::CommunityRoles {
4337            roles: vec![crate::community::roles::Role::admin(role_id.clone())],
4338            grants: vec![crate::community::roles::MemberGrant { member: me.public_key().to_hex(), role_ids: vec![role_id] }],
4339        };
4340        crate::db::community::set_community_roles(&cid, &roster, 1).unwrap();
4341
4342        let key_lo = [0x10u8; 32]; // owner's (the winner)
4343        let key_hi = [0x99u8; 32]; // MINE (the losing fork I authored + currently hold)
4344        // Owner's rekey: rotator = owner, blob for ME.
4345        let blob_lo = super::super::rekey::build_rekey_blob(owner.secret_key(), &me.public_key(), scope, crate::community::Epoch(1), &key_lo).unwrap();
4346        let ev_lo = super::super::rekey::build_channel_rekey_event(
4347            &Keys::generate(), &owner, &root, &channel_id, crate::community::Epoch(1), crate::community::Epoch(0), &commit0, &[blob_lo]).unwrap();
4348        // MY rekey: rotator = me (the admin), blob for ME (self-delivered, as rotate_channel always adds self).
4349        let blob_hi = super::super::rekey::build_rekey_blob(me.secret_key(), &me.public_key(), scope, crate::community::Epoch(1), &key_hi).unwrap();
4350        let ev_hi = super::super::rekey::build_channel_rekey_event(
4351            &Keys::generate(), &me, &root, &channel_id, crate::community::Epoch(1), crate::community::Epoch(0), &commit0, &[blob_hi]).unwrap();
4352
4353        let relay = MemoryRelay::new();
4354        relay.inject(&ev_hi, &community.relays);
4355        relay.inject(&ev_lo, &community.relays);
4356
4357        // The rekeys are under genesis (prior) root; advance the SERVER root so genesis is no longer current.
4358        crate::db::community::advance_server_root_epoch(&cid, 1, &[0x42u8; 32]).unwrap();
4359        // I currently hold MY OWN (higher) key at channel epoch 1.
4360        crate::db::community::advance_channel_epoch(&cid, &chan_hex, 1, &key_hi).unwrap();
4361        let community = crate::db::community::load_community(&community.id).unwrap().unwrap();
4362
4363        let _ = catch_up_channel_rekeys(&relay, &community, &channel_id).await.unwrap();
4364        assert_eq!(crate::db::community::held_epoch_key(&cid, &chan_hex, 1).unwrap(), Some(key_lo),
4365            "I authored the losing fork but must converge DOWN to the owner's lower key");
4366    }
4367
4368    #[tokio::test]
4369    async fn reorg_through_a_fork_heals_the_forked_past_epoch() {
4370        // I sit on the LOSING sibling at a PAST channel epoch (epoch 1) and then reorg forward when an
4371        // authorized epoch-2 rekey continues from the WINNING epoch-1 key. Advancing the head alone leaves
4372        // epoch 1 on the wrong key (its messages unreadable). catch_up must re-converge the forked PAST epoch
4373        // to the lowest sibling — not just the head.
4374        let (_tmp, _guard) = init_test_db();
4375        let owner = Keys::generate();
4376        let me = Keys::generate();
4377        become_local(&me);
4378        let community = saved_community_owned_by(&owner);
4379        let cid = community.id.to_hex();
4380        let channel_id = community.channels[0].id;
4381        let chan_hex = channel_id.to_hex();
4382        let scope = super::super::derive::RekeyScope::Channel(channel_id);
4383        let genesis_key = *community.channels[0].key.as_bytes();
4384        let root = *community.server_root_key.as_bytes();
4385        let commit0 = super::super::rekey::epoch_key_commitment(crate::community::Epoch(0), &genesis_key);
4386
4387        // Two owner-authorized epoch-1 siblings (the fork), both delivering a blob to me.
4388        let key_lo1 = [0x10u8; 32]; // winner at epoch 1
4389        let key_hi1 = [0x99u8; 32]; // loser at epoch 1 (what I currently hold)
4390        let key_e2 = [0x20u8; 32]; // epoch 2, continuing from the WINNER's key_lo1
4391        let blob_lo1 = super::super::rekey::build_rekey_blob(owner.secret_key(), &me.public_key(), scope, crate::community::Epoch(1), &key_lo1).unwrap();
4392        let blob_hi1 = super::super::rekey::build_rekey_blob(owner.secret_key(), &me.public_key(), scope, crate::community::Epoch(1), &key_hi1).unwrap();
4393        let ev_lo1 = super::super::rekey::build_channel_rekey_event(
4394            &Keys::generate(), &owner, &root, &channel_id, crate::community::Epoch(1), crate::community::Epoch(0), &commit0, &[blob_lo1]).unwrap();
4395        let ev_hi1 = super::super::rekey::build_channel_rekey_event(
4396            &Keys::generate(), &owner, &root, &channel_id, crate::community::Epoch(1), crate::community::Epoch(0), &commit0, &[blob_hi1]).unwrap();
4397        // Epoch 2 cites the WINNER's epoch-1 key — applying it while I hold key_hi1 is the reorg.
4398        let commit1_win = super::super::rekey::epoch_key_commitment(crate::community::Epoch(1), &key_lo1);
4399        let blob_e2 = super::super::rekey::build_rekey_blob(owner.secret_key(), &me.public_key(), scope, crate::community::Epoch(2), &key_e2).unwrap();
4400        let ev_e2 = super::super::rekey::build_channel_rekey_event(
4401            &Keys::generate(), &owner, &root, &channel_id, crate::community::Epoch(2), crate::community::Epoch(1), &commit1_win, &[blob_e2]).unwrap();
4402
4403        let relay = MemoryRelay::new();
4404        relay.inject(&ev_lo1, &community.relays);
4405        relay.inject(&ev_hi1, &community.relays);
4406        relay.inject(&ev_e2, &community.relays);
4407
4408        // All three rekeys are under the genesis (now-prior) server root.
4409        crate::db::community::advance_server_root_epoch(&cid, 1, &[0x42u8; 32]).unwrap();
4410        // I'm sitting on the LOSING epoch-1 key.
4411        crate::db::community::advance_channel_epoch(&cid, &chan_hex, 1, &key_hi1).unwrap();
4412        let community = crate::db::community::load_community(&community.id).unwrap().unwrap();
4413
4414        let reached = catch_up_channel_rekeys(&relay, &community, &channel_id).await.unwrap();
4415        assert_eq!(reached, 2, "reorged forward to the head epoch");
4416        assert_eq!(crate::db::community::held_epoch_key(&cid, &chan_hex, 2).unwrap(), Some(key_e2), "head epoch adopted");
4417        assert_eq!(crate::db::community::held_epoch_key(&cid, &chan_hex, 1).unwrap(), Some(key_lo1),
4418            "the FORKED past epoch re-converged to the lowest sibling (its messages become readable)");
4419    }
4420
4421    #[tokio::test]
4422    async fn window_heal_converges_an_already_reorged_past_fork() {
4423        // A member sitting at head epoch 2 holding the LOSING sibling at epoch 1, with NO new rekey to apply
4424        // this sync (so the in-sync forked-epoch set stays empty). The recent-window heal must STILL
4425        // re-converge epoch 1 to the lowest sibling — otherwise its messages are stranded forever. Distinct
4426        // from `reorg_through_a_fork_*` (which reorgs in-sync).
4427        let (_tmp, _guard) = init_test_db();
4428        let owner = Keys::generate();
4429        let me = Keys::generate();
4430        become_local(&me);
4431        let community = saved_community_owned_by(&owner);
4432        let cid = community.id.to_hex();
4433        let channel_id = community.channels[0].id;
4434        let chan_hex = channel_id.to_hex();
4435        let scope = super::super::derive::RekeyScope::Channel(channel_id);
4436        let genesis_key = *community.channels[0].key.as_bytes();
4437        let root = *community.server_root_key.as_bytes();
4438        let commit0 = super::super::rekey::epoch_key_commitment(crate::community::Epoch(0), &genesis_key);
4439
4440        let key_lo1 = [0x10u8; 32]; // winner at epoch 1 (on the wire, authorized, blob for me)
4441        let key_hi1 = [0x99u8; 32]; // loser at epoch 1 (what I currently hold)
4442        let key_e2 = [0x20u8; 32]; // my head at epoch 2 (already reorged here under the old build)
4443        let blob_lo1 = super::super::rekey::build_rekey_blob(owner.secret_key(), &me.public_key(), scope, crate::community::Epoch(1), &key_lo1).unwrap();
4444        let blob_hi1 = super::super::rekey::build_rekey_blob(owner.secret_key(), &me.public_key(), scope, crate::community::Epoch(1), &key_hi1).unwrap();
4445        let ev_lo1 = super::super::rekey::build_channel_rekey_event(
4446            &Keys::generate(), &owner, &root, &channel_id, crate::community::Epoch(1), crate::community::Epoch(0), &commit0, &[blob_lo1]).unwrap();
4447        let ev_hi1 = super::super::rekey::build_channel_rekey_event(
4448            &Keys::generate(), &owner, &root, &channel_id, crate::community::Epoch(1), crate::community::Epoch(0), &commit0, &[blob_hi1]).unwrap();
4449
4450        let relay = MemoryRelay::new();
4451        relay.inject(&ev_lo1, &community.relays);
4452        relay.inject(&ev_hi1, &community.relays);
4453        // NOTE: no epoch-2 rekey on the relay — nothing for the forward walk to apply, so the heal is the
4454        // ONLY thing that can fix epoch 1.
4455
4456        crate::db::community::advance_server_root_epoch(&cid, 1, &[0x42u8; 32]).unwrap();
4457        // Simulate the prior-build reorg: I hold the LOSING epoch-1 key and have already advanced to epoch 2.
4458        crate::db::community::advance_channel_epoch(&cid, &chan_hex, 1, &key_hi1).unwrap();
4459        crate::db::community::advance_channel_epoch(&cid, &chan_hex, 2, &key_e2).unwrap();
4460        let community = crate::db::community::load_community(&community.id).unwrap().unwrap();
4461
4462        let reached = catch_up_channel_rekeys(&relay, &community, &channel_id).await.unwrap();
4463        assert_eq!(reached, 2, "head unchanged (no new rekey to apply)");
4464        assert_eq!(crate::db::community::held_epoch_key(&cid, &chan_hex, 2).unwrap(), Some(key_e2), "head epoch untouched");
4465        assert_eq!(crate::db::community::held_epoch_key(&cid, &chan_hex, 1).unwrap(), Some(key_lo1),
4466            "the already-forked past epoch re-converged to the lowest sibling via the window heal (no in-sync reorg)");
4467    }
4468
4469    #[tokio::test]
4470    async fn channel_heal_cannot_converge_to_a_key_i_was_not_given() {
4471        // The winning (lower) fork's channel rekey carries NO blob for me
4472        // (the other re-founder's retain set excluded me — e.g. it kept the just-banned victim and dropped
4473        // me in the concurrent-ban window). I literally cannot DECRYPT that key, so the heal can't adopt it
4474        // and I stay stranded on my own higher key. This proves the live bug is RETAIN-SET incompleteness in
4475        // concurrent re-founding, NOT the heal logic (which the two tests above prove correct). The fix must
4476        // guarantee each re-founder's rekey reaches the OTHER re-founder.
4477        let (_tmp, _guard) = init_test_db();
4478        let owner = Keys::generate();
4479        let me = Keys::generate();
4480        become_local(&me);
4481        let community = saved_community_owned_by(&owner);
4482        let cid = community.id.to_hex();
4483        let channel_id = community.channels[0].id;
4484        let chan_hex = channel_id.to_hex();
4485        let scope = super::super::derive::RekeyScope::Channel(channel_id);
4486        let genesis_key = *community.channels[0].key.as_bytes();
4487        let root = *community.server_root_key.as_bytes();
4488        let commit0 = super::super::rekey::epoch_key_commitment(crate::community::Epoch(0), &genesis_key);
4489
4490        let key_lo = [0x10u8; 32]; // owner's (lower) — but its rekey DOES NOT include me
4491        let key_hi = [0x99u8; 32]; // mine (higher) — the one I currently hold
4492        // Owner's lower rekey delivers ONLY to a third party (the banned victim's seat), NOT to me.
4493        let other = Keys::generate();
4494        let blob_lo = super::super::rekey::build_rekey_blob(owner.secret_key(), &other.public_key(), scope, crate::community::Epoch(1), &key_lo).unwrap();
4495        let ev_lo = super::super::rekey::build_channel_rekey_event(
4496            &Keys::generate(), &owner, &root, &channel_id, crate::community::Epoch(1), crate::community::Epoch(0), &commit0, &[blob_lo]).unwrap();
4497        // My higher rekey delivers to me.
4498        let blob_hi = super::super::rekey::build_rekey_blob(owner.secret_key(), &me.public_key(), scope, crate::community::Epoch(1), &key_hi).unwrap();
4499        let ev_hi = super::super::rekey::build_channel_rekey_event(
4500            &Keys::generate(), &owner, &root, &channel_id, crate::community::Epoch(1), crate::community::Epoch(0), &commit0, &[blob_hi]).unwrap();
4501
4502        let relay = MemoryRelay::new();
4503        relay.inject(&ev_lo, &community.relays);
4504        relay.inject(&ev_hi, &community.relays);
4505        crate::db::community::advance_server_root_epoch(&cid, 1, &[0x42u8; 32]).unwrap();
4506        crate::db::community::advance_channel_epoch(&cid, &chan_hex, 1, &key_hi).unwrap();
4507        let community = crate::db::community::load_community(&community.id).unwrap().unwrap();
4508
4509        let _ = catch_up_channel_rekeys(&relay, &community, &channel_id).await.unwrap();
4510        // Excluded from the winning rekey: I can't decrypt the lower key, so I keep my own and cannot converge.
4511        assert_eq!(crate::db::community::held_epoch_key(&cid, &chan_hex, 1).unwrap(), Some(key_hi),
4512            "excluded from the winning rekey ⇒ cannot converge");
4513    }
4514
4515    #[tokio::test]
4516    async fn refounding_channel_rekey_is_sealed_under_the_prior_root() {
4517        // #262 fix: a channel rekey accompanying a re-founding must be ENVELOPED + ADDRESSED under the PRIOR
4518        // (shared) root, NOT the re-founder's new one — so a base-fork loser (who dropped its own new root)
4519        // can still open it. This pins the write side: rotate_channel seals under the passed envelope_root,
4520        // and the event opens under that root and NOT under the community's current/new root.
4521        let (_tmp, _guard) = init_test_db();
4522        let owner = Keys::generate();
4523        become_local(&owner); // owner is supreme → authorized to rotate
4524        let community = saved_community_owned_by(&owner);
4525        let channel_id = community.channels[0].id;
4526        let prior_root = [0x11u8; 32]; // the shared pre-rotation root (≠ the community's current root)
4527
4528        let relay = MemoryRelay::new();
4529        rotate_channel(&relay, &community, &channel_id, &[owner.public_key()], &prior_root).await.unwrap();
4530
4531        // Addressed at the PRIOR-root pseudonym...
4532        let z = super::super::derive::rekey_pseudonym(&crate::community::ServerRootKey(prior_root), &channel_id, crate::community::Epoch(1)).to_hex();
4533        let q = Query { kinds: vec![event_kind::COMMUNITY_REKEY], z_tags: vec![z], ..Default::default() };
4534        let evs = relay.fetch(&q, &community.relays).await.unwrap();
4535        assert_eq!(evs.len(), 1, "channel rekey is addressed at the PRIOR-root pseudonym");
4536        // ...and opens ONLY under the prior root, NOT the community's current (new) root.
4537        assert!(super::super::rekey::open_rekey_event(&evs[0], &prior_root).is_ok(),
4538            "opens under the prior (shared) root every retained member still holds");
4539        assert!(super::super::rekey::open_rekey_event(&evs[0], community.server_root_key.as_bytes()).is_err(),
4540            "does NOT open under the current/new root (which a base-fork loser would have dropped)");
4541    }
4542
4543    #[tokio::test]
4544    async fn apply_channel_rekey_converges_past_a_divergent_prior_epoch() {
4545        // FORK-CONVERGENCE: I hold epoch-1 = my LOSING fork key. An AUTHORIZED rekey
4546        // to epoch 2 cites a DIFFERENT epoch-1 key (the winner's, which I never held) and delivers epoch-2 to
4547        // ME. The relaxed continuity check must ADOPT it (converge forward onto the authorized chain), not
4548        // reject it as a "foreign chain" and strand me on the dead fork forever.
4549        let (_tmp, _guard) = init_test_db();
4550        let owner = Keys::generate();
4551        let me = Keys::generate();
4552        become_local(&me);
4553        let community = saved_community_owned_by(&owner);
4554        let cid = community.id.to_hex();
4555        let channel_id = community.channels[0].id;
4556        let chan_hex = channel_id.to_hex();
4557        let scope = super::super::derive::RekeyScope::Channel(channel_id);
4558        let root = *community.server_root_key.as_bytes();
4559
4560        // I'm on my LOSING fork at epoch 1.
4561        let my_fork_key = [0xAAu8; 32];
4562        crate::db::community::advance_channel_epoch(&cid, &chan_hex, 1, &my_fork_key).unwrap();
4563
4564        // Owner's epoch-2 rekey continues from the WINNER's epoch-1 (a key I never held) + delivers to me.
4565        let winner_epoch1 = [0xBBu8; 32];
4566        let new_key = [0x22u8; 32];
4567        let commit = super::super::rekey::epoch_key_commitment(crate::community::Epoch(1), &winner_epoch1);
4568        let blob = super::super::rekey::build_rekey_blob(owner.secret_key(), &me.public_key(), scope, crate::community::Epoch(2), &new_key).unwrap();
4569        let ev = super::super::rekey::build_channel_rekey_event(
4570            &Keys::generate(), &owner, &root, &channel_id, crate::community::Epoch(2), crate::community::Epoch(1), &commit, &[blob]).unwrap();
4571        let parsed = super::super::rekey::open_rekey_event(&ev, &root).unwrap();
4572
4573        let outcome = apply_channel_rekey(&community, &parsed).unwrap();
4574        assert!(matches!(outcome, RekeyOutcome::Applied { head_advanced: true }),
4575            "must converge forward past the divergent prior epoch, got {outcome:?}");
4576        assert_eq!(crate::db::community::held_epoch_key(&cid, &chan_hex, 2).unwrap(), Some(new_key),
4577            "adopted the winner's epoch-2 key");
4578    }
4579
4580    #[tokio::test]
4581    async fn catch_up_server_root_stops_when_removed_from_base() {
4582        // Recipient of base epoch 1 but NOT epoch 2 (removed from the base). The walk applies 1, opens
4583        // the epoch-2 envelope (I hold root_1) but finds no blob → NotARecipient → stops at 1.
4584        let (_tmp, _guard) = init_test_db();
4585        let owner = Keys::generate();
4586        let me = Keys::generate();
4587        become_local(&me);
4588        let community = saved_community_owned_by(&owner);
4589        let scope = super::super::derive::RekeyScope::ServerRoot;
4590        let relay = MemoryRelay::new();
4591
4592        // Epoch 1 → me (cites genesis).
4593        let root1 = [0x11u8; 32];
4594        let b1 = super::super::rekey::build_rekey_blob(owner.secret_key(), &me.public_key(), scope, crate::community::Epoch(1), &root1).unwrap();
4595        let e1 = super::super::rekey::build_server_root_rekey_event(
4596            &Keys::generate(), &owner, community.server_root_key.as_bytes(), &community.id,
4597            crate::community::Epoch(1), crate::community::Epoch(0),
4598            &super::super::rekey::epoch_key_commitment(crate::community::Epoch(0), community.server_root_key.as_bytes()), &[b1],
4599        ).unwrap();
4600        // Epoch 2 → someone else (I'm removed), enveloped under root_1, cites root_1.
4601        let other = Keys::generate();
4602        let b2 = super::super::rekey::build_rekey_blob(owner.secret_key(), &other.public_key(), scope, crate::community::Epoch(2), &[0x22u8; 32]).unwrap();
4603        let e2 = super::super::rekey::build_server_root_rekey_event(
4604            &Keys::generate(), &owner, &root1, &community.id,
4605            crate::community::Epoch(2), crate::community::Epoch(1),
4606            &super::super::rekey::epoch_key_commitment(crate::community::Epoch(1), &root1), &[b2],
4607        ).unwrap();
4608        relay.inject(&e1, &community.relays);
4609        relay.inject(&e2, &community.relays);
4610
4611        let reached = catch_up_server_root(&relay, &community).await.unwrap();
4612        assert_eq!(reached.epoch, 1, "stops at the last base epoch I was a recipient of");
4613        assert!(reached.removed, "excluded by an AUTHORIZED (owner) base rotation → flagged removed so the caller erases");
4614        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
4615        assert_eq!(reloaded.server_root_epoch, crate::community::Epoch(1));
4616    }
4617
4618    #[tokio::test]
4619    async fn catch_up_is_a_noop_with_no_rotations() {
4620        let (_tmp, _guard) = init_test_db();
4621        let owner = Keys::generate();
4622        let me = Keys::generate();
4623        become_local(&me);
4624        let community = saved_community_owned_by(&owner);
4625        let relay = MemoryRelay::new(); // empty: no rekeys published
4626        let reached = catch_up_channel_rekeys(&relay, &community, &community.channels[0].id).await.unwrap();
4627        assert_eq!(reached, 0, "no rotations → stays at the held epoch");
4628    }
4629
4630    #[tokio::test]
4631    async fn catch_up_stops_when_removed_midway() {
4632        // I'm a recipient of epoch 1 but NOT epoch 2 (removed). Catch-up applies epoch 1, finds no blob
4633        // for epoch 2 (NotARecipient), and stops — head at 1, not dragged forward to a key I lack.
4634        let (_tmp, _guard) = init_test_db();
4635        let owner = Keys::generate();
4636        let me = Keys::generate();
4637        become_local(&me);
4638        let community = saved_community_owned_by(&owner);
4639        let channel_id = community.channels[0].id;
4640        let chan = &community.channels[0];
4641        let scope = super::super::derive::RekeyScope::Channel(channel_id);
4642        let relay = MemoryRelay::new();
4643
4644        // Epoch 1: blob for me (cites genesis).
4645        let k1 = [0x11u8; 32];
4646        let b1 = super::super::rekey::build_rekey_blob(owner.secret_key(), &me.public_key(), scope, crate::community::Epoch(1), &k1).unwrap();
4647        let e1 = super::super::rekey::build_channel_rekey_event(
4648            &Keys::generate(), &owner, community.server_root_key.as_bytes(), &channel_id,
4649            crate::community::Epoch(1), crate::community::Epoch(0),
4650            &super::super::rekey::epoch_key_commitment(crate::community::Epoch(0), chan.key.as_bytes()), &[b1],
4651        ).unwrap();
4652        // Epoch 2: blob for SOMEONE ELSE (I was removed) — cites k1.
4653        let other = Keys::generate();
4654        let b2 = super::super::rekey::build_rekey_blob(owner.secret_key(), &other.public_key(), scope, crate::community::Epoch(2), &[0x22u8; 32]).unwrap();
4655        let e2 = super::super::rekey::build_channel_rekey_event(
4656            &Keys::generate(), &owner, community.server_root_key.as_bytes(), &channel_id,
4657            crate::community::Epoch(2), crate::community::Epoch(1),
4658            &super::super::rekey::epoch_key_commitment(crate::community::Epoch(1), &k1), &[b2],
4659        ).unwrap();
4660        relay.inject(&e1, &community.relays);
4661        relay.inject(&e2, &community.relays);
4662
4663        let reached = catch_up_channel_rekeys(&relay, &community, &channel_id).await.unwrap();
4664        assert_eq!(reached, 1, "stops at the last epoch I was a recipient of");
4665        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
4666        assert_eq!(reloaded.channels[0].epoch, crate::community::Epoch(1));
4667    }
4668
4669    #[tokio::test]
4670    async fn rotate_channel_rejects_unauthorized() {
4671        let (_tmp, _guard) = init_test_db();
4672        let owner = Keys::generate();
4673        let rogue = Keys::generate();
4674        become_local(&rogue); // not the owner, holds no role
4675        let community = saved_community_owned_by(&owner);
4676        let relay = MemoryRelay::new();
4677        assert!(
4678            rotate_channel(&relay, &community, &community.channels[0].id, &[], community.server_root_key.as_bytes()).await.is_err(),
4679            "a non-authorized member cannot rotate"
4680        );
4681        // My head did not move.
4682        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
4683        assert_eq!(reloaded.channels[0].epoch, crate::community::Epoch(0));
4684    }
4685
4686    // --- rotate_server_root (#4c) ---
4687
4688    #[tokio::test]
4689    async fn rotate_server_root_publishes_recoverable_rekey_and_advances_base() {
4690        use crate::community::derive::{base_rekey_pseudonym, recipient_pseudonym};
4691        use crate::community::rekey::{open_rekey_blob, open_rekey_event, rekey_pairwise_secret};
4692        let (_tmp, _guard) = init_test_db();
4693        let owner = Keys::generate();
4694        become_local(&owner); // owner is supreme (holds BAN)
4695        let community = saved_community_owned_by(&owner);
4696        let genesis_root = *community.server_root_key.as_bytes();
4697        let member = Keys::generate();
4698        let relay = MemoryRelay::new();
4699
4700        let new_epoch = rotate_server_root(&relay, &community, &[member.public_key()]).await.expect("rotate base");
4701        assert_eq!(new_epoch, 1);
4702
4703        // Owner's base head advanced to a fresh root.
4704        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
4705        assert_eq!(reloaded.server_root_epoch, crate::community::Epoch(1));
4706        assert_ne!(reloaded.server_root_key.as_bytes(), &genesis_root, "base root is fresh-random, not the genesis");
4707
4708        // The base rekey is found at the PRIOR-root-derived address and opens under the PRIOR (genesis) root.
4709        let addr = base_rekey_pseudonym(&crate::community::ServerRootKey(genesis_root), &community.id, crate::community::Epoch(1)).to_hex();
4710        let found = relay
4711            .fetch(&Query { kinds: vec![event_kind::COMMUNITY_REKEY], z_tags: vec![addr], ..Default::default() }, &community.relays)
4712            .await
4713            .unwrap();
4714        assert_eq!(found.len(), 1, "base rekey addressable by its prior-root pseudonym");
4715        let parsed = open_rekey_event(&found[0], &genesis_root).unwrap();
4716        assert!(matches!(parsed.scope, crate::community::derive::RekeyScope::ServerRoot));
4717        assert_eq!(parsed.rotator, owner.public_key());
4718        assert_eq!(parsed.blobs.len(), 2, "member + me (multi-device)");
4719
4720        // The member recovers a root, and it equals the owner's advanced base head (one source of truth).
4721        let secret = rekey_pairwise_secret(member.secret_key(), &parsed.rotator).unwrap();
4722        let loc = recipient_pseudonym(&secret, parsed.scope, parsed.new_epoch).to_hex();
4723        let mine = parsed.blobs.iter().find(|b| b.locator == loc).expect("member's blob present");
4724        let recovered = open_rekey_blob(member.secret_key(), &parsed.rotator, parsed.scope, parsed.new_epoch, mine).unwrap();
4725        assert_eq!(reloaded.server_root_key.as_bytes(), &recovered, "member's recovered root == owner's advanced base head");
4726    }
4727
4728    #[tokio::test]
4729    async fn rotate_server_root_failed_publish_leaves_base_unadvanced() {
4730        let (_tmp, _guard) = init_test_db();
4731        let owner = Keys::generate();
4732        become_local(&owner);
4733        let community = saved_community_owned_by(&owner);
4734        let member = Keys::generate();
4735        assert!(rotate_server_root(&FailingRelay, &community, &[member.public_key()]).await.is_err());
4736        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
4737        assert_eq!(reloaded.server_root_epoch, crate::community::Epoch(0), "base head stays put on publish failure");
4738    }
4739
4740    #[tokio::test]
4741    async fn rotate_server_root_dedups_self_in_recipients() {
4742        // Passing my own pubkey in `recipients` must not produce a duplicate blob (I'm always added).
4743        use crate::community::rekey::open_rekey_event;
4744        let (_tmp, _guard) = init_test_db();
4745        let owner = Keys::generate();
4746        become_local(&owner);
4747        let community = saved_community_owned_by(&owner);
4748        let relay = MemoryRelay::new();
4749        rotate_server_root(&relay, &community, &[owner.public_key()]).await.unwrap();
4750        let addr = crate::community::derive::base_rekey_pseudonym(
4751            &crate::community::ServerRootKey(*community.server_root_key.as_bytes()), &community.id, crate::community::Epoch(1),
4752        )
4753        .to_hex();
4754        let found = relay
4755            .fetch(&Query { kinds: vec![event_kind::COMMUNITY_REKEY], z_tags: vec![addr], ..Default::default() }, &community.relays)
4756            .await
4757            .unwrap();
4758        let parsed = open_rekey_event(&found[0], community.server_root_key.as_bytes()).unwrap();
4759        assert_eq!(parsed.blobs.len(), 1, "self listed in recipients yields exactly one blob, not two");
4760    }
4761
4762    #[tokio::test]
4763    async fn rotate_server_root_rejects_unauthorized() {
4764        let (_tmp, _guard) = init_test_db();
4765        let owner = Keys::generate();
4766        let rogue = Keys::generate();
4767        become_local(&rogue); // no BAN, not owner
4768        let community = saved_community_owned_by(&owner);
4769        let relay = MemoryRelay::new();
4770        assert!(rotate_server_root(&relay, &community, &[]).await.is_err(), "a non-BAN member cannot rotate the base");
4771        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
4772        assert_eq!(reloaded.server_root_epoch, crate::community::Epoch(0));
4773    }
4774
4775    #[tokio::test]
4776    async fn rotate_server_root_reanchors_the_control_plane_to_the_new_epoch() {
4777        // #4e-2 orchestration: a base rotation carries the control plane to the new epoch as part of the
4778        // SAME operation — a member reading the new root reaches the roster without a separate step.
4779        let (_tmp, _guard) = init_test_db();
4780        let relay = MemoryRelay::new();
4781        // create publishes 3 genesis editions (GroupRoot + #general ChannelMetadata + Admin role) and
4782        // records all three heads.
4783        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
4784        let cid = community.id.to_hex();
4785        assert_eq!(crate::db::community::edition_head_entity_ids(&cid).unwrap().len(), 3);
4786
4787        let member = Keys::generate();
4788        assert_eq!(rotate_server_root(&relay, &community, &[member.public_key()]).await.unwrap(), 1);
4789        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
4790        assert_eq!(reloaded.server_root_epoch, crate::community::Epoch(1), "base head advanced");
4791
4792        // The Admin role is reachable at the NEW epoch under the NEW root — re-anchored by the rotation.
4793        let z = crate::community::roster::control_pseudonym(&reloaded.server_root_key, &community.id, crate::community::Epoch(1));
4794        let evs = relay
4795            .fetch(&Query { kinds: vec![event_kind::COMMUNITY_CONTROL], z_tags: vec![z], ..Default::default() }, &community.relays)
4796            .await
4797            .unwrap();
4798        let inners: Vec<_> = evs
4799            .iter()
4800            .filter_map(|o| crate::community::roster::open_control_edition(o, &reloaded.server_root_key).ok())
4801            .collect();
4802        let folded = crate::community::roster::fold_roster(&inners, &community.id, &Default::default());
4803        assert!(!folded.roles.roles.is_empty(), "control plane re-anchored at the new epoch as part of the rotation");
4804    }
4805
4806    #[tokio::test]
4807    async fn admin_refounding_carries_heads_verbatim_preserving_owner_and_peer_roles() {
4808        // The verbatim-heads payoff: a NON-OWNER admin re-founds, and because each head is re-wrapped (never
4809        // re-authored), the owner deed AND every peer admin's owner-signed grant ride along untouched — so
4810        // ownership and all roles survive, while the count compacts to one edition per entity.
4811        use crate::community::roles::Permissions;
4812        let (_tmp, _guard) = init_test_db();
4813        let owner = crate::state::MY_SECRET_KEY.to_keys().unwrap();
4814        let owner_hex = owner.public_key().to_hex();
4815        let relay = MemoryRelay::new();
4816        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
4817        let cid = community.id.to_hex();
4818        let admin_role = crate::db::community::get_community_roles(&cid).unwrap().roles[0].role_id.clone();
4819
4820        // Owner grants TWO admins (both grants OWNER-signed).
4821        let alice = Keys::generate();
4822        let bob = Keys::generate();
4823        set_member_grant(&relay, &community, &alice.public_key().to_hex(), vec![admin_role.clone()]).await.unwrap();
4824        set_member_grant(&relay, &community, &bob.public_key().to_hex(), vec![admin_role.clone()]).await.unwrap();
4825        let _ = fetch_and_apply_control(&relay, &community).await;
4826        let community = crate::db::community::load_community(&community.id).unwrap().unwrap();
4827
4828        // Drive the GroupRoot ABOVE v1 with a real published edit, so this exercises verbatim-carry of a
4829        // >v1 head (it must keep its real version, NOT reset to v1) — not just a v1 genesis.
4830        let mut edited = community.clone();
4831        edited.name = "HQ renamed".into();
4832        republish_community_metadata(&relay, &edited).await.unwrap();
4833        let _ = fetch_and_apply_control(&relay, &community).await;
4834        let community = crate::db::community::load_community(&community.id).unwrap().unwrap();
4835        assert!(crate::db::community::get_edition_head(&cid, &cid).unwrap().unwrap().0 >= 2, "GroupRoot now above v1");
4836
4837        // ALICE (a non-owner admin) re-founds. She holds BAN, so it's authorized; she re-WRAPS heads.
4838        become_local(&alice);
4839        let new_epoch = rotate_server_root(&relay, &community, &[owner.public_key(), bob.public_key()]).await.unwrap();
4840        assert_eq!(new_epoch, 1);
4841        let community = crate::db::community::load_community(&community.id).unwrap().unwrap();
4842        assert_eq!(community.server_root_epoch, crate::community::Epoch(1));
4843
4844        // Fold the new epoch fresh (floor 0): owner unchanged + BOTH alice and bob still admins.
4845        let z = crate::community::roster::control_pseudonym(&community.server_root_key, &community.id, crate::community::Epoch(1));
4846        let evs = relay.fetch(&Query { kinds: vec![event_kind::COMMUNITY_CONTROL], z_tags: vec![z], ..Default::default() }, &community.relays).await.unwrap();
4847        let inners: Vec<_> = evs.iter().filter_map(|o| crate::community::roster::open_control_edition(o, &community.server_root_key).ok()).collect();
4848        let folded = crate::community::roster::fold_roster(&inners, &community.id, &Default::default());
4849        let authed = crate::community::roster::authorize_delegation(&folded, Some(&owner_hex));
4850        assert!(authed.is_authorized(&alice.public_key().to_hex(), Some(&owner_hex), Permissions::BAN), "alice (re-founder) still admin");
4851        assert!(authed.is_authorized(&bob.public_key().to_hex(), Some(&owner_hex), Permissions::BAN), "bob (peer admin) NOT demoted by alice's re-founding");
4852        let new_owner = folded.root_meta.as_ref().and_then(|m| m.owner_attestation.as_ref())
4853            .and_then(|j| Event::from_json(j).ok()).map(|e| e.pubkey.to_hex());
4854        assert_eq!(new_owner.as_deref(), Some(owner_hex.as_str()), "owner deed carried verbatim — ownership intact after an admin re-founding");
4855        assert_eq!(folded.root_meta.as_ref().map(|m| m.name.as_str()), Some("HQ renamed"),
4856            "the >v1 GroupRoot head carried verbatim (content preserved across the re-founding)");
4857        // Compacted: each entity appears at most once at the new epoch.
4858        let mut per_entity: std::collections::HashMap<[u8; 32], usize> = std::collections::HashMap::new();
4859        for i in &inners {
4860            if let Ok(p) = crate::community::edition::parse_edition_inner(i) { *per_entity.entry(p.entity_id).or_default() += 1; }
4861        }
4862        assert!(per_entity.values().all(|&c| c == 1), "one edition per entity at the new epoch (compacted)");
4863    }
4864
4865    /// Block-until-synced: an admin write (rekey) is REFUSED when we're network-isolated — no relay returns
4866    /// the control plane we KNOW exists (we hold edition heads). Acting blind on a stale view, or advancing
4867    /// local state we can't publish, must not happen offline.
4868    #[tokio::test]
4869    async fn admin_write_blocked_when_isolated() {
4870        let (_tmp, _guard) = init_test_db();
4871        let me = Keys::generate();
4872        become_local(&me);
4873        let community = saved_community_owned_by(&me);
4874        let cid = community.id.to_hex();
4875        // We hold a local edition head → we KNOW a control plane exists (so an empty fetch = isolation).
4876        crate::db::community::set_edition_head_with_id(&cid, &cid, 1, &[1u8; 32], &[1u8; 32]).unwrap();
4877        crate::db::community::set_read_cut_target_epoch(&cid, 1).unwrap();
4878        // FailingRelay.fetch returns Ok(empty) — the isolated case (no relay responds with anything).
4879        let err = reseal_base_to_observed(&FailingRelay, &community).await.unwrap_err();
4880        assert!(err.contains("offline") || err.contains("can't reach any relay"),
4881            "isolated admin write must fail closed, got: {err}");
4882        // Untouched: no base rotation happened.
4883        assert_eq!(crate::db::community::load_community(&community.id).unwrap().unwrap().server_root_epoch,
4884            crate::community::Epoch(0), "no rotation while isolated");
4885    }
4886
4887    /// O2 — a re-founding rotates per-channel message keys too, not just the base. Without this a removed
4888    /// member holding a channel key keeps reading new messages (the base cut only covers control + @everyone).
4889    #[tokio::test]
4890    async fn refounding_rotates_channel_keys_too() {
4891        let (_tmp, _guard) = init_test_db();
4892        let relay = MemoryRelay::new();
4893        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
4894        let channel_id = community.channels[0].id;
4895        assert_eq!(community.channels[0].epoch, crate::community::Epoch(0));
4896        assert_eq!(community.server_root_epoch, crate::community::Epoch(0));
4897
4898        run_read_cut(&relay, &community, true).await.unwrap();
4899
4900        let after = crate::db::community::load_community(&community.id).unwrap().unwrap();
4901        assert_eq!(after.server_root_epoch, crate::community::Epoch(1), "base rotated");
4902        let ch = after.channels.iter().find(|c| c.id == channel_id).unwrap();
4903        assert_eq!(ch.epoch, crate::community::Epoch(1), "channel key rotated too (O2)");
4904        assert_eq!(crate::db::community::channel_rekeyed_at_server_epoch(&community.id.to_hex(), &channel_id.to_hex()).unwrap(),
4905            1, "channel marked rekeyed for the new base epoch");
4906        assert!(!crate::db::community::get_read_cut_pending(&community.id.to_hex()).unwrap(),
4907            "a complete read-cut clears the pending flag");
4908    }
4909
4910    /// W2 durability — a re-founding interrupted AFTER the base rotated but BEFORE a channel rekey landed
4911    /// (outage / power cut / mass relay failure mid-cut) must RESUME, not restart: the retry skips the
4912    /// already-done base (no second epoch, no second control-plane re-anchor) and finishes only the
4913    /// un-rotated channel. Without resumability the retry double-rotated the base every time.
4914    #[tokio::test]
4915    async fn read_cut_resumes_without_double_base_rotation_after_channel_failure() {
4916        // Base + channel rekeys are both COMMUNITY_REKEY (3303); the base rekey is published BEFORE any
4917        // channel rekey, so the 1st 3303 is the base (allowed) and every later one is a channel (failed
4918        // while armed). Control re-anchor (3308) is always allowed.
4919        struct ChannelRekeyFails {
4920            inner: MemoryRelay,
4921            rekeys: std::sync::atomic::AtomicUsize,
4922            fail_channel: std::sync::atomic::AtomicBool,
4923        }
4924        #[async_trait::async_trait]
4925        impl Transport for ChannelRekeyFails {
4926            async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> { self.inner.publish(e, r).await }
4927            async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
4928                if e.kind.as_u16() == event_kind::COMMUNITY_REKEY {
4929                    let n = self.rekeys.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4930                    if n >= 1 && self.fail_channel.load(std::sync::atomic::Ordering::Relaxed) {
4931                        return Err("channel rekey relay down".into());
4932                    }
4933                }
4934                self.inner.publish_durable(e, r).await
4935            }
4936            async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> { self.inner.fetch(q, r).await }
4937        }
4938        let (_tmp, _guard) = init_test_db();
4939        let relay = ChannelRekeyFails {
4940            inner: MemoryRelay::new(),
4941            rekeys: std::sync::atomic::AtomicUsize::new(0),
4942            fail_channel: std::sync::atomic::AtomicBool::new(true),
4943        };
4944        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
4945        let channel_id = community.channels[0].id;
4946        let cid = community.id.to_hex();
4947        let ch_hex = channel_id.to_hex();
4948
4949        // Phase 1: base rotates, the channel rekey fails → the cut is left PENDING, base at epoch 1.
4950        assert!(run_read_cut(&relay, &community, true).await.is_err(), "the channel failure surfaces an error");
4951        let mid = crate::db::community::load_community(&community.id).unwrap().unwrap();
4952        assert_eq!(mid.server_root_epoch, crate::community::Epoch(1), "base advanced exactly once");
4953        assert_eq!(mid.channels.iter().find(|c| c.id == channel_id).unwrap().epoch, crate::community::Epoch(0),
4954            "channel NOT rotated (its rekey failed)");
4955        assert!(crate::db::community::get_read_cut_pending(&cid).unwrap(), "cut left pending after the failure");
4956        assert_eq!(crate::db::community::get_read_cut_target_epoch(&cid).unwrap(), 1, "target recorded durably");
4957        assert_eq!(crate::db::community::channel_rekeyed_at_server_epoch(&cid, &ch_hex).unwrap(), 0,
4958            "channel not yet marked for this cut");
4959
4960        // Phase 2: relay heals; the retry RESUMES — no second base rotation, just the leftover channel.
4961        relay.fail_channel.store(false, std::sync::atomic::Ordering::Relaxed);
4962        retry_pending_read_cut(&relay, &mid).await.unwrap();
4963        let done = crate::db::community::load_community(&community.id).unwrap().unwrap();
4964        assert_eq!(done.server_root_epoch, crate::community::Epoch(1),
4965            "base NOT rotated again — resumed at the same epoch (no double base rotation)");
4966        assert_eq!(done.channels.iter().find(|c| c.id == channel_id).unwrap().epoch, crate::community::Epoch(1),
4967            "the un-rotated channel finished on resume");
4968        assert_eq!(crate::db::community::channel_rekeyed_at_server_epoch(&cid, &ch_hex).unwrap(), 1,
4969            "channel marked rekeyed for the cut epoch");
4970        assert!(!crate::db::community::get_read_cut_pending(&cid).unwrap(), "pending cleared after the resume completes");
4971    }
4972
4973    #[tokio::test]
4974    async fn rotate_server_root_aborts_when_the_snapshot_does_not_land() {
4975        // Re-founding re-wraps the current heads, but a relay that won't ACK the re-wrapped control editions
4976        // leaves the snapshot incomplete → the rotation must abort with the base head NOT advanced (never
4977        // advance onto a plane no member folds).
4978        // Relay that ACKs everything UNTIL `fail` is set, then rejects control-edition (3308) publishes.
4979        struct ControlPublishFails { inner: MemoryRelay, fail: std::sync::atomic::AtomicBool }
4980        #[async_trait::async_trait]
4981        impl Transport for ControlPublishFails {
4982            async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> { self.inner.publish(e, r).await }
4983            async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
4984                if self.fail.load(std::sync::atomic::Ordering::Relaxed) && e.kind.as_u16() == event_kind::COMMUNITY_CONTROL {
4985                    return Err("control relay down".into());
4986                }
4987                self.inner.publish_durable(e, r).await
4988            }
4989            async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> { self.inner.fetch(q, r).await }
4990        }
4991        let (_tmp, _guard) = init_test_db();
4992        let relay = ControlPublishFails { inner: MemoryRelay::new(), fail: std::sync::atomic::AtomicBool::new(false) };
4993        // Create normally (genesis editions publish + heads recorded), THEN start failing control publishes.
4994        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
4995        relay.fail.store(true, std::sync::atomic::Ordering::Relaxed);
4996
4997        assert!(
4998            rotate_server_root(&relay, &community, &[]).await.is_err(),
4999            "a snapshot whose editions can't be re-published must abort the rotation"
5000        );
5001        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
5002        assert_eq!(reloaded.server_root_epoch, crate::community::Epoch(0), "base head NOT advanced when the snapshot doesn't land");
5003    }
5004
5005    #[tokio::test]
5006    async fn acquire_before_commit_a_reanchor_fetch_miss_publishes_no_base_rekey() {
5007        // #264 ACQUIRE-BEFORE-COMMIT: the re-anchor snapshot (the only mid-rekey fetch) is now fetched + sealed
5008        // BEFORE the base rekey is published. So a control-plane fetch miss (a head not propagated) aborts the
5009        // rotation with the base rekey NEVER on the wire — no half-published state to strand a member. Under the
5010        // old publish-first ordering the base rekey was already on relays when the fetch gate tripped.
5011        use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
5012        struct ReanchorFetchEmpty { inner: MemoryRelay, drop_control: AtomicBool, base_rekeys: AtomicUsize }
5013        #[async_trait::async_trait]
5014        impl Transport for ReanchorFetchEmpty {
5015            async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> { self.inner.publish(e, r).await }
5016            async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
5017                if e.kind.as_u16() == event_kind::COMMUNITY_REKEY {
5018                    self.base_rekeys.fetch_add(1, Ordering::Relaxed);
5019                }
5020                self.inner.publish_durable(e, r).await
5021            }
5022            async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
5023                if self.drop_control.load(Ordering::Relaxed) && q.kinds.iter().any(|k| *k == event_kind::COMMUNITY_CONTROL) {
5024                    return Ok(vec![]); // the re-anchor's heads are unreachable this instant
5025                }
5026                self.inner.fetch(q, r).await
5027            }
5028        }
5029        let (_tmp, _guard) = init_test_db();
5030        let relay = ReanchorFetchEmpty { inner: MemoryRelay::new(), drop_control: AtomicBool::new(false), base_rekeys: AtomicUsize::new(0) };
5031        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
5032        relay.drop_control.store(true, Ordering::Relaxed);
5033
5034        assert!(rotate_server_root(&relay, &community, &[]).await.is_err(),
5035            "a re-anchor fetch miss must abort the rotation");
5036        assert_eq!(relay.base_rekeys.load(Ordering::Relaxed), 0,
5037            "the base rekey must NOT be published when the pre-publish fetch gate trips (acquire-before-commit)");
5038        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
5039        assert_eq!(reloaded.server_root_epoch, crate::community::Epoch(0), "base head NOT advanced");
5040    }
5041
5042    // --- reanchor_control_plane (#4e-1) ---
5043
5044    #[tokio::test]
5045    async fn reanchor_carries_role_and_grant_to_the_new_epoch_under_the_new_root() {
5046        let (_tmp, _guard) = init_test_db();
5047        let relay = MemoryRelay::new();
5048        // create_community publishes the auto Admin ROLE edition (3308) at the epoch-0 control pseudonym.
5049        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
5050        let cid = community.id.to_hex();
5051        let admin_role_id = crate::db::community::get_community_roles(&cid).unwrap().roles[0].role_id.clone();
5052        let member = Keys::generate();
5053        // Compaction snapshots the LOCAL folded state, so seed the grant into it (publish + apply).
5054        set_member_grant(&relay, &community, &member.public_key().to_hex(), vec![admin_role_id]).await.unwrap();
5055        let _ = fetch_and_apply_control(&relay, &community).await;
5056        let community = crate::db::community::load_community(&community.id).unwrap().unwrap();
5057
5058        // Re-anchor by COMPACTION to a fresh root + epoch 1: each entity re-genesised to v1.
5059        let new_root = [0x99u8; 32];
5060        let snap = reanchor_control_plane(&relay, &community, &new_root, crate::community::Epoch(1)).await.unwrap();
5061        assert!(snap.iter().all(|e| e.published), "every snapshot edition published");
5062        assert_eq!(snap.len(), 4, "GroupRoot + channel + Admin role + grant compacted to v1");
5063
5064        // At the NEW epoch under the NEW root, the role + grant fold back (as fresh v1 geneses, community-scoped).
5065        let new_z = crate::community::roster::control_pseudonym(
5066            &crate::community::ServerRootKey(new_root), &community.id, crate::community::Epoch(1),
5067        );
5068        let after = relay
5069            .fetch(&Query { kinds: vec![event_kind::COMMUNITY_CONTROL], z_tags: vec![new_z], ..Default::default() }, &community.relays)
5070            .await
5071            .unwrap();
5072        let inners: Vec<_> = after
5073            .iter()
5074            .filter_map(|o| crate::community::roster::open_control_edition(o, &crate::community::ServerRootKey(new_root)).ok())
5075            .collect();
5076        let folded = crate::community::roster::fold_roster(&inners, &community.id, &Default::default());
5077        assert!(!folded.roles.roles.is_empty(), "Admin role reachable at the new epoch");
5078        assert!(
5079            folded.roles.grants.iter().any(|g| g.member == member.public_key().to_hex()),
5080            "grant carried to the new epoch under the new root"
5081        );
5082    }
5083
5084    #[tokio::test]
5085    async fn grant_after_a_rekey_survives_the_fold_at_the_new_epoch() {
5086        // REGRESSION (epoch consistency): a grant published AFTER a server-root rotation must seal at the
5087        // CURRENT epoch — where the re-anchored role definition now lives — and the fetch must look there
5088        // too. The bug: live publishes + the fetch hardcoded epoch 0 while the re-anchor moved the control
5089        // plane to the new epoch, so a post-rekey grant referenced a role the fetch never saw → the member
5090        // silently lost admin (exactly what we hit live).
5091        use crate::community::roles::Permissions;
5092        let (_tmp, _guard) = init_test_db();
5093        let relay = MemoryRelay::new();
5094        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
5095        let cid = community.id.to_hex();
5096        let owner = crate::state::MY_SECRET_KEY.to_keys().unwrap();
5097        let admin_role_id = crate::db::community::get_community_roles(&cid).unwrap().roles[0].role_id.clone();
5098
5099        // Rotate the base → epoch 1 (re-anchors the Admin role + GroupRoot under the new epoch).
5100        rotate_server_root(&relay, &community, &[owner.public_key()]).await.expect("rotate base");
5101        let community = crate::db::community::load_community(&community.id).unwrap().unwrap();
5102        assert_eq!(community.server_root_epoch, crate::community::Epoch(1), "advanced to the new epoch");
5103
5104        // Grant Alice the Admin role NOW (post-rekey): the live publish seals at server_root_epoch (1).
5105        let alice = "aa".repeat(32);
5106        set_member_grant(&relay, &community, &alice, vec![admin_role_id]).await.unwrap();
5107
5108        // A fresh fetch+apply at the new epoch folds the re-anchored role AND the post-rekey grant TOGETHER.
5109        let roster = fetch_and_apply_roles(&relay, &community).await.unwrap();
5110        assert!(
5111            roster.has_permission(&alice, Permissions::BAN),
5112            "post-rekey grant survives — Alice is Admin at the new epoch (pre-fix: dropped, role unreachable)"
5113        );
5114        assert_eq!(roster.highest_position(&alice), Some(1));
5115    }
5116
5117    /// Increment 2 — the demote AUTO-re-asserts: when the demoted member HEADS the GroupRoot, revoking
5118    /// them publishes an owner-authored re-assert of their content as the new head, so Concord Convergence
5119    /// keeps it for every client (incl. fresh joiners). End-to-end of the demote path.
5120    #[tokio::test]
5121    async fn demote_re_asserts_the_demoted_members_metadata_head() {
5122        let (_tmp, _guard) = init_test_db();
5123        let relay = MemoryRelay::new();
5124        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
5125        let cid = community.id.to_hex();
5126        let owner = crate::state::MY_SECRET_KEY.to_keys().unwrap();
5127        let admin_role = crate::db::community::get_community_roles(&cid).unwrap().roles[0].role_id.clone();
5128        let alice = Keys::generate();
5129        let alice_hex = alice.public_key().to_hex();
5130
5131        set_member_grant(&relay, &community, &alice_hex, vec![admin_role]).await.unwrap();
5132        // Alice (admin) renames → she heads the GroupRoot.
5133        become_local(&alice);
5134        let mut as_alice = crate::db::community::load_community(&community.id).unwrap().unwrap();
5135        as_alice.name = "Alice's HQ".into();
5136        republish_community_metadata(&relay, &as_alice).await.unwrap();
5137        let community = crate::db::community::load_community(&community.id).unwrap().unwrap();
5138        assert_eq!(
5139            fetch_control_folded(&relay, &community).await.unwrap().root_author.map(|a| a.to_hex()),
5140            Some(alice_hex.clone()), "alice heads the GroupRoot after her edit",
5141        );
5142
5143        // Owner demotes alice → auto re-assert.
5144        become_local(&owner);
5145        let community = crate::db::community::load_community(&community.id).unwrap().unwrap();
5146        set_member_grant(&relay, &community, &alice_hex, vec![]).await.unwrap();
5147
5148        let community = crate::db::community::load_community(&community.id).unwrap().unwrap();
5149        let folded = fetch_control_folded(&relay, &community).await.unwrap();
5150        assert_eq!(folded.root_author.map(|a| a.to_hex()), Some(owner.public_key().to_hex()),
5151            "the demote re-asserted the GroupRoot under the owner");
5152        assert_eq!(folded.root_meta.as_ref().unwrap().name, "Alice's HQ",
5153            "the re-assert preserves the demoted member's content");
5154    }
5155
5156    /// Increment 2 — skip-if-not-head: demoting a member who does NOT head the GroupRoot publishes no
5157    /// re-assert (zero unnecessary editions — the common case). The owner made the last edit here.
5158    #[tokio::test]
5159    async fn demote_skips_reassert_when_member_does_not_head() {
5160        let (_tmp, _guard) = init_test_db();
5161        let relay = MemoryRelay::new();
5162        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
5163        let cid = community.id.to_hex();
5164        let admin_role = crate::db::community::get_community_roles(&cid).unwrap().roles[0].role_id.clone();
5165        let alice = Keys::generate();
5166        let alice_hex = alice.public_key().to_hex();
5167
5168        set_member_grant(&relay, &community, &alice_hex, vec![admin_role]).await.unwrap();
5169        // OWNER makes the last metadata edit → the owner heads it, not alice.
5170        let mut c = crate::db::community::load_community(&community.id).unwrap().unwrap();
5171        c.name = "Owner's HQ".into();
5172        republish_community_metadata(&relay, &c).await.unwrap();
5173        let community = crate::db::community::load_community(&community.id).unwrap().unwrap();
5174        let before = fetch_control_folded(&relay, &community).await.unwrap().root_head.unwrap().version;
5175
5176        set_member_grant(&relay, &community, &alice_hex, vec![]).await.unwrap();
5177        let community = crate::db::community::load_community(&community.id).unwrap().unwrap();
5178        let after = fetch_control_folded(&relay, &community).await.unwrap().root_head.unwrap().version;
5179        assert_eq!(after, before, "no re-assert published — the demoted member didn't head the GroupRoot");
5180    }
5181
5182    #[tokio::test]
5183    async fn reanchor_carries_the_banlist_edition_to_the_new_epoch() {
5184        // The banlist is now a 3308 edition at the community-scoped banlist locator, so re-anchoring
5185        // (kind-agnostic within 3308) carries it forward — a post-rotation joiner gets the current bans.
5186        let (_tmp, _guard) = init_test_db();
5187        let relay = MemoryRelay::new();
5188        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
5189        let carol = "cc".repeat(32);
5190        // Seed the banlist into LOCAL state (publish + apply), since compaction snapshots the local set.
5191        publish_banlist(&relay, &community, &[carol.clone()]).await.unwrap();
5192        let _ = fetch_and_apply_control(&relay, &community).await;
5193        let community = crate::db::community::load_community(&community.id).unwrap().unwrap();
5194
5195        // Re-anchor by COMPACTION to a fresh root + epoch 1: the banlist is re-genesised forward.
5196        let new_root = [0x99u8; 32];
5197        let n = reanchor_control_plane(&relay, &community, &new_root, crate::community::Epoch(1)).await.unwrap();
5198        assert!(n.iter().all(|e| e.published), "every snapshot edition published");
5199        assert_eq!(n.len(), 4, "GroupRoot + channel + Admin role + banlist compacted to v1");
5200
5201        // Fetch at the new epoch under the new root → the banlist folds back with Carol still banned.
5202        let new_z = crate::community::roster::control_pseudonym(
5203            &crate::community::ServerRootKey(new_root), &community.id, crate::community::Epoch(1),
5204        );
5205        let after = relay
5206            .fetch(&Query { kinds: vec![event_kind::COMMUNITY_CONTROL], z_tags: vec![new_z], ..Default::default() }, &community.relays)
5207            .await
5208            .unwrap();
5209        let inners: Vec<_> = after
5210            .iter()
5211            .filter_map(|o| crate::community::roster::open_control_edition(o, &crate::community::ServerRootKey(new_root)).ok())
5212            .collect();
5213        let folded = crate::community::roster::fold_roster(&inners, &community.id, &Default::default());
5214        assert_eq!(folded.banned, vec![carol], "banlist reachable at the new epoch under the new root");
5215    }
5216
5217    // --- apply_server_root_rekey (#4b) ---
5218
5219    /// An owner-authored base rekey to `new_epoch` carrying one ServerRoot blob for `recipient_pk`,
5220    /// citing the community's current (genesis epoch-0) root. Returns the opened ParsedRekey.
5221    fn owner_base_rekey(
5222        owner: &Keys, community: &Community, recipient_pk: &nostr_sdk::PublicKey, new_epoch: u64, new_root: &[u8; 32],
5223    ) -> super::super::rekey::ParsedRekey {
5224        let prev = community.server_root_epoch.0;
5225        let blob = super::super::rekey::build_rekey_blob(
5226            owner.secret_key(), recipient_pk, super::super::derive::RekeyScope::ServerRoot, crate::community::Epoch(new_epoch), new_root,
5227        )
5228        .unwrap();
5229        let commit = super::super::rekey::epoch_key_commitment(crate::community::Epoch(prev), community.server_root_key.as_bytes());
5230        let outer = super::super::rekey::build_server_root_rekey_event(
5231            &Keys::generate(), owner, community.server_root_key.as_bytes(), &community.id,
5232            crate::community::Epoch(new_epoch), crate::community::Epoch(prev), &commit, &[blob],
5233        )
5234        .unwrap();
5235        super::super::rekey::open_rekey_event(&outer, community.server_root_key.as_bytes()).unwrap()
5236    }
5237
5238    #[test]
5239    fn apply_server_root_rekey_recovers_new_root_and_advances_base() {
5240        let (_tmp, _guard) = init_test_db();
5241        let owner = Keys::generate();
5242        let me = Keys::generate();
5243        become_local(&me);
5244        let community = saved_community_owned_by(&owner);
5245        let cid = community.id.to_hex();
5246        let new_root = [0xCDu8; 32];
5247
5248        let parsed = owner_base_rekey(&owner, &community, &me.public_key(), 1, &new_root);
5249        assert_eq!(apply_server_root_rekey(&community, &parsed).unwrap(), RekeyOutcome::Applied { head_advanced: true });
5250
5251        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
5252        assert_eq!(reloaded.server_root_epoch, crate::community::Epoch(1));
5253        assert_eq!(reloaded.server_root_key.as_bytes(), &new_root, "base head advanced to the new root");
5254        // Genesis root retained (cross-epoch control/base history stays decryptable).
5255        assert!(crate::db::community::held_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 0).unwrap().is_some());
5256        assert_eq!(crate::db::community::held_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 1).unwrap(), Some(new_root));
5257    }
5258
5259    #[test]
5260    fn apply_server_root_rekey_not_a_recipient_leaves_base_unchanged() {
5261        let (_tmp, _guard) = init_test_db();
5262        let owner = Keys::generate();
5263        let me = Keys::generate();
5264        become_local(&me);
5265        let community = saved_community_owned_by(&owner);
5266        let other = Keys::generate(); // blob wrapped to someone else → I was removed in this rotation
5267        let parsed = owner_base_rekey(&owner, &community, &other.public_key(), 1, &[0x11u8; 32]);
5268        assert_eq!(apply_server_root_rekey(&community, &parsed).unwrap(), RekeyOutcome::NotARecipient);
5269        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
5270        assert_eq!(reloaded.server_root_epoch, crate::community::Epoch(0), "removed-from-base member's head unchanged");
5271    }
5272
5273    #[test]
5274    fn apply_server_root_rekey_rejects_rotator_without_ban() {
5275        let (_tmp, _guard) = init_test_db();
5276        let owner = Keys::generate();
5277        let me = Keys::generate();
5278        become_local(&me);
5279        let community = saved_community_owned_by(&owner);
5280        // A rotator who is neither owner nor BAN-ranked cannot rotate the base.
5281        let rogue = Keys::generate();
5282        let parsed = owner_base_rekey(&rogue, &community, &me.public_key(), 1, &[0x22u8; 32]);
5283        assert!(apply_server_root_rekey(&community, &parsed).is_err(), "unauthorized base rotation rejected");
5284    }
5285
5286    #[test]
5287    fn apply_server_root_rekey_reorgs_onto_authorized_chain_despite_prior_mismatch() {
5288        // BASE FORK-CONVERGENCE (mirrors the channel reorg): I hold the genesis root, but an AUTHORIZED
5289        // (owner, BAN) epoch-1 base rekey continues from a DIFFERENT epoch-0 root (I lost a concurrent
5290        // re-founding). It must be ADOPTED — converge forward onto the authorized chain — not rejected and
5291        // left to stall every later base rotation. Authority + ECDH recipiency are the gates, not continuity.
5292        let (_tmp, _guard) = init_test_db();
5293        let owner = Keys::generate();
5294        let me = Keys::generate();
5295        become_local(&me);
5296        let community = saved_community_owned_by(&owner);
5297        let blob = super::super::rekey::build_rekey_blob(
5298            owner.secret_key(), &me.public_key(), super::super::derive::RekeyScope::ServerRoot, crate::community::Epoch(1), &[0x33u8; 32],
5299        )
5300        .unwrap();
5301        // Commit over a WRONG prior root (not the genesis I hold) → continuity mismatch (the losing fork).
5302        let bad = super::super::rekey::epoch_key_commitment(crate::community::Epoch(0), &[0xFFu8; 32]);
5303        let outer = super::super::rekey::build_server_root_rekey_event(
5304            &Keys::generate(), &owner, community.server_root_key.as_bytes(), &community.id,
5305            crate::community::Epoch(1), crate::community::Epoch(0), &bad, &[blob],
5306        )
5307        .unwrap();
5308        let parsed = super::super::rekey::open_rekey_event(&outer, community.server_root_key.as_bytes()).unwrap();
5309        let outcome = apply_server_root_rekey(&community, &parsed);
5310        assert!(
5311            matches!(outcome, Ok(RekeyOutcome::Applied { .. })),
5312            "an authorized base chain must be adopted (reorg), not rejected as foreign; got {outcome:?}"
5313        );
5314    }
5315
5316    #[test]
5317    fn apply_server_root_rekey_catchup_archives_without_regressing_base_head() {
5318        // Parity with the channel no-regress test: applying an OLDER base epoch archives its root but
5319        // must not regress the base head (the forward-walk can deliver out of order).
5320        let (_tmp, _guard) = init_test_db();
5321        let owner = Keys::generate();
5322        let me = Keys::generate();
5323        become_local(&me);
5324        let community = saved_community_owned_by(&owner);
5325        let cid = community.id.to_hex();
5326
5327        let r5 = [0x55u8; 32];
5328        let p5 = owner_base_rekey(&owner, &community, &me.public_key(), 5, &r5);
5329        assert_eq!(apply_server_root_rekey(&community, &p5).unwrap(), RekeyOutcome::Applied { head_advanced: true });
5330        let r3 = [0x33u8; 32];
5331        let p3 = owner_base_rekey(&owner, &community, &me.public_key(), 3, &r3);
5332        assert_eq!(apply_server_root_rekey(&community, &p3).unwrap(), RekeyOutcome::Applied { head_advanced: false });
5333
5334        assert_eq!(crate::db::community::held_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 3).unwrap(), Some(r3));
5335        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
5336        assert_eq!(reloaded.server_root_epoch, crate::community::Epoch(5), "base head stayed at newest");
5337        assert_eq!(reloaded.server_root_key.as_bytes(), &r5);
5338    }
5339
5340    #[test]
5341    fn apply_server_root_rekey_authorizes_a_granted_ban_admin() {
5342        // role-based: a non-owner who holds a role carrying BAN may rotate the base. Re-founding re-wraps
5343        // each head verbatim (never re-authors), so an admin re-founder can't demote peers or steal ownership
5344        // — which is exactly why this stays BAN-gated rather than owner-only.
5345        let (_tmp, _guard) = init_test_db();
5346        let owner = Keys::generate();
5347        let me = Keys::generate();
5348        become_local(&me);
5349        let community = saved_community_owned_by(&owner);
5350        let cid = community.id.to_hex();
5351
5352        let admin = Keys::generate();
5353        let role_id = "d".repeat(64);
5354        let roster = crate::community::roles::CommunityRoles {
5355            roles: vec![crate::community::roles::Role::admin(role_id.clone())],
5356            grants: vec![crate::community::roles::MemberGrant { member: admin.public_key().to_hex(), role_ids: vec![role_id] }],
5357        };
5358        crate::db::community::set_community_roles(&cid, &roster, 1).unwrap();
5359
5360        let parsed = owner_base_rekey(&admin, &community, &me.public_key(), 1, &[0x77u8; 32]);
5361        assert_eq!(
5362            apply_server_root_rekey(&community, &parsed).unwrap(),
5363            RekeyOutcome::Applied { head_advanced: true },
5364            "a BAN-granted admin (not the owner) can rotate the base"
5365        );
5366    }
5367
5368    #[test]
5369    fn apply_server_root_rekey_accepts_when_prior_root_not_held() {
5370        // Catch-up from further back: a base rekey citing a prior epoch whose root I don't hold skips
5371        // the continuity check (ECDH blob + authority still authenticate) and applies.
5372        let (_tmp, _guard) = init_test_db();
5373        let owner = Keys::generate();
5374        let me = Keys::generate();
5375        become_local(&me);
5376        let community = saved_community_owned_by(&owner);
5377
5378        let new_root = [0x99u8; 32];
5379        let blob = super::super::rekey::build_rekey_blob(
5380            owner.secret_key(), &me.public_key(), super::super::derive::RekeyScope::ServerRoot, crate::community::Epoch(5), &new_root,
5381        )
5382        .unwrap();
5383        // Cites epoch 4 (whose root I never held); commitment is over a root I don't have.
5384        let commit = super::super::rekey::epoch_key_commitment(crate::community::Epoch(4), &[0xEEu8; 32]);
5385        let outer = super::super::rekey::build_server_root_rekey_event(
5386            &Keys::generate(), &owner, community.server_root_key.as_bytes(), &community.id,
5387            crate::community::Epoch(5), crate::community::Epoch(4), &commit, &[blob],
5388        )
5389        .unwrap();
5390        let parsed = super::super::rekey::open_rekey_event(&outer, community.server_root_key.as_bytes()).unwrap();
5391        assert_eq!(apply_server_root_rekey(&community, &parsed).unwrap(), RekeyOutcome::Applied { head_advanced: true });
5392        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
5393        assert_eq!(reloaded.server_root_epoch, crate::community::Epoch(5));
5394    }
5395
5396    #[test]
5397    fn apply_server_root_rekey_rejects_channel_scope() {
5398        // A channel-scoped rekey must NOT be applied as a base rotation (fail closed).
5399        let (_tmp, _guard) = init_test_db();
5400        let owner = Keys::generate();
5401        let me = Keys::generate();
5402        become_local(&me);
5403        let community = saved_community_owned_by(&owner);
5404        let channel_parsed = owner_channel_rekey(&owner, &community, &me.public_key(), 1, &[0x44u8; 32]);
5405        assert!(apply_server_root_rekey(&community, &channel_parsed).is_err(), "channel scope rejected by base apply");
5406    }
5407
5408    #[test]
5409    fn apply_channel_rekey_not_a_recipient() {
5410        let (_tmp, _guard) = init_test_db();
5411        let owner = Keys::generate();
5412        let me = Keys::generate();
5413        become_local(&me);
5414        let community = saved_community_owned_by(&owner);
5415        // The blob is wrapped to SOMEONE ELSE, so my locator finds nothing.
5416        let other = Keys::generate();
5417        let parsed = owner_channel_rekey(&owner, &community, &other.public_key(), 1, &[0x11u8; 32]);
5418        assert_eq!(apply_channel_rekey(&community, &parsed).unwrap(), RekeyOutcome::NotARecipient);
5419        // Nothing committed: head stays at epoch 0.
5420        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
5421        assert_eq!(reloaded.channels[0].epoch, crate::community::Epoch(0));
5422    }
5423
5424    #[test]
5425    fn apply_channel_rekey_rejects_unauthorized_rotator() {
5426        let (_tmp, _guard) = init_test_db();
5427        let owner = Keys::generate();
5428        let me = Keys::generate();
5429        become_local(&me);
5430        let community = saved_community_owned_by(&owner);
5431        // A rotator who is NEITHER the owner NOR holds MANAGE_CHANNELS in the (empty) roster.
5432        let rogue = Keys::generate();
5433        let parsed = owner_channel_rekey(&rogue, &community, &me.public_key(), 1, &[0x22u8; 32]);
5434        assert!(apply_channel_rekey(&community, &parsed).is_err(), "unauthorized rotation must be rejected");
5435    }
5436
5437    #[test]
5438    fn apply_channel_rekey_reorgs_onto_authorized_chain_despite_prior_mismatch() {
5439        // FORK-CONVERGENCE ("reorg"): I hold genesis epoch-0, but an AUTHORIZED (owner) epoch-1 rekey
5440        // cites a DIFFERENT epoch-0 key (a chain I'm not on) and delivers epoch-1 to ME. Authority (checked
5441        // first) + recipient (the blob opens) are the real gates, so I REORG forward onto the authorized
5442        // chain instead of rejecting + stranding myself. (The commitment is continuity, not security — it
5443        // yields to convergence. An UNAUTHORIZED rotator with the same mismatch is still rejected by the
5444        // authority gate; see apply_channel_rekey_rejects_unauthorized_rotation.)
5445        let (_tmp, _guard) = init_test_db();
5446        let owner = Keys::generate();
5447        let me = Keys::generate();
5448        become_local(&me);
5449        let community = saved_community_owned_by(&owner);
5450        let chan = &community.channels[0];
5451        let scope = super::super::derive::RekeyScope::Channel(chan.id);
5452        let new_key = [0x33u8; 32];
5453        let blob = super::super::rekey::build_rekey_blob(owner.secret_key(), &me.public_key(), scope, crate::community::Epoch(1), &new_key).unwrap();
5454        // Commit over a DIFFERENT prior key than the genesis I hold → a divergent prior epoch (a fork).
5455        let other_commit = super::super::rekey::epoch_key_commitment(crate::community::Epoch(0), &[0xFFu8; 32]);
5456        let outer = super::super::rekey::build_channel_rekey_event(
5457            &Keys::generate(), &owner, community.server_root_key.as_bytes(), &chan.id,
5458            crate::community::Epoch(1), crate::community::Epoch(0), &other_commit, &[blob],
5459        )
5460        .unwrap();
5461        let parsed = super::super::rekey::open_rekey_event(&outer, community.server_root_key.as_bytes()).unwrap();
5462        let outcome = apply_channel_rekey(&community, &parsed).unwrap();
5463        assert!(matches!(outcome, RekeyOutcome::Applied { .. }),
5464            "an authorized chain must be adopted (reorg), not rejected as foreign; got {outcome:?}");
5465        assert_eq!(crate::db::community::held_epoch_key(&community.id.to_hex(), &chan.id.to_hex(), 1).unwrap(), Some(new_key));
5466    }
5467
5468    #[test]
5469    fn apply_channel_rekey_catchup_archives_without_regressing_head() {
5470        let (_tmp, _guard) = init_test_db();
5471        let owner = Keys::generate();
5472        let me = Keys::generate();
5473        become_local(&me);
5474        let community = saved_community_owned_by(&owner);
5475        let cid = community.id.to_hex();
5476        let chan_hex = community.channels[0].id.to_hex();
5477
5478        // Apply epoch 5 first → head advances to 5.
5479        let k5 = [0x55u8; 32];
5480        let p5 = owner_channel_rekey(&owner, &community, &me.public_key(), 5, &k5);
5481        assert_eq!(apply_channel_rekey(&community, &p5).unwrap(), RekeyOutcome::Applied { head_advanced: true });
5482        // Now apply an OLDER epoch 3 (catch-up) → archived, but head must NOT regress.
5483        let k3 = [0x33u8; 32];
5484        let p3 = owner_channel_rekey(&owner, &community, &me.public_key(), 3, &k3);
5485        assert_eq!(apply_channel_rekey(&community, &p3).unwrap(), RekeyOutcome::Applied { head_advanced: false });
5486
5487        assert_eq!(crate::db::community::held_epoch_key(&cid, &chan_hex, 3).unwrap(), Some(k3), "old epoch archived");
5488        assert_eq!(crate::db::community::held_epoch_key(&cid, &chan_hex, 5).unwrap(), Some(k5));
5489        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
5490        assert_eq!(reloaded.channels[0].epoch, crate::community::Epoch(5), "head stayed at the newest epoch");
5491        assert_eq!(reloaded.channels[0].key.as_bytes(), &k5);
5492    }
5493
5494    #[tokio::test]
5495    async fn create_community_persists_and_publishes_metadata() {
5496        use crate::community::transport::Query;
5497        use crate::stored_event::event_kind;
5498
5499        let (_tmp, _guard) = init_test_db();
5500        let relay = MemoryRelay::new();
5501        let community = create_community(&relay, "Vector HQ", "general", vec!["r1".into()])
5502            .await
5503            .expect("create");
5504
5505        // Returned shape.
5506        assert_eq!(community.name, "Vector HQ");
5507        assert_eq!(community.channels.len(), 1);
5508        assert_eq!(community.channels[0].name, "general");
5509
5510        // Persisted locally (reloadable with matching keys).
5511        let loaded = crate::db::community::load_community(&community.id).unwrap().expect("persisted");
5512        assert_eq!(loaded.channels[0].name, "general");
5513        assert_eq!(loaded.server_root_key.as_bytes(), community.server_root_key.as_bytes());
5514
5515        // GroupRoot + ChannelMetadata are 3308 editions on the control plane, keyless
5516        // (the actor's inner real-npub signature is the authority proof).
5517        let meta_events = relay
5518            .fetch(
5519                &Query { kinds: vec![event_kind::APPLICATION_SPECIFIC], ..Default::default() },
5520                &community.relays,
5521            )
5522            .await
5523            .unwrap();
5524        assert!(meta_events.is_empty(), "no legacy 30078 metadata events");
5525
5526        // The control plane carries THREE genesis editions, all real-npub signed by the OWNER: the
5527        // GroupRoot (vsk=0), the #general ChannelMetadata (vsk=2), and the auto Admin role (vsk=1).
5528        let z = crate::community::roster::control_pseudonym(&community.server_root_key, &community.id, crate::community::Epoch(0));
5529        let control = relay
5530            .fetch(
5531                &Query { kinds: vec![event_kind::COMMUNITY_CONTROL], z_tags: vec![z], ..Default::default() },
5532                &community.relays,
5533            )
5534            .await
5535            .unwrap();
5536        assert_eq!(control.len(), 3, "GroupRoot + ChannelMetadata + Admin role editions");
5537        let owner_pk = crate::state::my_public_key().unwrap();
5538        let parsed: Vec<_> = control
5539            .iter()
5540            .filter_map(|o| crate::community::roster::open_control_edition(o, &community.server_root_key).ok())
5541            .filter_map(|i| crate::community::edition::parse_edition_inner(&i).ok())
5542            .collect();
5543        assert!(parsed.iter().all(|p| p.author == owner_pk), "every genesis edition authored by the owner");
5544        // The GroupRoot edition (vsk=0) carries the community name + owner attestation.
5545        let root = parsed.iter().find(|p| p.entity_id == community.id.0).expect("GroupRoot edition");
5546        let root_meta: crate::community::metadata::CommunityMetadata = serde_json::from_str(&root.content).unwrap();
5547        assert_eq!(root_meta.name, "Vector HQ");
5548        assert!(root_meta.owner_attestation.is_some());
5549        // The Admin role edition (vsk=1) is the genesis of the Admin chain.
5550        let role: crate::community::roles::Role = parsed
5551            .iter()
5552            .find_map(|p| serde_json::from_str::<crate::community::roles::Role>(&p.content).ok().filter(|r| r.name == "Admin"))
5553            .expect("Admin role edition");
5554        assert_eq!(role.position, 1);
5555        assert!(role.permissions.contains(crate::community::roles::Permissions::ADMIN_ALL));
5556
5557        // Cached locally too (the owner's client immediately knows the Admin role exists).
5558        let cached = crate::db::community::get_community_roles(&community.id.to_hex()).unwrap();
5559        assert_eq!(cached.roles.len(), 1);
5560        assert!(cached.grants.is_empty(), "owner is implicit position 0, takes no grant");
5561    }
5562
5563    #[tokio::test]
5564    async fn role_grant_round_trips_through_relays_and_revokes() {
5565        use crate::community::roles::Permissions;
5566        let (_tmp, _guard) = init_test_db();
5567        let relay = MemoryRelay::new();
5568        let community = create_community(&relay, "HQ", "general", vec!["r1".into()])
5569            .await
5570            .expect("create");
5571        let cid = community.id.to_hex();
5572        let alice = "aa".repeat(32);
5573        let admin_role_id = crate::db::community::get_community_roles(&cid).unwrap().roles[0]
5574            .role_id
5575            .clone();
5576
5577        // Owner grants Alice the Admin role.
5578        set_member_grant(&relay, &community, &alice, vec![admin_role_id.clone()])
5579            .await
5580            .unwrap();
5581        assert!(
5582            crate::db::community::get_community_roles(&cid).unwrap().is_privileged(&alice),
5583            "local cache reflects the grant immediately"
5584        );
5585
5586        // A fresh fetch+apply reconstructs the whole graph from the relays: Alice is a BAN-capable
5587        // Admin, and the role definition came back too.
5588        let roster = fetch_and_apply_roles(&relay, &community).await.unwrap();
5589        assert!(roster.has_permission(&alice, Permissions::BAN));
5590        assert!(roster.has_permission(&alice, Permissions::MANAGE_ROLES));
5591        assert_eq!(roster.roles.len(), 1);
5592        assert_eq!(roster.highest_position(&alice), Some(1));
5593
5594        // Revoke (empty grant) → Alice loses the role and the empty grant is pruned from the cache.
5595        set_member_grant(&relay, &community, &alice, vec![]).await.unwrap();
5596        let after = crate::db::community::get_community_roles(&cid).unwrap();
5597        assert!(!after.is_privileged(&alice), "revoked member holds no role");
5598        assert!(after.grants.is_empty(), "empty grant pruned");
5599    }
5600
5601    #[tokio::test]
5602    async fn admin_cannot_grant_a_peer_rank_role() {
5603        // escalation defense at the authoring gate: an Admin (position 1) may NOT grant the Admin
5604        // role (also position 1) — equal can't escalate equal. Only the owner (position 0, strictly
5605        // above) can. Closes the raw-command path even though the MVP UI gates the toggle on owner.
5606        let (_tmp, _guard) = init_test_db();
5607        let relay = MemoryRelay::new();
5608        let community = create_community(&relay, "HQ", "general", vec!["r1".into()])
5609            .await
5610            .expect("create");
5611        let cid = community.id.to_hex();
5612        let admin_role_id =
5613            crate::db::community::get_community_roles(&cid).unwrap().roles[0].role_id.clone();
5614        let alice = Keys::generate();
5615        // Owner seeds Alice as an Admin (set_member_grant is the low-level write, not the gated action).
5616        set_member_grant(&relay, &community, &alice.public_key().to_hex(), vec![admin_role_id.clone()])
5617            .await
5618            .unwrap();
5619
5620        // Now ACT as Alice and try to grant the Admin role to Bob — refused.
5621        crate::state::set_my_public_key(alice.public_key());
5622        let bob = Keys::generate().public_key();
5623        let err = grant_role(&relay, &community, bob, &admin_role_id).await.unwrap_err();
5624        assert!(err.contains("below your own"), "peer-rank grant refused, got: {err}");
5625    }
5626
5627    #[tokio::test]
5628    async fn create_community_mints_a_verifiable_owner_attestation() {
5629        // The owner attestation is mandatory at creation (no root → no community) and must prove the
5630        // creator as owner, bound to this community.
5631        let (_tmp, _guard) = init_test_db();
5632        let me = crate::state::my_public_key().unwrap();
5633        let relay = MemoryRelay::new();
5634        let community = create_community(&relay, "HQ", "general", vec!["r1".into()])
5635            .await
5636            .expect("create");
5637        let att = community.owner_attestation.as_ref().expect("attestation is mandatory");
5638        let proven = super::super::owner::verify_owner_attestation(att, &community.id.to_hex());
5639        assert_eq!(proven, Some(me), "the creator is the proven owner");
5640        // It can't be transplanted to a different community id.
5641        assert_eq!(
5642            super::super::owner::verify_owner_attestation(att, &"f".repeat(64)),
5643            None,
5644        );
5645    }
5646
5647    #[tokio::test]
5648    async fn admin_cannot_ban_a_peer_admin() {
5649        // hierarchy at the banlist gate: an Admin (pos 1, holds BAN) cannot ban a *peer* Admin
5650        // (also pos 1) — equal can't act on equal; only someone strictly above (the owner) can. Closes
5651        // the B1 sibling hole (the outrank gate had been wired on grant/revoke but not on the banlist).
5652        let (_tmp, _guard) = init_test_db();
5653        let relay = MemoryRelay::new();
5654        let community = create_community(&relay, "HQ", "general", vec!["r1".into()])
5655            .await
5656            .expect("create");
5657        let cid = community.id.to_hex();
5658        let admin_role_id =
5659            crate::db::community::get_community_roles(&cid).unwrap().roles[0].role_id.clone();
5660        let alice = Keys::generate();
5661        let bob = Keys::generate();
5662        // Owner seeds both as Admins (set_member_grant is the low-level write, not the gated action).
5663        set_member_grant(&relay, &community, &alice.public_key().to_hex(), vec![admin_role_id.clone()])
5664            .await
5665            .unwrap();
5666        set_member_grant(&relay, &community, &bob.public_key().to_hex(), vec![admin_role_id.clone()])
5667            .await
5668            .unwrap();
5669
5670        // Act as Alice (the edition is signed by the vault identity → become her, not just set the
5671        // pubkey): she may NOT ban peer-admin Bob (rejected at the gate, before any signing).
5672        become_local(&alice);
5673        let err = publish_banlist(&relay, &community, &[bob.public_key().to_hex()])
5674            .await
5675            .unwrap_err();
5676        assert!(err.contains("outranks you"), "peer-admin ban refused, got: {err}");
5677    }
5678
5679    #[tokio::test]
5680    async fn roster_reconstructs_purely_from_relay() {
5681        // Prove the fetch path reconstructs from the relay editions, NOT the optimistic local cache:
5682        // publish the role + a grant, WIPE the local roster cache, then fetch — a populated result
5683        // can then only have come from the relay.
5684        let (_tmp, _guard) = init_test_db();
5685        let relay = MemoryRelay::new();
5686        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
5687        let cid = community.id.to_hex();
5688        let admin_role_id =
5689            crate::db::community::get_community_roles(&cid).unwrap().roles[0].role_id.clone();
5690        let alice = "aa".repeat(32);
5691        set_member_grant(&relay, &community, &alice, vec![admin_role_id.clone()]).await.unwrap();
5692
5693        // Wipe the local cache so a populated result can ONLY come from the relay.
5694        crate::db::community::set_community_roles(&cid, &crate::community::roles::CommunityRoles::default(), 0).unwrap();
5695        assert!(crate::db::community::get_community_roles(&cid).unwrap().roles.is_empty(), "cache wiped");
5696
5697        let roster = fetch_and_apply_roles(&relay, &community).await.unwrap();
5698        assert!(roster.is_admin(&alice), "roster reconstructed from relay editions, not the cache");
5699        assert_eq!(roster.roles.len(), 1, "the Admin role edition folded back");
5700    }
5701
5702    #[tokio::test]
5703    async fn admin_cannot_unban_a_peer_admin() {
5704        // hierarchy on the REMOVAL side: an Admin can't unban (drop from the banlist) a peer Admin
5705        // the owner banned — gating only additions would let a low admin undo a superior's ban.
5706        let (_tmp, _guard) = init_test_db();
5707        let relay = MemoryRelay::new();
5708        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
5709        let cid = community.id.to_hex();
5710        let admin_role_id =
5711            crate::db::community::get_community_roles(&cid).unwrap().roles[0].role_id.clone();
5712        let alice = Keys::generate();
5713        let bob = Keys::generate();
5714        set_member_grant(&relay, &community, &alice.public_key().to_hex(), vec![admin_role_id.clone()])
5715            .await
5716            .unwrap();
5717        set_member_grant(&relay, &community, &bob.public_key().to_hex(), vec![admin_role_id.clone()])
5718            .await
5719            .unwrap();
5720        // Owner banned peer-admin Bob (seed the banlist directly).
5721        crate::db::community::set_community_banlist(&cid, &[bob.public_key().to_hex()], 1000).unwrap();
5722
5723        // Alice (admin) tries to clear the banlist → unbanning peer-admin Bob is refused.
5724        become_local(&alice);
5725        let err = publish_banlist(&relay, &community, &[]).await.unwrap_err();
5726        assert!(err.contains("unban"), "unbanning a peer admin refused, got: {err}");
5727    }
5728
5729    #[tokio::test]
5730    async fn create_community_rejects_signer_identity_mismatch() {
5731        // The vault must hold the ACTIVE identity's key to sign the attestation locally. If the active
5732        // pubkey differs from the vault key (a stale/half-swapped session) and there's no bunker
5733        // client, creation fails rather than minting an attestation owned by the wrong identity.
5734        let (_tmp, _guard) = init_test_db(); // seeds matching vault key + my_public_key
5735        let other = Keys::generate();
5736        crate::state::set_my_public_key(other.public_key()); // force a mismatch
5737        let relay = MemoryRelay::new();
5738        let err = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap_err();
5739        assert!(err.contains("identity signer"), "signer mismatch refused, got: {err}");
5740    }
5741
5742    #[tokio::test]
5743    async fn banlist_newer_edition_applies_older_is_refused() {
5744        let (_tmp, _guard) = init_test_db();
5745        let relay = MemoryRelay::new();
5746        let community = create_community(&relay, "HQ", "general", vec!["r1".into()])
5747            .await
5748            .expect("create");
5749        let id_hex = community.id.to_hex();
5750        let banlist_entity = crate::simd::hex::bytes_to_hex_32(&crate::community::derive::banlist_locator(&community.id));
5751        let mallory = "aa".repeat(32);
5752        let bob = "bb".repeat(32);
5753
5754        // An owner-signed v1 banlist edition (banning Mallory) is injected on the relay WITHOUT touching
5755        // local state, so the local head stays at 0 and the first fetch must fold it from the relay.
5756        let owner = crate::state::MY_SECRET_KEY.to_keys().unwrap();
5757        let inner = crate::community::roster::build_banlist_edition(&owner, &community.id, &[mallory.clone()], 1, None, 1000, None).unwrap();
5758        let outer = crate::community::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, crate::community::Epoch(0)).unwrap();
5759        relay.inject(&outer, &community.relays);
5760
5761        // Fetch folds the v1 edition, verifies the owner held BAN, applies it + advances the head.
5762        let applied = fetch_and_apply_banlist(&relay, &community).await.unwrap();
5763        assert_eq!(applied, vec![mallory.clone()]);
5764        let (head_v, _) = crate::db::community::get_edition_head(&id_hex, &banlist_entity).unwrap().unwrap();
5765        assert_eq!(head_v, 1, "banlist edition head advanced to v1");
5766
5767        // We now hold a NEWER local edition (v2, banning Mallory + Bob); the relay still carries only
5768        // v1 — a re-fetch must NOT roll us back to it (refuse-downgrade by edition version).
5769        crate::db::community::set_community_banlist(&id_hex, &[mallory.clone(), bob.clone()], 2).unwrap();
5770        crate::db::community::set_edition_head(&id_hex, &banlist_entity, 2, &[0x22u8; 32]).unwrap();
5771        let after = fetch_and_apply_banlist(&relay, &community).await.unwrap();
5772        assert_eq!(after, vec![mallory, bob], "older relay edition refused, local banlist preserved");
5773    }
5774
5775    #[tokio::test]
5776    async fn unauthorized_banlist_edition_is_rejected() {
5777        // The keyless BAN-authority gate: a validly-signed banlist edition from a signer who holds no
5778        // BAN role (not the owner, never granted) is DROPPED on fetch — the inner signature proves
5779        // authorship, not authority. Authority is re-verified against the authorized roster.
5780        let (_tmp, _guard) = init_test_db();
5781        let relay = MemoryRelay::new();
5782        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
5783        let bob = "bb".repeat(32);
5784
5785        // A random identity (no role) signs + injects a v1 banlist edition banning Bob.
5786        let mallory = Keys::generate();
5787        let inner = crate::community::roster::build_banlist_edition(&mallory, &community.id, &[bob], 1, None, 1000, None).unwrap();
5788        let outer = crate::community::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, crate::community::Epoch(0)).unwrap();
5789        relay.inject(&outer, &community.relays);
5790
5791        // Fetch must reject it (signer not authorized) — the banlist stays empty.
5792        let applied = fetch_and_apply_banlist(&relay, &community).await.unwrap();
5793        assert!(applied.is_empty(), "an unauthorized signer's banlist edition is rejected");
5794    }
5795
5796    #[tokio::test]
5797    async fn banlist_receiver_enforces_per_target_outrank() {
5798        // The receive-side gate, not just the BAN bit: an Admin (holds BAN) who bans a PEER Admin
5799        // is rejected on fetch — equal can't act on equal. A bit-only check would fail open here.
5800        let (_tmp, _guard) = init_test_db();
5801        let relay = MemoryRelay::new();
5802        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
5803        let cid = community.id.to_hex();
5804        let admin_role_id = crate::db::community::get_community_roles(&cid).unwrap().roles[0].role_id.clone();
5805        let alice = Keys::generate();
5806        let bob = Keys::generate();
5807        // Owner grants both Admin (so both sit at position 1, peers).
5808        set_member_grant(&relay, &community, &alice.public_key().to_hex(), vec![admin_role_id.clone()]).await.unwrap();
5809        set_member_grant(&relay, &community, &bob.public_key().to_hex(), vec![admin_role_id]).await.unwrap();
5810
5811        // Alice (Admin) authors a banlist banning peer-admin Bob, citing her own (owner-granted) Admin
5812        // grant, injected on the relay.
5813        let cite = authority_citation(&community, &alice.public_key().to_hex());
5814        let inner = crate::community::roster::build_banlist_edition(&alice, &community.id, &[bob.public_key().to_hex()], 1, None, 1000, cite.as_ref()).unwrap();
5815        let outer = crate::community::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, crate::community::Epoch(0)).unwrap();
5816        relay.inject(&outer, &community.relays);
5817
5818        // Fetch must reject it — Alice doesn't strictly outrank her peer Bob.
5819        let applied = fetch_and_apply_banlist(&relay, &community).await.unwrap();
5820        assert!(applied.is_empty(), "an admin can't ban a peer admin (receiver-side outrank)");
5821    }
5822
5823    #[tokio::test]
5824    async fn banlist_admin_bans_regular_member_applies() {
5825        // The positive companion to the peer-rejection: an Admin (holds BAN) banning a REGULAR member
5826        // (no role, sits below) IS authorized on the receiver — Alice strictly outranks them.
5827        let (_tmp, _guard) = init_test_db();
5828        let relay = MemoryRelay::new();
5829        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
5830        let cid = community.id.to_hex();
5831        let admin_role_id = crate::db::community::get_community_roles(&cid).unwrap().roles[0].role_id.clone();
5832        let alice = Keys::generate();
5833        set_member_grant(&relay, &community, &alice.public_key().to_hex(), vec![admin_role_id]).await.unwrap();
5834
5835        let carol = "cc".repeat(32);
5836        // Alice cites her owner-granted Admin grant — the pinned authority a non-owner must carry.
5837        let cite = authority_citation(&community, &alice.public_key().to_hex());
5838        let inner = crate::community::roster::build_banlist_edition(&alice, &community.id, &[carol.clone()], 1, None, 1000, cite.as_ref()).unwrap();
5839        let outer = crate::community::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, crate::community::Epoch(0)).unwrap();
5840        relay.inject(&outer, &community.relays);
5841
5842        let applied = fetch_and_apply_banlist(&relay, &community).await.unwrap();
5843        assert_eq!(applied, vec![carol], "an admin's ban of a regular member applies");
5844    }
5845
5846    #[tokio::test]
5847    async fn owner_banlist_needs_no_citation() {
5848        // The owner is supreme and cites nothing — an owner-signed banlist edition with NO citation
5849        // applies. This is the `owner_hex == actor` bypass in `authority_citation_satisfied`.
5850        let (_tmp, _guard) = init_test_db();
5851        let relay = MemoryRelay::new();
5852        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
5853        let victim = "cc".repeat(32);
5854
5855        // Owner hand-signs an uncited v1 banlist, injected on the relay (local head stays 0 → folds fresh).
5856        let owner = crate::state::MY_SECRET_KEY.to_keys().unwrap();
5857        let inner = crate::community::roster::build_banlist_edition(&owner, &community.id, &[victim.clone()], 1, None, 1000, None).unwrap();
5858        let outer = crate::community::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, crate::community::Epoch(0)).unwrap();
5859        relay.inject(&outer, &community.relays);
5860
5861        let applied = fetch_and_apply_banlist(&relay, &community).await.unwrap();
5862        assert_eq!(applied, vec![victim], "an owner's uncited ban applies");
5863    }
5864
5865    #[tokio::test]
5866    async fn banlist_with_forged_citation_hash_is_rejected() {
5867        // fork guard: an authorized admin who cites her real grant entity + version but the WRONG
5868        // hash (a non-canonical fork at the tip) is rejected — the cited proof must be the one we folded.
5869        let (_tmp, _guard) = init_test_db();
5870        let relay = MemoryRelay::new();
5871        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
5872        let cid = community.id.to_hex();
5873        let admin_role_id = crate::db::community::get_community_roles(&cid).unwrap().roles[0].role_id.clone();
5874        let alice = Keys::generate();
5875        set_member_grant(&relay, &community, &alice.public_key().to_hex(), vec![admin_role_id]).await.unwrap();
5876
5877        let carol = "cc".repeat(32);
5878        // Real entity + version, but a fabricated hash → the cited edition isn't the one that won the fold.
5879        let mut cite = authority_citation(&community, &alice.public_key().to_hex()).unwrap();
5880        cite.edition_hash = [0xEE; 32];
5881        let inner = crate::community::roster::build_banlist_edition(&alice, &community.id, &[carol], 1, None, 1000, Some(&cite)).unwrap();
5882        let outer = crate::community::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, crate::community::Epoch(0)).unwrap();
5883        relay.inject(&outer, &community.relays);
5884
5885        let applied = fetch_and_apply_banlist(&relay, &community).await.unwrap();
5886        assert!(applied.is_empty(), "a forged-hash citation is rejected");
5887    }
5888
5889    #[tokio::test]
5890    async fn banlist_citing_unsynced_future_version_is_rejected() {
5891        // The completeness gate (fail closed): a genuinely-authorized admin who cites a FUTURE version of
5892        // her grant that nobody has (≥ what we folded) is rejected — we can't confirm authority at a
5893        // version we haven't synced. Isolates the sync-floor from the permission check (she IS an admin).
5894        let (_tmp, _guard) = init_test_db();
5895        let relay = MemoryRelay::new();
5896        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
5897        let cid = community.id.to_hex();
5898        let admin_role_id = crate::db::community::get_community_roles(&cid).unwrap().roles[0].role_id.clone();
5899        let alice = Keys::generate();
5900        set_member_grant(&relay, &community, &alice.public_key().to_hex(), vec![admin_role_id]).await.unwrap();
5901
5902        let carol = "cc".repeat(32);
5903        let mut cite = authority_citation(&community, &alice.public_key().to_hex()).unwrap();
5904        cite.version += 5; // cite a grant version that doesn't exist on any relay
5905        let inner = crate::community::roster::build_banlist_edition(&alice, &community.id, &[carol], 1, None, 1000, Some(&cite)).unwrap();
5906        let outer = crate::community::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, crate::community::Epoch(0)).unwrap();
5907        relay.inject(&outer, &community.relays);
5908
5909        let applied = fetch_and_apply_banlist(&relay, &community).await.unwrap();
5910        assert!(applied.is_empty(), "citing an unsynced future grant version fails closed");
5911    }
5912
5913    #[tokio::test]
5914    async fn demoted_banner_superseded_ban_is_rejected() {
5915        // Refuse-superseded: an admin bans (citing her v1 grant), then the owner revokes her admin role.
5916        // Her citation is still SATISFIED (we hold a later v2 head of her grant), but the current
5917        // authorized roster no longer ranks her → the per-target outrank fails → the stale ban is dropped.
5918        let (_tmp, _guard) = init_test_db();
5919        let relay = MemoryRelay::new();
5920        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
5921        let cid = community.id.to_hex();
5922        let admin_role_id = crate::db::community::get_community_roles(&cid).unwrap().roles[0].role_id.clone();
5923        let alice = Keys::generate();
5924        set_member_grant(&relay, &community, &alice.public_key().to_hex(), vec![admin_role_id]).await.unwrap();
5925
5926        let carol = "cc".repeat(32);
5927        // Alice bans Carol while she IS an admin, citing her v1 grant.
5928        let cite = authority_citation(&community, &alice.public_key().to_hex());
5929        let inner = crate::community::roster::build_banlist_edition(&alice, &community.id, &[carol], 1, None, 1000, cite.as_ref()).unwrap();
5930        let outer = crate::community::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, crate::community::Epoch(0)).unwrap();
5931        relay.inject(&outer, &community.relays);
5932
5933        // Owner revokes Alice's admin (publishes her v2 empty grant).
5934        set_member_grant(&relay, &community, &alice.public_key().to_hex(), vec![]).await.unwrap();
5935
5936        let applied = fetch_and_apply_banlist(&relay, &community).await.unwrap();
5937        assert!(applied.is_empty(), "a since-demoted banner's stale ban is rejected (refuse-superseded)");
5938    }
5939
5940    #[tokio::test]
5941    async fn withheld_revocation_cannot_resurrect_a_demoted_banners_grant() {
5942        // The refuse-downgrade FLOOR: we have already synced Alice's revocation (her grant head is
5943        // at v2 locally), but a hostile relay serves only her OLD v1 admin grant + her stale ban,
5944        // withholding v2. The fold seeds Alice's grant from the held v2 floor, so the below-floor v1 is
5945        // refused — her grant never re-materializes, and the stale ban is dropped. (Without the floor,
5946        // the fold would roll back to v1 and re-authorize her: the H1 fail-open this closes.)
5947        let (_tmp, _guard) = init_test_db();
5948        let relay = MemoryRelay::new();
5949        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
5950        let cid = community.id.to_hex();
5951        let admin_role_id = crate::db::community::get_community_roles(&cid).unwrap().roles[0].role_id.clone();
5952        let alice = Keys::generate();
5953        set_member_grant(&relay, &community, &alice.public_key().to_hex(), vec![admin_role_id]).await.unwrap();
5954
5955        // Alice (admin at v1) bans Carol, citing her v1 grant — only this + her v1 grant reach the relay.
5956        let carol = "cc".repeat(32);
5957        let cite = authority_citation(&community, &alice.public_key().to_hex());
5958        let inner = crate::community::roster::build_banlist_edition(&alice, &community.id, &[carol], 1, None, 1000, cite.as_ref()).unwrap();
5959        let outer = crate::community::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, crate::community::Epoch(0)).unwrap();
5960        relay.inject(&outer, &community.relays);
5961
5962        // We've SEEN the revocation (head floor for Alice's grant advanced to v2 locally) but the relay
5963        // withholds the v2 edition itself.
5964        let alice_bytes = alice.public_key().to_bytes();
5965        let grant_entity = crate::simd::hex::bytes_to_hex_32(&crate::community::derive::grant_locator(&community.id, &alice_bytes));
5966        crate::db::community::set_edition_head(&cid, &grant_entity, 2, &[0xAB; 32]).unwrap();
5967
5968        let applied = fetch_and_apply_banlist(&relay, &community).await.unwrap();
5969        assert!(applied.is_empty(), "a withheld revocation can't roll the banner's grant back to re-authorize them");
5970    }
5971
5972    #[tokio::test]
5973    async fn invite_registry_round_trips_and_drives_is_public() {
5974        // computed mode: a fresh community is Private (empty registry); a peer folds the owner's
5975        // registry edition purely from the relay and computes Public; clearing the registry (revoke the
5976        // last link) flips it back to Private — the privatize precondition.
5977        let (_tmp, _guard) = init_test_db();
5978        let relay = MemoryRelay::new();
5979        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
5980        assert!(!is_public(&community).unwrap(), "a fresh community is Private");
5981
5982        // Owner's per-creator link edition v1 injected on the relay (no local head yet → folds fresh,
5983        // like a peer). The owner holds CREATE_INVITE (ADMIN_ALL), so the fold authorizes + unions it.
5984        let owner = crate::state::MY_SECRET_KEY.to_keys().unwrap();
5985        let loc = "1a".repeat(32);
5986        let inner = crate::community::roster::build_invite_links_edition(&owner, &community.id, &[loc.clone()], 1, None, 1000, None).unwrap();
5987        let outer = crate::community::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, crate::community::Epoch(0)).unwrap();
5988        relay.inject(&outer, &community.relays);
5989
5990        let applied = fetch_and_apply_invite_links(&relay, &community).await.unwrap();
5991        assert_eq!(applied, vec![loc], "the owner's link edition folds + unions from the relay");
5992        assert!(is_public(&community).unwrap(), "mode recomputed Public from the folded aggregate");
5993
5994        // The owner retires their links (newer v2, empty) → aggregate empties → Private.
5995        publish_my_invite_links(&relay, &community, &[]).await.unwrap();
5996        let applied = fetch_and_apply_invite_links(&relay, &community).await.unwrap();
5997        assert!(applied.is_empty() && !is_public(&community).unwrap(), "an empty aggregate is Private");
5998    }
5999
6000    #[tokio::test]
6001    async fn metadata_edit_round_trips_to_a_lagging_member() {
6002        // metadata fold: a member holding only the genesis v1 folds the owner's GroupRoot v2 from the
6003        // relay and applies the display edit. (Edition built + injected directly so the local head stays
6004        // at v1 — `set_edition_head` is monotonic, so a republish would advance it and defeat the test.)
6005        let (_tmp, _guard) = init_test_db();
6006        let relay = MemoryRelay::new();
6007        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6008        let cid = community.id.to_hex();
6009        let owner = crate::state::MY_SECRET_KEY.to_keys().unwrap();
6010        let (genesis_v, genesis_hash) = crate::db::community::get_edition_head(&cid, &cid).unwrap().unwrap();
6011        assert_eq!(genesis_v, 1);
6012
6013        let mut edited = crate::community::metadata::CommunityMetadata::of(&community);
6014        edited.name = "Renamed HQ".into();
6015        edited.description = Some("now with a topic".into());
6016        let inner = crate::community::roster::build_community_root_edition(&owner, &community.id, &edited, 2, Some(&genesis_hash), 4000, None).unwrap();
6017        let outer = crate::community::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, crate::community::Epoch(0)).unwrap();
6018        relay.inject(&outer, &community.relays);
6019
6020        fetch_and_apply_metadata(&relay, &community).await.unwrap();
6021        let after = crate::db::community::load_community(&community.id).unwrap().unwrap();
6022        assert_eq!(after.name, "Renamed HQ", "the owner's GroupRoot edit folded from the relay");
6023        assert_eq!(after.description.as_deref(), Some("now with a topic"));
6024        assert_eq!(crate::db::community::get_edition_head(&cid, &cid).unwrap().unwrap().0, 2, "head advanced to v2");
6025    }
6026
6027    #[tokio::test]
6028    async fn unauthorized_metadata_edit_is_ignored() {
6029        // A signer WITHOUT manage-metadata authority can't move the community's display, even with a
6030        // perfectly-chained, validly-signed GroupRoot edition (the author gate, not just the chain).
6031        let (_tmp, _guard) = init_test_db();
6032        let relay = MemoryRelay::new();
6033        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6034        let cid = community.id.to_hex();
6035        let (_, genesis_hash) = crate::db::community::get_edition_head(&cid, &cid).unwrap().unwrap();
6036
6037        let mallory = Keys::generate();
6038        let mut hacked = crate::community::metadata::CommunityMetadata::of(&community);
6039        hacked.name = "Pwned".into();
6040        let inner = crate::community::roster::build_community_root_edition(&mallory, &community.id, &hacked, 2, Some(&genesis_hash), 5000, None).unwrap();
6041        let outer = crate::community::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, crate::community::Epoch(0)).unwrap();
6042        relay.inject(&outer, &community.relays);
6043
6044        fetch_and_apply_metadata(&relay, &community).await.unwrap();
6045        let after = crate::db::community::load_community(&community.id).unwrap().unwrap();
6046        assert_eq!(after.name, "HQ", "a non-manage-metadata signer's GroupRoot edit is rejected");
6047        assert_eq!(crate::db::community::get_edition_head(&cid, &cid).unwrap().unwrap().0, 1, "an unauthorized edit never advances the head");
6048    }
6049
6050    #[tokio::test]
6051    async fn channel_rename_round_trips_from_owner_edition() {
6052        // The vsk=2 ChannelMetadata fold: an owner-signed channel rename (v2, chained off genesis) folds
6053        // and applies to the matching channel.
6054        let (_tmp, _guard) = init_test_db();
6055        let relay = MemoryRelay::new();
6056        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6057        let cid = community.id.to_hex();
6058        let owner = crate::state::MY_SECRET_KEY.to_keys().unwrap();
6059        let channel = community.channels[0].clone();
6060        let ch_hex = channel.id.to_hex();
6061        let (_, genesis_ch_hash) = crate::db::community::get_edition_head(&cid, &ch_hex).unwrap().unwrap();
6062
6063        let meta = crate::community::metadata::ChannelMetadata { name: "announcements".into() };
6064        let inner = crate::community::roster::build_channel_metadata_edition(&owner, &channel.id, &meta, 2, Some(&genesis_ch_hash), 6000, None).unwrap();
6065        let outer = crate::community::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, crate::community::Epoch(0)).unwrap();
6066        relay.inject(&outer, &community.relays);
6067
6068        fetch_and_apply_metadata(&relay, &community).await.unwrap();
6069        let after = crate::db::community::load_community(&community.id).unwrap().unwrap();
6070        assert_eq!(after.channels[0].name, "announcements", "the owner's channel rename folded + applied");
6071        assert_eq!(crate::db::community::get_edition_head(&cid, &ch_hex).unwrap().unwrap().0, 2, "channel head advanced to v2");
6072    }
6073
6074    /// Build a v2 GroupRoot edition by `author` (name/created over genesis) → (sealed outer, self_hash,
6075    /// inner_id). Two of these with different (name, created) form a same-version concurrent fork.
6076    fn root_fork_v2(author: &Keys, community: &Community, name: &str, created: u64, genesis_hash: &[u8; 32]) -> (Event, [u8; 32], [u8; 32]) {
6077        let mut meta = crate::community::metadata::CommunityMetadata::of(community);
6078        meta.name = name.into();
6079        let inner = crate::community::roster::build_community_root_edition(author, &community.id, &meta, 2, Some(genesis_hash), created, None).unwrap();
6080        let self_hash = crate::community::version::edition_hash(&community.id.0, 2, Some(genesis_hash), inner.content.as_bytes());
6081        let inner_id = inner.id.to_bytes();
6082        let outer = crate::community::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, crate::community::Epoch(0)).unwrap();
6083        (outer, self_hash, inner_id)
6084    }
6085
6086    /// A concurrent v2 ChannelMetadata fork (the channel analogue of [`root_fork_v2`]): a v2 rename chained
6087    /// off the channel's genesis, returned as (sealed outer, self_hash, inner_id).
6088    fn channel_fork_v2(author: &Keys, community: &Community, channel_id: &crate::community::ChannelId, name: &str, created: u64, genesis_hash: &[u8; 32]) -> (Event, [u8; 32], [u8; 32]) {
6089        let meta = crate::community::metadata::ChannelMetadata { name: name.into() };
6090        let inner = crate::community::roster::build_channel_metadata_edition(author, channel_id, &meta, 2, Some(genesis_hash), created, None).unwrap();
6091        let self_hash = crate::community::version::edition_hash(&channel_id.0, 2, Some(genesis_hash), inner.content.as_bytes());
6092        let inner_id = inner.id.to_bytes();
6093        let outer = crate::community::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, crate::community::Epoch(0)).unwrap();
6094        (outer, self_hash, inner_id)
6095    }
6096
6097    /// W1 — channel metadata converges on a same-version fork exactly like GroupRoot: two authorized editors
6098    /// rename a channel concurrently (both v2, different content); a client holding the LOSER (higher inner
6099    /// id) converges onto the deterministic winner (lower inner id) instead of clinging to its own.
6100    #[tokio::test]
6101    async fn channel_same_version_fork_converges_to_the_lower_inner_id() {
6102        let (_tmp, _guard) = init_test_db();
6103        let relay = MemoryRelay::new();
6104        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6105        let cid = community.id.to_hex();
6106        let owner = crate::state::MY_SECRET_KEY.to_keys().unwrap();
6107        let channel_id = community.channels[0].id;
6108        let ch_hex = channel_id.to_hex();
6109        let (_, genesis_hash) = crate::db::community::get_edition_head(&cid, &ch_hex).unwrap().unwrap();
6110
6111        let (out_a, ha, ida) = channel_fork_v2(&owner, &community, &channel_id, "alpha", 1000, &genesis_hash);
6112        let (out_b, hb, idb) = channel_fork_v2(&owner, &community, &channel_id, "bravo", 2000, &genesis_hash);
6113        let (win_name, win_h, win_id, lose_name, lose_h, lose_id) = if ida < idb {
6114            ("alpha", ha, ida, "bravo", hb, idb)
6115        } else {
6116            ("bravo", hb, idb, "alpha", ha, ida)
6117        };
6118        // Hold the LOSER locally (head + channel name), then see both forks.
6119        crate::db::community::set_edition_head_with_id(&cid, &ch_hex, 2, &lose_h, &lose_id).unwrap();
6120        {
6121            let mut c = crate::db::community::load_community(&community.id).unwrap().unwrap();
6122            c.channels.iter_mut().find(|ch| ch.id == channel_id).unwrap().name = lose_name.into();
6123            crate::db::community::save_community(&c).unwrap();
6124        }
6125        relay.inject(&out_a, &community.relays);
6126        relay.inject(&out_b, &community.relays);
6127
6128        fetch_and_apply_metadata(&relay, &community).await.unwrap();
6129        let after = crate::db::community::load_community(&community.id).unwrap().unwrap();
6130        let ch_name = &after.channels.iter().find(|c| c.id == channel_id).unwrap().name;
6131        assert_eq!(ch_name, win_name, "channel converged on the lower-inner-id winner, not our held fork");
6132        assert_eq!(crate::db::community::get_edition_head(&cid, &ch_hex).unwrap().unwrap(), (2, win_h), "channel head self_hash converged at the SAME version");
6133        assert_eq!(crate::db::community::get_edition_head_inner_id(&cid, &ch_hex).unwrap(), Some(win_id), "channel head inner_id moved to the winner");
6134
6135        // Flip-flop-proof: a second pass holding the winner keeps it.
6136        fetch_and_apply_metadata(&relay, &community).await.unwrap();
6137        let after2 = crate::db::community::load_community(&community.id).unwrap().unwrap();
6138        assert_eq!(&after2.channels.iter().find(|c| c.id == channel_id).unwrap().name, win_name, "no flip back to the higher-id fork");
6139    }
6140
6141    /// W1 — channel authority gate runs BEFORE the tiebreak: a demoted/unauthorized author's same-version
6142    /// channel rename loses even with the lowest inner id; the authorized rename is applied.
6143    #[tokio::test]
6144    async fn channel_same_version_fork_excludes_an_unauthorized_lower_id_edition() {
6145        let (_tmp, _guard) = init_test_db();
6146        let relay = MemoryRelay::new();
6147        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6148        let cid = community.id.to_hex();
6149        let owner = crate::state::MY_SECRET_KEY.to_keys().unwrap();
6150        let channel_id = community.channels[0].id;
6151        let ch_hex = channel_id.to_hex();
6152        let (_, genesis_hash) = crate::db::community::get_edition_head(&cid, &ch_hex).unwrap().unwrap();
6153
6154        let (owner_out, owner_h, owner_id) = channel_fork_v2(&owner, &community, &channel_id, "legit", 1000, &genesis_hash);
6155        // Grind mallory's created_at until her forgery sorts FIRST author-blind (lower inner id).
6156        let mallory = Keys::generate();
6157        let mal_out = {
6158            let mut chosen = None;
6159            for t in 1..=10_000u64 {
6160                let cand = channel_fork_v2(&mallory, &community, &channel_id, "forged", t, &genesis_hash);
6161                if cand.2 < owner_id { chosen = Some(cand.0); break; }
6162            }
6163            chosen.expect("a mallory channel edition with a lower inner id")
6164        };
6165        relay.inject(&owner_out, &community.relays);
6166        relay.inject(&mal_out, &community.relays);
6167
6168        fetch_and_apply_metadata(&relay, &community).await.unwrap();
6169        let after = crate::db::community::load_community(&community.id).unwrap().unwrap();
6170        assert_eq!(&after.channels.iter().find(|c| c.id == channel_id).unwrap().name, &"legit".to_string(), "the channel forgery never wins despite a lower inner id");
6171        assert_eq!(crate::db::community::get_edition_head(&cid, &ch_hex).unwrap().unwrap(), (2, owner_h), "the authorized channel edition is the head");
6172    }
6173
6174    /// epoch-primary floor: a re-founding re-genesises every entity to v1 under the NEW epoch, and that
6175    /// v1 must supersede the held high version (else compaction is impossible) — WITHOUT weakening in-epoch
6176    /// refuse-downgrade. Exercises the `set_edition_head` write guard directly.
6177    #[tokio::test]
6178    async fn epoch_primary_floor_lets_a_refounding_v1_supersede_a_held_high_version() {
6179        let (_tmp, _guard) = init_test_db();
6180        let relay = MemoryRelay::new();
6181        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6182        let cid = community.id.to_hex();
6183        // Drive the GroupRoot head to v5 within epoch 0.
6184        for v in 2..=5u64 {
6185            crate::db::community::set_edition_head_with_id(&cid, &cid, v, &[v as u8; 32], &[v as u8; 32]).unwrap();
6186        }
6187        assert_eq!(crate::db::community::get_edition_head(&cid, &cid).unwrap().unwrap().0, 5);
6188        // In-epoch refuse-downgrade still holds: a lower version is a no-op.
6189        crate::db::community::set_edition_head_with_id(&cid, &cid, 3, &[0x33; 32], &[0x33; 32]).unwrap();
6190        assert_eq!(crate::db::community::get_edition_head(&cid, &cid).unwrap().unwrap().0, 5, "in-epoch downgrade refused");
6191
6192        // Re-found: bump the community to epoch 1, then write the compacted GroupRoot genesis (v1 @ epoch 1).
6193        crate::db::community::advance_server_root_epoch(&cid, 1, &[0xEE; 32]).unwrap();
6194        crate::db::community::set_edition_head_with_id(&cid, &cid, 1, &[0x01; 32], &[0x01; 32]).unwrap();
6195        let (v, h) = crate::db::community::get_edition_head(&cid, &cid).unwrap().unwrap();
6196        assert_eq!((v, h), (1, [0x01; 32]), "epoch-1 v1 supersedes epoch-0 v5 (epoch-primary)");
6197        assert_eq!(
6198            crate::db::community::get_all_edition_heads_epoched(&cid).unwrap().get(&cid).map(|(e, v, _)| (*e, *v)),
6199            Some((1, 1)),
6200            "head now recorded at epoch 1",
6201        );
6202        // And within the NEW epoch, refuse-downgrade resumes: v1 holds, a re-presented v1 stays.
6203        crate::db::community::set_edition_head_with_id(&cid, &cid, 1, &[0xAA; 32], &[0x02; 32]).unwrap();
6204        assert_eq!(crate::db::community::get_edition_head(&cid, &cid).unwrap().unwrap().1, [0x01; 32], "same-epoch same-version is not an advance");
6205    }
6206
6207    /// T1 — Concord Convergence: two authorized editors edit from the same base, both produce v2 with
6208    /// different content. A client holding the LOSER (higher inner id) converges IN PLACE onto the
6209    /// deterministic winner (lower inner id) instead of clinging to its own — the live divergence bug.
6210    #[tokio::test]
6211    async fn same_version_fork_converges_to_the_lower_inner_id() {
6212        let (_tmp, _guard) = init_test_db();
6213        let relay = MemoryRelay::new();
6214        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6215        let cid = community.id.to_hex();
6216        let owner = crate::state::MY_SECRET_KEY.to_keys().unwrap();
6217        let (_, genesis_hash) = crate::db::community::get_edition_head(&cid, &cid).unwrap().unwrap();
6218
6219        let (out_a, ha, ida) = root_fork_v2(&owner, &community, "Alpha", 1000, &genesis_hash);
6220        let (out_b, hb, idb) = root_fork_v2(&owner, &community, "Bravo", 2000, &genesis_hash);
6221        // Winner = lower inner id; we hold the loser.
6222        let (win_name, win_h, win_id, lose_name, lose_h, lose_id) = if ida < idb {
6223            ("Alpha", ha, ida, "Bravo", hb, idb)
6224        } else {
6225            ("Bravo", hb, idb, "Alpha", ha, ida)
6226        };
6227        crate::db::community::set_edition_head_with_id(&cid, &cid, 2, &lose_h, &lose_id).unwrap();
6228        {
6229            let mut c = crate::db::community::load_community(&community.id).unwrap().unwrap();
6230            c.name = lose_name.into();
6231            crate::db::community::save_community(&c).unwrap();
6232        }
6233        relay.inject(&out_a, &community.relays);
6234        relay.inject(&out_b, &community.relays);
6235
6236        fetch_and_apply_metadata(&relay, &community).await.unwrap();
6237        let after = crate::db::community::load_community(&community.id).unwrap().unwrap();
6238        assert_eq!(after.name, win_name, "converged on the lower-inner-id winner, not our own held fork");
6239        assert_eq!(crate::db::community::get_edition_head(&cid, &cid).unwrap().unwrap(), (2, win_h), "head self_hash converged at the SAME version");
6240        assert_eq!(crate::db::community::get_edition_head_inner_id(&cid, &cid).unwrap(), Some(win_id), "head inner_id moved to the winner");
6241
6242        // Flip-flop-proof: holding the winner, a second pass seeing both forks keeps the winner.
6243        fetch_and_apply_metadata(&relay, &community).await.unwrap();
6244        assert_eq!(crate::db::community::load_community(&community.id).unwrap().unwrap().name, win_name, "no flip back to the higher-id fork");
6245    }
6246
6247    /// T2 — the converged head feeds the next edit: v3 chains prev_hash from the CONVERGED winner, so a
6248    /// fresh fold reaches v3 contiguously (no re-fork). Guards the silent same-version no-op trap (B2/B5).
6249    #[tokio::test]
6250    async fn converged_head_chains_the_next_edit_without_reforking() {
6251        let (_tmp, _guard) = init_test_db();
6252        let relay = MemoryRelay::new();
6253        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6254        let cid = community.id.to_hex();
6255        let owner = crate::state::MY_SECRET_KEY.to_keys().unwrap();
6256        let (_, genesis_hash) = crate::db::community::get_edition_head(&cid, &cid).unwrap().unwrap();
6257
6258        let (out_a, ha, ida) = root_fork_v2(&owner, &community, "Alpha", 1000, &genesis_hash);
6259        let (out_b, hb, idb) = root_fork_v2(&owner, &community, "Bravo", 2000, &genesis_hash);
6260        let (lose_h, lose_id) = if ida < idb { (hb, idb) } else { (ha, ida) };
6261        crate::db::community::set_edition_head_with_id(&cid, &cid, 2, &lose_h, &lose_id).unwrap();
6262        relay.inject(&out_a, &community.relays);
6263        relay.inject(&out_b, &community.relays);
6264        fetch_and_apply_metadata(&relay, &community).await.unwrap();
6265        assert_eq!(crate::db::community::get_edition_head(&cid, &cid).unwrap().unwrap().0, 2, "converged at v2");
6266
6267        let mut c = crate::db::community::load_community(&community.id).unwrap().unwrap();
6268        c.name = "Third".into();
6269        republish_community_metadata(&relay, &c).await.unwrap();
6270        assert_eq!(crate::db::community::get_edition_head(&cid, &cid).unwrap().unwrap().0, 3, "advanced to v3 off the converged head");
6271
6272        let empty: std::collections::HashMap<String, (u64, [u8; 32])> = std::collections::HashMap::new();
6273        let folded = crate::community::roster::fold_roster(&fetch_control_inners(&relay, &community).await, &community.id, &empty);
6274        assert_eq!(folded.root_head.as_ref().map(|h| h.version), Some(3), "a fresh fold reaches v3");
6275        assert!(!folded.gapped_entities.contains(&community.id.0), "the chain is contiguous genesis -> winner -> v3");
6276    }
6277
6278    /// T3 — authority gate runs BEFORE the tiebreak: an UNAUTHORIZED same-version edition loses even with
6279    /// the lowest inner id. We apply the authorized edition, never the forgery that sorts first.
6280    #[tokio::test]
6281    async fn same_version_fork_excludes_an_unauthorized_lower_id_edition() {
6282        let (_tmp, _guard) = init_test_db();
6283        let relay = MemoryRelay::new();
6284        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6285        let cid = community.id.to_hex();
6286        let owner = crate::state::MY_SECRET_KEY.to_keys().unwrap();
6287        let (_, genesis_hash) = crate::db::community::get_edition_head(&cid, &cid).unwrap().unwrap();
6288
6289        let (owner_out, owner_h, owner_id) = root_fork_v2(&owner, &community, "Legit", 1000, &genesis_hash);
6290        // Grind mallory's created_at until her forgery sorts FIRST author-blind (lower inner id).
6291        let mallory = Keys::generate();
6292        let (mal_out, mal_id) = {
6293            let mut chosen = None;
6294            for t in 1..=10_000u64 {
6295                let cand = root_fork_v2(&mallory, &community, "Forged", t, &genesis_hash);
6296                if cand.2 < owner_id { chosen = Some((cand.0, cand.2)); break; }
6297            }
6298            chosen.expect("a mallory edition with a lower inner id")
6299        };
6300        assert!(mal_id < owner_id, "premise: the forgery sorts first author-blind");
6301        relay.inject(&owner_out, &community.relays);
6302        relay.inject(&mal_out, &community.relays);
6303
6304        // Floor stays at genesis v1, so the consumer must CHOOSE among the v2 candidates.
6305        fetch_and_apply_metadata(&relay, &community).await.unwrap();
6306        let after = crate::db::community::load_community(&community.id).unwrap().unwrap();
6307        assert_eq!(after.name, "Legit", "the forgery never wins despite a lower inner id");
6308        assert_eq!(crate::db::community::get_edition_head(&cid, &cid).unwrap().unwrap(), (2, owner_h), "the authorized edition is the head");
6309    }
6310
6311    /// T4 — the convergence exemption is DISPLAY-ONLY: a same-version fork on an authority record
6312    /// (banlist) where we hold the higher-id edition stays QUARANTINED (gapped, not folded). Converging
6313    /// authority off a withheld view would be a relay-choosable censorship lever, so it fails closed.
6314    #[tokio::test]
6315    async fn same_version_fork_on_an_authority_record_fails_closed() {
6316        let (_tmp, _guard) = init_test_db();
6317        let relay = MemoryRelay::new();
6318        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6319        let cid = community.id.to_hex();
6320        let owner = crate::state::MY_SECRET_KEY.to_keys().unwrap();
6321        let bl_eid = crate::community::derive::banlist_locator(&community.id);
6322        let bl_hex = crate::simd::hex::bytes_to_hex_32(&bl_eid);
6323
6324        let prev = [0x99u8; 32]; // both v2 forks cite the same (held) v1; the ==floor anchor checks self_hash
6325        let build_ban = |list: &[String], created: u64| {
6326            let inner = crate::community::roster::build_banlist_edition(&owner, &community.id, list, 2, Some(&prev), created, None).unwrap();
6327            let self_hash = crate::community::version::edition_hash(&bl_eid, 2, Some(&prev), inner.content.as_bytes());
6328            let outer = crate::community::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, crate::community::Epoch(0)).unwrap();
6329            (outer, self_hash, inner.id.to_bytes())
6330        };
6331        let (out_a, ha, ida) = build_ban(&["aa".repeat(32)], 1000);
6332        let (out_b, hb, idb) = build_ban(&["bb".repeat(32)], 2000);
6333        // Hold the higher-id edition → the fold's winner (lower id) differs → adopting it would require a
6334        // same-version swap, which an authority record must REFUSE.
6335        let (lose_h, lose_id) = if ida < idb { (hb, idb) } else { (ha, ida) };
6336        crate::db::community::set_edition_head_with_id(&cid, &bl_hex, 2, &lose_h, &lose_id).unwrap();
6337        relay.inject(&out_a, &community.relays);
6338        relay.inject(&out_b, &community.relays);
6339
6340        let floors = crate::db::community::get_all_edition_heads(&cid).unwrap();
6341        let folded = crate::community::roster::fold_roster(&fetch_control_inners(&relay, &community).await, &community.id, &floors);
6342        assert!(folded.gapped_entities.contains(&bl_eid), "the authority-record fork is quarantined");
6343        assert!(folded.banlist_head.is_none() && folded.banlist_author.is_none(), "no banlist folded off the withheld view");
6344    }
6345
6346    #[tokio::test]
6347    async fn editions_sign_through_the_active_client_signer() {
6348        // The bunker code path: with a NOSTR_CLIENT signer installed, authority editions sign through
6349        // `client.signer()` (the same route a NIP-46 bunker takes) rather than the local-vault fallback.
6350        // Proven end-to-end: create a community while the client signer is active, then fold + authorize
6351        // its genesis (the owner attestation must verify → the editions were signed by the right identity).
6352        let (_tmp, _guard) = init_test_db();
6353        let owner = crate::state::MY_SECRET_KEY.to_keys().unwrap();
6354        crate::state::set_nostr_client(nostr_sdk::Client::builder().signer(owner.clone()).build());
6355
6356        let relay = MemoryRelay::new();
6357        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6358        let cid = community.id.to_hex();
6359
6360        // A banlist edition (a non-genesis authority action) also signs via the client path + folds.
6361        publish_banlist(&relay, &community, &["dd".repeat(32)]).await.unwrap();
6362        let floors = crate::db::community::get_all_edition_heads(&cid).unwrap();
6363        let folded = crate::community::roster::fold_roster(
6364            &fetch_control_inners(&relay, &community).await, &community.id, &floors);
6365        assert_eq!(folded.banlist_author, Some(owner.public_key()), "banlist signed by the client signer");
6366        assert!(folded.root_author.is_some(), "genesis GroupRoot folded");
6367        let _ = crate::state::take_nostr_client();
6368    }
6369
6370    /// Fetch + open the control-plane inner editions for a community (epoch 0) — test helper.
6371    async fn fetch_control_inners(relay: &MemoryRelay, community: &Community) -> Vec<Event> {
6372        let z = crate::community::roster::control_pseudonym(&community.server_root_key, &community.id, crate::community::Epoch(0));
6373        let query = Query { kinds: vec![event_kind::COMMUNITY_CONTROL], z_tags: vec![z], ..Default::default() };
6374        let mut out = Vec::new();
6375        for ev in relay.fetch(&query, &community.relays).await.unwrap() {
6376            if let Ok(inner) = crate::community::roster::open_control_edition(&ev, &community.server_root_key) {
6377                out.push(inner);
6378            }
6379        }
6380        out
6381    }
6382
6383    /// Drop the local secret key while keeping a client signer + the public key — the test shape of a
6384    /// NIP-46 bunker account (signs remotely, no raw local key for ECDH rekeys).
6385    fn simulate_bunker(owner: &Keys) {
6386        crate::state::set_nostr_client(nostr_sdk::Client::builder().signer(owner.clone()).build());
6387        crate::state::MY_SECRET_KEY.clear(&[]);
6388        assert!(crate::state::MY_SECRET_KEY.to_keys().is_none(), "bunker sim: no local key");
6389    }
6390
6391    #[tokio::test]
6392    async fn am_i_banned_detects_own_npub_in_banlist() {
6393        // The ban self-remove signal: `am_i_banned` is true iff the local npub is in the folded banlist.
6394        let (_tmp, _guard) = init_test_db();
6395        let relay = MemoryRelay::new();
6396        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6397        let me = crate::state::MY_SECRET_KEY.to_keys().unwrap().public_key().to_hex();
6398        let cid = community.id.to_hex();
6399        assert!(!am_i_banned(&community), "not banned on a fresh community");
6400        // Inject ourselves into the cached banlist (the fold would do this from a real edition).
6401        crate::db::community::set_community_banlist(&cid, &[me], 1).unwrap();
6402        assert!(am_i_banned(&community), "own npub in the banlist → banned → self-remove");
6403        crate::db::community::set_community_banlist(&cid, &[], 2).unwrap();
6404        assert!(!am_i_banned(&community), "cleared banlist → not banned");
6405    }
6406
6407    #[tokio::test]
6408    async fn bunker_owner_cannot_ban_in_private_community() {
6409        // Fail-fast: a private-community ban needs a read-cut rekey, which a bunker account can't do. It
6410        // must refuse BEFORE publishing — no "banned but still readable" half-state.
6411        let (_tmp, _guard) = init_test_db();
6412        let owner = crate::state::MY_SECRET_KEY.to_keys().unwrap();
6413        let relay = MemoryRelay::new();
6414        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6415        simulate_bunker(&owner);
6416
6417        let victim = "cc".repeat(32);
6418        let err = publish_banlist(&relay, &community, &[victim]).await.unwrap_err();
6419        assert!(err.contains("private community") && err.contains("bunker"), "clear bunker explanation: {err}");
6420        assert!(
6421            crate::db::community::get_community_banlist(&community.id.to_hex()).unwrap().is_empty(),
6422            "the ban must NOT half-apply (nothing published or persisted)"
6423        );
6424        let _ = crate::state::take_nostr_client();
6425    }
6426
6427    #[tokio::test]
6428    async fn bunker_owner_can_ban_in_public_community() {
6429        // A PUBLIC ban doesn't rekey (anti-memberlist), so a bunker account CAN ban — the guard must not
6430        // over-block. (Mint a link → Public, then ban as a bunker.)
6431        let (_tmp, _guard) = init_test_db();
6432        let owner = crate::state::MY_SECRET_KEY.to_keys().unwrap();
6433        let relay = MemoryRelay::new();
6434        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6435        create_public_invite(&relay, &community, None, None).await.unwrap();
6436        let community = crate::db::community::load_community(&community.id).unwrap().unwrap();
6437        assert!(is_public(&community).unwrap(), "minting a link made it Public");
6438        simulate_bunker(&owner);
6439
6440        let victim = "cc".repeat(32);
6441        publish_banlist(&relay, &community, &[victim.clone()]).await.unwrap();
6442        assert_eq!(
6443            crate::db::community::get_community_banlist(&community.id.to_hex()).unwrap(),
6444            vec![victim],
6445            "a public ban from a bunker account succeeds (no rekey needed)"
6446        );
6447        let _ = crate::state::take_nostr_client();
6448    }
6449
6450    #[tokio::test]
6451    async fn bunker_owner_cannot_privatize() {
6452        // Fail-fast: revoking the LAST link privatizes → re-founding rekey, which a bunker can't do. Must
6453        // refuse before publishing, leaving the community Public (no half-apply).
6454        let (_tmp, _guard) = init_test_db();
6455        let owner = crate::state::MY_SECRET_KEY.to_keys().unwrap();
6456        let relay = MemoryRelay::new();
6457        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6458        let (token, _) = create_public_invite(&relay, &community, None, None).await.unwrap();
6459        let community = crate::db::community::load_community(&community.id).unwrap().unwrap();
6460        simulate_bunker(&owner);
6461
6462        let err = revoke_public_invite(&relay, &community, &crate::simd::hex::hex_to_bytes_32(&token)).await.unwrap_err();
6463        assert!(err.contains("private") && err.contains("bunker"), "clear bunker explanation: {err}");
6464        let after = crate::db::community::load_community(&community.id).unwrap().unwrap();
6465        assert!(is_public(&after).unwrap(), "the revoke must NOT half-apply — community stays Public");
6466        let _ = crate::state::take_nostr_client();
6467    }
6468
6469    #[tokio::test]
6470    async fn non_owner_admin_can_edit_community_metadata() {
6471        // The "no hardcoding" crux: a NON-OWNER member granted the Admin role (which carries
6472        // MANAGE_METADATA) can move the community's display, verified purely by the folded roster — not a
6473        // hardcoded owner check.
6474        let (_tmp, _guard) = init_test_db();
6475        let relay = MemoryRelay::new();
6476        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6477        let cid = community.id.to_hex();
6478        let (_, genesis_hash) = crate::db::community::get_edition_head(&cid, &cid).unwrap().unwrap();
6479
6480        // Owner grants `admin` the Admin role (publishes the grant edition to the relay).
6481        let admin = Keys::generate();
6482        let admin_role_id = crate::db::community::get_community_roles(&cid).unwrap().roles[0].role_id.clone();
6483        set_member_grant(&relay, &community, &admin.public_key().to_hex(), vec![admin_role_id]).await.unwrap();
6484
6485        // `admin` (NOT the owner) publishes a GroupRoot v2 renaming the community.
6486        let mut edited = crate::community::metadata::CommunityMetadata::of(&community);
6487        edited.name = "Admin Renamed".into();
6488        let inner = crate::community::roster::build_community_root_edition(&admin, &community.id, &edited, 2, Some(&genesis_hash), 7000, None).unwrap();
6489        let outer = crate::community::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, crate::community::Epoch(0)).unwrap();
6490        relay.inject(&outer, &community.relays);
6491
6492        fetch_and_apply_metadata(&relay, &community).await.unwrap();
6493        let after = crate::db::community::load_community(&community.id).unwrap().unwrap();
6494        assert_eq!(after.name, "Admin Renamed", "a MANAGE_METADATA admin (not the owner) can edit metadata");
6495    }
6496
6497    #[tokio::test]
6498    async fn banning_an_admin_revokes_their_role() {
6499        // Removal strips authority: a banned admin's grant must NOT dangle — else unban silently restores
6500        // admin and the roster keeps listing a non-member as admin. Public community isolates the role-strip
6501        // from the read-cut.
6502        let (_tmp, _guard) = init_test_db();
6503        let relay = MemoryRelay::new();
6504        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6505        let cid = community.id.to_hex();
6506        create_public_invite(&relay, &community, None, None).await.unwrap();
6507        let community = crate::db::community::load_community(&community.id).unwrap().unwrap();
6508
6509        let alice = Keys::generate();
6510        let alice_hex = alice.public_key().to_hex();
6511        let admin_role_id = crate::db::community::get_community_roles(&cid).unwrap().roles[0].role_id.clone();
6512        set_member_grant(&relay, &community, &alice_hex, vec![admin_role_id]).await.unwrap();
6513        let holds_role = |hex: &str| crate::db::community::get_community_roles(&cid).unwrap()
6514            .grants.iter().any(|g| g.member == hex && !g.role_ids.is_empty());
6515        assert!(holds_role(&alice_hex), "alice is admin pre-ban");
6516
6517        publish_banlist(&relay, &community, &[alice_hex.clone()]).await.unwrap();
6518        assert!(!holds_role(&alice_hex), "banning an admin revokes their role — no dangling grant");
6519    }
6520
6521    #[tokio::test]
6522    async fn kicking_an_admin_revokes_their_role() {
6523        // Same removal-strips-authority rule for the soft tier: a kicked admin who rejoins (fresh invite)
6524        // must NOT be silently still-admin.
6525        let (_tmp, _guard) = init_test_db();
6526        let relay = MemoryRelay::new();
6527        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6528        let cid = community.id.to_hex();
6529        let alice = Keys::generate();
6530        let alice_hex = alice.public_key().to_hex();
6531        let admin_role_id = crate::db::community::get_community_roles(&cid).unwrap().roles[0].role_id.clone();
6532        set_member_grant(&relay, &community, &alice_hex, vec![admin_role_id]).await.unwrap();
6533        let holds_role = |hex: &str| crate::db::community::get_community_roles(&cid).unwrap()
6534            .grants.iter().any(|g| g.member == hex && !g.role_ids.is_empty());
6535        assert!(holds_role(&alice_hex), "alice is admin pre-kick");
6536
6537        publish_kick(&relay, &community, &community.channels[0], &alice_hex).await.unwrap();
6538        assert!(!holds_role(&alice_hex), "kicking an admin revokes their role");
6539    }
6540
6541    #[tokio::test]
6542    async fn republish_channel_metadata_renames_and_publishes() {
6543        // The producer (the write side the consumer test was missing): renaming via
6544        // `republish_channel_metadata` updates the local channel AND advances the channel head.
6545        let (_tmp, _guard) = init_test_db();
6546        let relay = MemoryRelay::new();
6547        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6548        let cid = community.id.to_hex();
6549        let channel = community.channels[0].clone();
6550        let ch_hex = channel.id.to_hex();
6551
6552        republish_channel_metadata(&relay, &community, &channel.id, "lobby").await.unwrap();
6553        let after = crate::db::community::load_community(&community.id).unwrap().unwrap();
6554        assert_eq!(after.channels[0].name, "lobby", "the producer renamed the channel locally");
6555        assert_eq!(crate::db::community::get_edition_head(&cid, &ch_hex).unwrap().unwrap().0, 2, "channel head advanced");
6556    }
6557
6558    #[tokio::test]
6559    async fn revoking_the_last_link_privatizes_and_rotates_the_base() {
6560        // The privatize trigger: minting links flips the computed mode to Public WITHOUT rotating;
6561        // revoking a non-last link stays Public, no rotation; revoking the LAST link flips to Private AND
6562        // re-founds the community (rotate the base/server-root to the observed participants → epoch bump),
6563        // sealing out link-joined lurkers.
6564        let (_tmp, _guard) = init_test_db();
6565        let relay = MemoryRelay::new();
6566        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6567        assert!(!is_public(&community).unwrap(), "a fresh community is Private");
6568        assert_eq!(community.server_root_epoch, crate::community::Epoch(0));
6569
6570        // Mint two links → Public, base NOT rotated.
6571        let (t1, _) = create_public_invite(&relay, &community, None, None).await.unwrap();
6572        let (t2, _) = create_public_invite(&relay, &community, None, None).await.unwrap();
6573        let c = crate::db::community::load_community(&community.id).unwrap().unwrap();
6574        assert!(is_public(&c).unwrap(), "minting a link flips the mode to Public");
6575        assert_eq!(c.server_root_epoch, crate::community::Epoch(0), "minting links does NOT rotate the base");
6576
6577        // Revoke the first of two → one link remains → still Public, still no rotation.
6578        revoke_public_invite(&relay, &c, &crate::simd::hex::hex_to_bytes_32(&t1)).await.unwrap();
6579        let c = crate::db::community::load_community(&community.id).unwrap().unwrap();
6580        assert!(is_public(&c).unwrap(), "one link remains → still Public");
6581        assert_eq!(c.server_root_epoch, crate::community::Epoch(0), "revoking a non-last link does NOT rotate");
6582
6583        // Revoke the LAST link → Private + base rotated (re-founding).
6584        revoke_public_invite(&relay, &c, &crate::simd::hex::hex_to_bytes_32(&t2)).await.unwrap();
6585        let c = crate::db::community::load_community(&community.id).unwrap().unwrap();
6586        assert!(!is_public(&c).unwrap(), "revoking the last link flips to Private");
6587        assert_eq!(c.server_root_epoch, crate::community::Epoch(1), "privatize re-founded: the base key rotated");
6588
6589        // Idempotency: re-revoking the already-gone token must NOT re-found again (no second epoch
6590        // bump) — privatize fires only on a genuine Public→Private transition (`had_links`).
6591        revoke_public_invite(&relay, &c, &crate::simd::hex::hex_to_bytes_32(&t2)).await.unwrap();
6592        let c = crate::db::community::load_community(&community.id).unwrap().unwrap();
6593        assert_eq!(c.server_root_epoch, crate::community::Epoch(1), "a no-op re-revoke does not double-rotate");
6594    }
6595
6596    #[tokio::test]
6597    async fn private_ban_reseals_base_public_ban_does_not() {
6598        // rekey-on-removal: banning in a PRIVATE community re-seals the base (epoch bump → the banned
6599        // member's read access is cut); in a PUBLIC community the base is NOT rotated (anti-memberlist).
6600        let (_tmp, _guard) = init_test_db();
6601        let relay = MemoryRelay::new();
6602        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6603        let victim = "cc".repeat(32);
6604
6605        // PRIVATE (no links) → banning rotates the base.
6606        assert!(!is_public(&community).unwrap(), "fresh community is Private");
6607        publish_banlist(&relay, &community, &[victim.clone()]).await.unwrap();
6608        let c = crate::db::community::load_community(&community.id).unwrap().unwrap();
6609        assert_eq!(c.server_root_epoch, crate::community::Epoch(1), "a private-community ban re-seals the base");
6610
6611        // Go PUBLIC (mint a link), then ban another member → the base must NOT rotate again.
6612        create_public_invite(&relay, &c, None, None).await.unwrap();
6613        let c = crate::db::community::load_community(&community.id).unwrap().unwrap();
6614        assert!(is_public(&c).unwrap(), "minted a link → Public");
6615        publish_banlist(&relay, &c, &[victim.clone(), "dd".repeat(32)]).await.unwrap();
6616        let c2 = crate::db::community::load_community(&community.id).unwrap().unwrap();
6617        assert_eq!(c2.server_root_epoch, crate::community::Epoch(1), "a public-community ban does NOT rotate the base");
6618    }
6619
6620    #[tokio::test]
6621    async fn private_ban_seals_the_banned_member_out_of_the_new_root() {
6622        // rekey-on-removal SECURITY crux: a banned member must be EXCLUDED from the re-seal
6623        // recipient set so they CANNOT recover the new root — read access actually cut, not just epoch
6624        // bumped. Exercises the banlist(hex)→activity(bech32) reconciliation AND the persist-before-reseal
6625        // ordering end-to-end. The existing ban tests assert the epoch bump but never that the victim is
6626        // sealed out — this is the assertion that matters.
6627        use crate::community::derive::{base_rekey_pseudonym, recipient_pseudonym};
6628        use crate::community::rekey::{open_rekey_event, rekey_pairwise_secret};
6629        use crate::types::Message;
6630        use nostr_sdk::ToBech32;
6631        let (_tmp, _guard) = init_test_db();
6632        let relay = MemoryRelay::new();
6633        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6634        let cid = community.id.to_hex();
6635        let genesis_root = *community.server_root_key.as_bytes();
6636        let channel_hex = community.channels[0].id.to_hex();
6637
6638        // The victim posts → observed participant (absent the ban, they'd BE a re-seal recipient).
6639        let victim = Keys::generate();
6640        let victim_b32 = victim.public_key().to_bech32().unwrap();
6641        let mut m = Message::default();
6642        m.id = "aa".repeat(32);
6643        m.npub = Some(victim_b32.clone());
6644        m.at = 1000;
6645        crate::db::events::save_message(&channel_hex, &m).await.unwrap();
6646        assert!(
6647            crate::db::community::community_member_activity(&cid).unwrap().iter().any(|(np, _)| np == &victim_b32),
6648            "victim is observed before the ban"
6649        );
6650
6651        // Ban the victim (private community) → re-seal at epoch 1.
6652        publish_banlist(&relay, &community, &[victim.public_key().to_hex()]).await.unwrap();
6653        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
6654        assert_eq!(reloaded.server_root_epoch, crate::community::Epoch(1), "private ban re-seals the base");
6655        assert!(
6656            !crate::db::community::community_member_activity(&cid).unwrap().iter().any(|(np, _)| np == &victim_b32),
6657            "the banned victim is no longer observed (banlist hex → bech32 reconciliation worked)"
6658        );
6659
6660        // The base rekey at epoch 1 must carry NO blob for the victim → they can't recover the new root.
6661        let addr = base_rekey_pseudonym(&crate::community::ServerRootKey(genesis_root), &community.id, crate::community::Epoch(1)).to_hex();
6662        let found = relay
6663            .fetch(&Query { kinds: vec![event_kind::COMMUNITY_REKEY], z_tags: vec![addr], ..Default::default() }, &community.relays)
6664            .await
6665            .unwrap();
6666        assert_eq!(found.len(), 1, "the base rekey is published");
6667        let parsed = open_rekey_event(&found[0], &genesis_root).unwrap();
6668        let secret = rekey_pairwise_secret(victim.secret_key(), &parsed.rotator).unwrap();
6669        let loc = recipient_pseudonym(&secret, parsed.scope, parsed.new_epoch).to_hex();
6670        assert!(
6671            parsed.blobs.iter().all(|b| b.locator != loc),
6672            "the BANNED victim has NO blob — sealed OUT of the new root (read access is actually cut)"
6673        );
6674    }
6675
6676    /// A relay that simulates an account swap MID-PUBLISH: it bumps the session generation inside
6677    /// publish/publish_durable, so a `SessionGuard` captured before the call is invalid by the time the
6678    /// caller re-checks after the await. The actual store delegates to an inner MemoryRelay.
6679    struct SwapDuringPublishRelay {
6680        inner: MemoryRelay,
6681    }
6682    #[async_trait::async_trait]
6683    impl Transport for SwapDuringPublishRelay {
6684        async fn publish(&self, event: &Event, relays: &[String]) -> Result<(), String> {
6685            crate::state::bump_session_generation();
6686            self.inner.publish(event, relays).await
6687        }
6688        async fn publish_durable(&self, event: &Event, relays: &[String]) -> Result<(), String> {
6689            crate::state::bump_session_generation();
6690            self.inner.publish_durable(event, relays).await
6691        }
6692        async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
6693            self.inner.fetch(query, relays).await
6694        }
6695    }
6696
6697    /// A write straddling I/O re-checks the session: a swap bumps the
6698    /// generation DURING `set_member_grant`'s publish. The edition is published under account A, but the
6699    /// post-await `is_valid()` gate must SKIP the local persist, so account B's DB is never written.
6700    #[tokio::test]
6701    async fn account_swap_during_grant_publish_skips_the_local_persist() {
6702        let (_tmp, _guard) = init_test_db();
6703        let setup = MemoryRelay::new();
6704        let community = create_community(&setup, "HQ", "general", vec!["r1".into()]).await.unwrap();
6705        let cid = community.id.to_hex();
6706        let member = "cc".repeat(32);
6707        let entity_hex = crate::simd::hex::bytes_to_hex_32(
6708            &crate::community::derive::grant_locator(&community.id, &crate::simd::hex::hex_to_bytes_32(&member)));
6709        assert!(crate::db::community::get_edition_head(&cid, &entity_hex).unwrap().is_none(), "no grant head yet");
6710
6711        let swap = SwapDuringPublishRelay { inner: MemoryRelay::new() };
6712        set_member_grant(&swap, &community, &member, vec!["a".repeat(64)]).await.unwrap();
6713
6714        assert!(
6715            crate::db::community::get_edition_head(&cid, &entity_hex).unwrap().is_none(),
6716            "session straddled a swap → persist skipped → no local grant head (account B uncorrupted)"
6717        );
6718    }
6719
6720    /// A swap during `publish_banlist`'s publish must leave NO half-applied state — the banlist isn't
6721    /// persisted, the private-community base isn't rotated, and `read_cut_pending` isn't flipped (every step
6722    /// gates on `is_valid()`). No ban half-lands in the wrong account.
6723    #[tokio::test]
6724    async fn account_swap_during_ban_publish_applies_nothing_locally() {
6725        let (_tmp, _guard) = init_test_db();
6726        let setup = MemoryRelay::new();
6727        let community = create_community(&setup, "HQ", "general", vec!["r1".into()]).await.unwrap();
6728        let cid = community.id.to_hex();
6729        assert!(!is_public(&community).unwrap(), "fresh community is Private (a ban would normally re-seal)");
6730
6731        let swap = SwapDuringPublishRelay { inner: MemoryRelay::new() };
6732        publish_banlist(&swap, &community, &["cc".repeat(32)]).await.unwrap();
6733
6734        assert!(crate::db::community::get_community_banlist(&cid).unwrap().is_empty(),
6735            "banlist persist skipped on the stale session");
6736        assert_eq!(crate::db::community::load_community(&community.id).unwrap().unwrap().server_root_epoch,
6737            crate::community::Epoch(0), "no read-cut re-seal → base NOT rotated into the wrong account");
6738        assert!(!crate::db::community::get_read_cut_pending(&cid).unwrap(),
6739            "read_cut_pending untouched (need_cut requires is_valid())");
6740    }
6741
6742    /// `swap_session` leaves no cross-account residue — STATE and the key vaults are
6743    /// cleared, so account B can't inherit account A's chats/keys.
6744    #[tokio::test]
6745    async fn swap_session_clears_per_account_state_and_keys() {
6746        let (_tmp, _guard) = init_test_db();
6747        {
6748            let mut st = crate::state::STATE.lock().await;
6749            st.db_loaded = true;
6750            st.is_syncing = true;
6751        }
6752        assert!(crate::state::MY_SECRET_KEY.has_key(), "account A holds a live key");
6753
6754        crate::VectorCore.swap_session().await;
6755
6756        let st = crate::state::STATE.lock().await;
6757        assert!(st.chats.is_empty() && st.profiles.is_empty(), "STATE chats/profiles cleared on swap");
6758        assert!(!st.db_loaded && !st.is_syncing, "db_loaded / is_syncing reset");
6759        assert!(!crate::state::MY_SECRET_KEY.has_key(), "key vault cleared — no leak into account B");
6760    }
6761
6762    /// A clean join PERSISTS the community up front (so the catch-up/fold can read it
6763    /// back) and registers the channel as a chat. Without the up-front save, the fold's load returns None
6764    /// and nothing persists.
6765    #[tokio::test]
6766    async fn join_finalization_persists_and_registers_the_channel() {
6767        let (_tmp, _guard) = init_test_db();
6768        crate::state::STATE.lock().await.chats.clear(); // drop any residue from a prior serialized test
6769        let relay = MemoryRelay::new();
6770        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6771        // A different identity joins.
6772        become_local(&Keys::generate());
6773
6774        crate::VectorCore.finalize_member_join(community.clone(), &relay, None).await.unwrap();
6775
6776        assert!(crate::db::community::load_community(&community.id).unwrap().is_some(), "community persisted on join");
6777        assert!(!crate::state::STATE.lock().await.chats.is_empty(), "the channel is registered as a chat");
6778    }
6779
6780    /// If the folded banlist names the joiner, `am_i_banned` fires and the
6781    /// just-saved community is torn back DOWN, the join returns Err, and — since the presence beacon publish
6782    /// is AFTER the ban check — no phantom join is announced. No orphaned community row is left behind.
6783    #[tokio::test]
6784    async fn join_finalization_tears_down_a_banned_joiner() {
6785        let (_tmp, _guard) = init_test_db();
6786        let relay = MemoryRelay::new();
6787        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6788        // Go Public (mint a link) so the ban is anti-memberlist and does NOT rotate the base.
6789        create_public_invite(&relay, &community, None, None).await.unwrap();
6790        let community = crate::db::community::load_community(&community.id).unwrap().unwrap();
6791
6792        // Ban a would-be joiner, then become them.
6793        let joiner = Keys::generate();
6794        publish_banlist(&relay, &community, &[joiner.public_key().to_hex()]).await.unwrap();
6795        become_local(&joiner);
6796        assert!(crate::db::community::load_community(&community.id).unwrap().is_some(), "community present pre-join");
6797
6798        let result = crate::VectorCore.finalize_member_join(community.clone(), &relay, None).await;
6799        assert!(result.is_err(), "a banned joiner's finalize must fail");
6800        assert!(result.unwrap_err().to_string().contains("banned"), "the error names the ban");
6801        assert!(
6802            crate::db::community::load_community(&community.id).unwrap().is_none(),
6803            "the just-saved community is torn back down — no orphaned row for a banned joiner"
6804        );
6805    }
6806
6807    /// `delete_community` must wipe EVERY community-scoped table — a missed one leaves authority/key
6808    /// residue a leave/re-join would fold. Populates all six scoped tables (+ the denormalized banlist),
6809    /// deletes, asserts each is empty. `community_message_keys` is DELIBERATELY retained — those are our
6810    /// OWN send-side ephemeral signing keys, and the right to NIP-09-delete our own content from relays
6811    /// outlives membership (even after a ban/leave), so they must survive a community delete.
6812    #[tokio::test]
6813    async fn delete_community_wipes_every_community_scoped_table() {
6814        let (_tmp, _guard) = init_test_db();
6815        let relay = MemoryRelay::new();
6816        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6817        let cid = community.id.to_hex();
6818
6819        // Populate every community-scoped table.
6820        crate::db::community::store_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 1, &[0x11u8; 32]).unwrap();
6821        crate::db::community::save_public_invite("tok", &cid, "https://x/invite#y", None, None).unwrap();
6822        crate::db::community::save_pending_invite(&cid, "{}", "npub1inviter").unwrap();
6823        crate::db::community::set_edition_head(&cid, &cid, 1, &[0x22u8; 32]).unwrap();
6824        crate::db::community::set_community_banlist(&cid, &["cc".repeat(32)], 100).unwrap();
6825
6826        // Sanity — all populated before the delete.
6827        assert!(crate::db::community::community_exists(&community.id).unwrap());
6828        assert!(!crate::db::community::held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap().is_empty());
6829        assert!(!crate::db::community::list_public_invites(&cid).unwrap().is_empty());
6830        assert!(crate::db::community::list_pending_invites().unwrap().iter().any(|p| p.community_id == cid));
6831        assert!(!crate::db::community::get_all_edition_heads(&cid).unwrap().is_empty());
6832        assert!(!crate::db::community::get_community_banlist(&cid).unwrap().is_empty());
6833
6834        crate::db::community::delete_community(&cid).unwrap();
6835
6836        // Every scoped table is empty for this community — no residue.
6837        assert!(!crate::db::community::community_exists(&community.id).unwrap(), "communities row gone");
6838        assert!(crate::db::community::load_community(&community.id).unwrap().is_none(), "community not loadable");
6839        assert!(crate::db::community::held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap().is_empty(), "epoch keys wiped");
6840        assert!(crate::db::community::list_public_invites(&cid).unwrap().is_empty(), "public invites wiped");
6841        assert!(!crate::db::community::list_pending_invites().unwrap().iter().any(|p| p.community_id == cid), "pending invites wiped");
6842        assert!(crate::db::community::get_all_edition_heads(&cid).unwrap().is_empty(), "edition heads wiped");
6843        assert!(crate::db::community::get_community_banlist(&cid).unwrap().is_empty(), "banlist wiped with the channels");
6844    }
6845
6846    /// A hostile relay piles JUNK at the control coordinate — a kind-3308 event at the right `#z` but
6847    /// with garbage content (not sealed under the server root). `open_control_edition` fails to decrypt it,
6848    /// so it's dropped before the fold; the genuine genesis plane still folds. No panic, no corruption.
6849    #[tokio::test]
6850    async fn fetch_control_folded_skips_junk_injected_at_the_coordinate() {
6851        let (_tmp, _guard) = init_test_db();
6852        let relay = MemoryRelay::new();
6853        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6854        let owner_hex = crate::state::MY_SECRET_KEY.to_keys().unwrap().public_key().to_hex();
6855
6856        // Garbage 3308 at the real control pseudonym, ephemeral-signed (outers always are).
6857        let z = crate::community::roster::control_pseudonym(&community.server_root_key, &community.id, community.server_root_epoch);
6858        let junk = nostr_sdk::EventBuilder::new(nostr_sdk::Kind::Custom(event_kind::COMMUNITY_CONTROL), "not a sealed edition")
6859            .tags([nostr_sdk::Tag::custom(nostr_sdk::TagKind::Custom("z".into()), [z])])
6860            .sign_with_keys(&Keys::generate())
6861            .unwrap();
6862        relay.publish(&junk, &community.relays).await.unwrap();
6863
6864        let folded = fetch_control_folded(&relay, &community).await.unwrap();
6865        assert!(
6866            !crate::community::roster::authorize_delegation(&folded, Some(&owner_hex)).roles.is_empty(),
6867            "the genuine Admin role still folds; the un-openable junk is silently dropped"
6868        );
6869    }
6870
6871    /// Every relay is dead/empty. The fold returns an empty roster, never a panic — a member with no
6872    /// reachable relay degrades to "no view," not a crash.
6873    #[tokio::test]
6874    async fn fetch_control_folded_on_dead_relays_is_empty_not_a_panic() {
6875        let (_tmp, _guard) = init_test_db();
6876        let community = saved_community_owned_by(&Keys::generate());
6877        let folded = fetch_control_folded(&FailingRelay, &community).await.unwrap();
6878        assert!(folded.roles.roles.is_empty() && folded.root_meta.is_none(), "dead relays → empty fold, no panic");
6879    }
6880
6881    #[tokio::test]
6882    async fn successful_private_ban_leaves_no_read_cut_pending() {
6883        // The happy path leaves no outstanding read-cut: the re-seal succeeds, so the flag is cleared.
6884        let (_tmp, _guard) = init_test_db();
6885        let relay = MemoryRelay::new();
6886        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6887        let cid = community.id.to_hex();
6888        publish_banlist(&relay, &community, &["cc".repeat(32)]).await.unwrap();
6889        assert!(!crate::db::community::get_read_cut_pending(&cid).unwrap(), "a successful re-seal leaves no pending read-cut");
6890        let c = crate::db::community::load_community(&community.id).unwrap().unwrap();
6891        assert_eq!(c.server_root_epoch, crate::community::Epoch(1));
6892    }
6893
6894    #[tokio::test]
6895    async fn failed_reseal_sets_pending_then_sync_retry_recovers() {
6896        // The recoverability fix (closes the #5c-1 HIGH for the total-outage case): a private ban whose
6897        // read-cut re-seal FAILS (the base rekey can't reach relays) still applies the ban, marks
6898        // `read_cut_pending`, and propagates the error — then a later community sync retries the re-seal
6899        // and recovers (the banned member's read access is finally cut), with no manual re-ban.
6900        let (_tmp, _guard) = init_test_db();
6901        let relay = RekeyFailingRelay::new(); // the base rekey (3303) will fail; the banlist edition lands
6902        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6903        let cid = community.id.to_hex();
6904        let victim = "cc".repeat(32);
6905
6906        // The ban applies (banlist persisted) but the read-cut re-seal fails → Err + pending set, base not rotated.
6907        assert!(publish_banlist(&relay, &community, &[victim.clone()]).await.is_err(), "the re-seal's base rekey fails");
6908        assert!(crate::db::community::get_read_cut_pending(&cid).unwrap(), "a failed re-seal leaves read_cut_pending set");
6909        assert_eq!(crate::db::community::get_community_banlist(&cid).unwrap(), vec![victim.clone()], "the ban itself still applied");
6910        let c = crate::db::community::load_community(&community.id).unwrap().unwrap();
6911        assert_eq!(c.server_root_epoch, crate::community::Epoch(0), "base NOT rotated while the re-seal is pending");
6912
6913        // The relay recovers; the sync-path retry re-attempts the read-cut and succeeds.
6914        relay.allow_rekey();
6915        retry_pending_read_cut(&relay, &c).await.unwrap();
6916        assert!(!crate::db::community::get_read_cut_pending(&cid).unwrap(), "pending cleared after the retry succeeds");
6917        let c2 = crate::db::community::load_community(&community.id).unwrap().unwrap();
6918        assert_eq!(c2.server_root_epoch, crate::community::Epoch(1), "the read-cut finally rotated the base");
6919    }
6920
6921    #[tokio::test]
6922    async fn privatize_reseals_to_observed_participants_not_just_owner() {
6923        // Regression for the bech32-vs-hex recipient bug (B1): privatize must re-seal to the OBSERVED
6924        // participants (parsed from the events table's BECH32 npubs), not collapse to owner-only. Alice
6925        // posts → she's observed → after privatize she is a base-rekey recipient and recovers the new root.
6926        use crate::community::derive::{base_rekey_pseudonym, recipient_pseudonym};
6927        use crate::community::rekey::{open_rekey_blob, open_rekey_event, rekey_pairwise_secret};
6928        use crate::types::Message;
6929        use nostr_sdk::ToBech32;
6930        let (_tmp, _guard) = init_test_db();
6931        let relay = MemoryRelay::new();
6932        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6933        let cid = community.id.to_hex();
6934        let genesis_root = *community.server_root_key.as_bytes();
6935        let channel_hex = community.channels[0].id.to_hex();
6936
6937        // Alice posts in the channel → community_member_activity observes her (bech32 npub in events).
6938        let alice = Keys::generate();
6939        let alice_b32 = alice.public_key().to_bech32().unwrap();
6940        let mut m = Message::default();
6941        m.id = "aa".repeat(32);
6942        m.npub = Some(alice_b32.clone());
6943        m.at = 1000;
6944        crate::db::events::save_message(&channel_hex, &m).await.unwrap();
6945        assert!(
6946            crate::db::community::community_member_activity(&cid).unwrap().iter().any(|(np, _)| np == &alice_b32),
6947            "alice is an observed participant"
6948        );
6949
6950        // Mint a link → Public, then revoke it (last link) → privatize re-seals to {owner, alice}.
6951        let (token_hex, _) = create_public_invite(&relay, &community, None, None).await.unwrap();
6952        revoke_public_invite(&relay, &community, &crate::simd::hex::hex_to_bytes_32(&token_hex)).await.unwrap();
6953        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
6954        assert_eq!(reloaded.server_root_epoch, crate::community::Epoch(1), "privatize rotated the base");
6955
6956        // Alice MUST be a recipient of the base rekey → recovers the new root (with the B1 bug she'd be
6957        // sealed out, leaving only the owner).
6958        let addr = base_rekey_pseudonym(&crate::community::ServerRootKey(genesis_root), &community.id, crate::community::Epoch(1)).to_hex();
6959        let found = relay
6960            .fetch(&Query { kinds: vec![event_kind::COMMUNITY_REKEY], z_tags: vec![addr], ..Default::default() }, &community.relays)
6961            .await
6962            .unwrap();
6963        assert_eq!(found.len(), 1, "the base rekey is published");
6964        let parsed = open_rekey_event(&found[0], &genesis_root).unwrap();
6965        let secret = rekey_pairwise_secret(alice.secret_key(), &parsed.rotator).unwrap();
6966        let loc = recipient_pseudonym(&secret, parsed.scope, parsed.new_epoch).to_hex();
6967        let alice_blob = parsed.blobs.iter().find(|b| b.locator == loc).expect("alice's blob present (NOT sealed out)");
6968        let recovered = open_rekey_blob(alice.secret_key(), &parsed.rotator, parsed.scope, parsed.new_epoch, alice_blob).unwrap();
6969        assert_eq!(reloaded.server_root_key.as_bytes(), &recovered, "alice recovers the new root = owner's advanced base");
6970    }
6971
6972    #[tokio::test]
6973    async fn unpermissioned_invite_links_edition_is_rejected() {
6974        // authority: a creator's link edition counts only if they held CREATE_INVITE. A member without
6975        // it forging a link edition at their own coordinate (validly signed + version-shaped) is dropped
6976        // on fold — so an unpermissioned member can't flip the community Public.
6977        let (_tmp, _guard) = init_test_db();
6978        let relay = MemoryRelay::new();
6979        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
6980
6981        let mallory = Keys::generate();
6982        let loc = "2b".repeat(32);
6983        let inner = crate::community::roster::build_invite_links_edition(&mallory, &community.id, &[loc], 1, None, 1000, None).unwrap();
6984        let outer = crate::community::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, crate::community::Epoch(0)).unwrap();
6985        relay.inject(&outer, &community.relays);
6986
6987        let applied = fetch_and_apply_invite_links(&relay, &community).await.unwrap();
6988        assert!(applied.is_empty(), "an unpermissioned member's link edition is rejected");
6989        assert!(!is_public(&community).unwrap(), "mode stays Private despite the forged edition");
6990    }
6991
6992    #[tokio::test]
6993    async fn invite_links_union_across_authorized_creators() {
6994        // per-creator: the owner AND a granted admin (both hold CREATE_INVITE) each publish their OWN
6995        // link edition; the fold UNIONS both authorized creators' locators into the aggregate. Proves
6996        // multiple creators + non-owner authorization (no shared registry, no MANAGE_INVITES).
6997        let (_tmp, _guard) = init_test_db();
6998        let relay = MemoryRelay::new();
6999        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
7000        let cid = community.id.to_hex();
7001
7002        // Owner mints a link → their own per-creator edition.
7003        create_public_invite(&relay, &community, None, None).await.unwrap();
7004        let owner_loc = public_invite::locator_hex(&crate::simd::hex::hex_to_bytes_32(
7005            &crate::db::community::list_public_invites(&cid).unwrap()[0].token));
7006
7007        // Grant `admin` the Admin role (carries CREATE_INVITE), then inject THEIR own link edition.
7008        let admin = Keys::generate();
7009        let admin_role_id = crate::db::community::get_community_roles(&cid).unwrap().roles[0].role_id.clone();
7010        set_member_grant(&relay, &community, &admin.public_key().to_hex(), vec![admin_role_id]).await.unwrap();
7011        let admin_loc = "ab".repeat(32);
7012        let inner = crate::community::roster::build_invite_links_edition(&admin, &community.id, &[admin_loc.clone()], 1, None, 2000, None).unwrap();
7013        let outer = crate::community::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, crate::community::Epoch(0)).unwrap();
7014        relay.inject(&outer, &community.relays);
7015
7016        let agg = fetch_and_apply_invite_links(&relay, &community).await.unwrap();
7017        assert!(agg.contains(&owner_loc), "owner's link in the aggregate");
7018        assert!(agg.contains(&admin_loc), "the granted admin's link unions in too");
7019        assert!(is_public(&community).unwrap());
7020
7021        // B1: the owner revoking THEIR link must NOT privatize — the admin's link keeps it Public. The
7022        // revoke refreshes the aggregate from the relay first, so it sees the admin's still-live link even
7023        // if the local cache were stale. Base epoch stays 0 (no re-founding rekey).
7024        let c = crate::db::community::load_community(&community.id).unwrap().unwrap();
7025        let owner_token = crate::db::community::list_public_invites(&cid).unwrap()[0].token.clone();
7026        revoke_public_invite(&relay, &c, &crate::simd::hex::hex_to_bytes_32(&owner_token)).await.unwrap();
7027        let c = crate::db::community::load_community(&community.id).unwrap().unwrap();
7028        assert_eq!(c.server_root_epoch, crate::community::Epoch(0), "another creator's link remains → no privatize rekey");
7029        assert!(is_public(&c).unwrap(), "still Public (admin's link is live)");
7030    }
7031
7032    #[tokio::test]
7033    async fn failed_banlist_publish_does_not_persist_locally() {
7034        // Rollback honesty: if the ban edition never reaches relays, our local banlist must stay
7035        // untouched — else we'd one-sidedly drop a member's messages the rest of the community sees.
7036        let (_tmp, _guard) = init_test_db();
7037        let relay = MemoryRelay::new();
7038        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
7039        let id_hex = community.id.to_hex();
7040        assert!(crate::db::community::get_community_banlist(&id_hex).unwrap().is_empty());
7041
7042        let victim = "cc".repeat(32);
7043        let err = publish_banlist(&FailingRelay, &community, &[victim]).await;
7044        assert!(err.is_err(), "a failed publish must propagate");
7045        assert!(
7046            crate::db::community::get_community_banlist(&id_hex).unwrap().is_empty(),
7047            "local banlist must be untouched when the publish failed"
7048        );
7049    }
7050
7051    #[tokio::test]
7052    async fn metadata_failed_publish_does_not_persist_locally() {
7053        // Metadata is RELAY-AUTHORITATIVE now (`fetch_and_apply_metadata` is the consumer fold): a failed
7054        // publish must NOT save locally, else we'd show an edit no member can see (and the phantom-head
7055        // rule keeps the edition head from advancing too). Convergence is publish-then-fold, not re-publish.
7056        let (_tmp, _guard) = init_test_db();
7057        let relay = MemoryRelay::new();
7058        let mut community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
7059        community.name = "Renamed HQ".to_string();
7060        assert!(republish_community_metadata(&FailingRelay, &community).await.is_err());
7061        let loaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
7062        assert_eq!(loaded.name, "HQ", "a failed metadata publish leaves the local name unchanged");
7063    }
7064
7065    #[tokio::test]
7066    async fn send_persists_key_then_delete_round_trip() {
7067        let (_tmp, _guard) = init_test_db();
7068        let relay = MemoryRelay::new();
7069        let community = Community::create("HQ", "general", vec!["r1".into()]);
7070        let channel = community.channels[0].clone();
7071        let alice = Keys::generate();
7072
7073        // send_message persists the ephemeral key keyed by the INNER message id...
7074        let _outer = send_message(&relay, &community, &channel, &alice, "deletable", 1).await.unwrap();
7075        let before = fetch_channel_messages(&relay, &community, &channel).await.unwrap();
7076        assert_eq!(before.len(), 1);
7077        let message_id = before[0].message_id.to_hex();
7078
7079        // ...so delete_message (by inner message id, what the UI holds) removes it.
7080        delete_message(&relay, &message_id).await.unwrap();
7081        let after = fetch_channel_messages(&relay, &community, &channel).await.unwrap();
7082        assert!(after.is_empty(), "message should be deleted after delete_message");
7083
7084        // The key is single-use: a second delete finds nothing retained.
7085        assert!(delete_message(&relay, &message_id).await.is_err());
7086    }
7087
7088    #[tokio::test]
7089    async fn failed_delete_publish_preserves_key() {
7090        // B2: the deletion key is single-use, so a FAILED NIP-09 publish must NOT consume
7091        // it — otherwise the message is permanently undeletable.
7092        let (_tmp, _guard) = init_test_db();
7093        let relay = MemoryRelay::new();
7094        let community = Community::create("HQ", "general", vec!["r1".into()]);
7095        let channel = community.channels[0].clone();
7096        let alice = Keys::generate();
7097        send_message(&relay, &community, &channel, &alice, "delete me", 1).await.unwrap();
7098        let message_id = fetch_channel_messages(&relay, &community, &channel).await.unwrap()[0]
7099            .message_id
7100            .to_hex();
7101
7102        // Delete via a transport whose publish fails → error, key retained.
7103        assert!(delete_message(&FailingRelay, &message_id).await.is_err());
7104
7105        // The key survived, so a retry over a working relay succeeds.
7106        delete_message(&relay, &message_id).await.unwrap();
7107        assert!(fetch_channel_messages(&relay, &community, &channel).await.unwrap().is_empty());
7108    }
7109
7110    #[tokio::test]
7111    async fn delete_unknown_message_errors() {
7112        let (_tmp, _guard) = init_test_db();
7113        let relay = MemoryRelay::new();
7114        // A message id we never sent → no retained key → error, no panic.
7115        let fake = Keys::generate();
7116        let bogus = EventBuilder::new(Kind::Custom(1), "x").sign_with_keys(&fake).unwrap().id;
7117        assert!(delete_message(&relay, &bogus.to_hex()).await.is_err());
7118    }
7119
7120    #[tokio::test]
7121    async fn accept_invite_persists_member_view() {
7122        let (_tmp, _guard) = init_test_db();
7123        let owner = Community::create("HQ", "general", vec!["r1".into()]);
7124        let invite = crate::community::invite::build_invite(&owner);
7125
7126        let joined = accept_invite(&invite).expect("accept");
7127        assert!(!is_proven_owner(&joined), "joined as member, not owner");
7128        // Persisted + reloadable with the same read keys.
7129        let loaded = crate::db::community::load_community(&owner.id).unwrap().expect("saved");
7130        assert_eq!(loaded.channels[0].key.as_bytes(), owner.channels[0].key.as_bytes());
7131    }
7132
7133    #[tokio::test]
7134    async fn accept_invite_does_not_downgrade_owned_community() {
7135        // We OWN a Community (proven via the owner attestation); an invite reusing its id must be
7136        // refused so it can't overwrite our row.
7137        let (_tmp, _guard) = init_test_db();
7138        let relay = MemoryRelay::new();
7139        let owner = create_community(&relay, "HQ", "general", vec![]).await.unwrap();
7140        assert!(is_proven_owner(&owner), "we are the proven owner");
7141
7142        let invite = crate::community::invite::build_invite(&owner);
7143        let err = accept_invite(&invite).unwrap_err();
7144        assert!(err.contains("already own"), "must refuse to downgrade an owned community, got: {err}");
7145
7146        // The owner row is intact (same server-root key).
7147        let reloaded = crate::db::community::load_community(&owner.id).unwrap().unwrap();
7148        assert_eq!(reloaded.server_root_key.as_bytes(), owner.server_root_key.as_bytes());
7149    }
7150
7151    #[tokio::test]
7152    async fn accept_invite_rejects_id_collision_under_different_authority() {
7153        // We hold Community X as a MEMBER (authority pubkey A). A hostile bundle reuses
7154        // X's id but names a DIFFERENT authority + channel keys. It must be rejected so
7155        // our keys/authority/relays can't be silently swapped (community_id is
7156        // unauthenticated random bytes).
7157        let (_tmp, _guard) = init_test_db();
7158        let legit = Community::create("X", "general", vec!["wss://legit".into()]);
7159        let member_x = accept_invite(&crate::community::invite::build_invite(&legit)).unwrap();
7160        let original_key = member_x.channels[0].key.as_bytes().to_vec();
7161
7162        // Attacker's own Community, then forge its id to collide with X.
7163        let attacker = Community::create("evil", "general", vec!["wss://evil".into()]);
7164        let mut hostile = crate::community::invite::build_invite(&attacker);
7165        hostile.community_id = legit.id.to_hex();
7166        // The attacker's bundle carries its OWN server-root key, which differs from X's — the
7167        // keyless authority anchor the dedup compares.
7168        assert_ne!(hostile.server_root_key, crate::simd::hex::bytes_to_hex_32(member_x.server_root_key.as_bytes()));
7169
7170        assert!(accept_invite(&hostile).is_err(), "id-collision under new authority must be rejected");
7171
7172        // X's stored channel key is unchanged.
7173        let reloaded = crate::db::community::load_community(&legit.id).unwrap().unwrap();
7174        assert_eq!(reloaded.channels[0].key.as_bytes().to_vec(), original_key);
7175        assert_eq!(reloaded.relays, vec!["wss://legit".to_string()]);
7176    }
7177
7178    #[tokio::test]
7179    async fn rejected_accept_leaves_pending_invite_intact() {
7180        // Mirrors the accept command's peek→accept→(delete only on success) order: a
7181        // rejected accept must NOT destroy the parked invite (no silent data loss).
7182        let (_tmp, _guard) = init_test_db();
7183
7184        // We own this community (proven via the attestation), so an invite reusing its id is rejected.
7185        let owner = attested_community("HQ", "general", vec![]);
7186        crate::db::community::save_community(&owner).unwrap();
7187        let bundle = crate::community::invite::build_invite(&owner).to_json().unwrap();
7188        let cid = owner.id.to_hex();
7189        crate::db::community::save_pending_invite(&cid, &bundle, "npub1inviter").unwrap();
7190
7191        // Command sequence: peek (no delete) → accept (errs) → row survives.
7192        let peeked = crate::db::community::get_pending_invite(&cid).unwrap().expect("parked");
7193        let invite = crate::community::invite::CommunityInvite::from_json(&peeked).unwrap();
7194        assert!(accept_invite(&invite).is_err(), "owning the id → reject");
7195        assert!(
7196            crate::db::community::pending_invite_exists(&cid).unwrap(),
7197            "rejected accept must leave the invite parked"
7198        );
7199
7200        // A successful accept (community we don't already hold) clears the row.
7201        let other = Community::create("Other", "general", vec![]);
7202        let ob = crate::community::invite::build_invite(&other).to_json().unwrap();
7203        let ocid = other.id.to_hex();
7204        crate::db::community::save_pending_invite(&ocid, &ob, "npub1inviter").unwrap();
7205        let op = crate::db::community::get_pending_invite(&ocid).unwrap().unwrap();
7206        let oinvite = crate::community::invite::CommunityInvite::from_json(&op).unwrap();
7207        accept_invite(&oinvite).expect("accept ok");
7208        crate::db::community::delete_pending_invite(&ocid).unwrap();
7209        assert!(!crate::db::community::pending_invite_exists(&ocid).unwrap(), "cleared on success");
7210    }
7211
7212    #[tokio::test]
7213    async fn public_invite_create_fetch_accept_revoke_round_trip() {
7214        let (_tmp, _guard) = init_test_db();
7215        let relay = MemoryRelay::new();
7216        let mut owner = Community::create("Public HQ", "general", vec!["r1".into(), "r2".into()]);
7217        owner.description = Some("everyone welcome".into());
7218        // Sign the owner attestation with the seeded identity so `create_public_invite`'s proven-owner
7219        // gate passes. The owner community is in-memory only here (create_public_invite persists the
7220        // token, not the community), so this single DB cleanly plays the joiner on accept.
7221        let owner_keys = crate::state::MY_SECRET_KEY.to_keys().unwrap();
7222        owner.owner_attestation = Some(
7223            crate::community::owner::build_owner_attestation_unsigned(owner_keys.public_key(), &owner.id.to_hex())
7224                .sign_with_keys(&owner_keys).unwrap().as_json(),
7225        );
7226        // Owner mints a link.
7227        let (token_hex, url) = create_public_invite(&relay, &owner, None, None).await.expect("mint");
7228        assert!(url.contains('#'));
7229        assert_eq!(crate::db::community::list_public_invites(&owner.id.to_hex()).unwrap().len(), 1);
7230
7231        // A joiner parses the URL → fetches → previews → accepts.
7232        let (relays, token) = public_invite::parse_invite_url(&url).unwrap();
7233        assert_eq!(crate::simd::hex::bytes_to_hex_32(&token), token_hex);
7234        let bundle = fetch_public_invite(&relay, &relays, &token).await.expect("fetch");
7235        assert_eq!(bundle.preview.name, "Public HQ");
7236        assert_eq!(bundle.preview.description.as_deref(), Some("everyone welcome"));
7237
7238        let joined = accept_public_invite(&bundle, 0).expect("accept");
7239        assert_eq!(joined.id, owner.id);
7240        assert_eq!(joined.description.as_deref(), Some("everyone welcome"), "preview patched in");
7241
7242        // Owner revokes the last link → the link no longer resolves AND the community re-founds (Private).
7243        revoke_public_invite(&relay, &owner, &token).await.expect("revoke");
7244        assert!(fetch_public_invite(&relay, &relays, &token).await.is_err(), "revoked link is dead");
7245        assert!(crate::db::community::list_public_invites(&owner.id.to_hex()).unwrap().is_empty());
7246    }
7247
7248    #[tokio::test]
7249    async fn revoked_invite_dies_even_if_one_relay_kept_the_bundle() {
7250        // Mixed-relay race (the exact case the tombstone defends): the tombstone replaces the bundle on r1,
7251        // but r2 was down during revoke and still serves the live bundle. fetch must STILL report the link
7252        // dead — a token-signed Revoked tombstone on ANY relay is authoritative and wins ties with a bundle.
7253        let (_tmp, _guard) = init_test_db();
7254        let relay = MemoryRelay::new();
7255        let owner = attested_community("HQ", "general", vec!["r1".into(), "r2".into()]);
7256        let (_token_hex, url) = create_public_invite(&relay, &owner, None, None).await.unwrap();
7257        let (relays, token) = public_invite::parse_invite_url(&url).unwrap();
7258        assert!(fetch_public_invite(&relay, &relays, &token).await.is_ok(), "live on both relays");
7259
7260        // The tombstone reaches ONLY r1 (replaces the bundle there); r2 still has the live bundle.
7261        let tombstone = public_invite::build_public_invite_tombstone(&token).unwrap();
7262        relay.inject(&tombstone, &["r1".to_string()]);
7263
7264        assert!(
7265            fetch_public_invite(&relay, &relays, &token).await.is_err(),
7266            "a tombstone on any one relay kills the link, even with a stale live bundle elsewhere",
7267        );
7268    }
7269
7270    #[tokio::test]
7271    async fn fetch_skips_relay_shadow_junk_to_genuine_bundle() {
7272        // A hostile relay piles a NEWER event at the same locator d-tag, signed by a
7273        // different key (relay-shadow attack). fetch must skip it (fails token verify)
7274        // and still surface the genuine bundle, not report "no invite".
7275        use nostr_sdk::prelude::{EventBuilder, Keys, Kind, Tag, TagKind, Timestamp};
7276
7277        let (_tmp, _guard) = init_test_db();
7278        let relay = MemoryRelay::new();
7279        let owner = attested_community("HQ", "general", vec!["r1".into()]);
7280        let (_t, url) = create_public_invite(&relay, &owner, None, None).await.unwrap();
7281        let (relays, token) = public_invite::parse_invite_url(&url).unwrap();
7282
7283        // Attacker posts junk at the same locator with a far-future created_at so it
7284        // sorts newest.
7285        let attacker = Keys::generate();
7286        let junk = EventBuilder::new(Kind::Custom(event_kind::APPLICATION_SPECIFIC), "garbage")
7287            .tags([
7288                Tag::identifier(public_invite::locator_hex(&token)),
7289                Tag::custom(TagKind::Custom("vsk".into()), ["6".to_string()]),
7290                Tag::custom(TagKind::Custom("v".into()), ["1".to_string()]),
7291            ])
7292            .custom_created_at(Timestamp::from_secs(9_000_000_000))
7293            .sign_with_keys(&attacker)
7294            .unwrap();
7295        relay.publish(&junk, &relays).await.unwrap();
7296
7297        // Genuine bundle is still found despite the newer shadow.
7298        let bundle = fetch_public_invite(&relay, &relays, &token).await.expect("genuine survives shadow");
7299        assert_eq!(bundle.preview.name, "HQ");
7300    }
7301
7302    #[tokio::test]
7303    async fn expired_public_invite_is_refused() {
7304        let (_tmp, _guard) = init_test_db();
7305        let relay = MemoryRelay::new();
7306        let owner = attested_community("HQ", "general", vec!["r1".into()]);
7307        let (_t, url) = create_public_invite(&relay, &owner, Some(1000), None).await.unwrap();
7308        let (relays, token) = public_invite::parse_invite_url(&url).unwrap();
7309        let bundle = fetch_public_invite(&relay, &relays, &token).await.unwrap();
7310        // Past expiry → accept refuses, nothing joined.
7311        assert!(accept_public_invite(&bundle, 2000).is_err());
7312        assert!(crate::db::community::load_community(&owner.id).unwrap().is_none());
7313    }
7314
7315    #[tokio::test]
7316    async fn republish_metadata_saves_and_publishes() {
7317        use crate::community::CommunityImage;
7318        let (_tmp, _guard) = init_test_db();
7319        let relay = MemoryRelay::new();
7320        // create_community mints the owner attestation (the seeded vault identity is the owner) and the
7321        // genesis GroupRoot edition (v1) — so the owner is proven + holds MANAGE_METADATA implicitly.
7322        let mut owner = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
7323        let cid = owner.id.to_hex();
7324
7325        // Edit name + description + icon, republish (publishes the GroupRoot edition at v2).
7326        owner.name = "HQ Renamed".into();
7327        owner.description = Some("now with topic".into());
7328        owner.icon = Some(CommunityImage {
7329            url: "https://b/x".into(), key: "aa".repeat(32), nonce: "bb".repeat(12),
7330            hash: "cc".repeat(32), ext: "png".into(),
7331        });
7332        republish_community_metadata(&relay, &owner).await.expect("republish");
7333
7334        // Persisted locally.
7335        let loaded = crate::db::community::load_community(&owner.id).unwrap().unwrap();
7336        assert_eq!(loaded.name, "HQ Renamed");
7337        assert_eq!(loaded.description.as_deref(), Some("now with topic"));
7338        assert_eq!(loaded.icon.unwrap().url, "https://b/x");
7339
7340        // The GroupRoot edition advanced to v2 and carries the new metadata. Fetch the control plane,
7341        // fold the GroupRoot entity (entity_id == community_id), confirm the head + content.
7342        let (head_v, _) = crate::db::community::get_edition_head(&cid, &cid).unwrap().unwrap();
7343        assert_eq!(head_v, 2, "GroupRoot edition advanced v1 (create) → v2 (republish)");
7344        let z = crate::community::roster::control_pseudonym(&owner.server_root_key, &owner.id, crate::community::Epoch(0));
7345        let control = relay
7346            .fetch(&Query { kinds: vec![event_kind::COMMUNITY_CONTROL], z_tags: vec![z], ..Default::default() }, &owner.relays)
7347            .await
7348            .unwrap();
7349        let newest = control
7350            .iter()
7351            .filter_map(|o| crate::community::roster::open_control_edition(o, &owner.server_root_key).ok())
7352            .filter_map(|i| crate::community::edition::parse_edition_inner(&i).ok())
7353            .filter(|p| p.entity_id == owner.id.0)
7354            .max_by_key(|p| p.version)
7355            .expect("GroupRoot edition on the relay");
7356        let meta: crate::community::metadata::CommunityMetadata = serde_json::from_str(&newest.content).unwrap();
7357        assert_eq!(meta.name, "HQ Renamed");
7358        assert_eq!(meta.icon.unwrap().ext, "png");
7359    }
7360
7361    #[tokio::test]
7362    async fn member_cannot_republish_metadata() {
7363        let (_tmp, _guard) = init_test_db();
7364        let relay = MemoryRelay::new();
7365        let owner = Community::create("HQ", "general", vec!["r1".into()]);
7366        let member = crate::community::invite::accept_invite(&crate::community::invite::build_invite(&owner)).unwrap();
7367        assert!(republish_community_metadata(&relay, &member).await.is_err());
7368    }
7369
7370    #[tokio::test]
7371    async fn member_cannot_mint_public_invite() {
7372        let (_tmp, _guard) = init_test_db();
7373        let relay = MemoryRelay::new();
7374        let owner = Community::create("HQ", "general", vec!["r1".into()]);
7375        let member = crate::community::invite::accept_invite(&crate::community::invite::build_invite(&owner)).unwrap();
7376        assert!(create_public_invite(&relay, &member, None, None).await.is_err(), "members can't mint links");
7377    }
7378
7379    #[tokio::test]
7380    async fn accept_oversized_bundle_rejected() {
7381        let (_tmp, _guard) = init_test_db();
7382        let owner = Community::create("HQ", "general", vec![]);
7383        let mut invite = crate::community::invite::build_invite(&owner);
7384        // Blow past the channel cap.
7385        let template = invite.channels[0].clone();
7386        for _ in 0..300 {
7387            invite.channels.push(template.clone());
7388        }
7389        assert!(accept_invite(&invite).is_err(), "oversized bundle must be rejected");
7390        assert!(crate::db::community::load_community(&owner.id).unwrap().is_none(), "nothing persisted");
7391    }
7392
7393    // --- owner dissolution (GroupDissolved tombstone) ---
7394
7395    /// Seal + publish a GroupDissolved tombstone (vsk=10) authored by `author` to the community's control
7396    /// plane at the CURRENT epoch, so a subsequent `fetch_and_apply_control` folds it. `created_at` is
7397    /// caller-chosen so a test can prove backdating doesn't gate the binary seal.
7398    async fn publish_tombstone<T: Transport + ?Sized>(transport: &T, community: &Community, author: &Keys, created_at: u64) {
7399        let inner = crate::community::roster::build_group_dissolved_edition_unsigned(author.public_key(), &community.id, created_at)
7400            .sign_with_keys(author).unwrap();
7401        let outer = crate::community::roster::seal_control_edition(&Keys::generate(), &inner, &community.server_root_key, &community.id, community.server_root_epoch).unwrap();
7402        transport.publish_durable(&outer, &community.relays).await.unwrap();
7403    }
7404
7405    /// A relay wrapping MemoryRelay that COUNTS rekey (3303) publishes — for asserting dissolution emits
7406    /// none. Everything else delegates to the inner relay.
7407    struct RekeyCountingRelay {
7408        inner: MemoryRelay,
7409        rekeys: std::sync::atomic::AtomicUsize,
7410    }
7411    impl RekeyCountingRelay {
7412        fn new() -> Self { Self { inner: MemoryRelay::new(), rekeys: std::sync::atomic::AtomicUsize::new(0) } }
7413        fn count(&self, e: &Event) {
7414            if e.kind.as_u16() == event_kind::COMMUNITY_REKEY {
7415                self.rekeys.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7416            }
7417        }
7418    }
7419    #[async_trait::async_trait]
7420    impl Transport for RekeyCountingRelay {
7421        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> { self.count(e); self.inner.publish(e, r).await }
7422        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> { self.count(e); self.inner.publish_durable(e, r).await }
7423        async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> { self.inner.fetch(q, r).await }
7424    }
7425
7426    #[tokio::test]
7427    async fn owner_tombstone_folds_to_dissolved() {
7428        let (_tmp, _guard) = init_test_db();
7429        let relay = MemoryRelay::new();
7430        // The seeded local identity is the proven owner of a created community.
7431        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
7432        let cid = community.id.to_hex();
7433        let owner = crate::state::MY_SECRET_KEY.to_keys().unwrap();
7434        publish_tombstone(&relay, &community, &owner, 1000).await;
7435
7436        assert!(!crate::db::community::get_community_dissolved(&cid).unwrap(), "alive before the fold");
7437        fetch_and_apply_control(&relay, &community).await.unwrap();
7438        assert!(crate::db::community::get_community_dissolved(&cid).unwrap(), "owner tombstone seals the community");
7439    }
7440
7441    #[tokio::test]
7442    async fn non_owner_tombstone_is_ignored() {
7443        let (_tmp, _guard) = init_test_db();
7444        let relay = MemoryRelay::new();
7445        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
7446        let cid = community.id.to_hex();
7447        // A BAN-capable admin is NOT enough: dissolution is the owner's call alone. A random
7448        // non-owner author publishing the tombstone must be rejected.
7449        let mallory = Keys::generate();
7450        publish_tombstone(&relay, &community, &mallory, 1000).await;
7451
7452        fetch_and_apply_control(&relay, &community).await.unwrap();
7453        assert!(!crate::db::community::get_community_dissolved(&cid).unwrap(), "a non-owner tombstone is ignored");
7454    }
7455
7456    #[tokio::test]
7457    async fn unreadable_deed_rejects_the_tombstone() {
7458        let (_tmp, _guard) = init_test_db();
7459        let relay = MemoryRelay::new();
7460        let owner = crate::state::MY_SECRET_KEY.to_keys().unwrap();
7461        let mut community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
7462        let cid = community.id.to_hex();
7463        publish_tombstone(&relay, &community, &owner, 1000).await;
7464        // Strip the deed: the owner can no longer be derived → fail-closed, the tombstone is unverifiable.
7465        community.owner_attestation = None;
7466        crate::db::community::save_community(&community).unwrap();
7467        let stripped = crate::db::community::load_community(&community.id).unwrap().unwrap();
7468
7469        fetch_and_apply_control(&relay, &stripped).await.unwrap();
7470        assert!(!crate::db::community::get_community_dissolved(&cid).unwrap(), "unverifiable tombstone is rejected, not death-by-default");
7471    }
7472
7473    #[tokio::test]
7474    async fn binary_seal_drops_every_subsequent_event_with_no_timestamp_test() {
7475        let (_tmp, _guard) = init_test_db();
7476        let relay = MemoryRelay::new();
7477        let owner = crate::state::MY_SECRET_KEY.to_keys().unwrap();
7478        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
7479        let cid = community.id.to_hex();
7480        publish_tombstone(&relay, &community, &owner, 1000).await;
7481        fetch_and_apply_control(&relay, &community).await.unwrap();
7482        assert!(crate::db::community::get_community_dissolved(&cid).unwrap());
7483
7484        // The channel reloaded after the seal carries the denormalized dissolved flag → inbound drops all.
7485        let sealed = crate::db::community::load_community(&community.id).unwrap().unwrap();
7486        let channel = sealed.channels[0].clone();
7487        let me = owner.public_key();
7488
7489        // A subsequent message — even BACKDATED before the tombstone — is dropped (no created_at gate).
7490        let backdated = super::super::envelope::seal_message(
7491            &Keys::generate(), &channel.key, &channel.id, channel.epoch, "ghost", 1,
7492        ).unwrap();
7493        let mut state = crate::state::ChatState::new();
7494        assert!(super::super::inbound::process_incoming(&mut state, &backdated, &channel, &me).is_none(),
7495            "a backdated message after the seal is dropped (binary seal, no timestamp test)");
7496
7497        // A subsequent control edition does not advance the fold either (it short-circuits on the flag).
7498        publish_tombstone(&relay, &sealed, &owner, 2000).await;
7499        assert_eq!(fetch_and_apply_control(&relay, &sealed).await.unwrap(), 0,
7500            "control fold stops advancing once sealed");
7501    }
7502
7503    #[tokio::test]
7504    async fn dissolve_community_emits_no_rekey_and_no_epoch_bump() {
7505        let (_tmp, _guard) = init_test_db();
7506        let relay = RekeyCountingRelay::new();
7507        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
7508        let cid = community.id.to_hex();
7509        // Mint a public link so the link-retire path actually runs (and must NOT privatize-rekey).
7510        create_public_invite(&relay, &community, None, None).await.unwrap();
7511        let before_epoch = crate::db::community::load_community(&community.id).unwrap().unwrap().server_root_epoch;
7512
7513        dissolve_community(&relay, &community).await.unwrap();
7514
7515        assert!(crate::db::community::get_community_dissolved(&cid).unwrap(), "sealed locally");
7516        assert_eq!(relay.rekeys.load(std::sync::atomic::Ordering::Relaxed), 0,
7517            "dissolution publishes NO 3303 rekey (no last-link privatize re-founding)");
7518        assert_eq!(crate::db::community::load_community(&community.id).unwrap().unwrap().server_root_epoch, before_epoch,
7519            "base epoch unchanged — dissolution rotates nothing");
7520    }
7521
7522    #[tokio::test]
7523    async fn duplicate_owner_tombstones_are_idempotent() {
7524        let (_tmp, _guard) = init_test_db();
7525        let relay = MemoryRelay::new();
7526        let owner = crate::state::MY_SECRET_KEY.to_keys().unwrap();
7527        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
7528        let cid = community.id.to_hex();
7529        // Two owner tombstones (distinct created_at → distinct inner ids) at the locator.
7530        publish_tombstone(&relay, &community, &owner, 1000).await;
7531        publish_tombstone(&relay, &community, &owner, 2000).await;
7532
7533        fetch_and_apply_control(&relay, &community).await.unwrap();
7534        assert!(crate::db::community::get_community_dissolved(&cid).unwrap(), "duplicates still just dissolve, no error");
7535        // A second fold over the same plane is a harmless no-op (already sealed).
7536        assert_eq!(fetch_and_apply_control(&relay, &community).await.unwrap(), 0);
7537    }
7538
7539    #[test]
7540    fn apply_server_root_rekey_refuses_once_dissolved() {
7541        let (_tmp, _guard) = init_test_db();
7542        let owner = Keys::generate();
7543        let me = Keys::generate();
7544        become_local(&me);
7545        let community = saved_community_owned_by(&owner);
7546        let cid = community.id.to_hex();
7547        crate::db::community::set_community_dissolved(&cid).unwrap();
7548
7549        let parsed = owner_base_rekey(&owner, &community, &me.public_key(), 1, &[0xCDu8; 32]);
7550        assert!(apply_server_root_rekey(&community, &parsed).is_err(),
7551            "a base rekey cannot cross a tombstone");
7552        assert_eq!(crate::db::community::load_community(&community.id).unwrap().unwrap().server_root_epoch,
7553            crate::community::Epoch(0), "base epoch did not advance");
7554    }
7555
7556    #[tokio::test]
7557    async fn tombstone_detected_after_a_base_rotation() {
7558        let (_tmp, _guard) = init_test_db();
7559        let relay = MemoryRelay::new();
7560        let owner = crate::state::MY_SECRET_KEY.to_keys().unwrap();
7561        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
7562        let cid = community.id.to_hex();
7563        // Re-found the base (epoch 0 → 1); the dissolved locator is rotation-STABLE, so a tombstone
7564        // published AFTER the rotation (sealed under the new root) is still found by a post-rotation client.
7565        rotate_server_root(&relay, &community, &[owner.public_key()]).await.unwrap();
7566        let rotated = crate::db::community::load_community(&community.id).unwrap().unwrap();
7567        assert_eq!(rotated.server_root_epoch, crate::community::Epoch(1));
7568        publish_tombstone(&relay, &rotated, &owner, 1000).await;
7569
7570        fetch_and_apply_control(&relay, &rotated).await.unwrap();
7571        assert!(crate::db::community::get_community_dissolved(&cid).unwrap(),
7572            "tombstone at the rotation-stable locator is detected post-rotation");
7573    }
7574
7575    #[tokio::test]
7576    async fn stable_coordinate_tombstone_survives_a_concurrent_rotation() {
7577        // Cross-epoch: a tombstone published ONLY at the rotation-stable coordinate is
7578        // discovered by a client that has since advanced to a LATER epoch — whose control_pseudonym differs,
7579        // so the tombstone is NOT in that epoch's control fold. Only the stable-coordinate probe can find it.
7580        // This is the case a concurrent re-founding creates (tombstone at epoch N, joiner on epoch N+1).
7581        let (_tmp, _guard) = init_test_db();
7582        let relay = MemoryRelay::new();
7583        let owner = crate::state::MY_SECRET_KEY.to_keys().unwrap();
7584        let community = create_community(&relay, "HQ", "general", vec!["r1".into()]).await.unwrap();
7585        let cid = community.id.to_hex();
7586        // Owner publishes the tombstone ONLY at the stable coordinate (no control_pseudonym copy).
7587        let inner = crate::community::roster::build_group_dissolved_edition_unsigned(owner.public_key(), &community.id, 1000)
7588            .sign_with_keys(&owner).unwrap();
7589        let stable = crate::community::roster::seal_dissolved_edition(&Keys::generate(), &inner, &community.id).unwrap();
7590        relay.inject(&stable, &community.relays);
7591        // Advance the base epoch (the local client hasn't folded the tombstone yet, so rotation is allowed —
7592        // exactly the concurrent-re-founder's state). The control_pseudonym now differs from epoch 0's.
7593        rotate_server_root(&relay, &community, &[owner.public_key()]).await.unwrap();
7594        let rotated = crate::db::community::load_community(&community.id).unwrap().unwrap();
7595        assert_eq!(rotated.server_root_epoch, crate::community::Epoch(1));
7596        assert!(!crate::db::community::get_community_dissolved(&cid).unwrap(), "not folded yet");
7597        // Fetch control at the NEW epoch: the tombstone is absent from this control_pseudonym; only the
7598        // stable-coordinate probe can surface it.
7599        fetch_and_apply_control(&relay, &rotated).await.unwrap();
7600        assert!(crate::db::community::get_community_dissolved(&cid).unwrap(),
7601            "stable-coordinate probe discovers the tombstone cross-epoch (C3 closed)");
7602    }
7603}