Skip to main content

vector_core/
lib.rs

1//! Vector Core — the single source of truth for all Vector clients, SDKs, and interfaces.
2//!
3//! This crate contains ALL of Vector's business logic, fully decoupled from Tauri.
4//! It can be used by:
5//! - **src-tauri**: The Tauri desktop/mobile app (thin command shell)
6//! - **vector-cli**: Command-line interface
7//! - **Vector SDK**: Bot and client libraries
8//! - Any future interface (web, embedded, etc.)
9//!
10//! # Architecture
11//!
12//! ```text
13//! ┌─────────────────────────────────────────────┐
14//! │              vector-core                     │
15//! │                                              │
16//! │  types ─ compact ─ state ─ db ─ crypto       │
17//! │  chat ─ profile ─ net ─ hex                  │
18//! │                                              │
19//! │  traits::EventEmitter (UI abstraction)       │
20//! │  VectorCore (high-level API)                 │
21//! └─────────────────────────────────────────────┘
22//!        ▲              ▲              ▲
23//!   src-tauri       vector-cli     Vector SDK
24//! (AppHandle)      (terminal)     (callbacks)
25//! ```
26
27// === Logging (must be first — #[macro_export] macros used by all modules) ===
28#[macro_use]
29mod macros;
30
31// === Foundation ===
32pub mod logging;
33pub mod error;
34pub mod traits;
35
36// Nostr SDK trait imports needed for bech32 operations
37use crate::event_ext::FinalizeUnsignedWithId;
38use nostr_sdk::prelude::{FinalizeEventAsync, ToBech32};
39
40// === Core Types ===
41pub mod event_ext;
42pub mod tags;
43pub mod types;
44pub mod profile;
45pub mod chat;
46pub mod compact;
47
48// === State ===
49pub mod state;
50
51// === Debug Stats ===
52#[cfg(debug_assertions)]
53pub mod stats;
54
55// === Crypto ===
56pub mod crypto;
57
58// === Signer (polymorphic: local vault vs. NIP-46 remote bunker) ===
59pub mod signer;
60
61// === NIP-55 offline signer (on-device Amber over Android IPC) ===
62pub mod nip55;
63
64// === Database ===
65pub mod db;
66
67// === Network ===
68pub mod net;
69pub mod negentropy;
70pub mod blossom;
71pub mod blossom_servers;
72pub mod blossom_capabilities;
73pub mod inbox_relays;
74pub mod emoji_packs;
75pub mod emoji_usage;
76pub mod badges;
77pub mod bot_interface;
78pub mod webxdc;
79#[cfg(feature = "tor")]
80pub mod tor;
81
82/// NIP-42 authenticator.
83///
84/// Many Concord/Armada communities live on AUTH-gating relays (Ditto's default
85/// gates kind-1059), where an unauthenticated client silently reads back ZERO
86/// events — a join's control-plane verify then fails closed and every community
87/// fetch comes up empty. Registering this is what unlocks those reads; a relay
88/// that doesn't challenge is unaffected.
89///
90/// The signer is resolved per challenge rather than captured at client
91/// construction, so a bunker that connects later (or an account swap) authks
92/// under the identity that is live *now*.
93#[derive(Debug)]
94pub struct VectorAuthenticator;
95
96impl nostr_sdk::prelude::Authenticator for VectorAuthenticator {
97    fn make_auth_event<'a>(
98        &'a self,
99        relay_url: &'a nostr_sdk::prelude::RelayUrl,
100        challenge: &'a str,
101    ) -> signer::BoxedFuture<'a, std::result::Result<nostr_sdk::prelude::Event, nostr_sdk::prelude::Error>>
102    {
103        Box::pin(async move {
104            let signer =
105                signer::active_signer().map_err(nostr_sdk::prelude::Error::other)?;
106            Ok(
107                nostr_sdk::prelude::ClientAuthentication::new(challenge, relay_url.clone())
108                    .finalize_async(&signer)
109                    .await?,
110            )
111        })
112    }
113}
114
115/// A `ClientBuilder` carrying Vector's client-wide policy: NIP-42 auth plus the
116/// embedded-Tor SOCKS proxy.
117///
118/// Callers should start from this rather than `ClientBuilder::new()` so both come
119/// along automatically.
120///
121/// The proxy is a closure, not a fixed address: nostr resolves it per connection
122/// attempt, so it reads the *current* Tor state. That covers relays added later
123/// in the session, which previously needed the transport re-applied per
124/// `add_relay`.
125pub fn nostr_client_builder() -> nostr_sdk::prelude::ClientBuilder {
126    apply_tor_proxy(
127        nostr_sdk::prelude::ClientBuilder::new()
128            .authenticator(VectorAuthenticator)
129            // The pool's own attempts need the Tor floor too, not just our explicit
130            // `try_connect` calls (0.45 default is 15s — under a circuit build).
131            .connect_timeout(relay_connect_timeout(std::time::Duration::from_secs(15))),
132    )
133}
134
135/// Register a relay with the pool's own auto-reconnect disabled.
136///
137/// Vector drives every reconnect from its reconcile loop, because it needs the
138/// connection lifecycle to be observable and to sequence with health checks and
139/// the Tor transport switch. The pool's retry is invisible to all of that, so two
140/// schedules end up fighting over one socket.
141///
142/// This exists as a helper rather than a per-call `.reconnect(false)` because
143/// `reconnect` is the one relay option `ClientBuilder` cannot default: it lives
144/// only on `RelayOptions`, so every registration site has to opt out by hand, and
145/// most of them silently didn't.
146pub trait ClientRelayExt {
147    /// `Client::add_relay` with `reconnect(false)` already applied.
148    fn add_managed_relay<'client, 'url, U>(
149        &'client self,
150        url: U,
151    ) -> nostr_sdk::prelude::AddRelay<'client, 'url>
152    where
153        U: Into<nostr_sdk::prelude::RelayUrlArg<'url>>;
154}
155
156impl ClientRelayExt for nostr_sdk::prelude::Client {
157    fn add_managed_relay<'client, 'url, U>(
158        &'client self,
159        url: U,
160    ) -> nostr_sdk::prelude::AddRelay<'client, 'url>
161    where
162        U: Into<nostr_sdk::prelude::RelayUrlArg<'url>>,
163    {
164        self.add_relay(url).reconnect(false)
165    }
166}
167
168/// Re-send every live subscription this relay is supposed to carry, after VECTOR
169/// reconnected it.
170///
171/// Vector owns every reconnect (`add_managed_relay` ⇒ `reconnect(false)`), and the
172/// pool re-applies live subs only inside its own retry path — which is exactly the
173/// path that was turned off. So a dropped socket comes back carrying NOTHING, and a
174/// catch-up fetch is not a subscription: the data lands once and then the stream is
175/// silent forever. Only an AUTH-gating relay healed, via its post-challenge re-send.
176///
177/// Driven off the pool's own subscription table rather than a list of known
178/// subscriptions, so a future subscription is covered without touching this. Only
179/// ids the pool already associates with `relay` are re-sent, so a relay-targeted
180/// subscription is never widened onto a relay it deliberately excluded. Same-id
181/// REQs are idempotent.
182pub async fn resubscribe_relay_after_reconnect(
183    client: &nostr_sdk::prelude::Client,
184    relay: &nostr_sdk::prelude::RelayUrl,
185) {
186    for (id, per_relay) in client.subscriptions().await {
187        let Some(filters) = per_relay.get(relay) else { continue };
188        if filters.is_empty() {
189            continue;
190        }
191        let _ = client
192            .subscribe(nostr_sdk::prelude::ReqTarget::single(relay.clone(), filters.clone()))
193            .with_id(id)
194            .await;
195    }
196}
197
198/// Minimum a relay connect attempt gets while Tor is on.
199///
200/// Circuit construction dominates the handshake and routinely runs tens of
201/// seconds, especially on the first connection after the toggle.
202#[cfg(all(feature = "tor", not(target_arch = "wasm32")))]
203const TOR_RELAY_CONNECT_FLOOR: std::time::Duration = std::time::Duration::from_secs(60);
204
205/// Adjust a relay connect budget for the transport actually in use.
206///
207/// Clearnet TCP+TLS settles in well under a second, so the tight per-call budgets
208/// are right there and each caller's intent is preserved. Under Tor those same
209/// budgets expire mid-circuit, and because the health-check and reconcile loops
210/// treat a timeout as "unhealthy" they call `disconnect()` — which terminates the
211/// connection task — then retry, so a relay churns `pending → terminated` forever
212/// and never connects. Raising the floor lets the circuit finish.
213pub fn relay_connect_timeout(clearnet: std::time::Duration) -> std::time::Duration {
214    #[cfg(all(feature = "tor", not(target_arch = "wasm32")))]
215    {
216        if !matches!(tor::transport_state(), tor::TorTransportState::Disabled) {
217            return clearnet.max(TOR_RELAY_CONNECT_FLOOR);
218        }
219    }
220    clearnet
221}
222
223/// Floor for a relay round-trip (request → response) while Tor is active.
224#[cfg(all(feature = "tor", not(target_arch = "wasm32")))]
225const TOR_RELAY_REQUEST_FLOOR: std::time::Duration = std::time::Duration::from_secs(30);
226
227/// Adjust a relay request budget for the transport actually in use.
228///
229/// Companion to [`relay_connect_timeout`] for round trips rather than connections.
230/// A relay that answers a probe in 200ms direct can take many seconds through three
231/// hops, so a clearnet-sized budget reads a healthy relay as dead.
232pub fn relay_request_timeout(clearnet: std::time::Duration) -> std::time::Duration {
233    #[cfg(all(feature = "tor", not(target_arch = "wasm32")))]
234    {
235        if !matches!(tor::transport_state(), tor::TorTransportState::Disabled) {
236            return clearnet.max(TOR_RELAY_REQUEST_FLOOR);
237        }
238    }
239    clearnet
240}
241
242/// Apply the Tor proxy policy to any `ClientBuilder`.
243///
244/// Separate from [`nostr_client_builder`] because a client that authenticates as
245/// something other than the user (the Concord stream-auth plane key) still needs
246/// the same transport: without it the plane fetch connects direct and ties the
247/// user's IP to community membership.
248pub fn apply_tor_proxy(
249    builder: nostr_sdk::prelude::ClientBuilder,
250) -> nostr_sdk::prelude::ClientBuilder {
251    #[cfg(all(feature = "tor", not(target_arch = "wasm32")))]
252    let builder = builder.proxy(nostr_sdk::prelude::Proxy::custom(|_url| tor_proxy_target()));
253    builder
254}
255
256/// Resolve the proxy every connection attempt must use, for the transport in use.
257///
258/// Named rather than inlined into the `Proxy::custom` closure so the failsafe is
259/// testable: returning `None` here means "connect direct", so the only leak-safe
260/// answer while Tor is the chosen transport but not yet up is the blackhole.
261#[cfg(all(feature = "tor", not(target_arch = "wasm32")))]
262fn tor_proxy_target() -> Option<std::net::SocketAddr> {
263    match tor::transport_state() {
264        tor::TorTransportState::Active(addr) => Some(addr),
265        // Tor failsafe: route to a blackhole so a relay socket can't come up
266        // direct while Tor is mid-bootstrap.
267        tor::TorTransportState::RequiredButInactive => Some(tor::blackhole_proxy_addr()),
268        tor::TorTransportState::Disabled => None,
269    }
270}
271
272/// Sign an `EventBuilder` with the session signer.
273///
274/// Stands in for 0.44's `Client::sign_event_builder`, which went away when the
275/// client stopped owning a signer.
276pub async fn sign_builder(
277    builder: nostr_sdk::prelude::EventBuilder,
278) -> std::result::Result<nostr_sdk::prelude::Event, String> {
279    let signer = signer::active_signer()?;
280    builder
281        .finalize_async(&signer)
282        .await
283        .map_err(|e| e.to_string())
284}
285
286/// Sign an `EventBuilder` with the session signer and publish it.
287///
288/// Stands in for 0.44's `Client::send_event_builder`.
289pub async fn sign_and_send(
290    client: &nostr_sdk::prelude::Client,
291    builder: nostr_sdk::prelude::EventBuilder,
292) -> std::result::Result<nostr_sdk::prelude::SendEventOutput, String> {
293    let event = sign_builder(builder).await?;
294    client
295        .send_event(&event)
296        .await
297        .map_err(|e| e.to_string())
298}
299
300/// Seal, wrap and publish a rumor to `receiver`.
301///
302/// Stands in for 0.44's `Client::gift_wrap` / `gift_wrap_to`, which went away
303/// with the client's signer. An empty `relays` publishes pool-wide, matching
304/// `gift_wrap`; a non-empty one targets those relays, matching `gift_wrap_to`.
305pub async fn send_gift_wrap<'u, I, U, T>(
306    client: &nostr_sdk::prelude::Client,
307    relays: I,
308    receiver: &nostr_sdk::prelude::PublicKey,
309    rumor: nostr_sdk::prelude::UnsignedEvent,
310    extra_tags: T,
311) -> std::result::Result<nostr_sdk::prelude::SendEventOutput, String>
312where
313    I: IntoIterator<Item = U>,
314    U: Into<nostr_sdk::prelude::RelayUrlArg<'u>>,
315    T: IntoIterator<Item = nostr_sdk::prelude::Tag>,
316{
317    let signer = signer::active_signer()?;
318    let wrap = nostr_sdk::prelude::GiftWrapBuilder::new(*receiver, rumor)
319        .extra_tags(extra_tags)
320        .finalize_async(&signer)
321        .await
322        .map_err(|e| e.to_string())?;
323    let targets: Vec<nostr_sdk::prelude::RelayUrlArg<'u>> =
324        relays.into_iter().map(Into::into).collect();
325    if targets.is_empty() {
326        client.send_event(&wrap).await.map_err(|e| e.to_string())
327    } else {
328        client
329            .send_event(&wrap)
330            .to(targets)
331            .await
332            .map_err(|e| e.to_string())
333    }
334}
335
336/// Capabilities for a Community / "external" relay: GOSSIP only.
337///
338/// GOSSIP is read/write-capable when TARGETED — `can_read()` is
339/// `READ|GOSSIP|DISCOVERY` and `can_write()` is `WRITE|GOSSIP`, so per-relay
340/// targeted ops pass. But pool-wide ops select READ-only / WRITE-only relays, so
341/// the DM/giftwrap subscription and the user's outbox skip GOSSIP relays — the
342/// user's own traffic never touches relays they don't own.
343///
344/// No PING counterpart any more: 0.45 demoted PING from a capability flag to a
345/// per-relay option (`AddRelay::ping`) that already defaults to true, with
346/// `sleep_when_idle` defaulting to false. The 24/7 keepalive this used to buy is
347/// now the default, so it doesn't belong in the capability set.
348pub fn community_relay_capabilities() -> nostr_sdk::prelude::RelayCapabilities {
349    nostr_sdk::prelude::RelayCapabilities::GOSSIP
350}
351
352/// Relay options for a Discovery Relay (see `state::DISCOVERY_RELAYS`): the same
353/// GOSSIP|PING targeted-only isolation as Community relays — reachable via
354/// `fetch_events_from` / `send_event_to`, invisible to pool-wide DM/profile ops.
355/// An overlap with a user relay keeps the user's READ+WRITE flags (`add_relay`
356/// no-ops on an already-pooled url).
357pub fn discovery_relay_capabilities() -> nostr_sdk::prelude::RelayCapabilities {
358    community_relay_capabilities()
359}
360
361// === Event Storage ===
362pub mod stored_event;
363
364// === Rumor Processing ===
365pub mod rumor;
366
367// === Messaging ===
368pub mod sending;
369
370// === Per-DM Wallpapers ===
371pub mod wallpaper;
372
373// === Message Deletion (NIP-09 against retained gift-wraps) ===
374pub mod deletion;
375pub mod self_destruct;
376
377// === SIMD Operations ===
378pub mod simd;
379
380// === Community protocol (GROUP_PROTOCOL.md) ===
381pub mod community;
382
383// === Event Handler ===
384pub mod event_handler;
385
386// === Re-exports for convenience ===
387pub use types::{Message, Attachment, Reaction, EditEntry, ImageMetadata, SiteMetadata, LoginResult, AttachmentFile, mention, extract_mentions};
388pub use profile::{Profile, ProfileFlags, SlimProfile, Status};
389pub use chat::{Chat, ChatType, ChatMetadata, SerializableChat};
390pub use compact::{CompactMessage, CompactMessageVec, NpubInterner};
391pub use state::{
392    ChatState, NOSTR_CLIENT, MY_SECRET_KEY, MY_PUBLIC_KEY, STATE, ENCRYPTION_KEY,
393    nostr_client, my_public_key, has_active_session,
394    set_nostr_client, set_my_public_key,
395    take_nostr_client, clear_my_public_key,
396    set_pending_bunker_setup, pending_bunker_setup, clear_pending_bunker_setup,
397    set_pending_nip55_setup, pending_nip55_setup, clear_pending_nip55_setup,
398};
399pub use crypto::{GuardedKey, GuardedSigner};
400pub use signer::{
401    SignerKind, signer_kind, set_signer_kind, is_bunker, is_keyless,
402    BUNKER_SIGNER, bunker_signer, set_bunker_signer, take_bunker_signer,
403    build_bunker_signer, prewarm_bunker, drain_bunker_state,
404    parse_bunker_remote_pubkey, parse_bunker_relays,
405    BunkerConnectionState, bunker_state, set_bunker_state,
406    VectorAuthUrlHandler, attempt_bunker_login, WatchedBunkerSigner,
407    vector_metadata, build_nostrconnect_uri, build_nostrconnect_session,
408    VECTOR_APP_NAME, VECTOR_APP_URL, VECTOR_APP_ICON,
409};
410pub use nip55::{
411    Nip55Backend, Nip55Error, Nip55ResolverOutcome, Nip55Signer, Nip55State,
412    set_nip55_backend, nip55_backend, nip55_state, set_nip55_state, drain_nip55_state,
413    nip55_is_installed, nip55_pair, nip55_perms_json,
414    VECTOR_NIP55_SIGN_KINDS, VECTOR_NIP55_ENCRYPT_TYPES,
415};
416pub use error::{VectorError, Result};
417pub use traits::{EventEmitter, NoOpEmitter, set_event_emitter, emit_event};
418pub use db::{set_app_data_dir, get_app_data_dir};
419pub use sending::{SendCallback, NoOpSendCallback, SendConfig, SendResult};
420pub use deletion::{delete_own_dm, DeleteOutcome};
421pub use stored_event::{StoredEvent, StoredEventBuilder, SystemEventType};
422pub use rumor::{RumorEvent, RumorContext, ConversationType, RumorProcessingResult, process_rumor};
423pub use profile::{SyncPriority, ProfileSyncHandler, NoOpProfileSyncHandler};
424pub use event_handler::{InboundEventHandler, NoOpEventHandler, PreparedEvent, process_event};
425
426use std::path::PathBuf;
427use std::sync::Arc;
428
429// ============================================================================
430// VectorCore — High-level API
431// ============================================================================
432
433/// Configuration for initializing VectorCore.
434pub struct CoreConfig {
435    /// Path to the app data directory (e.g., ~/.local/share/io.vectorapp/data/)
436    pub data_dir: PathBuf,
437    /// Optional event emitter for UI integration
438    pub event_emitter: Option<Box<dyn EventEmitter>>,
439}
440
441/// The main entry point for Vector Core.
442///
443/// Provides a high-level API for all Vector operations. Internally uses
444/// global state (same pattern as the Tauri backend) for compatibility.
445///
446/// ```no_run
447/// use vector_core::{VectorCore, CoreConfig};
448/// use std::path::PathBuf;
449///
450/// # async fn example() -> vector_core::Result<()> {
451/// let core = VectorCore::init(CoreConfig {
452///     data_dir: PathBuf::from("/tmp/vector-data"),
453///     event_emitter: None,
454/// })?;
455///
456/// // Login with nsec
457/// let result = core.login("nsec1...", None).await?;
458/// println!("Logged in as {}", result.npub);
459/// # Ok(())
460/// # }
461/// ```
462#[derive(Clone, Copy)]
463pub struct VectorCore;
464
465impl VectorCore {
466    /// Initialize Vector Core with the given configuration.
467    pub fn init(config: CoreConfig) -> Result<Self> {
468        // Set data directory
469        db::set_app_data_dir(config.data_dir);
470
471        // Set event emitter (or no-op)
472        if let Some(emitter) = config.event_emitter {
473            traits::set_event_emitter(emitter);
474        }
475
476        // Install rustls ring provider
477        let _ = rustls::crypto::ring::default_provider().install_default();
478
479        Ok(VectorCore)
480    }
481
482    /// Get all available accounts.
483    pub fn accounts(&self) -> Result<Vec<String>> {
484        db::get_accounts().map_err(VectorError::from)
485    }
486
487    /// Login with an nsec key or mnemonic seed phrase.
488    pub async fn login(&self, key: &str, password: Option<&str>) -> Result<LoginResult> {
489        use nostr_sdk::prelude::*;
490
491        // Parse the key
492        let keys = if key.starts_with("nsec1") {
493            let secret = SecretKey::from_bech32(key)
494                .map_err(|e| VectorError::Nostr(format!("Invalid nsec: {}", e)))?;
495            Keys::new(secret)
496        } else {
497            // Treat as mnemonic (NIP-06: derive from BIP-39 seed)
498            Keys::from_mnemonic(key, None)
499                .map_err(|e| VectorError::Nostr(format!("Key derivation failed: {}", e)))?
500        };
501
502        let public_key = keys.public_key();
503        let npub = public_key.to_bech32()
504            .map_err(|e| VectorError::Nostr(format!("Failed to encode npub: {}", e)))?;
505
506        // Store in GuardedKey vault (pass other vaults to protect during decoy writes)
507        let secret_bytes = keys.secret_key().to_secret_bytes();
508        state::MY_SECRET_KEY.set(secret_bytes, &[&state::ENCRYPTION_KEY]);
509        state::set_my_public_key(public_key);
510
511        // Initialize database for this account
512        db::set_current_account(npub.clone())?;
513        db::init_database(&npub)?;
514
515        // Store nsec for encryption setup
516        {
517            let nsec = keys.secret_key().to_bech32()
518                .map_err(|e| VectorError::Nostr(format!("Failed to encode nsec: {}", e)))?;
519            *state::PENDING_NSEC.lock().unwrap() = Some(nsec.clone());
520
521            // NEVER clobber an existing encrypted key with the plaintext nsec. An account with encryption
522            // enabled keeps its key encrypted-at-rest (PIN-derived); overwriting it with the raw nsec — e.g.
523            // a no-password headless/diagnostic login (the concord CLI) — would leave the GUI deriving the
524            // right key from the correct PIN but trying to decrypt a value that's no longer ciphertext, i.e.
525            // "incorrect pin" with the real key effectively lost. MY_SECRET_KEY is already set in-memory above,
526            // so login works regardless; only persist the raw key when there's no encrypted key to protect.
527            let existing_encrypted = db::get_pkey().ok().flatten().is_some_and(|v| !v.starts_with("nsec1"));
528            if !(state::resolve_encryption_enabled_from_db() && existing_encrypted) {
529                db::set_pkey(&nsec)?;
530            }
531        }
532
533        // Use the canonical resolver so this high-level API agrees with
534        // crypto::is_encryption_enabled and the Android bg-sync probe.
535        let has_encryption = state::resolve_encryption_enabled_from_db();
536
537        if has_encryption {
538            if let Some(pwd) = password {
539                let key = crate::crypto::hash_pass(pwd).await;
540                state::ENCRYPTION_KEY.set(key, &[&state::MY_SECRET_KEY]);
541            }
542        }
543        // Seed the atomic unconditionally — `is_encryption_enabled_fast()`
544        // must agree with the DB regardless of branch.
545        state::init_encryption_enabled();
546
547        // Build Nostr client — tor-aware options so a headless consumer with
548        // the Tor pref ON proxies (or blackholes) instead of dialing direct.
549        let client = crate::nostr_client_builder()
550            // Relay health monitor — powers the reconnect-driven catch-up in `listen()`.
551            .monitor(Monitor::new(1024))
552            .build();
553
554        // Add trusted relays
555        for relay in state::TRUSTED_RELAYS {
556            client.add_managed_relay(*relay).await.ok();
557        }
558
559        // Connect
560        client.connect().await;
561
562        let _ = { state::set_nostr_client(client); Ok::<(), ()>(()) };
563
564        Ok(LoginResult { npub, has_encryption })
565    }
566
567    /// Generate a fresh random account secret key (bech32 nsec). Lets a headless client spin up a
568    /// brand-new identity (`add_account` with no key) without depending on nostr-sdk directly.
569    pub fn generate_nsec(&self) -> Result<String> {
570        use nostr_sdk::prelude::*;
571        Keys::generate().secret_key().to_bech32()
572            .map_err(|e| VectorError::Nostr(format!("Failed to encode nsec: {}", e)))
573    }
574
575    /// Send a NIP-17 gift-wrapped text DM using the full pipeline. Retries a
576    /// transient publish miss (headless preset, 3 attempts) so an SDK/CLI bot rides
577    /// out a relay blip instead of silently dropping the message on the first miss;
578    /// `self_send: false` keeps it a plain send (no inbox self-copy).
579    pub async fn send_dm(&self, to_npub: &str, content: &str) -> Result<sending::SendResult> {
580        let config = SendConfig { self_send: false, ..SendConfig::headless() };
581        sending::send_dm(to_npub, content, None, &config, Arc::new(NoOpSendCallback)).await
582            .map_err(|e| VectorError::Other(e))
583    }
584
585    /// Send a DM as a threaded reply to `replied_to` (an existing message's event id).
586    pub async fn send_dm_reply(&self, to_npub: &str, replied_to: &str, content: &str) -> Result<sending::SendResult> {
587        let config = SendConfig { self_send: false, ..SendConfig::headless() };
588        sending::send_dm(to_npub, content, Some(replied_to), &config, Arc::new(NoOpSendCallback)).await
589            .map_err(|e| VectorError::Other(e))
590    }
591
592    /// Download a received attachment and decrypt it to plaintext bytes. Fetches the encrypted blob
593    /// from its Blossom URL (SSRF/Tor-aware client, size-capped) and AES-decrypts with the
594    /// attachment's embedded key + nonce. Walks the primary URL then any BUD-04 `fallback`
595    /// mirrors (same ciphertext on other hosts) until one serves. Prefer
596    /// [`download_attachment_from`](Self::download_attachment_from) when the message author is
597    /// known — it adds the BUD-03 hash-swap over the author's advertised servers.
598    pub async fn download_attachment(&self, attachment: &Attachment) -> Result<Vec<u8>> {
599        self.download_attachment_from(attachment, None).await
600    }
601
602    /// [`download_attachment`](Self::download_attachment) with the full source walk: primary URL →
603    /// embedded `fallback` mirrors → BUD-03 hash-swap (the same content-address on each of the
604    /// author's kind-10063 servers). `author_npub` is the message author (your own npub for your
605    /// own messages); `None` skips the hash-swap stage.
606    pub async fn download_attachment_from(
607        &self,
608        attachment: &Attachment,
609        author_npub: Option<&str>,
610    ) -> Result<Vec<u8>> {
611        use futures_util::StreamExt;
612        const MAX_DOWNLOAD: usize = 256 * 1024 * 1024;
613        if attachment.url.is_empty() {
614            return Err(VectorError::Other("attachment has no URL".into()));
615        }
616        let client = crate::net::build_http_client(std::time::Duration::from_secs(120)).map_err(VectorError::Other)?;
617        let mut last_err = String::from("download failed");
618        let mut candidates: Vec<String> = vec![attachment.url.clone()];
619        candidates.extend(attachment.fallback_urls.iter().cloned());
620        let mut hash_swap_tried = false;
621        let mut i = 0;
622        'sources: while i < candidates.len() {
623            let url = candidates[i].clone();
624            i += 1;
625            // One-time last resort once every embedded source has failed: the author's advertised
626            // servers may hold the blob under the same content-address.
627            let extend_with_swap = |candidates: &mut Vec<String>, servers: &[String]| {
628                let extra = crate::blossom::hash_swap_candidates(&attachment.url, servers);
629                for c in extra {
630                    if !candidates.contains(&c) {
631                        candidates.push(c);
632                    }
633                }
634            };
635            macro_rules! next_source {
636                () => {{
637                    log_net_fail!("[Download] source failed ({}): {}", url, last_err);
638                    if i == candidates.len() && !hash_swap_tried {
639                        hash_swap_tried = true;
640                        let servers = crate::blossom_servers::author_swap_servers(author_npub, false).await;
641                        extend_with_swap(&mut candidates, &servers);
642                    }
643                    continue 'sources;
644                }};
645            }
646            // SSRF guard: URLs are attacker-controlled (off an inbound message). build_http_client
647            // only validates redirect HOPS, not the initial request — so validate each source here
648            // (matches the native download path). With Tor off this is the only egress guard.
649            if let Err(e) = crate::net::validate_url_not_private(&url) {
650                last_err = e.to_string();
651                next_source!();
652            }
653            let resp = match client.get(&url).send().await {
654                Ok(r) => r,
655                Err(e) => {
656                    last_err = format!("download: {e}");
657                    next_source!();
658                }
659            };
660            if !resp.status().is_success() {
661                last_err = format!("download failed: HTTP {}", resp.status());
662                next_source!();
663            }
664            // Stream with a cap so a hostile/oversized blob can't OOM the process. The cap is
665            // permanent — every mirror serves the same blob, so don't bother trying the next.
666            let mut encrypted: Vec<u8> = Vec::with_capacity(
667                resp.content_length().map(|l| (l as usize).min(MAX_DOWNLOAD)).unwrap_or(64 * 1024),
668            );
669            let mut stream = resp.bytes_stream();
670            while let Some(chunk) = stream.next().await {
671                let chunk = match chunk {
672                    Ok(c) => c,
673                    Err(e) => {
674                        last_err = format!("read body: {e}");
675                        next_source!();
676                    }
677                };
678                if encrypted.len() + chunk.len() > MAX_DOWNLOAD {
679                    return Err(VectorError::Other("attachment exceeds 256 MiB cap".into()));
680                }
681                encrypted.extend_from_slice(&chunk);
682            }
683            match crate::crypto::decrypt_data(&encrypted, &attachment.key, &attachment.nonce) {
684                Ok(plain) => {
685                    if i > 1 {
686                        log_net_info!("[Download] fallback source {}/{} served {}", i, candidates.len(), url);
687                    }
688                    return Ok(plain);
689                }
690                Err(e) => {
691                    // A host serving wrong bytes under the right URL must not
692                    // veto sources still holding the real ciphertext.
693                    last_err = format!("decrypt: {e}");
694                    next_source!();
695                }
696            }
697        }
698        log_net_fail!("[Download] all {} source(s) failed for {}: {}", candidates.len(), attachment.url, last_err);
699        Err(VectorError::Other(last_err))
700    }
701
702    /// Send a NIP-17 gift-wrapped file attachment DM.
703    pub async fn send_file(&self, to_npub: &str, file_path: &str) -> Result<sending::SendResult> {
704        let path = std::path::Path::new(file_path);
705        let bytes = std::fs::read(path)
706            .map_err(|e| VectorError::Io(e))?;
707        let filename = path.file_name()
708            .and_then(|n| n.to_str())
709            .unwrap_or("file");
710        let extension = path.extension()
711            .and_then(|e| e.to_str())
712            .unwrap_or("bin");
713
714        sending::send_file_dm(
715            to_npub,
716            std::sync::Arc::new(bytes),
717            filename,
718            extension,
719            None,
720            &SendConfig::default(),
721            Arc::new(NoOpSendCallback),
722        ).await.map_err(|e| VectorError::Other(e))
723    }
724
725    /// Send a NIP-25 reaction to a DM message. `emoji_url` carries the NIP-30
726    /// image URL when reacting with a custom-pack emoji (content stays
727    /// `:shortcode:`). Returns the reaction's rumor id. Local echo + persistence
728    /// are best-effort — the gift-wrap send is the source of truth.
729    pub async fn send_reaction(
730        &self,
731        to_npub: &str,
732        reference_id: &str,
733        emoji: &str,
734        emoji_url: Option<&str>,
735    ) -> Result<String> {
736        use nostr_sdk::prelude::*;
737
738        let client = state::nostr_client().ok_or(VectorError::Other("Not connected".into()))?;
739        let my_public_key = state::my_public_key().ok_or(VectorError::Other("Not logged in".into()))?;
740
741        let reference_event = EventId::from_hex(reference_id)
742            .map_err(|e| VectorError::Nostr(e.to_string()))?;
743        let receiver_pubkey = PublicKey::from_bech32(to_npub)
744            .map_err(|e| VectorError::Nostr(e.to_string()))?;
745
746        // NIP-30 custom-emoji tag — only when content is `:shortcode:` and a URL is present.
747        let custom_emoji_tag = emoji_url.and_then(|url| {
748            if !emoji.starts_with(':') || !emoji.ends_with(':') || emoji.len() < 3 || url.is_empty() {
749                return None;
750            }
751            let shortcode = &emoji[1..emoji.len() - 1];
752            if shortcode.is_empty() { return None; }
753            Some(Tag::custom("emoji", [shortcode.to_string(), url.to_string()]))
754        });
755
756        let reaction_target = nostr_sdk::prelude::nip25::ReactionTarget {
757            event_id: reference_event,
758            public_key: receiver_pubkey,
759            coordinate: None,
760            kind: Some(Kind::PrivateDirectMessage),
761            relay_hint: None,
762        };
763        let mut builder =
764            nostr_sdk::prelude::nip25::ReactionBuilder::new(reaction_target, emoji)
765                .into_event_builder();
766        if let Some(tag) = custom_emoji_tag {
767            builder = builder.tag(tag);
768        }
769        let rumor = builder.finalize_unsigned_with_id(my_public_key);
770        let inner_rumor_id = rumor.id;
771        let rumor_id = inner_rumor_id.ok_or(VectorError::Other("Failed to get rumor ID".into()))?.to_hex();
772
773        // Retain the recipient wrap's ephemeral key + targeted relays so the
774        // reaction can later be revoked with a NIP-09 relay nuke (mirrors the
775        // DM message send path). Without retention the reaction is undeletable.
776        let outcome = inbox_relays::send_gift_wrap_retained(&client, &receiver_pubkey, rumor.clone(), [])
777            .await.map_err(VectorError::Other)?;
778        if !outcome.output.success.is_empty() {
779            if let Some(rid) = inner_rumor_id {
780                if let Err(e) = db::nip17_keys::store_wrap_key(
781                    &outcome.wrap_event_id, &rid, &receiver_pubkey,
782                    db::nip17_keys::WrapRole::Recipient,
783                    &outcome.wrap_secret, &outcome.targeted_relays,
784                ) {
785                    crate::log_warn!("[Reaction] failed to persist wrap key: {}", e);
786                }
787            }
788        }
789
790        // Self-wrap for multi-device recovery + retain its key too, so another
791        // device (or this one) can later revoke. Bail on account swap.
792        let self_wrap_client = client.clone();
793        let self_wrap_session = state::SessionGuard::capture();
794        tokio::spawn(async move {
795            if !self_wrap_session.is_valid() { return; }
796            if let Ok(self_outcome) = inbox_relays::send_gift_wrap_retained(
797                &self_wrap_client, &my_public_key, rumor, [],
798            ).await {
799                if !self_wrap_session.is_valid() { return; }
800                if !self_outcome.output.success.is_empty() {
801                    if let Some(rid) = inner_rumor_id {
802                        let _ = db::nip17_keys::store_wrap_key(
803                            &self_outcome.wrap_event_id, &rid, &my_public_key,
804                            db::nip17_keys::WrapRole::SelfSend,
805                            &self_outcome.wrap_secret, &self_outcome.targeted_relays,
806                        );
807                    }
808                }
809            }
810        });
811
812        // Best-effort optimistic local echo + persistence.
813        let reaction = Reaction {
814            id: rumor_id.clone(),
815            reference_id: reference_id.to_string(),
816            author_id: my_public_key.to_bech32().unwrap_or_else(|_| my_public_key.to_hex()),
817            emoji: emoji.to_string(),
818            emoji_url: emoji_url.map(|s| s.to_string()),
819        };
820        let msg_for_save = {
821            let mut st = state::STATE.lock().await;
822            match st.add_reaction_to_message(reference_id, reaction) {
823                Some((cid, true)) => st.find_message(reference_id).map(|(_, m)| (cid, m)),
824                _ => None,
825            }
826        };
827        if let Some((cid, mut msg)) = msg_for_save {
828            let _ = db::events::save_message(&cid, &msg).await;
829            traits::emit_message_update(&cid, reference_id, &mut msg).await;
830        }
831
832        Ok(rumor_id)
833    }
834
835    /// Send an ephemeral typing indicator to a DM recipient. Fire-and-forget
836    /// with a 30-second NIP-40 expiry so relays purge it quickly.
837    pub async fn send_typing(&self, to_npub: &str) -> Result<()> {
838        use nostr_sdk::prelude::*;
839
840        let client = state::nostr_client().ok_or(VectorError::Other("Not connected".into()))?;
841        let my_public_key = state::my_public_key().ok_or(VectorError::Other("Not logged in".into()))?;
842        let pubkey = PublicKey::from_bech32(to_npub).map_err(|e| VectorError::Nostr(e.to_string()))?;
843
844        let expiry = Timestamp::from_secs(Timestamp::now().as_secs() + 30);
845        let rumor = EventBuilder::new(Kind::ApplicationSpecificData, "typing")
846            .tag(Tag::public_key(pubkey))
847            .tag(Tag::custom("d", vec!["vector"]))
848            .tag(Tag::expiration(expiry))
849            .finalize_unsigned_with_id(my_public_key);
850
851        // Client no longer wraps: build the wrap, then publish it to the target relays.
852        let signer = signer::active_signer().map_err(VectorError::Other)?;
853        let wrap = nostr_sdk::prelude::GiftWrapBuilder::new(pubkey, rumor.clone())
854            .extra_tags([Tag::expiration(expiry)])
855            .finalize_async(&signer)
856            .await
857            .map_err(|e| VectorError::Nostr(e.to_string()))?;
858        client
859            .send_event(&wrap)
860            .to(state::active_trusted_relays().await)
861            .await
862            .map_err(|e| VectorError::Nostr(e.to_string()))?;
863        Ok(())
864    }
865
866    /// Edit a DM you previously sent (kind-16 edit) with an optimistic local
867    /// echo. Returns the edit event id. Persistence is best-effort and only
868    /// happens when the chat already exists locally.
869    pub async fn edit_dm(&self, to_npub: &str, message_id: &str, new_content: &str) -> Result<String> {
870        use nostr_sdk::prelude::*;
871
872        let client = state::nostr_client().ok_or(VectorError::Other("Not connected".into()))?;
873        let my_public_key = state::my_public_key().ok_or(VectorError::Other("Not logged in".into()))?;
874        let my_npub = my_public_key.to_bech32().map_err(|e| VectorError::Nostr(e.to_string()))?;
875        let receiver_pubkey = PublicKey::from_bech32(to_npub).map_err(|e| VectorError::Nostr(e.to_string()))?;
876        let reference_event = EventId::from_hex(message_id).map_err(|e| VectorError::Nostr(e.to_string()))?;
877
878        // NIP-30: resolve `:shortcode:` so the edit carries emoji image tags.
879        let emoji_tags = emoji_packs::resolve_outbound_emoji_tags(new_content);
880
881        let mut builder = EventBuilder::new(
882            Kind::from_u16(stored_event::event_kind::MESSAGE_EDIT),
883            new_content,
884        ).tag(Tag::event(reference_event));
885        for et in &emoji_tags {
886            builder = builder.tag(Tag::custom(
887                "emoji",
888                [et.shortcode.clone(), et.url.clone()],
889            ));
890        }
891        let rumor = builder.finalize_unsigned_with_id(my_public_key);
892        let edit_id = rumor.id.ok_or(VectorError::Other("Failed to get edit rumor ID".into()))?.to_hex();
893        let edit_ts_ms = rumor.created_at.as_secs() * 1000;
894
895        // Optimistic local echo + best-effort persistence.
896        let msg_for_emit = {
897            let mut st = state::STATE.lock().await;
898            st.update_message_in_chat(to_npub, message_id, |msg| {
899                msg.apply_edit(new_content.to_string(), edit_ts_ms, emoji_tags.clone());
900                msg.preview_metadata = None;
901            })
902        };
903        if let Some(mut msg) = msg_for_emit {
904            traits::emit_message_update(to_npub, message_id, &mut msg).await;
905            if let Ok(db_chat_id) = db::id_cache::get_chat_id_by_identifier(to_npub) {
906                let _ = db::events::save_edit_event(
907                    &edit_id, message_id, new_content, &emoji_tags, db_chat_id, None, &my_npub,
908                ).await;
909            }
910        }
911
912        inbox_relays::send_gift_wrap(&client, &receiver_pubkey, rumor.clone(), [])
913            .await.map_err(VectorError::Other)?;
914
915        let self_wrap_client = client.clone();
916        let self_wrap_session = state::SessionGuard::capture();
917        tokio::spawn(async move {
918            if !self_wrap_session.is_valid() { return; }
919            let Ok(signer) = signer::active_signer() else { return };
920            if let Ok(wrap) = nostr_sdk::prelude::GiftWrapBuilder::new(my_public_key, rumor)
921                .finalize_async(&signer)
922                .await
923            {
924                let _ = self_wrap_client.send_event(&wrap).await;
925            }
926        });
927
928        Ok(edit_id)
929    }
930
931    /// Delete a DM you sent (NIP-09 over the retained gift-wrap keys).
932    pub async fn delete_dm(&self, message_id: &str) -> Result<deletion::DeleteOutcome> {
933        use nostr_sdk::prelude::*;
934        let rumor_id = EventId::from_hex(message_id).map_err(|e| VectorError::Nostr(e.to_string()))?;
935        deletion::delete_own_dm(&rumor_id).await.map_err(VectorError::Other)
936    }
937
938    /// Get chats from the in-memory state.
939    pub async fn get_chats(&self) -> Vec<SerializableChat> {
940        let state = state::STATE.lock().await;
941        state.chats.iter()
942            .map(|c| c.to_serializable_with_last_n(1, &state.interner))
943            .collect()
944    }
945
946    /// Get messages for a chat (paginated).
947    pub async fn get_messages(&self, chat_id: &str, limit: usize, offset: usize) -> Vec<Message> {
948        let state = state::STATE.lock().await;
949        if let Some(chat) = state.get_chat(chat_id) {
950            let msgs = chat.get_all_messages(&state.interner);
951            let start = offset.min(msgs.len());
952            let end = (offset + limit).min(msgs.len());
953            msgs[start..end].to_vec()
954        } else {
955            Vec::new()
956        }
957    }
958
959    /// Get a profile by npub.
960    pub async fn get_profile(&self, npub: &str) -> Option<SlimProfile> {
961        let state = state::STATE.lock().await;
962        state.get_profile(npub)
963            .map(|p| SlimProfile::from_profile(p, &state.interner))
964    }
965
966    /// Fetch a profile's metadata and status from relays.
967    pub async fn load_profile(&self, npub: &str) -> bool {
968        profile::sync::load_profile(npub.to_string(), &NoOpProfileSyncHandler).await
969    }
970
971    /// Update the current user's profile metadata and broadcast to relays.
972    pub async fn update_profile(&self, name: &str, avatar: &str, banner: &str, about: &str) -> bool {
973        profile::sync::update_profile(
974            name.to_string(), avatar.to_string(), banner.to_string(), about.to_string(),
975            &NoOpProfileSyncHandler,
976        ).await
977    }
978
979    /// Like [`update_profile`](Self::update_profile) but marks the profile as a bot (`bot: true` in
980    /// the metadata). The SDK uses this for every bot; build human clients on `update_profile`.
981    pub async fn update_bot_profile(&self, name: &str, avatar: &str, banner: &str, about: &str) -> bool {
982        profile::sync::update_bot_profile(
983            name.to_string(), avatar.to_string(), banner.to_string(), about.to_string(),
984            &NoOpProfileSyncHandler,
985        ).await
986    }
987
988    /// Update the current user's status and broadcast to relays.
989    pub async fn update_status(&self, status: &str) -> bool {
990        profile::sync::update_status(status.to_string()).await
991    }
992
993    /// Upload an image file to Blossom **unencrypted** and return its public URL — for avatars,
994    /// banners, and other images other clients must fetch directly. (The opposite of
995    /// [`send_file`](Self::send_file)'s encrypted attachments.) Pass the URL to [`update_profile`].
996    ///
997    /// [`update_profile`]: Self::update_profile
998    pub async fn upload_public_image(&self, file_path: &str) -> Result<String> {
999        let path = std::path::Path::new(file_path);
1000        let bytes = std::fs::read(path).map_err(VectorError::Io)?;
1001        if bytes.is_empty() {
1002            return Err(VectorError::Other("Empty image file".into()));
1003        }
1004        let extension = path.extension().and_then(|e| e.to_str()).unwrap_or("bin").to_lowercase();
1005        let mime = crate::crypto::mime_from_extension(&extension);
1006        let _client = state::nostr_client().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
1007        let signer = crate::signer::active_signer()
1008            .map_err(|e| VectorError::Other(format!("Signer unavailable: {e}")))?;
1009        let servers = crate::blossom_servers::compute_enabled_servers();
1010        if servers.is_empty() {
1011            return Err(VectorError::Other("No Blossom servers configured".into()));
1012        }
1013        // Avatars/banners run larger than emojis (up to ~1MB), so give a more generous
1014        // 20s idle window before treating a silent server as dead and failing over.
1015        crate::blossom::upload_blob_with_failover(
1016            signer,
1017            servers,
1018            std::sync::Arc::new(bytes),
1019            Some(mime),
1020            Some(std::time::Duration::from_secs(20)),
1021        )
1022        .await
1023        .map_err(VectorError::Other)
1024    }
1025
1026    /// Block a user by npub.
1027    pub async fn block_user(&self, npub: &str) -> bool {
1028        profile::sync::block_user(npub.to_string(), &NoOpProfileSyncHandler).await
1029    }
1030
1031    /// Unblock a user by npub.
1032    pub async fn unblock_user(&self, npub: &str) -> bool {
1033        profile::sync::unblock_user(npub.to_string(), &NoOpProfileSyncHandler).await
1034    }
1035
1036    /// Set a nickname for a profile.
1037    pub async fn set_nickname(&self, npub: &str, nickname: &str) -> bool {
1038        profile::sync::set_nickname(npub.to_string(), nickname.to_string(), &NoOpProfileSyncHandler).await
1039    }
1040
1041    /// Get all blocked profiles.
1042    pub async fn get_blocked_users(&self) -> Vec<SlimProfile> {
1043        profile::sync::get_blocked_users().await
1044    }
1045
1046    /// Queue a profile for background sync.
1047    pub fn queue_profile_sync(&self, npub: &str, priority: SyncPriority) {
1048        profile::sync::queue_profile_sync(npub.to_string(), priority, false);
1049    }
1050
1051    /// Get the current user's npub.
1052    pub fn my_npub(&self) -> Option<String> {
1053        state::my_public_key()
1054            .and_then(|pk| ToBech32::to_bech32(&pk).ok())
1055    }
1056
1057    // === Communities (headless) ===
1058    // The GUI's Tauri commands carry optimistic-echo + emit machinery a headless client
1059    // doesn't need; these are the lean equivalents over the same `community::service` layer,
1060    // so a CLI / agent can join, read, post, and sync a Community.
1061
1062    /// List every Community held locally (owned or joined), each with its channels.
1063    pub async fn list_communities(&self) -> Vec<serde_json::Value> {
1064        use crate::community::ConcordProtocol;
1065        let ids = crate::db::community::list_community_ids().unwrap_or_default();
1066        let mut out = Vec::new();
1067        for id in ids {
1068            // Dual-stack: dispatch each held community by its stored protocol.
1069            match crate::db::community::community_protocol(&id).ok().flatten() {
1070                Some(ConcordProtocol::V2) => {
1071                    if let Ok(Some(c)) = crate::db::community::load_community_v2(&id) {
1072                        let me = state::my_public_key();
1073                        let is_owner = me.is_some_and(|m| c.owner().is_ok_and(|o| o == m));
1074                        out.push(serde_json::json!({
1075                            "community_id": crate::simd::hex::bytes_to_hex_32(&c.identity.community_id.0),
1076                            "version": 2,
1077                            "name": c.name,
1078                            "description": c.description,
1079                            "is_owner": is_owner,
1080                            // `readable` is the field a bot needs and could never
1081                            // compute: a private channel we've been told about but
1082                            // hold no key for is enumerable-but-unreadable, which
1083                            // is what distinguishes "not a member" from "member
1084                            // awaiting the key vend".
1085                            "channels": c.channels.iter()
1086                                .map(|ch| serde_json::json!({
1087                                    "channel_id": crate::simd::hex::bytes_to_hex_32(&ch.id.0),
1088                                    "name": ch.name,
1089                                    "private": ch.private,
1090                                    "readable": !(ch.private && ch.key.is_none()),
1091                                    "epoch": ch.epoch.0,
1092                                }))
1093                                .collect::<Vec<_>>(),
1094                        }));
1095                    }
1096                }
1097                _ => {
1098                    if let Ok(Some(c)) = crate::db::community::load_community(&id) {
1099                        out.push(serde_json::json!({
1100                            "community_id": c.id.to_hex(),
1101                            "version": 1,
1102                            "name": c.name,
1103                            "description": c.description,
1104                            "is_owner": crate::community::service::is_proven_owner(&c),
1105                            "channels": c.channels.iter()
1106                                .map(|ch| serde_json::json!({ "channel_id": ch.id.to_hex(), "name": ch.name }))
1107                                .collect::<Vec<_>>(),
1108                        }));
1109                    }
1110                }
1111            }
1112        }
1113        out
1114    }
1115
1116    /// Create a fresh **Concord v2** community owned by the local identity (the
1117    /// SDK's default; the GUI's `create_community` stays v1 during the migration
1118    /// window). Mints the self-certifying id + genesis, persists, publishes, and
1119    /// registers each channel as a chat. Returns a `version: 2` JSON summary.
1120    pub async fn create_community_v2(&self, name: &str) -> Result<serde_json::Value> {
1121        use crate::community::{v2::service as v2, transport::LiveTransport};
1122        let relays: Vec<String> = crate::state::active_trusted_relays()
1123            .await
1124            .iter()
1125            .map(|s| s.to_string())
1126            .collect();
1127        if relays.is_empty() {
1128            return Err(VectorError::Other("no relays available to host the Community".into()));
1129        }
1130        let session = state::SessionGuard::capture();
1131        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
1132        let community = v2::create_community(&transport, name, relays, None)
1133            .await
1134            .map_err(VectorError::Other)?;
1135        self.register_v2_chats(&community, &session).await;
1136        // Start streaming this community's planes right away.
1137        if let Some(client) = state::nostr_client() {
1138            crate::community::v2::realtime::refresh_subscription(&client).await;
1139        }
1140        Ok(Self::v2_summary(&community))
1141    }
1142
1143    /// If `channel_id` belongs to a locally-held **v2** community, its
1144    /// `CommunityId`; `Ok(None)` for a v1 channel or unknown. The routing key for
1145    /// every dual-stack message op — a DB read error PROPAGATES (fail-closed)
1146    /// instead of silently routing a v2 channel down the v1 path on a transient
1147    /// failure.
1148    fn v2_community_for_channel(&self, channel_id: &str) -> Result<Option<crate::community::CommunityId>> {
1149        use crate::community::ConcordProtocol;
1150        let Some(cid_hex) = crate::db::community::community_id_for_channel(channel_id).map_err(VectorError::Other)? else {
1151            return Ok(None);
1152        };
1153        let cid = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&cid_hex));
1154        Ok(match crate::db::community::community_protocol(&cid).map_err(VectorError::Other)? {
1155            Some(ConcordProtocol::V2) => Some(cid),
1156            _ => None,
1157        })
1158    }
1159
1160    /// The `version: 2` JSON summary the SDK/facade hands back for a v2 community.
1161    fn v2_summary(community: &crate::community::v2::community::CommunityV2) -> serde_json::Value {
1162        let me = state::my_public_key();
1163        let is_owner = me.is_some_and(|m| community.owner().is_ok_and(|o| o == m));
1164        serde_json::json!({
1165            "community_id": crate::simd::hex::bytes_to_hex_32(&community.identity.community_id.0),
1166            "version": 2,
1167            "name": community.name,
1168            "description": community.description,
1169            "is_owner": is_owner,
1170            "channels": community.channels.iter()
1171                .map(|c| serde_json::json!({ "channel_id": crate::simd::hex::bytes_to_hex_32(&c.id.0), "name": c.name, "private": c.private }))
1172                .collect::<Vec<_>>(),
1173        })
1174    }
1175
1176    /// Register each of a v2 community's channels as a chat row (so it surfaces in
1177    /// the chat list / `communities()`), mirroring the v1 create path. `session`
1178    /// is captured by the caller BEFORE its network I/O, so this STATE write is
1179    /// skipped if the account swapped mid-flight (else we'd write A's community
1180    /// into B's in-memory chats).
1181    pub async fn register_v2_chats(&self, community: &crate::community::v2::community::CommunityV2, session: &state::SessionGuard) {
1182        register_v2_chats_inner(community, session).await
1183    }
1184}
1185
1186/// Free-function body of [`VectorCore::register_v2_chats`] — also the migration finalize's
1187/// chat stamp (it runs from a spawned task with no facade handle; only globals are touched).
1188pub(crate) async fn register_v2_chats_inner(community: &crate::community::v2::community::CommunityV2, session: &state::SessionGuard) {
1189    let owner_npub = community.owner().ok().and_then(|p| ToBech32::to_bech32(&p).ok());
1190        let me = state::my_public_key();
1191        let is_owner = me.is_some_and(|m| community.owner().is_ok_and(|o| o == m));
1192        let id_hex = crate::simd::hex::bytes_to_hex_32(&community.identity.community_id.0);
1193        // The chat list shows ONE row per community — the primary channel under the
1194        // community's metadata (v1-group parity; multi-channel UI is a later cut).
1195        let Some(primary) = community.primary_channel() else { return };
1196        let primary_hex = crate::simd::hex::bytes_to_hex_32(&primary.id.0);
1197        // Every channel gets a real chat row carrying its own name plus the community's
1198        // primary id. The chat list still shows ONE row per community (it renders only the
1199        // primary), but the sibling rows are now addressable, which is what lets the UI
1200        // reach a multi-channel community's other channels.
1201        let slims = {
1202            let mut st = state::STATE.lock().await;
1203            if !session.is_valid() {
1204                return; // account swapped during the join/create — don't write into the new one.
1205            }
1206            let mut slims = Vec::new();
1207            for ch in &community.channels {
1208                let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
1209                st.upsert_community_chat(
1210                    &ch_hex,
1211                    &community.name,
1212                    community.description.as_deref().unwrap_or(""),
1213                    &id_hex,
1214                    is_owner,
1215                    community.icon.is_some(),
1216                    owner_npub.as_deref(),
1217                    Some(community.created_at_ms),
1218                    community.dissolved,
1219                    crate::community::ConcordProtocol::V2,
1220                    &ch.name,
1221                    &primary_hex,
1222                );
1223                if let Some(chat) = st.chats.iter().find(|c| c.id == ch_hex) {
1224                    slims.push(crate::db::chats::SlimChatDB::from_chat(chat, &st.interner));
1225                }
1226            }
1227            slims
1228        };
1229        // Persist the rows so a fresh boot reloads each channel's name/metadata
1230        // instead of the bare auto-created anchor. Session re-check: don't write
1231        // account A's rows into a swapped-in account B's DB.
1232        if !session.is_valid() {
1233            return;
1234        }
1235        for slim in &slims {
1236            let _ = crate::db::chats::save_slim_chat(slim);
1237        }
1238}
1239
1240impl VectorCore {
1241    /// Join a Community from a public invite URL (`vectorapp.io/invite#...`). Fetches the
1242    /// token-encrypted bundle, persists the member-view Community, and registers its channels
1243    /// as chats. Returns a JSON summary.
1244    pub async fn join_community(&self, invite_url: &str) -> Result<serde_json::Value> {
1245        use crate::community::{public_invite, service, transport::LiveTransport};
1246        // Dual-stack: a v2 link is `…/invite/<naddr>#<fragment>` (a naddr in the
1247        // path); a v1 link is `…/invite#<base64url>` (fragment only). Try the v2
1248        // parser first — it only succeeds on the v2 shape — then fall through to v1.
1249        if crate::community::v2::invite::parse_invite_link(invite_url).is_ok() {
1250            let session = state::SessionGuard::capture();
1251            let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
1252            let community = crate::community::v2::service::accept_public_link(&transport, invite_url)
1253                .await
1254                .map_err(VectorError::Other)?;
1255            self.register_v2_chats(&community, &session).await;
1256            if let Some(client) = state::nostr_client() {
1257                crate::community::v2::realtime::refresh_subscription(&client).await;
1258            }
1259            // Seed the membership store post-join. With a live listen the follow
1260            // worker does it (and SURFACES the folded joins as presence lines —
1261            // the joiner sees the room's history, own join included); headless
1262            // callers seed directly (membership only, no feed to surface).
1263            if crate::community::v2::realtime::follow_worker_running() {
1264                crate::community::v2::realtime::enqueue_follow(community.id());
1265            } else {
1266                let seed_session = state::SessionGuard::capture();
1267                let seed_community = community.clone();
1268                tokio::spawn(async move {
1269                    if !seed_session.is_valid() {
1270                        return;
1271                    }
1272                    let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(20));
1273                    if matches!(
1274                        crate::community::v2::service::sync_guestbook(&transport, &seed_community, &seed_session).await,
1275                        Ok(fresh) if !fresh.is_empty()
1276                    ) {
1277                        let cid_hex = crate::simd::hex::bytes_to_hex_32(&seed_community.id().0);
1278                        emit_event("community_refreshed", &serde_json::json!({ "community_id": cid_hex }));
1279                    }
1280                });
1281            }
1282            return Ok(Self::v2_summary(&community));
1283        }
1284        let (relays, token) = public_invite::parse_invite_url(invite_url)
1285            .map_err(|e| VectorError::Other(e.to_string()))?;
1286        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
1287        let bundle = service::fetch_public_invite(&transport, &relays, &token)
1288            .await
1289            .map_err(VectorError::Other)?;
1290        let now = std::time::SystemTime::now()
1291            .duration_since(std::time::UNIX_EPOCH)
1292            .map(|d| d.as_secs())
1293            .unwrap_or(0);
1294        // Post-timelock door: a FRESH v1 join needs a migration carrier (the v2 on-ramp)
1295        // or it is refused. Decode-only view — nothing persists unless the gate passes.
1296        let probe_view = crate::community::invite::accept_invite(&bundle.join).map_err(VectorError::Other)?;
1297        crate::community::migration::gate_fresh_v1_join(&transport, &probe_view, now)
1298            .await
1299            .map_err(VectorError::Other)?;
1300        let community = service::accept_public_invite(&bundle, now).map_err(VectorError::Other)?;
1301        // Attribute our join presence to the link we used (creator + label) so the owner's per-link
1302        // counter ticks. Mirrors the desktop public-join path.
1303        let attribution = bundle.creator_npub.clone().map(|by| (by, bundle.label.clone()));
1304        self.finalize_member_join(community, &transport, attribution).await
1305    }
1306
1307    /// List the parked private invites (giftwrapped) awaiting acceptance. Each entry is the
1308    /// community id, its name (from the stored bundle), and the inviter's npub.
1309    pub fn list_pending_invites(&self) -> Result<Vec<serde_json::Value>> {
1310        let rows = crate::db::community::list_pending_invites().map_err(VectorError::Other)?;
1311        Ok(rows.iter().map(|p| {
1312            // A v2 bundle carries owner_salt/community_root and self-certifies its
1313            // owner; a successful (validating) v2 parse means the modern protocol.
1314            if let Ok(v2) = crate::community::v2::invite::CommunityInvite::from_bundle_json(&p.bundle_json) {
1315                serde_json::json!({
1316                    "community_id": p.community_id,
1317                    "name": v2.name,
1318                    "inviter_npub": p.inviter_npub,
1319                    "version": 2,
1320                })
1321            } else {
1322                let name = crate::community::invite::CommunityInvite::from_json(&p.bundle_json)
1323                    .ok().map(|i| i.name).unwrap_or_default();
1324                serde_json::json!({
1325                    "community_id": p.community_id,
1326                    "name": name,
1327                    "inviter_npub": p.inviter_npub,
1328                    "version": 1,
1329                })
1330            }
1331        }).collect())
1332    }
1333
1334    /// Accept a PARKED private invite by community id: rebuild the member-view Community from the stored
1335    /// bundle, finalize the join exactly like a public link, then drop the pending row. Mirrors the
1336    /// desktop's consent-then-join for an invite delivered over a gift wrap.
1337    pub async fn accept_pending_invite(&self, community_id: &str) -> Result<serde_json::Value> {
1338        use crate::community::transport::LiveTransport;
1339        let bundle_json = crate::db::community::get_pending_invite(community_id)
1340            .map_err(VectorError::Other)?
1341            .ok_or_else(|| VectorError::Other(format!("no pending invite for {community_id}")))?;
1342        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
1343
1344        // Dual-stack: a validating v2 bundle parse means a v2 Direct Invite.
1345        if crate::community::v2::invite::CommunityInvite::from_bundle_json(&bundle_json).is_ok() {
1346            let session = state::SessionGuard::capture();
1347            // The inviter's hex (parked at receive) attributes the Guestbook Join.
1348            let inviter = crate::db::community::list_pending_invites()
1349                .ok()
1350                .and_then(|rows| rows.into_iter().find(|p| p.community_id == community_id).map(|p| p.inviter_npub));
1351            // On failure the parked row is LEFT INTACT for retry — we must NOT auto-delete
1352            // on a verify failure: the multi-relay transport launders an unreachable-relay
1353            // error into an empty fetch, which yields the same "could not verify" as a
1354            // forged root (and a control-plane flood does too), so an auto-delete would
1355            // erase a GENUINE invite on a transient blip or an attacker's flood. A
1356            // pre-planted forged-root bundle (deferred protocol residual) is instead
1357            // cleared by the user declining it.
1358            let community = crate::community::v2::service::accept_parked_invite(&transport, &bundle_json, inviter.as_deref())
1359                .await
1360                .map_err(VectorError::Other)?;
1361            if !session.is_valid() {
1362                return Err(VectorError::Other("account changed during join".into()));
1363            }
1364            self.register_v2_chats(&community, &session).await;
1365            if let Some(client) = state::nostr_client() {
1366                crate::community::v2::realtime::refresh_subscription(&client).await;
1367            }
1368            crate::community::v2::realtime::enqueue_follow(community.id());
1369            let _ = crate::db::community::delete_pending_invite(community_id);
1370            return Ok(Self::v2_summary(&community));
1371        }
1372
1373        // v1 route.
1374        use crate::community::invite::{accept_invite, CommunityInvite};
1375        let invite = CommunityInvite::from_json(&bundle_json).map_err(VectorError::Other)?;
1376        let community = accept_invite(&invite).map_err(VectorError::Other)?;
1377        // Post-timelock door: a FRESH v1 join needs a migration carrier (the v2 on-ramp) or it
1378        // is refused — before finalize persists anything. The migrated fence inside
1379        // finalize_member_join still wins for held communities.
1380        let now = std::time::SystemTime::now()
1381            .duration_since(std::time::UNIX_EPOCH)
1382            .map(|d| d.as_secs())
1383            .unwrap_or(0);
1384        crate::community::migration::gate_fresh_v1_join(&transport, &community, now)
1385            .await
1386            .map_err(VectorError::Other)?;
1387        // Private invites carry no public-link label; the inviter attribution metric is link-only.
1388        let summary = self.finalize_member_join(community, &transport, None).await?;
1389        let _ = crate::db::community::delete_pending_invite(community_id);
1390        Ok(summary)
1391    }
1392
1393    /// Shared finalization for joining a Community as a member — public link OR accepted private invite.
1394    /// Walks any base rekey, folds the LATEST control plane (so the joiner sees current metadata, not
1395    /// the bundle's genesis snapshot), refuses if banned, registers the channels as chats, and announces
1396    /// presence. Returns the JSON summary.
1397    pub(crate) async fn finalize_member_join<T: crate::community::transport::Transport + ?Sized>(
1398        &self,
1399        community: crate::community::Community,
1400        transport: &T,
1401        attribution: Option<(String, Option<String>)>,
1402    ) -> Result<serde_json::Value> {
1403        use crate::community::service;
1404        // Migration fence: if this v1 community already flipped to v2, a stale parked
1405        // invite or a lingering link must NOT re-run `save_community` — its blind UPSERT would
1406        // re-parent the stitched channel rows back to v1 with v1 keys (the catastrophic mixed
1407        // state). Short-circuit to "already upgraded"; the rows stay v2-owned. This is
1408        // `migrated_to`-aware (not a blind dissolved gate) precisely so a FRESH joiner redeeming
1409        // a still-live link stays on the open on-ramp path below.
1410        if let Ok(Some(v2)) = crate::db::community::get_migrated_to(&community.id.to_hex()) {
1411            return Ok(serde_json::json!({
1412                "community_id": v2,
1413                "version": 2,
1414                "migrated": true,
1415            }));
1416        }
1417        // Persist the member-view row up front: the catch-up, the control fold, and chat registration all
1418        // read it back from the DB. A private bundle (unlike a public one with a preview) arrives with no
1419        // display metadata, so nothing else would have saved it. UPSERT — re-saving a public join is a no-op.
1420        crate::db::community::save_community(&community).map_err(VectorError::Other)?;
1421        // The bundle's root can predate a base rotation, so walk any rekey first (no-op if none) — then
1422        // re-load so the control fold + registration happen at the CURRENT epoch.
1423        if let Ok(c) = service::catch_up_server_root(transport, &community).await {
1424            if c.removed {
1425                let _ = crate::db::community::delete_community(&community.id.to_hex());
1426                return Err(VectorError::Other("you have been removed from this community".into()));
1427            }
1428        }
1429        let community = crate::db::community::load_community(&community.id)
1430            .map_err(VectorError::Other)?
1431            .unwrap_or(community);
1432        // Fold the LATEST control plane before we register anything — the joiner should see the current
1433        // name/description/roster/mode immediately, not a stale snapshot. Banlist first: an honest client
1434        // REFUSES to join if this npub is banned (and the just-saved community is torn back down).
1435        let _ = service::fetch_and_apply_control(transport, &community).await;
1436        if service::am_i_banned(&community) {
1437            let _ = crate::db::community::delete_community(&community.id.to_hex());
1438            return Err(VectorError::Other("you are banned from this community".into()));
1439        }
1440        // Re-load so the chat we register + the summary we return carry the freshly-folded latest metadata.
1441        let community = crate::db::community::load_community(&community.id)
1442            .map_err(VectorError::Other)?
1443            .unwrap_or(community);
1444        let owner_npub = community
1445            .owner_attestation
1446            .as_ref()
1447            .and_then(|att| crate::community::owner::verify_owner_attestation(att, &community.id.to_hex()))
1448            .and_then(|pk| ToBech32::to_bech32(&pk).ok());
1449        {
1450            let created_at_ms = crate::db::community::community_created_at_ms(&community.id);
1451            let primary_hex = community.channels.first().map(|c| c.id.to_hex()).unwrap_or_default();
1452            let mut st = state::STATE.lock().await;
1453            for ch in &community.channels {
1454                st.upsert_community_chat(
1455                    &ch.id.to_hex(),
1456                    &community.name,
1457                    community.description.as_deref().unwrap_or(""),
1458                    &community.id.to_hex(),
1459                    crate::community::service::is_proven_owner(&community),
1460                    community.icon.is_some(),
1461                    owner_npub.as_deref(),
1462                    created_at_ms,
1463                    community.dissolved,
1464                    crate::community::ConcordProtocol::V1,
1465                    &ch.name,
1466                    &primary_hex,
1467                );
1468            }
1469        }
1470        // Best-effort join announcement (kind 3306) into the primary channel so honest peers
1471        // see us in their member list even before we post. Failure must not fail the join.
1472        if let Some(primary) = community.channels.first() {
1473            let _ = service::publish_presence(transport, &community, primary, true, attribution).await;
1474        }
1475        Ok(serde_json::json!({
1476            "community_id": community.id.to_hex(),
1477            "version": 1,
1478            "name": community.name,
1479            "channels": community.channels.iter()
1480                .map(|c| serde_json::json!({ "channel_id": c.id.to_hex(), "name": c.name }))
1481                .collect::<Vec<_>>(),
1482        }))
1483    }
1484
1485
1486    // ── Channels (CORD-03) ───────────────────────────────────────────────────
1487
1488    /// Resolve a v2 community by id, or explain why it isn't one.
1489    fn v2_community(community_id: &str) -> Result<crate::community::v2::community::CommunityV2> {
1490        use crate::community::CommunityId;
1491        if community_id.len() != 64 {
1492            return Err(VectorError::Other("malformed community id".into()));
1493        }
1494        let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
1495        match crate::db::community::community_protocol(&cid).ok().flatten() {
1496            Some(crate::community::ConcordProtocol::V2) => crate::db::community::load_community_v2(&cid)
1497                .map_err(VectorError::Other)?
1498                .ok_or_else(|| VectorError::Other("v2 community not found".into())),
1499            Some(_) => Err(VectorError::Other(
1500                "channel management is Concord v2 only — this community still uses the legacy protocol".into(),
1501            )),
1502            None => Err(VectorError::Other("community not found".into())),
1503        }
1504    }
1505
1506    fn channel_id_of(channel_id: &str) -> Result<crate::community::ChannelId> {
1507        crate::simd::hex::hex_to_bytes_32_checked(channel_id)
1508            .map(crate::community::ChannelId)
1509            .ok_or_else(|| VectorError::Other("malformed channel id".into()))
1510    }
1511
1512    /// Create a channel. A private one mints its own key plus the channel-scoped
1513    /// access Role that is its access list (CORD-03/04); grant that role with
1514    /// [`grant_channel_access`](Self::grant_channel_access) to let someone read it.
1515    /// Returns the new channel id (32-byte hex).
1516    pub async fn create_channel(&self, community_id: &str, name: &str, private: bool) -> Result<String> {
1517        use crate::community::{v2::service, transport::LiveTransport};
1518        let community = Self::v2_community(community_id)?;
1519        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
1520        let id = if private {
1521            service::create_private_channel(&transport, &community, name).await
1522        } else {
1523            service::create_public_channel(&transport, &community, name).await
1524        }
1525        .map_err(VectorError::Other)?;
1526        // Subscribe the new channel's chat plane now — waiting on the round-trip of
1527        // our own vsk-2 edition would leave the creator deaf to first replies.
1528        if let Some(client) = state::nostr_client() {
1529            crate::community::v2::realtime::refresh_subscription(&client).await;
1530        }
1531        Ok(crate::simd::hex::bytes_to_hex_32(&id.0))
1532    }
1533
1534    /// Rename a channel (a versioned edit of the same entity, so its history and
1535    /// id survive). Other folded fields are carried through untouched.
1536    pub async fn rename_channel(&self, community_id: &str, channel_id: &str, name: &str) -> Result<()> {
1537        use crate::community::{v2::service, transport::LiveTransport};
1538        let community = Self::v2_community(community_id)?;
1539        let id = Self::channel_id_of(channel_id)?;
1540        let mut meta = community
1541            .channel(&id)
1542            .ok_or_else(|| VectorError::Other("unknown channel".into()))?
1543            .metadata();
1544        meta.name = name.to_string();
1545        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
1546        service::edit_channel_metadata(&transport, &community, &id, &meta)
1547            .await
1548            .map_err(VectorError::Other)
1549    }
1550
1551    /// Tombstone a channel. Deletion is terminal and the id is never reused;
1552    /// history stays readable to anyone who already holds its keys.
1553    pub async fn delete_channel(&self, community_id: &str, channel_id: &str) -> Result<()> {
1554        use crate::community::{v2::service, transport::LiveTransport};
1555        let community = Self::v2_community(community_id)?;
1556        let id = Self::channel_id_of(channel_id)?;
1557        let name = community.channel(&id).map(|c| c.name.clone()).unwrap_or_default();
1558        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
1559        service::delete_channel(&transport, &community, &id, &name)
1560            .await
1561            .map_err(VectorError::Other)
1562    }
1563
1564    /// Grant `npub` read access to a private channel: adds the channel's access
1565    /// role and vends the key to them (CORD-03 "delivered on grant").
1566    pub async fn grant_channel_access(&self, community_id: &str, channel_id: &str, npub: &str) -> Result<()> {
1567        use crate::community::{v2::service, transport::LiveTransport};
1568        let community = Self::v2_community(community_id)?;
1569        let id = Self::channel_id_of(channel_id)?;
1570        let member = nostr_sdk::prelude::PublicKey::parse(npub)
1571            .map_err(|e| VectorError::Other(format!("bad npub: {e}")))?;
1572        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
1573        service::grant_channel_access(&transport, &community, &id, &member)
1574            .await
1575            .map_err(VectorError::Other)
1576    }
1577
1578    /// Revoke `npub`'s read access: drops the access role and rekeys the channel
1579    /// so the removal actually severs them (CORD-06). They keep whatever history
1580    /// they already read — a rekey protects the future, never the past.
1581    pub async fn revoke_channel_access(&self, community_id: &str, channel_id: &str, npub: &str) -> Result<()> {
1582        use crate::community::{v2::service, transport::LiveTransport};
1583        let community = Self::v2_community(community_id)?;
1584        let id = Self::channel_id_of(channel_id)?;
1585        let member = nostr_sdk::prelude::PublicKey::parse(npub)
1586            .map_err(|e| VectorError::Other(format!("bad npub: {e}")))?;
1587        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
1588        service::revoke_channel_access(&transport, &community, &id, &member)
1589            .await
1590            .map_err(VectorError::Other)
1591    }
1592
1593    /// Who may read a private channel: the channel-scoped Roles that are its
1594    /// access list (CORD-04 §2) and the members holding them.
1595    ///
1596    /// Sync read off the folded roster. `members` is exactly the access-role
1597    /// holders; `owner` is reported alongside because the owner is entitled
1598    /// whether or not they hold one (a channel's creator is granted the role, so
1599    /// an owner-created channel lists them in both).
1600    pub fn channel_access(&self, community_id: &str, channel_id: &str) -> Result<serde_json::Value> {
1601        use nostr_sdk::prelude::{PublicKey, ToBech32};
1602        let community = Self::v2_community(community_id)?;
1603        let id = Self::channel_id_of(channel_id)?;
1604        let ch = community
1605            .channel(&id)
1606            .ok_or_else(|| VectorError::Other("unknown channel".into()))?;
1607        // Normalised id, not the caller's string: an uppercase-hex argument loads
1608        // the community but would miss the roster row and silently report nobody.
1609        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
1610        let roster = crate::db::community::get_community_roles(&cid_hex).map_err(VectorError::Other)?;
1611        let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
1612        let chan_hex = crate::simd::hex::bytes_to_hex_32(&id.0);
1613        let access_ids = roster.channel_role_ids(&chan_hex);
1614        let roles: Vec<serde_json::Value> = roster
1615            .channel_roles(&chan_hex)
1616            .into_iter()
1617            .map(|r| serde_json::json!({ "role_id": r.role_id, "name": r.name }))
1618            .collect();
1619        let members: Vec<String> = roster
1620            .grants
1621            .iter()
1622            .filter(|g| !banned.contains(&g.member))
1623            .filter(|g| g.role_ids.iter().any(|rid| access_ids.contains(rid)))
1624            .filter_map(|g| PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok()))
1625            .collect();
1626        Ok(serde_json::json!({
1627            "channel_id": chan_hex,
1628            "private": ch.private,
1629            "readable": !(ch.private && ch.key.is_none()),
1630            "owner": community.owner().ok().and_then(|o| o.to_bech32().ok()),
1631            "roles": roles,
1632            "members": members,
1633        }))
1634    }
1635
1636    /// Mint a public invite link for a Community this identity owns. Returns the shareable URL.
1637    /// `expires_at_ms` is an ABSOLUTE unix timestamp in MILLISECONDS (v2's native unit and the
1638    /// `InviteEntry` wire's); the v1 path takes seconds, so it is converted here rather than at
1639    /// each call site. `label` is the attribution bucket shown as "joined via <label>".
1640    pub async fn create_public_invite(
1641        &self,
1642        community_id: &str,
1643        expires_at_ms: Option<u64>,
1644        label: Option<String>,
1645    ) -> Result<String> {
1646        use crate::community::{service, transport::LiveTransport, CommunityId};
1647        if community_id.len() != 64 {
1648            return Err(VectorError::Other("malformed community id".into()));
1649        }
1650        let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
1651        // Dual-stack: mint a v2 link for a v2 community (naddr#fragment).
1652        if let Some(Some(crate::community::ConcordProtocol::V2)) =
1653            crate::db::community::community_protocol(&cid).ok()
1654        {
1655            let community = crate::db::community::load_community_v2(&cid)
1656                .map_err(VectorError::Other)?
1657                .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
1658            let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
1659            // v2 `build_invite_url` appends its own `/invite/<naddr>`, so pass the
1660            // bare domain (strip the `/invite` the v1 constant carries).
1661            let base = crate::community::public_invite::INVITE_URL_BASE.trim_end_matches("/invite");
1662            let minted =
1663                crate::community::v2::service::mint_public_link(&transport, &community, base, expires_at_ms, label)
1664                    .await
1665                    .map_err(VectorError::Other)?;
1666            return Ok(minted.url);
1667        }
1668        let community = crate::db::community::load_community(&CommunityId(
1669            crate::simd::hex::hex_to_bytes_32(community_id),
1670        ))
1671        .map_err(VectorError::Other)?
1672        .ok_or_else(|| VectorError::Other("community not found".into()))?;
1673        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
1674        let expires_at_secs = expires_at_ms.map(|ms| ms / 1000);
1675        let (_token, url) = service::create_public_invite(&transport, &community, expires_at_secs, label)
1676            .await
1677            .map_err(VectorError::Other)?;
1678        Ok(url)
1679    }
1680
1681    /// Send a PRIVATE invite: gift-wrap this Community's invite bundle directly to an npub over a NIP-17
1682    /// DM (the same transport as a regular DM). The invitee parks it pending consent (accept_pending_invite).
1683    /// Requires CREATE_INVITE; a banned npub can't be re-invited. Returns the wrap's event id + relays.
1684    pub async fn invite_to_community(&self, community_id: &str, invitee_npub: &str) -> Result<serde_json::Value> {
1685        use crate::community::{service, CommunityId};
1686        use crate::sending::{send_rumor_dm, NoOpSendCallback, SendCallback, SendConfig};
1687
1688        let session = crate::state::SessionGuard::capture();
1689        let my_pk = crate::state::my_public_key()
1690            .ok_or_else(|| VectorError::Other("Public key not set".into()))?;
1691
1692        if community_id.len() != 64 {
1693            return Err(VectorError::Other("malformed community id".into()));
1694        }
1695        let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
1696        // Dual-stack: a v2 community sends a Direct Invite (3313 giftwrap).
1697        // DELIBERATELY ungated, unlike v1's CREATE_INVITE + banlist pre-check: a
1698        // Direct Invite is an ungateable key handoff (CORD-05 §6 — "any keyholder
1699        // can whisper keys"), so any member may extend one; the real access cut is
1700        // the rekey, not a permission on inviting.
1701        if let Some(Some(crate::community::ConcordProtocol::V2)) =
1702            crate::db::community::community_protocol(&cid).ok()
1703        {
1704            let recipient = nostr_sdk::prelude::PublicKey::parse(invitee_npub)
1705                .map_err(|e| VectorError::Other(format!("bad invitee npub: {e}")))?;
1706            let client = crate::state::nostr_client().ok_or_else(|| VectorError::Other("Not connected".into()))?;
1707            // Gift-wrap the 3313 Direct-Invite rumor (the bundle JSON) to the RECIPIENT'S
1708            // inbox relays (kind-10050) — a not-yet-member sees it on their DM sub;
1709            // the community relays wouldn't reach them. `#k=3313` per CORD-05 §6.
1710            //
1711            // Load + snapshot UNDER the rotation lock: a bundle minted while a Ban's
1712            // refound is mid-rotation carries the root being buried, and its joiner
1713            // lands on a dead epoch only to self-evict on the rekey exclusion.
1714            let bundle = {
1715                let lock = crate::community::v2::realtime::follow_lock(&cid);
1716                let _rotation = lock.lock().await;
1717                let community = crate::db::community::load_community_v2(&cid)
1718                    .map_err(VectorError::Other)?
1719                    .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
1720                crate::community::v2::service::bundle_of(
1721                    &community,
1722                    crate::community::v2::service::BundleAudience::Member(recipient),
1723                    Some(my_pk),
1724                    None,
1725                    None,
1726                )
1727            };
1728            let bundle_json = serde_json::to_string(&bundle).map_err(|e| VectorError::Other(e.to_string()))?;
1729            // Same 24h NIP-40 expiry as v1 (invite::DIRECT_INVITE_EXPIRY_SECS): a bundle is
1730            // live key material for a community that keeps rotating, so it must not linger.
1731            let expires_at = nostr_sdk::prelude::Timestamp::now().as_secs()
1732                + crate::community::invite::DIRECT_INVITE_EXPIRY_SECS;
1733            let expiry_tag = nostr_sdk::prelude::Tag::expiration(nostr_sdk::prelude::Timestamp::from_secs(expires_at));
1734            let rumor = nostr_sdk::prelude::EventBuilder::new(
1735                nostr_sdk::prelude::Kind::Custom(crate::community::v2::kind::DIRECT_INVITE),
1736                bundle_json,
1737            )
1738            .tag(expiry_tag.clone())
1739            .finalize_unsigned_with_id(my_pk);
1740            let k_tag = nostr_sdk::prelude::Tag::custom(
1741                "k",
1742                [crate::community::v2::kind::DIRECT_INVITE.to_string()],
1743            );
1744            if !session.is_valid() {
1745                return Err(VectorError::Other("account changed".into()));
1746            }
1747            crate::inbox_relays::send_gift_wrap(&client, &recipient, rumor, [k_tag, expiry_tag])
1748                .await
1749                .map_err(VectorError::Other)?;
1750            return Ok(serde_json::json!({ "invited": invitee_npub, "version": 2 }));
1751        }
1752        let community = crate::db::community::load_community(&CommunityId(
1753            crate::simd::hex::hex_to_bytes_32(community_id),
1754        ))
1755        .map_err(VectorError::Other)?
1756        .ok_or_else(|| VectorError::Other("community not found".into()))?;
1757
1758        if !service::caller_has_permission(&community, crate::community::roles::Permissions::CREATE_INVITE) {
1759            return Err(VectorError::Other("You need the create-invite permission to invite someone".into()));
1760        }
1761        let invitee_hex = nostr_sdk::prelude::PublicKey::parse(invitee_npub)
1762            .map_err(|_| VectorError::Other("invalid npub".into()))?
1763            .to_hex();
1764        if crate::db::community::get_community_banlist(community_id)
1765            .map_err(VectorError::Other)?
1766            .iter()
1767            .any(|b| b == &invitee_hex)
1768        {
1769            return Err(VectorError::Other("That member is banned from this community and can't be invited".into()));
1770        }
1771
1772        // The bundle is built from purely local state; bail if the account swapped before the gift-wrap.
1773        if !session.is_valid() {
1774            return Err(VectorError::Other("account changed during invite".into()));
1775        }
1776
1777        let now = nostr_sdk::prelude::Timestamp::now().as_secs();
1778        let rumor = crate::community::invite::build_invite_rumor(&community, my_pk, now)
1779            .map_err(VectorError::Other)?;
1780        let pending_id = format!("community-invite-{}", community_id);
1781        // self_send=false: the owner already holds the Community; the inbound guard would drop the echo.
1782        let config = SendConfig { self_send: false, ..SendConfig::gui() };
1783        let callback: Arc<dyn SendCallback> = Arc::new(NoOpSendCallback);
1784
1785        let result = send_rumor_dm(invitee_npub, &pending_id, rumor, &config, callback)
1786            .await
1787            .map_err(VectorError::Other)?;
1788
1789        Ok(serde_json::json!({
1790            "community_id": community_id,
1791            "invitee": invitee_npub,
1792            "wrap_event_id": result.event_id,
1793        }))
1794    }
1795
1796    /// The public invite links this account minted for a Community (to list + revoke). Each carries
1797    /// the hex `token` (the link secret) needed by [`Self::revoke_public_invite`]. A local read for
1798    /// both protocols — links minted on this device (a v2 mint also syncs the cross-device 13303
1799    /// record; v2 `join_count` is not yet tracked and is always 0).
1800    pub fn list_public_invites(&self, community_id: &str) -> Result<Vec<crate::db::community::PublicInviteRecord>> {
1801        crate::db::community::list_public_invites(community_id).map_err(VectorError::Other)
1802    }
1803
1804    /// Revoke a public invite link by its hex token. Retiring the LAST active link flips the Community to
1805    /// Private, which re-founds (rotates the base key + every channel key) to cut link-joined lurkers.
1806    /// Idempotent: a token this account doesn't hold is a no-op. Needs a local key when the revoke triggers
1807    /// the privatize rekey (a bunker account can't rotate).
1808    pub async fn revoke_public_invite(&self, community_id: &str, token: &str) -> Result<()> {
1809        use crate::community::{service, transport::LiveTransport, CommunityId};
1810        if community_id.len() != 64 {
1811            return Err(VectorError::Other("malformed community id".into()));
1812        }
1813        let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
1814        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(20));
1815        // Dual-stack: a v2 link is retired by its 16-byte token hex (re-post the
1816        // coordinate as a tombstone + tombstone the 13303 entry + refresh the Registry).
1817        if let Some(Some(crate::community::ConcordProtocol::V2)) = crate::db::community::community_protocol(&cid).ok() {
1818            let community = crate::db::community::load_community_v2(&cid)
1819                .map_err(VectorError::Other)?
1820                .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
1821            return crate::community::v2::service::revoke_public_link(&transport, &community, token)
1822                .await
1823                .map_err(VectorError::Other);
1824        }
1825        let token_bytes = crate::simd::hex::hex_to_bytes_32(token);
1826        let community = crate::db::community::load_community(&cid)
1827            .map_err(VectorError::Other)?
1828            .ok_or_else(|| VectorError::Other("community not found".into()))?;
1829        service::revoke_public_invite(&transport, &community, &token_bytes)
1830            .await
1831            .map_err(VectorError::Other)
1832    }
1833
1834    /// Post a text message to a Community channel. Returns the message id (the inner id).
1835    pub async fn send_community_message(
1836        &self,
1837        channel_id: &str,
1838        content: &str,
1839        replied_to: Option<&str>,
1840    ) -> Result<String> {
1841        use crate::community::{envelope, inbound, service, transport::LiveTransport};
1842        // Dual-stack: route by the owning community's stored protocol.
1843        if let Some(id) = self.v2_community_for_channel(channel_id)? {
1844            let community = crate::db::community::load_community_v2(&id)
1845                .map_err(VectorError::Other)?
1846                .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
1847            let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
1848            let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
1849            // The NIP-C7 q tag's author slot is a SHOULD — best-effort from the
1850            // held message, empty (= unknown) when the parent isn't in memory.
1851            let reply = match replied_to.filter(|r| !r.is_empty()) {
1852                Some(parent_id) => {
1853                    let author_hex = {
1854                        let st = state::STATE.lock().await;
1855                        st.find_message(parent_id)
1856                            .and_then(|(_, m)| m.npub.as_deref().and_then(|n| nostr_sdk::prelude::PublicKey::parse(n).ok()))
1857                            .map(|pk| pk.to_hex())
1858                            .unwrap_or_default()
1859                    };
1860                    Some((parent_id.to_string(), author_hex))
1861                }
1862                None => None,
1863            };
1864            let reply_ref = reply.as_ref().map(|(id, author)| (id.as_str(), author.as_str()));
1865            // NIP-30: resolve `:shortcode:` against subscribed packs so the rumor
1866            // carries `["emoji", ...]` pairs — parity with the v1 inner event.
1867            let emoji_owned = crate::emoji_packs::resolve_outbound_emoji_tags(content);
1868            let emoji_pairs: Vec<(&str, &str)> = emoji_owned.iter().map(|t| (t.shortcode.as_str(), t.url.as_str())).collect();
1869            return crate::community::v2::service::send_chat_message(&transport, &community, &ch, content, reply_ref, &emoji_pairs, vec![])
1870                .await
1871                .map_err(VectorError::Other);
1872        }
1873        let (community, channel) = self.resolve_channel(channel_id)?;
1874        let author_pk = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
1875        let reply = replied_to.filter(|r| !r.is_empty());
1876        let ms = std::time::SystemTime::now()
1877            .duration_since(std::time::UNIX_EPOCH)
1878            .map(|d| d.as_millis() as u64)
1879            .unwrap_or(0);
1880        let unsigned = envelope::build_inner_typed(
1881            author_pk,
1882            &channel.id,
1883            channel.epoch,
1884            crate::stored_event::event_kind::COMMUNITY_MESSAGE,
1885            content,
1886            ms,
1887            reply,
1888            &[],
1889        );
1890        let message_id = unsigned.id.ok_or_else(|| VectorError::Other("inner event has no id".into()))?.to_hex();
1891        let _client = state::nostr_client().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
1892        let signer = crate::signer::active_signer().map_err(|e| VectorError::Other(format!("Signer unavailable: {e}")))?;
1893        let inner = unsigned.finalize_async(&signer).await.map_err(|e| VectorError::Other(format!("sign: {e}")))?;
1894        let session = state::SessionGuard::capture();
1895        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
1896        let outer = service::send_signed_message(&transport, &community, &channel, &inner)
1897            .await
1898            .map_err(VectorError::Other)?;
1899        // Local echo so get_messages reflects the send (the relay echo dedups on inner id).
1900        // A swap during the publish must not echo account A's message into account B.
1901        if !session.is_valid() {
1902            return Ok(message_id);
1903        }
1904        let echoed = {
1905            let mut st = state::STATE.lock().await;
1906            inbound::process_incoming(&mut st, &outer, &channel, &author_pk)
1907        };
1908        if let Some(inbound::IncomingEvent::NewMessage(msg)) = echoed {
1909            let _ = crate::db::events::save_message(channel_id, &msg).await;
1910        }
1911        Ok(message_id)
1912    }
1913
1914    /// Send a file to a Community channel as an encrypted attachment. Returns the message id.
1915    /// Mirrors the DM file pipeline (encrypt → Blossom upload → NIP-92 `imeta`) but publishes
1916    /// over the community transport.
1917    pub async fn send_community_file(&self, channel_id: &str, file_path: &str) -> Result<String> {
1918        use crate::community::{attachments, envelope, inbound, service, transport::LiveTransport};
1919        let path = std::path::Path::new(file_path);
1920        let bytes = std::fs::read(path).map_err(VectorError::Io)?;
1921        if bytes.is_empty() {
1922            return Err(VectorError::Other("Empty file".into()));
1923        }
1924        let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("file").to_string();
1925        let extension = path.extension().and_then(|e| e.to_str()).unwrap_or("bin").to_lowercase();
1926
1927        // Snapshot the session BEFORE the upload: the destination below is resolved
1928        // from THIS account's DB, and the upload can outlive an account swap.
1929        let session = state::SessionGuard::capture();
1930        // Dual-stack: resolve the destination BEFORE the upload so a bad channel
1931        // fails fast (never spend an upload on an unroutable send).
1932        let v2_target = match self.v2_community_for_channel(channel_id)? {
1933            Some(id) => Some(
1934                crate::db::community::load_community_v2(&id)
1935                    .map_err(VectorError::Other)?
1936                    .ok_or_else(|| VectorError::Other("v2 community not found".into()))?,
1937            ),
1938            None => None,
1939        };
1940        let v1_target = match v2_target {
1941            Some(_) => None,
1942            None => Some(self.resolve_channel(channel_id)?),
1943        };
1944        let author_pk = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
1945
1946        let file_hash = crate::crypto::sha256_hex(&bytes);
1947        let mime = crate::crypto::mime_from_extension(&extension);
1948        let img_meta = crate::crypto::generate_image_metadata(&bytes);
1949
1950        // Save the plaintext locally (hash-keyed) so the sender previews it instantly.
1951        let download_dir = crate::db::get_download_dir();
1952        let _ = std::fs::create_dir_all(&download_dir);
1953        let local_name = if filename.is_empty() { format!("{}.{}", &file_hash, extension) } else { filename.clone() };
1954        let local_path = crate::crypto::resolve_unique_filename(&download_dir, &local_name);
1955        let _ = std::fs::write(&local_path, &bytes);
1956
1957        // Encrypt → upload to Blossom (signer reused for the envelope below).
1958        let params = crate::crypto::generate_encryption_params();
1959        let encrypted = crate::crypto::encrypt_data(&bytes, &params)?;
1960        let encrypted_size = encrypted.len() as u64;
1961
1962        let _client = state::nostr_client().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
1963        let signer = crate::signer::active_signer().map_err(|e| VectorError::Other(format!("Signer unavailable: {e}")))?;
1964        let servers = crate::blossom_servers::compute_enabled_servers();
1965        if servers.is_empty() {
1966            return Err(VectorError::Other("No Blossom servers configured".into()));
1967        }
1968        let noop_progress: crate::blossom::ProgressCallback = std::sync::Arc::new(|_, _| Ok(()));
1969        let url = crate::blossom::upload_blob_with_progress_and_failover(
1970            signer.clone(),
1971            servers,
1972            std::sync::Arc::new(encrypted),
1973            Some(mime),
1974            /* is_encrypted */ true,
1975            noop_progress,
1976            Some(3),
1977            Some(std::time::Duration::from_secs(2)),
1978            None,
1979        ).await.map_err(VectorError::Other)?;
1980
1981        let attachment = crate::types::Attachment {
1982            id: file_hash.clone(),
1983            key: params.key.clone(),
1984            nonce: params.nonce.clone(),
1985            extension: extension.clone(),
1986            name: filename.clone(),
1987            url,
1988            path: local_path.to_string_lossy().to_string(),
1989            size: encrypted_size,
1990            img_meta,
1991            downloading: false,
1992            downloaded: true,
1993            ..Default::default()
1994        };
1995        let imeta = vec![attachments::attachment_to_imeta(&attachment)];
1996
1997        // The upload straddled awaits — never publish a pre-swap destination.
1998        if !session.is_valid() {
1999            return Err(VectorError::Other("account changed during upload".into()));
2000        }
2001        // v2: the imeta rides the kind-9 rumor verbatim (NIP-92), content empty.
2002        if let Some(community) = v2_target {
2003            let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
2004            let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(30));
2005            return crate::community::v2::service::send_chat_message(&transport, &community, &ch, "", None, &[], imeta)
2006                .await
2007                .map_err(VectorError::Other);
2008        }
2009        let (community, channel) = v1_target.expect("v1 target resolved when no v2 community matched");
2010        let ms = std::time::SystemTime::now()
2011            .duration_since(std::time::UNIX_EPOCH)
2012            .map(|d| d.as_millis() as u64)
2013            .unwrap_or(0);
2014        let unsigned = envelope::build_inner_full(
2015            author_pk, &channel.id, channel.epoch,
2016            stored_event::event_kind::COMMUNITY_MESSAGE, "", ms, None, &[], &imeta,
2017        );
2018        let message_id = unsigned.id.ok_or_else(|| VectorError::Other("inner event has no id".into()))?.to_hex();
2019        let inner = unsigned.finalize_async(&signer).await.map_err(|e| VectorError::Other(format!("sign: {e}")))?;
2020        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(30));
2021        let outer = service::send_signed_message(&transport, &community, &channel, &inner)
2022            .await.map_err(VectorError::Other)?;
2023        // Local echo so get_messages reflects the send.
2024        let echoed = {
2025            let mut st = state::STATE.lock().await;
2026            inbound::process_incoming(&mut st, &outer, &channel, &author_pk)
2027        };
2028        if let Some(inbound::IncomingEvent::NewMessage(m)) = echoed {
2029            let _ = crate::db::events::save_message(channel_id, &m).await;
2030        }
2031        Ok(message_id)
2032    }
2033
2034    /// Send an ephemeral typing indicator to a Community channel.
2035    pub async fn send_community_typing(&self, channel_id: &str) -> Result<()> {
2036        use crate::community::{service, transport::LiveTransport};
2037        if let Some(id) = self.v2_community_for_channel(channel_id)? {
2038            let community = crate::db::community::load_community_v2(&id)
2039                .map_err(VectorError::Other)?
2040                .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2041            let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
2042            let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(8));
2043            return crate::community::v2::service::send_typing(&transport, &community, &ch)
2044                .await
2045                .map_err(VectorError::Other);
2046        }
2047        let (community, channel) = self.resolve_channel(channel_id)?;
2048        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(8));
2049        service::publish_typing_signal(&transport, &community, &channel)
2050            .await
2051            .map_err(VectorError::Other)
2052    }
2053
2054    /// React to a Community message. `emoji_url` carries the NIP-30 image URL for a custom
2055    /// `:shortcode:` reaction (parity with DMs).
2056    pub async fn send_community_reaction(
2057        &self,
2058        channel_id: &str,
2059        message_id: &str,
2060        emoji: &str,
2061        emoji_url: Option<&str>,
2062    ) -> Result<()> {
2063        let emoji_tags: Vec<crate::types::EmojiTag> = match emoji_url {
2064            Some(url) if emoji.starts_with(':') && emoji.ends_with(':') && emoji.len() >= 3 && !url.is_empty() => {
2065                vec![crate::types::EmojiTag { shortcode: emoji[1..emoji.len() - 1].to_string(), url: url.to_string() }]
2066            }
2067            _ => Vec::new(),
2068        };
2069        if let Some(id) = self.v2_community_for_channel(channel_id)? {
2070            let session = state::SessionGuard::capture();
2071            let community = crate::db::community::load_community_v2(&id)
2072                .map_err(VectorError::Other)?
2073                .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2074            let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
2075            let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2076            // NIP-25 names the reacted-to author (a required `p`). STATE first, then
2077            // the persisted row (v2 history + the send echo live in the shared events
2078            // store, so this almost always resolves locally); the channel-page fetch
2079            // is the last resort for a target this device never saw.
2080            let held = {
2081                let st = state::STATE.lock().await;
2082                st.find_message(message_id)
2083                    .and_then(|(_, m)| m.npub.as_deref().and_then(|n| nostr_sdk::prelude::PublicKey::parse(n).ok()))
2084            };
2085            let held = held.or_else(|| {
2086                crate::db::events::event_author(message_id)
2087                    .ok()
2088                    .flatten()
2089                    .and_then(|n| nostr_sdk::prelude::PublicKey::parse(&n).ok())
2090            });
2091            let target_author = match held {
2092                Some(pk) => pk,
2093                None => crate::community::v2::service::fetch_channel(&transport, &community, &ch, 500)
2094                    .await
2095                    .map_err(VectorError::Other)?
2096                    .iter()
2097                    .find(|f| f.event.opened().rumor_id.to_hex() == message_id)
2098                    .map(|f| f.event.opened().author)
2099                    .ok_or_else(|| VectorError::Other("reacted-to message not found".into()))?,
2100            };
2101            // The author lookup straddled awaits against THIS account's community.
2102            if !session.is_valid() {
2103                return Err(VectorError::Other("account changed before send".into()));
2104            }
2105            let pair = emoji_tags.first().map(|t| (t.shortcode.as_str(), t.url.as_str()));
2106            // The NIP-25 `k` names the target's rumor kind. Stored rows don't keep
2107            // wire-kind fidelity yet, so a reaction to a received kind-1111 thread
2108            // reply claims `9` — Armada's fold ignores reaction `k`, and exact
2109            // threading lands with the thread-aware GUI.
2110            return crate::community::v2::service::send_reaction(
2111                &transport, &community, &ch, message_id, &target_author.to_hex(), crate::community::v2::kind::MESSAGE, emoji, pair,
2112            )
2113            .await
2114            .map(|_| ())
2115            .map_err(VectorError::Other);
2116        }
2117        self.publish_community_control(
2118            channel_id, stored_event::event_kind::COMMUNITY_REACTION, emoji, message_id, &emoji_tags,
2119        ).await
2120    }
2121
2122    /// Edit one of your own Community messages.
2123    pub async fn edit_community_message(&self, channel_id: &str, message_id: &str, new_content: &str) -> Result<()> {
2124        let emoji_tags = emoji_packs::resolve_outbound_emoji_tags(new_content);
2125        if let Some(id) = self.v2_community_for_channel(channel_id)? {
2126            let community = crate::db::community::load_community_v2(&id)
2127                .map_err(VectorError::Other)?
2128                .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2129            let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
2130            let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2131            return crate::community::v2::service::send_edit(&transport, &community, &ch, message_id, new_content)
2132                .await
2133                .map(|_| ())
2134                .map_err(VectorError::Other);
2135        }
2136        self.publish_community_control(
2137            channel_id, stored_event::event_kind::COMMUNITY_EDIT, new_content, message_id, &emoji_tags,
2138        ).await
2139    }
2140
2141    /// Delete one of your own Community messages, resolving its channel from local
2142    /// state (the GUI path). A headless v2 consumer holds no local history — use
2143    /// [`Self::delete_community_message_in`] with the channel id instead.
2144    pub async fn delete_community_message(&self, message_id: &str) -> Result<()> {
2145        let channel_id = {
2146            let st = state::STATE.lock().await;
2147            match st.find_message(message_id) {
2148                Some((chat, _)) => chat.id.clone(),
2149                None => return Err(VectorError::Other("message not found (already deleted?)".into())),
2150            }
2151        };
2152        self.delete_community_message_in(&channel_id, message_id).await
2153    }
2154
2155    /// Delete one of your own Community messages in `channel_id`: a NIP-09 relay nuke when the
2156    /// per-message key is held (v1) or the in-plane kind-5 (v2), plus a cooperative tombstone so
2157    /// peers hide it, plus best-effort attachment cleanup.
2158    pub async fn delete_community_message_in(&self, channel_id: &str, message_id: &str) -> Result<()> {
2159        use crate::community::{service, transport::LiveTransport};
2160        let session = state::SessionGuard::capture();
2161        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2162
2163        // Attachment URLs come from local state when held (a headless v2 consumer
2164        // has none — blob cleanup is then the receiving peers' concern, not ours).
2165        let attachment_urls: Vec<String> = {
2166            let st = state::STATE.lock().await;
2167            st.find_message(message_id)
2168                .map(|(_, msg)| msg.attachments.iter().flat_map(|a| a.all_urls().map(str::to_string)).collect())
2169                .unwrap_or_default()
2170        };
2171
2172        if let Some(id) = self.v2_community_for_channel(channel_id)? {
2173            // v2: the cooperative in-plane kind-5 (the wrap-ciphertext scrub needs
2174            // the ephemeral wrap key, not retained in this cut).
2175            let community = crate::db::community::load_community_v2(&id)
2176                .map_err(VectorError::Other)?
2177                .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2178            let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(&channel_id));
2179            crate::community::v2::service::send_delete(
2180                &transport, &community, &ch, message_id, crate::community::v2::kind::MESSAGE,
2181            )
2182            .await
2183            .map_err(VectorError::Other)?;
2184        } else {
2185            // Layer 1 — relay nuke against the retained per-message key (best-effort).
2186            if crate::db::community::get_message_key(message_id).map(|k| k.is_some()).unwrap_or(false) {
2187                let _ = service::delete_message(&transport, message_id).await;
2188            }
2189            // Layer 2 — cooperative tombstone so peers hide it.
2190            self.publish_community_control(
2191                &channel_id, stored_event::event_kind::COMMUNITY_DELETE, "", message_id, &[],
2192            ).await?;
2193        }
2194        // Layer 3 — best-effort attachment blob delete.
2195        if !attachment_urls.is_empty() {
2196            if let Some(_client) = state::nostr_client() {
2197                if let Ok(signer) = crate::signer::active_signer() {
2198                    crate::blossom::delete_blobs_best_effort(signer, attachment_urls);
2199                }
2200            }
2201        }
2202        // Local removal — the publishes above straddled awaits; a swap must not let this
2203        // strip the message from a swapped-in account's STATE + DB (message_id is global).
2204        if !session.is_valid() {
2205            return Ok(());
2206        }
2207        let removed_chat = {
2208            let mut st = state::STATE.lock().await;
2209            st.remove_message(message_id).map(|(cid, _)| cid)
2210        };
2211        let _ = crate::db::events::delete_event(message_id).await;
2212        traits::emit_event_json("message_removed", serde_json::json!({
2213            "id": message_id, "chat_id": removed_chat.as_deref().unwrap_or(&channel_id), "reason": "deleted",
2214        }));
2215        Ok(())
2216    }
2217
2218    /// Moderation-hide someone ELSE's community message under `MANAGE_MESSAGES`
2219    /// (CORD-04 §3/§5). Protocol-agnostic: v2 seals the same kind-5 its authors
2220    /// use, v1 publishes its 3305 tombstone; both re-derive the actor's authority
2221    /// from the signed inner against the folded Roster, so this is an authority
2222    /// claim peers verify, never a local suppression.
2223    pub async fn hide_community_message(&self, channel_id: &str, message_id: &str) -> Result<()> {
2224        use crate::community::transport::LiveTransport;
2225        let session = state::SessionGuard::capture();
2226        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2227
2228        // You can only moderate a message you can see: the author resolves from
2229        // STATE, then the store for a row that has paged out of the window.
2230        let author_npub = {
2231            let st = state::STATE.lock().await;
2232            st.find_message(message_id).and_then(|(_, m)| m.npub)
2233        };
2234        let author_npub = match author_npub {
2235            Some(n) => n,
2236            None => crate::db::events::event_author(message_id)
2237                .ok()
2238                .flatten()
2239                .ok_or_else(|| VectorError::Other("can't resolve the target message's author".into()))?,
2240        };
2241        let author = nostr_sdk::prelude::PublicKey::parse(&author_npub)
2242            .map_err(|_| VectorError::Other("target message has an unreadable author".into()))?;
2243
2244        if let Some(id) = self.v2_community_for_channel(channel_id)? {
2245            let community = crate::db::community::load_community_v2(&id)
2246                .map_err(VectorError::Other)?
2247                .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2248            let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
2249            crate::community::v2::service::moderation_delete(
2250                &transport, &community, &ch, message_id, crate::community::v2::kind::MESSAGE, &author,
2251            )
2252            .await
2253            .map_err(VectorError::Other)?;
2254        } else {
2255            let cid = crate::db::community::community_id_for_channel(channel_id)
2256                .map_err(VectorError::Other)?
2257                .ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2258            let community = crate::db::community::load_community(&crate::community::CommunityId(
2259                crate::simd::hex::hex_to_bytes_32(&cid),
2260            ))
2261            .map_err(VectorError::Other)?
2262            .ok_or_else(|| VectorError::Other("community not found".into()))?;
2263            let channel = community
2264                .channels
2265                .iter()
2266                .find(|c| c.id.to_hex() == channel_id)
2267                .cloned()
2268                .ok_or_else(|| VectorError::Other("channel not found in community".into()))?;
2269            crate::community::service::publish_owner_hide(&transport, &community, &channel, message_id)
2270                .await
2271                .map_err(VectorError::Other)?;
2272        }
2273
2274        // The publish straddled a multi-second await; a swap must not strip the
2275        // message from the swapped-in account's STATE + DB (message_id is global).
2276        if !session.is_valid() {
2277            return Ok(());
2278        }
2279        let removed_chat = {
2280            let mut st = state::STATE.lock().await;
2281            st.remove_message(message_id).map(|(cid, _)| cid)
2282        };
2283        let _ = crate::db::events::delete_event(message_id).await;
2284        traits::emit_event_json("message_removed", serde_json::json!({
2285            "id": message_id, "chat_id": removed_chat.as_deref().unwrap_or(channel_id), "reason": "hidden",
2286        }));
2287        Ok(())
2288    }
2289
2290    /// Shared community control-event publish (reaction / edit / delete tombstone): build the
2291    /// inner-typed envelope, sign, send over the community transport, then locally echo + persist + emit.
2292    async fn publish_community_control(
2293        &self,
2294        channel_id: &str,
2295        kind: u16,
2296        content: &str,
2297        target: &str,
2298        emoji_tags: &[crate::types::EmojiTag],
2299    ) -> Result<()> {
2300        use crate::community::{envelope, inbound, service, transport::LiveTransport};
2301        let (community, channel) = self.resolve_channel(channel_id)?;
2302        let author_pk = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
2303        let ms = std::time::SystemTime::now()
2304            .duration_since(std::time::UNIX_EPOCH)
2305            .map(|d| d.as_millis() as u64)
2306            .unwrap_or(0);
2307        let unsigned = envelope::build_inner_typed(
2308            author_pk, &channel.id, channel.epoch, kind, content, ms, Some(target), emoji_tags,
2309        );
2310        let _client = state::nostr_client().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
2311        let signer = crate::signer::active_signer().map_err(|e| VectorError::Other(format!("Signer unavailable: {e}")))?;
2312        let inner = unsigned.finalize_async(&signer).await.map_err(|e| VectorError::Other(format!("sign: {e}")))?;
2313        let session = state::SessionGuard::capture();
2314        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2315        let outer = service::send_signed_message(&transport, &community, &channel, &inner)
2316            .await.map_err(VectorError::Other)?;
2317        // Local echo + persist + emit (relay echo dedups on inner id). A swap during the
2318        // publish must not echo account A's control event into account B.
2319        if !session.is_valid() {
2320            return Ok(());
2321        }
2322        let outcome = {
2323            let mut st = state::STATE.lock().await;
2324            inbound::process_incoming(&mut st, &outer, &channel, &author_pk)
2325        };
2326        if let Some(inbound::IncomingEvent::Updated { target_id, mut message, edit_event }) = outcome {
2327            if let Some(ev) = edit_event {
2328                let mut ev = (*ev).clone();
2329                if let Ok(cid) = crate::db::id_cache::get_chat_id_by_identifier(channel_id) { ev.chat_id = cid; }
2330                let _ = crate::db::events::save_event(&ev).await;
2331            } else {
2332                let _ = crate::db::events::save_message(channel_id, &message).await;
2333            }
2334            traits::emit_message_update(channel_id, &target_id, &mut message).await;
2335        }
2336        Ok(())
2337    }
2338
2339    /// Catch a Community channel up from relays. v1: fetch + ingest the latest page of messages,
2340    /// reactions, edits, and deletes, returning how many were brand-new. v2: consensus catch-up
2341    /// only (rekeys + control refold) — chat history delivers over the live handler bridge, so the
2342    /// count is always 0. Returns `(new_message_count, warnings)`; `warnings` are NON-FATAL errors
2343    /// hit during the sync (catch-up, control fold, read-cut resume) — surfaced rather than
2344    /// swallowed so a headless caller is never blind to "the sync ran but a re-founding couldn't
2345    /// be resumed."
2346    pub async fn sync_community_channel(&self, channel_id: &str, limit: usize) -> Result<(usize, Vec<String>)> {
2347        use crate::community::{inbound, send, service, transport::LiveTransport};
2348        let my_pk = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
2349        // v2: consensus catch-up (rekeys then control refold) + chat backfill. With a
2350        // running listen() the coalescing worker owns the follow (never run inline beside
2351        // it — two concurrent follows can whole-row clobber); headless, walk it inline.
2352        // The chat page is fetched + persisted either way, so get_messages backfills.
2353        if let Some(id) = self.v2_community_for_channel(channel_id)? {
2354            let warnings = if community::v2::realtime::follow_worker_running() {
2355                community::v2::realtime::enqueue_follow(&id);
2356                Vec::new()
2357            } else {
2358                Self::v2_inline_follow(&id).await
2359            };
2360            // Deepest catch-up walk: pages × page-size bounds one reconnect's fetch.
2361            // Chat plane = fetch ASAP. NOTE: fetch_plane does not consult the
2362            // evidence tier yet (#370) — until it does, the transport-seconds
2363            // bound is the effective limit; the declared Fast records intent.
2364            let new = Self::v2_backfill_channel(
2365                &id, channel_id, limit, 8, None,
2366                crate::community::transport::Evidence::Fast, 12,
2367            ).await;
2368            return Ok((new, warnings));
2369        }
2370        let (community, _) = self.resolve_channel(channel_id)?;
2371        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2372        let mut warnings: Vec<String> = Vec::new();
2373
2374        // FIRST: walk any base (server-root) rotation — a privatize / private-ban rekey advances the
2375        // epoch and re-anchors the control plane under the NEW root, so we must follow it BEFORE reading
2376        // control/messages or we'd look at stale-epoch pseudonyms and silently fall off. No-op (one cheap
2377        // probe) when there's been no rotation. Re-resolve after: the base epoch + root may have advanced.
2378        // An AUTHORIZED base rotation that excluded us (private ban / read-cut) is a removal: erase local
2379        // community data, exactly like an observed banlist/kick. This is the catch-all for a cut member who
2380        // can no longer decrypt the new control plane to read the banlist the normal way (`am_i_banned`).
2381        match service::catch_up_server_root(&transport, &community).await {
2382            Ok(c) if c.removed => {
2383                // ban-rekey exclusion is a self-removal → retain the held epoch keys for later self-scrub.
2384                let _ = crate::db::community::delete_community_retain_keys(&community.id.to_hex());
2385                return Ok((0, warnings));
2386            }
2387            Ok(_) => {}
2388            Err(e) => warnings.push(format!("base catch-up failed: {e}")),
2389        }
2390        let (community, _) = self.resolve_channel(channel_id)?;
2391
2392        // Headless clients have no realtime control-plane subscription, so fold the latest control editions
2393        // here (the desktop does the same on its own latest-page sync). Banlist FIRST: a ban that landed on
2394        // us self-removes like a kick (drop keys + local data, no rejoin). Then roles, the per-creator invite
2395        // links (Public/Private mode), and metadata (name/description/icon/channel-name) — so a rename, role,
2396        // ban, or mode change reaches this member on sync, not just in a realtime client.
2397        if let Err(e) = service::fetch_and_apply_control(&transport, &community).await {
2398            warnings.push(format!("control fold failed: {e}"));
2399        }
2400        if service::am_i_banned(&community) {
2401            // ban self-removal → retain the held epoch keys for later self-scrub.
2402            let _ = crate::db::community::delete_community_retain_keys(&community.id.to_hex());
2403            return Ok((0, warnings));
2404        }
2405        // Walk any CHANNEL rekey so we hold the current channel key before paging it, then re-resolve so the
2406        // batch below carries the fresh channel epoch/key + the freshly-folded banned set + metadata.
2407        let (community, channel) = self.resolve_channel(channel_id)?;
2408        if let Err(e) = service::catch_up_channel_rekeys(&transport, &community, &channel.id).await {
2409            warnings.push(format!("channel catch-up failed: {e}"));
2410        }
2411        // Resume any interrupted re-founding (a privatize/ban whose rotation aborted mid-way — e.g. a
2412        // transient relay miss on the re-anchor). The GUI's sync did this; the agent's path did NOT, so an
2413        // interrupted re-founding stayed `read_cut_pending` forever (channel frozen). Best-effort + surfaced.
2414        let (community, _) = self.resolve_channel(channel_id)?;
2415        if let Err(e) = service::retry_pending_read_cut(&transport, &community).await {
2416            warnings.push(format!("read-cut resume failed: {e}"));
2417        }
2418        let (community, channel) = self.resolve_channel(channel_id)?;
2419
2420        // Guard straddles the fetch: the persist walk below writes this account's DB.
2421        let session = state::SessionGuard::capture();
2422        let events = send::fetch_channel_page(&transport, &community, &channel, None, None, limit.max(1))
2423            .await
2424            .map_err(VectorError::Other)?;
2425        let outcomes = {
2426            let mut st = state::STATE.lock().await;
2427            inbound::process_channel_batch(&mut st, &events, &channel, &my_pk)
2428        };
2429        let mut new = 0usize;
2430        // Message saves COLLECT into one batched transaction; deletes are flush barriers
2431        // (see flush_message_batch — a save committing after a delete it preceded on the
2432        // wire would resurrect the deleted row).
2433        let mut pending: Vec<&crate::types::Message> = Vec::new();
2434        for o in &outcomes {
2435            // Every arm below writes this account's DB — a swap can land between them.
2436            if !session.is_valid() {
2437                pending.clear();
2438                break;
2439            }
2440            match o {
2441                inbound::IncomingEvent::NewMessage(m) => {
2442                    pending.push(m);
2443                    new += 1;
2444                }
2445                inbound::IncomingEvent::Updated { message, .. } => {
2446                    pending.push(message);
2447                }
2448                inbound::IncomingEvent::Removed { target_id } => {
2449                    crate::db::events::flush_message_batch(channel_id, &mut pending, &session).await;
2450                    let _ = crate::db::events::delete_event(target_id).await;
2451                }
2452                inbound::IncomingEvent::ReactionRemoved { reaction_id, .. } => {
2453                    // save_message is additive, so a revoked reaction's kind-7 row must be
2454                    // dropped explicitly or it resurrects on reload.
2455                    crate::db::events::flush_message_batch(channel_id, &mut pending, &session).await;
2456                    let _ = crate::db::events::delete_event(reaction_id).await;
2457                }
2458                inbound::IncomingEvent::Presence { npub, joined, event_id, created_at, invited_by, invited_label } => {
2459                    let et = if *joined {
2460                        crate::stored_event::SystemEventType::MemberJoined
2461                    } else {
2462                        crate::stored_event::SystemEventType::MemberLeft
2463                    };
2464                    // attribution persisted in the note: "invited_by[|label]".
2465                    let note = invited_by.as_ref().map(|by| match invited_label {
2466                        Some(l) if !l.is_empty() => format!("{by}|{l}"),
2467                        _ => by.clone(),
2468                    });
2469                    let _ = crate::db::events::save_system_event_at(event_id, channel_id, et, npub, note.as_deref(), *created_at, invited_by.as_deref(), invited_label.as_deref()).await;
2470                }
2471                inbound::IncomingEvent::WebxdcPeer { npub, topic_id, node_addr, event_id, created_at } => {
2472                    // Persist only (DM-parity row) — the miniapp layer bootstraps from the DB at
2473                    // game-open. Live gossip-feed pokes are the realtime subscription's job.
2474                    community::service::persist_webxdc_signal(
2475                        channel_id, npub, topic_id, node_addr.as_deref(), event_id, *created_at,
2476                    ).await;
2477                }
2478                inbound::IncomingEvent::Kicked { community_id }
2479                | inbound::IncomingEvent::SelfLeft { community_id } => {
2480                    // self-removal (kick of me, or a leave I/another device authored): drop the
2481                    // community's local state but RETAIN the held epoch keys (later self-scrub). The core-level
2482                    // half of leaving; a client shell layers on subscription-refresh + chat-row teardown + UI.
2483                    // Stop the batch — the community is gone, so later same-batch writes would orphan rows.
2484                    crate::db::events::flush_message_batch(channel_id, &mut pending, &session).await;
2485                    let _ = crate::db::community::delete_community_retain_keys(community_id);
2486                    break;
2487                }
2488                inbound::IncomingEvent::Typing { .. } => {
2489                    // Realtime-only ephemeral signal; never fetched in a sync batch. No-op.
2490                }
2491            }
2492        }
2493        crate::db::events::flush_message_batch(channel_id, &mut pending, &session).await;
2494        Ok((new, warnings))
2495    }
2496
2497    /// The composer's `/` picker snapshot for `chat_id`, answered INSTANTLY
2498    /// from local state: the chat's bot-flagged members (kind-0 `bot: true` —
2499    /// the SDK sets it on every bot it builds) and their last-known manifests
2500    /// from the persistent store. When the last refresh is older than a minute
2501    /// (or the bot set changed), ONE background REQ re-fetches every bot's
2502    /// manifest together (5s unification window), persists newer editions, and
2503    /// emits `chat_commands_updated` — the UI swaps the list in when it lands.
2504    /// Works for BOTH community protocols (an invocation is plain content; only
2505    /// the optional routing tag is v2-only) and DMs. The manifest REQ always
2506    /// includes the discovery indexers beside the chat's own relays, so an
2507    /// unreachable or stranger-dropping community relay can't blind the picker.
2508    pub async fn get_chat_commands(&self, chat_id: &str) -> crate::bot_interface::ChatCommandsSnapshot {
2509        use crate::bot_interface::{self, ChatCommandsSnapshot};
2510        use nostr_sdk::prelude::ToBech32;
2511
2512        let mut bots: Vec<nostr_sdk::prelude::PublicKey> = Vec::new();
2513        let mut relays: Vec<String> = Vec::new();
2514        let community_hex = crate::db::community::community_id_for_channel(chat_id).ok().flatten();
2515        if let Some(cid_hex) = community_hex {
2516            let mut members: Vec<nostr_sdk::prelude::PublicKey> = Vec::new();
2517            if let Ok(Some(community)) = Self::load_v2_if_v2(&cid_hex) {
2518                members = community::v2::service::stored_memberlist(&community).unwrap_or_default();
2519                relays = community.relays.clone();
2520            } else {
2521                let id = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&cid_hex));
2522                let Ok(Some(community)) = crate::db::community::load_community(&id) else {
2523                    return ChatCommandsSnapshot { bots: 0, commands: Vec::new(), fresh: true };
2524                };
2525                relays = community.relays.clone();
2526                for (npub, _) in crate::db::community::community_member_activity(&cid_hex).unwrap_or_default() {
2527                    if let Ok(pk) = nostr_sdk::prelude::PublicKey::parse(&npub) {
2528                        members.push(pk);
2529                    }
2530                }
2531            }
2532            let state = crate::state::STATE.lock().await;
2533            for pk in members {
2534                let Ok(npub) = pk.to_bech32();
2535                if state.get_profile(&npub).map(|p| p.flags.is_bot()).unwrap_or(false) {
2536                    bots.push(pk);
2537                }
2538            }
2539        } else if chat_id.starts_with("npub1") {
2540            if let Ok(pk) = nostr_sdk::prelude::PublicKey::parse(chat_id) {
2541                let is_bot = {
2542                    let state = crate::state::STATE.lock().await;
2543                    state.get_profile(chat_id).map(|p| p.flags.is_bot()).unwrap_or(false)
2544                };
2545                if is_bot {
2546                    bots.push(pk);
2547                    // The counterpart published its manifest to its own login
2548                    // relays/indexers — our connected pool is the read set.
2549                    if let Some(client) = crate::state::nostr_client() {
2550                        relays = client.relays().await.keys().map(|u| u.to_string()).collect();
2551                    }
2552                }
2553            }
2554        }
2555
2556        if bots.is_empty() {
2557            return ChatCommandsSnapshot { bots: 0, commands: Vec::new(), fresh: true };
2558        }
2559        // The chat's own relays PLUS the discovery indexers, one REQ across the
2560        // union — a room whose relays refuse kind 10304 still resolves.
2561        relays.extend(bot_interface::DISCOVERY_RELAYS.iter().map(|s| s.to_string()));
2562        relays.sort();
2563        relays.dedup();
2564        // Deterministic order: the freshness check compares the exact bot set,
2565        // and picker sections stay stable across refreshes.
2566        bots.sort_by_key(|p| p.to_hex());
2567        let bot_hexes: Vec<String> = bots.iter().map(|p| p.to_hex()).collect();
2568        let commands = bot_interface::assemble_from_store(&bot_hexes);
2569        let fresh = bot_interface::commands_fresh(chat_id, &bot_hexes);
2570        if !fresh {
2571            bot_interface::spawn_commands_refresh(chat_id.to_string(), bots.clone(), relays);
2572        }
2573        ChatCommandsSnapshot { bots: bots.len(), commands, fresh }
2574    }
2575
2576    /// Observed members of a Community (best-effort: those who've posted or announced a join,
2577    /// minus anyone who's left or is banned). v1 entries are `{npub, last_active}`; a v2 entry
2578    /// is `{npub}` (the Complete Memberlist carries no activity time). Best-effort throughout:
2579    /// a transport failure yields an empty list, never an error.
2580    pub async fn get_community_members(&self, community_id: &str) -> Vec<serde_json::Value> {
2581        use nostr_sdk::prelude::ToBech32;
2582        // v2: the Complete Memberlist from LOCAL state (persisted guestbook +
2583        // observed authors + roster grantees − banlist). The store is seeded
2584        // post-join and cursor-caught-up by the follow worker (boot/reconnect) +
2585        // live ingest; a cold store (a hold predating the store) seeds in the
2586        // background and refreshes the UI when it lands.
2587        match Self::load_v2_if_v2(community_id) {
2588            Ok(Some(community)) => {
2589                let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
2590                let (_, cursor) = crate::db::community::get_guestbook(&cid_hex).unwrap_or_default();
2591                if cursor == 0 {
2592                    if crate::community::v2::realtime::follow_worker_running() {
2593                        crate::community::v2::realtime::enqueue_follow(community.id());
2594                    } else {
2595                        let session = state::SessionGuard::capture();
2596                        let c2 = community.clone();
2597                        tokio::spawn(async move {
2598                            if !session.is_valid() {
2599                                return;
2600                            }
2601                            let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(20));
2602                            if matches!(crate::community::v2::service::sync_guestbook(&transport, &c2, &session).await, Ok(fresh) if !fresh.is_empty()) {
2603                                emit_event("community_refreshed", &serde_json::json!({ "community_id": cid_hex }));
2604                            }
2605                        });
2606                    }
2607                }
2608                return crate::community::v2::service::stored_memberlist(&community)
2609                    .unwrap_or_default()
2610                    .into_iter()
2611                    .filter_map(|pk| pk.to_bech32().ok())
2612                    .map(|npub| serde_json::json!({ "npub": npub }))
2613                    .collect();
2614            }
2615            Ok(None) => {} // genuinely v1 / unknown — fall through.
2616            // Can't determine the protocol: best-effort empty, never a v1 guess.
2617            Err(_) => return Vec::new(),
2618        }
2619        crate::db::community::community_member_activity(community_id)
2620            .unwrap_or_default()
2621            .into_iter()
2622            .map(|(npub, last_active)| serde_json::json!({ "npub": npub, "last_active": last_active }))
2623            .collect()
2624    }
2625
2626    /// One synchronous v2 follow pass — rekeys first (a base adopt moves the
2627    /// control address), then a control refold on the FRESH state, the same order
2628    /// the live follow worker runs. Returns non-fatal warnings.
2629    async fn v2_inline_follow(id: &crate::community::CommunityId) -> Vec<String> {
2630        use crate::community::transport::LiveTransport;
2631        let session = state::SessionGuard::capture();
2632        // Serialize with the live follow worker: `follow_worker_running` is
2633        // check-then-act, so a worker can spawn right after a caller saw `false` —
2634        // this shared per-community lock is what actually prevents two follows of
2635        // one community interleaving their whole-row saves.
2636        let lock = crate::community::v2::realtime::follow_lock(id);
2637        let _guard = lock.lock().await;
2638        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2639        let mut warnings: Vec<String> = Vec::new();
2640        let Ok(Some(community)) = crate::db::community::load_community_v2(id) else {
2641            warnings.push("v2 community not found".to_string());
2642            return warnings;
2643        };
2644        let cid_hex = crate::simd::hex::bytes_to_hex_32(&id.0);
2645        match crate::community::v2::service::follow_rekeys(&transport, &community, &session).await {
2646            // A tombstone surfaced during catch-up — sealed read-only; stop here.
2647            Ok(f) if f.dissolved => return warnings,
2648            Ok(f) if f.self_removed => {
2649                // An authorized rotation that excluded us IS a removal — but the
2650                // follow straddled awaits, so never delete from a swapped-in DB.
2651                if session.is_valid() {
2652                    let _ = crate::db::community::delete_community(&cid_hex);
2653                }
2654                return warnings;
2655            }
2656            Ok(_) => {}
2657            Err(e) => warnings.push(format!("v2 rekey follow failed: {e}")),
2658        }
2659        if let Ok(Some(fresh)) = crate::db::community::load_community_v2(id) {
2660            match crate::community::v2::service::follow_control(&transport, &fresh, &session).await {
2661                // A control change can reveal rekey work that predates it (a
2662                // just-announced private channel's key crate already sits on its
2663                // rekey plane), so walk the rekeys once more on the fresh state.
2664                Ok(Some(changed)) => {
2665                    if let Err(e) = crate::community::v2::service::follow_rekeys(&transport, &changed, &session).await {
2666                        warnings.push(format!("v2 rekey follow failed: {e}"));
2667                    }
2668                }
2669                Ok(None) => {}
2670                Err(e) => warnings.push(format!("v2 control follow failed: {e}")),
2671            }
2672        }
2673        // Banned by the freshly-folded banlist: a removal just like the rotation
2674        // exclusion above, and it arrives FIRST (CORD-04 §6 orders the Banlist edition
2675        // before the Refounding), so keying removal solely off the rotation leaves a
2676        // banned headless client running against a community that already dropped it.
2677        if let Some(me) = crate::my_public_key() {
2678            if crate::db::community::is_author_banned(&cid_hex, &me) && session.is_valid() {
2679                let _ = crate::db::community::delete_community(&cid_hex);
2680            }
2681        }
2682        warnings
2683    }
2684
2685    /// Fetch a v2 channel's recent chat history and PERSIST it into the shared events
2686    /// tables (the same store v1 uses), so `get_messages`/`get_new_messages` backfill for
2687    /// v2 exactly like v1. PAGES backwards until it reaches messages it already holds
2688    /// (bounded), so a reconnecting bot that slept through more than one page of traffic
2689    /// still catches the whole gap instead of only the newest `limit`. Reuses the v2
2690    /// inbound bridge (dedup + STATE aggregate) + the v1 save path. Returns the count of
2691    /// brand-new messages applied. Best-effort: a fetch failure is 0.
2692    /// Reconnect/boot catch-up for one v2 channel: fetches the newest pages
2693    /// and PAGES backwards until it reaches messages it already holds, then
2694    /// ingests through the shared pipeline. The boot volley fetches its own
2695    /// batches and shares only [`Self::v2_ingest_chat_page`].
2696    pub(crate) async fn v2_backfill_channel(
2697        id: &crate::community::CommunityId,
2698        channel_id: &str,
2699        limit: usize,
2700        max_pages: usize,
2701        since: Option<u64>,
2702        evidence: crate::community::transport::Evidence,
2703        transport_secs: u64,
2704    ) -> usize {
2705        // Guard straddles the fetch: a swap mid-fetch must not persist account A's chat
2706        // into account B's STATE/DB (the message ids are global).
2707        let session = state::SessionGuard::capture();
2708        let Some(my_pk) = state::my_public_key() else { return 0 };
2709        // CORD-02 §9: a dissolved community honors no NEW events — old history reads
2710        // through the explicit paths, but a catch-up sweep must not ingest anything
2711        // authored into the grave.
2712        if crate::db::community::get_community_dissolved(&crate::simd::hex::bytes_to_hex_32(&id.0)).unwrap_or(false) {
2713            return 0;
2714        }
2715        let Ok(Some(community)) = crate::db::community::load_community_v2(id) else { return 0 };
2716        let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
2717        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(transport_secs));
2718        let Ok(page) = crate::community::v2::service::fetch_channel_history(
2719            &transport,
2720            &community,
2721            &ch,
2722            limit.max(50),
2723            max_pages,
2724            since,
2725            evidence,
2726            // Keep paging while a page still contains a MESSAGE we don't hold; a page
2727            // whose messages are all known means we've reached our own history. Only
2728            // message kinds get their own rows (reactions/edits fold into their
2729            // targets), so a page with no messages is undecidable — keep paging.
2730            |page| {
2731                let mut saw_message = false;
2732                for f in page {
2733                    if matches!(&f.event, crate::community::v2::chat::ChatEvent::Message { .. }) {
2734                        saw_message = true;
2735                        if !crate::db::events::event_exists(&f.event.opened().rumor_id.to_hex()).unwrap_or(false) {
2736                            return true;
2737                        }
2738                    }
2739                }
2740                !saw_message
2741            },
2742        )
2743        .await
2744        else {
2745            return 0;
2746        };
2747        Self::v2_ingest_chat_page(channel_id, my_pk, session, page).await
2748    }
2749
2750    /// Ingest a fetched chat page: STATE apply, batched persist with delete
2751    /// barriers, then UI surfacing — shared by the reconnect backfill and the
2752    /// boot volley's batched paint path.
2753    pub(crate) async fn v2_ingest_chat_page(
2754        channel_id: &str,
2755        my_pk: nostr_sdk::prelude::PublicKey,
2756        session: crate::state::SessionGuard,
2757        page: Vec<crate::community::v2::service::FetchedEvent>,
2758    ) -> usize {
2759        use crate::community::v2::inbound::{apply_chat_to_state, ChatPersist};
2760        let mut new = 0usize;
2761        // Pass 1 — apply to STATE (per-item lock) and COLLECT outcomes in wire order.
2762        let mut outcomes: Vec<ChatPersist> = Vec::with_capacity(page.len());
2763        for f in &page {
2764            // Re-check every iteration — STATE mutates per item, and a swap can land between them.
2765            if !session.is_valid() {
2766                break;
2767            }
2768            // A backfilled WebXDC peer ad persists through the shared 30078 row
2769            // (recency-gated at read) so a reopening lobby lists peers who
2770            // advertised while this device was closed — v1 sync parity. Own
2771            // echoes drop; the ad is not a chat row.
2772            if let crate::community::v2::chat::ChatEvent::Webxdc { opened } = &f.event {
2773                if opened.author != my_pk {
2774                    if let Some((topic, addr)) = crate::webxdc::parse_peer_signal(&opened.rumor.content) {
2775                        let Ok(npub) = ToBech32::to_bech32(&opened.author);
2776                        crate::community::service::persist_webxdc_signal(
2777                            channel_id,
2778                            &npub,
2779                            &topic,
2780                            addr.as_deref(),
2781                            &opened.rumor_id.to_hex(),
2782                            opened.at_ms / 1000,
2783                        )
2784                        .await;
2785                    }
2786                }
2787                continue;
2788            }
2789            let outcome = {
2790                let mut st = state::STATE.lock().await;
2791                apply_chat_to_state(&mut st, &f.event, channel_id, &my_pk)
2792            };
2793            if let Some(outcome) = outcome {
2794                if matches!(outcome, ChatPersist::New(_)) {
2795                    new += 1;
2796                }
2797                outcomes.push(outcome);
2798            }
2799        }
2800        // Pass 2 — persist: message saves COLLECT into batched transactions; deletes are
2801        // flush barriers (a save committing after a delete it preceded on the wire would
2802        // resurrect the deleted row). One tx per page in the common no-delete case.
2803        let mut pending: Vec<&crate::types::Message> = Vec::new();
2804        for outcome in &outcomes {
2805            if !session.is_valid() {
2806                pending.clear();
2807                break;
2808            }
2809            match outcome {
2810                ChatPersist::New(m) => pending.push(m),
2811                ChatPersist::Updated { message, edit_event } => match edit_event {
2812                    Some(ev) => {
2813                        let mut ev = (**ev).clone();
2814                        // get-or-CREATE: a lookup-only id would leave a fresh channel's edit at
2815                        // chat_id 0 (orphaned, dropped on the reload fold).
2816                        if let Ok(cid) = crate::db::id_cache::get_or_create_chat_id(channel_id) {
2817                            ev.chat_id = cid;
2818                        }
2819                        let _ = crate::db::events::save_event(&ev).await;
2820                    }
2821                    None => pending.push(message),
2822                },
2823                ChatPersist::Removed(target_id) => {
2824                    crate::db::events::flush_message_batch(channel_id, &mut pending, &session).await;
2825                    let _ = crate::db::events::delete_event(target_id).await;
2826                }
2827                ChatPersist::ReactionRemoved { reaction_id, message } => {
2828                    crate::db::events::flush_message_batch(channel_id, &mut pending, &session).await;
2829                    let _ = crate::db::events::delete_event(reaction_id).await;
2830                    pending.push(message);
2831                }
2832            }
2833        }
2834        crate::db::events::flush_message_batch(channel_id, &mut pending, &session).await;
2835        // Pass 3 — surface to the live UI, mirroring v1's sweep + the live dispatch handler:
2836        // a silent DB-only backfill left the chat-list preview, unread badge, and sort order
2837        // stale until the channel was opened. Raw emits (no notification ping) — a boot
2838        // catch-up must not fire an OS ping per message. Headless consumers register no
2839        // emitter, so these are a no-op there. After the persists so nothing surfaces unsaved.
2840        if session.is_valid() {
2841            for outcome in &outcomes {
2842                match outcome {
2843                    ChatPersist::New(msg) => crate::traits::emit_event(
2844                        "message_new",
2845                        &serde_json::json!({ "message": msg, "chat_id": channel_id }),
2846                    ),
2847                    ChatPersist::Updated { message, .. }
2848                    | ChatPersist::ReactionRemoved { message, .. } => {
2849                        let mut message = message.clone();
2850                        let target_id = message.id.clone();
2851                        crate::traits::emit_message_update(channel_id, &target_id, &mut message).await;
2852                    }
2853                    ChatPersist::Removed(target_id) => crate::traits::emit_event(
2854                        "message_removed",
2855                        &serde_json::json!({ "id": target_id, "chat_id": channel_id, "reason": "deleted" }),
2856                    ),
2857                }
2858            }
2859        }
2860        new
2861    }
2862
2863    /// The held v2 community when `community_id` names one; `Ok(None)` for v1 (or
2864    /// unknown). A DB read error PROPAGATES (fail-closed) instead of falling open
2865    /// to the v1 route on a transient failure.
2866    fn load_v2_if_v2(community_id: &str) -> Result<Option<crate::community::v2::community::CommunityV2>> {
2867        if community_id.len() != 64 {
2868            return Ok(None);
2869        }
2870        let cid = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
2871        match crate::db::community::community_protocol(&cid).map_err(VectorError::Other)? {
2872            Some(crate::community::ConcordProtocol::V2) => crate::db::community::load_community_v2(&cid).map_err(VectorError::Other),
2873            _ => Ok(None),
2874        }
2875    }
2876
2877    // ── Community admin actions ── role-gated; vector-core re-checks authority on every action and peers
2878    // re-verify against the owner-rooted roster, so these can't forge standing. A bunker account can't ban
2879    // in a private community (the rekey needs a raw local key).
2880
2881    fn load_community_hex(community_id: &str) -> Result<crate::community::Community> {
2882        use crate::community::CommunityId;
2883        if community_id.len() != 64 {
2884            return Err(VectorError::Other("malformed community id".into()));
2885        }
2886        crate::db::community::load_community(&CommunityId(crate::simd::hex::hex_to_bytes_32(community_id)))
2887            .map_err(VectorError::Other)?
2888            .ok_or_else(|| VectorError::Other("community not found".into()))
2889    }
2890
2891    fn admin_role_id_of(community_id: &str) -> Result<String> {
2892        let roles = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
2893        roles.roles.iter()
2894            .find(|r| matches!(r.scope, crate::community::roles::RoleScope::Server)
2895                && r.permissions.contains(crate::community::roles::Permissions::ADMIN_ALL))
2896            .map(|r| r.role_id.clone())
2897            .ok_or_else(|| VectorError::Other("admin role not found (roster not synced?)".into()))
2898    }
2899
2900    /// My effective management capabilities in a community (role engine — owner is just position 0). Use to
2901    /// confirm a promotion/demotion landed. A local read: the roster is folded + persisted by the passive
2902    /// sync (v1) / control follow (v2), never fetched here.
2903    pub fn community_capabilities(&self, community_id: &str) -> Result<serde_json::Value> {
2904        use crate::community::service;
2905        if let Some(v2) = Self::load_v2_if_v2(community_id)? {
2906            use crate::community::roles::Permissions;
2907            let me = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?.to_hex();
2908            let owner_hex = v2.owner().map_err(VectorError::Other)?.to_hex();
2909            let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
2910            // A banned member holds no standing (CORD-04 §4), even if a since-skipped
2911            // roster persist still lists their grant — the banlist advances on its own gate.
2912            let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
2913            if banned.contains(&me) && me != owner_hex {
2914                return Ok(serde_json::json!({
2915                    "manage_metadata": false, "manage_channels": false, "create_invite": false, "kick": false,
2916                    "ban": false, "manage_messages": false, "manage_roles": false, "manage_admin_role": false,
2917                }));
2918            }
2919            let has = |p: u64| roster.is_authorized(&me, Some(&owner_hex), p);
2920            return Ok(serde_json::json!({
2921                "manage_metadata": has(Permissions::MANAGE_METADATA), "manage_channels": has(Permissions::MANAGE_CHANNELS),
2922                "create_invite": has(Permissions::CREATE_INVITE), "kick": has(Permissions::KICK), "ban": has(Permissions::BAN),
2923                "manage_messages": has(Permissions::MANAGE_MESSAGES), "manage_roles": has(Permissions::MANAGE_ROLES),
2924                // Only the owner (position 0) strictly outranks the position-1 Admin role.
2925                "manage_admin_role": me == owner_hex,
2926            }));
2927        }
2928        let community = Self::load_community_hex(community_id)?;
2929        let caps = service::caller_capabilities(&community);
2930        let manage_admin_role = Self::admin_role_id_of(community_id).ok()
2931            .map(|rid| service::caller_can_manage_role_id(&community, &rid))
2932            .unwrap_or(false);
2933        Ok(serde_json::json!({
2934            "manage_metadata": caps.manage_metadata, "manage_channels": caps.manage_channels,
2935            "create_invite": caps.create_invite, "kick": caps.kick, "ban": caps.ban,
2936            "manage_messages": caps.manage_messages, "manage_roles": caps.manage_roles,
2937            "manage_admin_role": manage_admin_role,
2938        }))
2939    }
2940
2941    /// The community's owner npub + the admin npubs (role overview). A local read,
2942    /// like [`Self::community_capabilities`].
2943    pub fn community_roles(&self, community_id: &str) -> Result<serde_json::Value> {
2944        use nostr_sdk::prelude::{PublicKey, ToBech32};
2945        if let Some(v2) = Self::load_v2_if_v2(community_id)? {
2946            let owner = v2.owner().map_err(VectorError::Other)?;
2947            let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
2948            // Exclude banned members from the admin list (a banned npub vanishes, §4).
2949            let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
2950            let admins: Vec<String> = roster.grants.iter()
2951                .filter(|g| roster.is_admin(&g.member) && !banned.contains(&g.member))
2952                .filter_map(|g| PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok()))
2953                .collect();
2954            return Ok(serde_json::json!({ "owner": owner.to_bech32().ok(), "admins": admins }));
2955        }
2956        let community = Self::load_community_hex(community_id)?;
2957        let owner = community.owner_attestation.as_ref()
2958            .and_then(|att| crate::community::owner::verify_owner_attestation(att, &community.id.to_hex()))
2959            .and_then(|pk| ToBech32::to_bech32(&pk).ok());
2960        let roles = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
2961        let admins: Vec<String> = roles.grants.iter().filter(|g| roles.is_admin(&g.member))
2962            .filter_map(|g| PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok()))
2963            .collect();
2964        Ok(serde_json::json!({ "owner": owner, "admins": admins }))
2965    }
2966
2967    /// Fold the v2 control plane back in right after publishing an authority change, so the
2968    /// LOCAL roster/banlist — which is what every read is served from (crowns, in-chat tags,
2969    /// capabilities, moderation gates) — is current by the time the call returns. `publish`
2970    /// only returns once a relay ACKed, so this refetch sees our own edition; the fold
2971    /// announces `community_refreshed` itself when the roster actually moved.
2972    ///
2973    /// Best-effort: the edition is already published, so a failed refold is a stale local
2974    /// cache the next follow repairs, never a failed action.
2975    async fn converge_v2_authority(
2976        transport: &crate::community::transport::LiveTransport,
2977        community_id: &str,
2978        session: &crate::state::SessionGuard,
2979    ) {
2980        if !session.is_valid() {
2981            return;
2982        }
2983        // Reload rather than reuse the caller's clone: the publish advanced edition floors,
2984        // and a rekey/refound may have moved the control address under us.
2985        if let Ok(Some(fresh)) = Self::load_v2_if_v2(community_id) {
2986            let _ = crate::community::v2::service::follow_control(transport, &fresh, session).await;
2987            // Membership is part of the view being converged: an unban must
2988            // re-fetch the Guestbook, because a Join that legally raced the ban
2989            // window may exist only on the relays — and our own just-published
2990            // edition doesn't echo back to trigger a follow.
2991            if let Ok(added) = crate::community::v2::service::sync_guestbook(transport, &fresh, session).await {
2992                if !added.is_empty() && session.is_valid() {
2993                    traits::emit_event_json(
2994                        "community_refreshed",
2995                        serde_json::json!({ "community_id": community_id }),
2996                    );
2997                }
2998            }
2999        }
3000    }
3001
3002    /// Grant a member the @admin role. Requires MANAGE_ROLES + outranking the role's position.
3003    pub async fn grant_admin(&self, community_id: &str, npub: &str) -> Result<()> {
3004        use crate::community::{service, transport::LiveTransport};
3005        let session = crate::state::SessionGuard::capture();
3006        let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
3007        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
3008        if let Some(v2) = Self::load_v2_if_v2(community_id)? {
3009            crate::community::v2::service::grant_admin(&transport, &v2, &member)
3010                .await
3011                .map_err(VectorError::Other)?;
3012            Self::converge_v2_authority(&transport, community_id, &session).await;
3013            return Ok(());
3014        }
3015        let community = Self::load_community_hex(community_id)?;
3016        let role_id = Self::admin_role_id_of(community_id)?;
3017        service::grant_role(&transport, &community, member, &role_id).await.map_err(VectorError::Other)
3018    }
3019
3020    /// Revoke a member's @admin role.
3021    pub async fn revoke_admin(&self, community_id: &str, npub: &str) -> Result<()> {
3022        use crate::community::{service, transport::LiveTransport};
3023        let session = crate::state::SessionGuard::capture();
3024        let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
3025        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
3026        if let Some(v2) = Self::load_v2_if_v2(community_id)? {
3027            crate::community::v2::service::revoke_admin(&transport, &v2, &member)
3028                .await
3029                .map_err(VectorError::Other)?;
3030            Self::converge_v2_authority(&transport, community_id, &session).await;
3031            return Ok(());
3032        }
3033        let community = Self::load_community_hex(community_id)?;
3034        let role_id = Self::admin_role_id_of(community_id)?;
3035        service::revoke_role(&transport, &community, member, &role_id).await.map_err(VectorError::Other)
3036    }
3037
3038    /// Cooperatively kick a member — they self-remove but can rejoin. Requires KICK + outrank.
3039    pub async fn kick_member(&self, community_id: &str, npub: &str) -> Result<()> {
3040        use crate::community::{service, transport::LiveTransport};
3041        let session = crate::state::SessionGuard::capture();
3042        let pk = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
3043        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
3044        if let Some(v2) = Self::load_v2_if_v2(community_id)? {
3045            crate::community::v2::service::kick_member(&transport, &v2, &pk)
3046                .await
3047                .map_err(VectorError::Other)?;
3048            // Catch the local Guestbook up on our own Kick, so the memberlist read
3049            // (which folds the STORE, not the network) drops them before this returns
3050            // instead of waiting on the relay echo. The control fold follows because a
3051            // Kick strips roles first (CORD-04 §6), which moves the roster too.
3052            if session.is_valid() {
3053                if let Ok(fresh) = crate::community::v2::service::sync_guestbook(&transport, &v2, &session).await {
3054                    if !fresh.is_empty() {
3055                        emit_event("community_refreshed", &serde_json::json!({ "community_id": community_id }));
3056                    }
3057                }
3058            }
3059            Self::converge_v2_authority(&transport, community_id, &session).await;
3060            return Ok(());
3061        }
3062        let community = Self::load_community_hex(community_id)?;
3063        let channel = community.channels.first().ok_or_else(|| VectorError::Other("community has no channel".into()))?;
3064        service::publish_kick(&transport, &community, channel, &pk.to_hex()).await.map(|_| ()).map_err(VectorError::Other)
3065    }
3066
3067    /// Ban (`true`) or unban (`false`) a member. Ban is terminal (no rejoin); in a private community it also
3068    /// fires the read-cut rekey (needs a local key). Requires BAN + outrank.
3069    pub async fn set_member_banned(&self, community_id: &str, npub: &str, banned: bool) -> Result<()> {
3070        use crate::community::{service, transport::LiveTransport, CommunityId};
3071        let session = crate::state::SessionGuard::capture();
3072        let pk = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
3073        let hex = pk.to_hex();
3074        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
3075        // Recompute the full list (latest-wins): drop any existing entry, then add if banning.
3076        let mut list = crate::db::community::get_community_banlist(community_id).map_err(VectorError::Other)?;
3077        list.retain(|h| h != &hex);
3078        if banned {
3079            list.push(hex);
3080        }
3081        // Dual-stack: a v2 Ban is the CORD-04 §6 three-removal composition, in order —
3082        // the Banlist edition first (instant silence), then the Grant strip (authority
3083        // removal), then the Refounding read-cut (cryptographic severance).
3084        if community_id.len() == 64 {
3085            let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
3086            if let Some(Some(crate::community::ConcordProtocol::V2)) = crate::db::community::community_protocol(&cid).ok() {
3087                // Rotation barrier: a Ban's refound holds this lock for its whole
3088                // multi-publish rotation while the row still names the OLD root. An
3089                // unban/reban clicked in that window must WAIT and then load the
3090                // post-commit root — unlocked, it publishes the edit to the epoch
3091                // being buried, where no reader will ever fold it. Dropped before
3092                // `refound_community`, which re-acquires it (non-reentrant).
3093                let community = {
3094                    let lock = crate::community::v2::realtime::follow_lock(&cid);
3095                    let _rotation = lock.lock().await;
3096                    let community = crate::db::community::load_community_v2(&cid)
3097                        .map_err(VectorError::Other)?
3098                        .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
3099                    crate::community::v2::service::set_banlist(&transport, &community, &list).await.map_err(VectorError::Other)?;
3100                    if banned {
3101                        crate::community::v2::service::grant_roles(&transport, &community, &pk, vec![]).await.map_err(VectorError::Other)?;
3102                    }
3103                    community
3104                };
3105                if banned {
3106                    crate::community::v2::service::refound_community(&transport, &community, &[pk]).await.map_err(VectorError::Other)?;
3107                }
3108                Self::converge_v2_authority(&transport, community_id, &session).await;
3109                return Ok(());
3110            }
3111        }
3112        let community = Self::load_community_hex(community_id)?;
3113        service::publish_banlist(&transport, &community, &list).await.map_err(VectorError::Other)
3114    }
3115
3116    /// Owner dissolution / "Delete Community": publish the terminal GroupDissolved tombstone (and
3117    /// retire the owner's own invite links, no rekey), sealing the community permanently. Owner-only
3118    /// (re-verified cryptographically in `service::dissolve_community`); irreversible.
3119    pub async fn dissolve_community(&self, community_id: &str) -> Result<()> {
3120        use crate::community::{service, transport::LiveTransport, CommunityId};
3121        if community_id.len() != 64 {
3122            return Err(VectorError::Other("malformed community id".into()));
3123        }
3124        let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
3125        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
3126        // Dual-stack: a v2 community dissolves at its own `community_id`-derived
3127        // dissolved plane (CORD-02 §9), NOT v1's control-plane roster edition.
3128        if let Some(Some(crate::community::ConcordProtocol::V2)) = crate::db::community::community_protocol(&cid).ok() {
3129            let community = crate::db::community::load_community_v2(&cid)
3130                .map_err(VectorError::Other)?
3131                .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
3132            return crate::community::v2::service::dissolve_community(&transport, &community)
3133                .await
3134                .map_err(VectorError::Other);
3135        }
3136        let community = Self::load_community_hex(community_id)?;
3137        service::dissolve_community(&transport, &community).await.map_err(VectorError::Other)
3138    }
3139
3140    /// Edit community metadata (name / description) as an authorized member (MANAGE_METADATA). `None` leaves
3141    /// a field unchanged; an empty description clears it.
3142    pub async fn edit_community_metadata(&self, community_id: &str, name: Option<&str>, description: Option<&str>) -> Result<()> {
3143        use crate::community::{service, transport::LiveTransport, CommunityId};
3144        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
3145        // Dual-stack: a v2 metadata edit is an authorized vsk-0 control edition.
3146        // Overlay onto the FULL held document (`CommunityV2::metadata()`) — an
3147        // edition replaces the entity, so a bare name edit would otherwise wipe
3148        // the icon/banner for every member (CORD-02 §6).
3149        if community_id.len() == 64 {
3150            let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
3151            if let Some(Some(crate::community::ConcordProtocol::V2)) = crate::db::community::community_protocol(&cid).ok() {
3152                let community = crate::db::community::load_community_v2(&cid)
3153                    .map_err(VectorError::Other)?
3154                    .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
3155                let mut meta = community.metadata();
3156                if let Some(n) = name {
3157                    meta.name = n.to_string();
3158                }
3159                if let Some(d) = description {
3160                    meta.description = if d.is_empty() { None } else { Some(d.to_string()) };
3161                }
3162                return crate::community::v2::service::edit_community_metadata(&transport, &community, &meta)
3163                    .await
3164                    .map_err(VectorError::Other);
3165            }
3166        }
3167        let mut community = Self::load_community_hex(community_id)?;
3168        if let Some(n) = name { community.name = n.to_string(); }
3169        if let Some(d) = description { community.description = if d.is_empty() { None } else { Some(d.to_string()) }; }
3170        service::republish_community_metadata(&transport, &community).await.map_err(VectorError::Other)
3171    }
3172
3173
3174
3175    /// Leave a Community: announce a best-effort "left" presence (before dropping keys), then
3176    /// drop the held keys + local channel chats. You need a fresh invite to rejoin.
3177    pub async fn leave_community(&self, community_id: &str) -> Result<()> {
3178        use crate::community::{transport::LiveTransport, CommunityId};
3179        if community_id.len() != 64 {
3180            return Err(VectorError::Other("malformed community id".into()));
3181        }
3182        let id = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
3183        // v2: guestbook Leave + cross-device List tombstone + local delete, in the service.
3184        if let Some(v2) = Self::load_v2_if_v2(community_id)? {
3185            let session = state::SessionGuard::capture();
3186            let channel_ids: Vec<String> =
3187                v2.channels.iter().map(|ch| crate::simd::hex::bytes_to_hex_32(&ch.id.0)).collect();
3188            let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
3189            crate::community::v2::service::leave_community(&transport, &v2)
3190                .await
3191                .map_err(VectorError::Other)?;
3192            if !session.is_valid() {
3193                return Err(VectorError::Other("account changed during leave".into()));
3194            }
3195            let mut st = state::STATE.lock().await;
3196            st.chats.retain(|c| !channel_ids.contains(&c.id));
3197            return Ok(());
3198        }
3199        let community = crate::db::community::load_community(&id).map_err(VectorError::Other)?;
3200        let channel_ids: Vec<String> = community
3201            .as_ref()
3202            .map(|c| c.channels.iter().map(|ch| ch.id.to_hex()).collect())
3203            .unwrap_or_default();
3204        // "Left" announcement BEFORE dropping keys (afterward we can't sign/seal into the channel).
3205        if let Some(ref c) = community {
3206            if let Some(primary) = c.channels.first() {
3207                let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
3208                let _ = crate::community::service::publish_presence(&transport, c, primary, false, None).await;
3209            }
3210        }
3211        // voluntary leave is a self-removal → retain the held epoch keys for later self-scrub.
3212        crate::db::community::delete_community_retain_keys(community_id).map_err(VectorError::Other)?;
3213        {
3214            let mut st = state::STATE.lock().await;
3215            st.chats.retain(|c| !channel_ids.contains(&c.id));
3216        }
3217        Ok(())
3218    }
3219
3220    /// Resolve a channel id to its owning Community + the Channel (with its secret key).
3221    fn resolve_channel(
3222        &self,
3223        channel_id: &str,
3224    ) -> Result<(crate::community::Community, crate::community::Channel)> {
3225        use crate::community::CommunityId;
3226        let community_id = crate::db::community::community_id_for_channel(channel_id)
3227            .map_err(VectorError::Other)?
3228            .ok_or_else(|| VectorError::Other("Unknown Community channel".into()))?;
3229        if community_id.len() != 64 {
3230            return Err(VectorError::Other("malformed community id".into()));
3231        }
3232        let community = crate::db::community::load_community(&CommunityId(
3233            crate::simd::hex::hex_to_bytes_32(&community_id),
3234        ))
3235        .map_err(VectorError::Other)?
3236        .ok_or_else(|| VectorError::Other("Community not found".into()))?;
3237        let channel = community
3238            .channels
3239            .iter()
3240            .find(|c| c.id.to_hex() == channel_id)
3241            .cloned()
3242            .ok_or_else(|| VectorError::Other("Channel not found in Community".into()))?;
3243        Ok((community, channel))
3244    }
3245
3246
3247    /// Sync DM history from relays using NIP-77 negentropy set reconciliation.
3248    ///
3249    /// Reconciles local wrapper history with relay state, fetches missing events,
3250    /// and processes them through the standard prepare → commit pipeline.
3251    ///
3252    /// Returns (total_events, new_messages).
3253    ///
3254    /// ```no_run
3255    /// # async fn example() -> vector_core::Result<()> {
3256    /// let core = vector_core::VectorCore;
3257    /// // Sync last 7 days of DMs
3258    /// let (events, new) = core.sync_dms(Some(7), &vector_core::NoOpEventHandler).await?;
3259    /// println!("Processed {} events, {} new messages", events, new);
3260    /// # Ok(())
3261    /// # }
3262    /// ```
3263    pub async fn sync_dms(
3264        &self,
3265        since_days: Option<u64>,
3266        handler: &dyn InboundEventHandler,
3267    ) -> Result<(u32, u32)> {
3268        use futures_util::StreamExt;
3269        use nostr_sdk::prelude::*;
3270
3271        let client = state::nostr_client()
3272            .ok_or(VectorError::Other("Not connected".into()))?;
3273        let my_pk = state::my_public_key()
3274            .ok_or(VectorError::Other("Not logged in".into()))?;
3275
3276        // Load known wrapper IDs + timestamps for negentropy fingerprinting
3277        let all_items = db::wrappers::load_negentropy_items().unwrap_or_default();
3278
3279        // Filter items to time window (or use all for full sync)
3280        let (items, filter) = if let Some(days) = since_days {
3281            let since_ts = Timestamp::now().as_secs().saturating_sub(days * 24 * 3600);
3282            let items: Vec<(EventId, Timestamp)> = all_items.iter()
3283                .filter(|(_, ts)| ts.as_secs() >= since_ts)
3284                .cloned()
3285                .collect();
3286            let filter = Filter::new()
3287                .pubkey(my_pk)
3288                .kind(Kind::GiftWrap)
3289                .since(Timestamp::from_secs(since_ts));
3290            (items, filter)
3291        } else {
3292            let filter = Filter::new()
3293                .pubkey(my_pk)
3294                .kind(Kind::GiftWrap);
3295            (all_items, filter)
3296        };
3297
3298        log_info!("[SyncDMs] {} negentropy items, since_days={:?}", items.len(), since_days);
3299
3300        // Dry-run negentropy: exchange fingerprints to identify missing events
3301        let sync_opts = nostr_sdk::prelude::SyncOptions::new()
3302            .direction(nostr_sdk::prelude::SyncDirection::Down)
3303            .initial_timeout(std::time::Duration::from_secs(10))
3304            .dry_run();
3305
3306        // Race all relays — first to reconcile drives the fetch. Relays with a
3307        // fresh no-NIP-77 verdict skip the doomed reconcile and get a bounded
3308        // REQ pass below instead.
3309        let relay_map = client.relays().await;
3310        let (all_relays, no_neg_relays): (Vec<(RelayUrl, Relay)>, Vec<(RelayUrl, Relay)>) =
3311            relay_map.iter()
3312                .map(|(url, relay)| (url.clone(), relay.clone()))
3313                .partition(|(url, _)| negentropy::neg_supported_cached(url.as_str()) != Some(false));
3314        drop(relay_map);
3315        let skipped_no_neg: Vec<String> = no_neg_relays.iter().map(|(u, _)| u.to_string()).collect();
3316        if !skipped_no_neg.is_empty() {
3317            log_info!("[SyncDMs] {} relay(s) on REQ path (no NIP-77)", skipped_no_neg.len());
3318        }
3319
3320        // Tor-aware like the GUI path — a fixed clearnet budget over Tor makes
3321        // a healthy relay's slow first frame look like connected-silence and
3322        // earns it a false 24h no-NEG verdict in the shared account KV.
3323        let neg_budget = relay_request_timeout(std::time::Duration::from_secs(10));
3324        let neg_outer = neg_budget + std::time::Duration::from_secs(5);
3325        let connect_allowance = relay_request_timeout(std::time::Duration::from_secs(3))
3326            .min(neg_outer);
3327        let mut relay_futs = futures_util::stream::FuturesUnordered::new();
3328        for (url, relay) in &all_relays {
3329            let url = url.clone();
3330            let relay = relay.clone();
3331            let f = filter.clone();
3332            let i = items.clone();
3333            let o = sync_opts.clone();
3334            relay_futs.push(async move {
3335                if !negentropy::wait_connected(&relay, connect_allowance).await {
3336                    return (url, None, false);
3337                }
3338                // Outer slack over the initial_timeout so the SDK's error
3339                // (which distinguishes refusal from silence) surfaces first.
3340                let result = tokio::time::timeout(
3341                    neg_outer,
3342                    relay.sync(f).items(i).opts(o),
3343                ).await;
3344                let connected = relay.status() == RelayStatus::Connected;
3345                (url, Some(result), connected)
3346            });
3347        }
3348
3349        // Collect missing IDs from all relays
3350        let cap_session = state::SessionGuard::capture();
3351        let mut all_missing: std::collections::HashSet<EventId> = std::collections::HashSet::new();
3352        while let Some((url, result, connected)) = relay_futs.next().await {
3353            let Some(result) = result else {
3354                log_warn!("[SyncDMs] {} skipped: not connected", url);
3355                continue;
3356            };
3357            match result {
3358                Ok(Ok(recon)) => {
3359                    let count = recon.remote.len();
3360                    all_missing.extend(recon.remote);
3361                    log_info!("[SyncDMs] {} reconciled: {} missing", url, count);
3362                    if cap_session.is_valid() {
3363                        negentropy::record_neg_support(url.as_str(), true);
3364                    }
3365                }
3366                Ok(Err(e)) => {
3367                    log_warn!("[SyncDMs] {} failed: {}", url, e);
3368                    if cap_session.is_valid()
3369                        && negentropy::classify_neg_sync_error(&e.to_string(), connected) == Some(false)
3370                    {
3371                        log_info!("[SyncDMs] {} marked no-NIP-77 for 24h", url);
3372                        negentropy::record_neg_support(url.as_str(), false);
3373                    }
3374                }
3375                Err(_) => log_warn!("[SyncDMs] {} timed out ({:?})", url, neg_outer),
3376            }
3377        }
3378
3379        let mut total_events = 0u32;
3380        let mut new_messages = 0u32;
3381
3382        // No-NIP-77 relays still contribute: one bounded REQ over the same
3383        // filter. The 500-event cap keeps a `since_days: None` call from
3384        // pulling a whole mailbox — deep history is negentropy's job on the
3385        // relays that speak it.
3386        if !skipped_no_neg.is_empty() {
3387            let req_filter = filter.clone().limit(500);
3388            match client
3389                .stream_events(nostr_sdk::prelude::ReqTarget::manual(
3390                    skipped_no_neg.iter().cloned().map(|u| (u, vec![req_filter.clone()])),
3391                ))
3392                .timeout(std::time::Duration::from_secs(20))
3393                .await
3394            {
3395                Ok(stream) => {
3396                    let mut seen: std::collections::HashSet<[u8; 32]> = std::collections::HashSet::new();
3397                    tokio::pin!(stream);
3398                    while let Some((_relay, res)) = stream.next().await {
3399                        let Ok(event) = res else { continue };
3400                        // Straddles the stream: a swap mid-drain must not push
3401                        // the old account's wrappers through the new account's
3402                        // pipeline (ErrorSkip would ledger them there).
3403                        if !cap_session.is_valid() { break; }
3404                        if !seen.insert(event.id.to_bytes()) { continue; }
3405                        total_events += 1;
3406                        let prepared = event_handler::prepare_event(event, &client, my_pk).await;
3407                        if event_handler::commit_prepared_event(prepared, false, handler).await {
3408                            new_messages += 1;
3409                        }
3410                    }
3411                }
3412                Err(e) => log_warn!("[SyncDMs] REQ pass failed: {}", e),
3413            }
3414        }
3415
3416        if all_missing.is_empty() {
3417            log_info!("[SyncDMs] No missing events");
3418            return Ok((total_events, new_messages));
3419        }
3420
3421        // Fetch missing events in batches
3422        log_info!("[SyncDMs] Fetching {} missing events", all_missing.len());
3423        let ids: Vec<EventId> = all_missing.into_iter().collect();
3424        let relay_strs: Vec<String> = client.relays().await.keys()
3425            .map(|u| u.to_string()).collect();
3426
3427        const BATCH_SIZE: usize = 500;
3428
3429        for batch in ids.chunks(BATCH_SIZE) {
3430            // The #p is not redundant: Ditto refuses gift-wrap REQs that carry
3431            // neither authors nor #p, even authed — ids-only returns nothing.
3432            let f = Filter::new().ids(batch.to_vec()).kind(Kind::GiftWrap).pubkey(my_pk);
3433            match client
3434                .stream_events(nostr_sdk::prelude::ReqTarget::manual(
3435                    relay_strs.iter().cloned().map(|u| (u, vec![f.clone()])),
3436                ))
3437                .timeout(std::time::Duration::from_secs(30))
3438                .await
3439            {
3440                Ok(stream) => {
3441                    let client_clone = client.clone();
3442                    let prepared_stream = stream
3443                        .filter_map(|(_relay, res)| async move { res.ok() })
3444                        .map(move |event| {
3445                            let c = client_clone.clone();
3446                            tokio::spawn(async move {
3447                                event_handler::prepare_event(event, &c, my_pk).await
3448                            })
3449                        })
3450                        .buffer_unordered(8);
3451                    tokio::pin!(prepared_stream);
3452
3453                    while let Some(result) = prepared_stream.next().await {
3454                        total_events += 1;
3455                        if let Ok(prepared) = result {
3456                            if event_handler::commit_prepared_event(prepared, false, handler).await {
3457                                new_messages += 1;
3458                            }
3459                        }
3460                    }
3461                }
3462                Err(e) => log_warn!("[SyncDMs] Batch fetch error: {}", e),
3463            }
3464        }
3465
3466        log_info!("[SyncDMs] Complete: {} events processed, {} new messages", total_events, new_messages);
3467        Ok((total_events, new_messages))
3468    }
3469
3470    // ========================================================================
3471    // Event Subscription
3472    // ========================================================================
3473
3474    /// Subscribe to incoming DM events (NIP-17 GiftWraps).
3475    ///
3476    /// Returns the subscription ID for use in a custom notification loop.
3477    /// For a complete listen-and-process loop, use [`listen()`](Self::listen) instead.
3478    pub async fn subscribe_dms(&self) -> Result<nostr_sdk::prelude::SubscriptionId> {
3479        use nostr_sdk::prelude::*;
3480        let client = state::nostr_client()
3481            .ok_or(VectorError::Other("Not connected".into()))?;
3482        let my_pk = state::my_public_key()
3483            .ok_or(VectorError::Other("Not logged in".into()))?;
3484
3485        let filter = Filter::new()
3486            .pubkey(my_pk)
3487            .kind(Kind::GiftWrap)
3488            .limit(0);
3489
3490        let output = client.subscribe(filter).await
3491            .map_err(|e| VectorError::Nostr(e.to_string()))?;
3492        Ok(output.value)
3493    }
3494
3495    /// Catch up every locally-held Community: fold control / re-foundings / rekeys / banlist and
3496    /// fetch recent messages into local state for each channel. State-only (does not replay to an
3497    /// [`InboundEventHandler`]). Called at `listen()` start and periodically for outage resilience;
3498    /// also safe to call manually after a known disconnect.
3499    ///
3500    /// Catch up every locally-held Community. v1 channels are synced inline; a v2
3501    /// community is ENQUEUED for the follow worker (control/rekey re-fold + adopt),
3502    /// non-blocking. State-only (no handler replay of history). Called at `listen()`
3503    /// start and on reconnect; safe to call manually — the v2 enqueue is a no-op if
3504    /// no `listen()` worker is running.
3505    pub async fn sync_communities(&self) -> Result<()> {
3506        // Discover + rehydrate memberships from the 13302 across devices (CORD-02 §8),
3507        // bootstrapping from the client's connected relays so even a fresh device that
3508        // holds no community yet can find them. Best-effort.
3509        {
3510            use crate::community::{transport::LiveTransport, v2::service as v2};
3511            let bootstrap: Vec<String> = match crate::state::nostr_client() {
3512                Some(client) => client.relays().await.keys().map(|r| r.to_string()).collect(),
3513                None => Vec::new(),
3514            };
3515            let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
3516            if let Ok(outcome) = v2::sync_community_list(&transport, &bootstrap).await {
3517                // Headless: core already dropped the rows; a GUI shell additionally clears the
3518                // chat rows + STATE via `removed` (see `ListSyncOutcome`).
3519                let joined = outcome.joined;
3520                for c in &joined {
3521                    if community::v2::realtime::follow_worker_running() {
3522                        community::v2::realtime::enqueue_follow(c.id());
3523                    } else {
3524                        let _ = Self::v2_inline_follow(c.id()).await;
3525                    }
3526                }
3527                if !joined.is_empty() {
3528                    if let Some(client) = crate::state::nostr_client() {
3529                        community::v2::realtime::refresh_subscription(&client).await;
3530                    }
3531                }
3532            }
3533        }
3534
3535        let ids = db::community::list_community_ids().map_err(VectorError::from)?;
3536        for id in ids {
3537            if matches!(db::community::community_protocol(&id).ok().flatten(), Some(crate::community::ConcordProtocol::V2)) {
3538                // With a live listen() the coalescing worker owns the follow; headless
3539                // (no worker) it would be dropped, so walk it inline instead.
3540                if community::v2::realtime::follow_worker_running() {
3541                    community::v2::realtime::enqueue_follow(&id);
3542                } else {
3543                    let _ = Self::v2_inline_follow(&id).await;
3544                }
3545                // Back-fill each channel's chat, exactly as the v1 arm below does.
3546                // Without this a headless client only ever sees messages that arrive
3547                // LIVE: anything sent while it was down — or while it held no key for
3548                // a private channel — is never fetched, so a bot granted access reads
3549                // an empty room. Cheap when there is nothing new (id-deduped), and a
3550                // channel we cannot read simply yields nothing.
3551                if let Ok(Some(c)) = db::community::load_community_v2(&id) {
3552                    for ch in &c.channels {
3553                        let hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
3554                        let _ = Self::v2_backfill_channel(
3555                            &id, &hex, 50, 2, None,
3556                            crate::community::transport::Evidence::Fast, 12,
3557                        ).await;
3558                    }
3559                }
3560                continue;
3561            }
3562            if let Ok(Some(community)) = db::community::load_community(&id) {
3563                for ch in &community.channels {
3564                    let _ = self.sync_community_channel(&ch.id.to_hex(), 50).await;
3565                }
3566            }
3567        }
3568        Ok(())
3569    }
3570
3571
3572    /// Start listening for incoming DMs.
3573    ///
3574    /// Blocks until the client disconnects. Processes GiftWraps
3575    /// (DMs, files) → prepare_event → commit_prepared_event.
3576    ///
3577    /// ```no_run
3578    /// use vector_core::*;
3579    /// use std::sync::Arc;
3580    ///
3581    /// struct MyBot;
3582    /// impl InboundEventHandler for MyBot {
3583    ///     fn on_dm_received(&self, chat_id: &str, msg: &Message, _is_new: bool) {
3584    ///         if msg.mine { return; }
3585    ///         let to = chat_id.to_string();
3586    ///         let reply = format!("Echo: {}", msg.content);
3587    ///         tokio::spawn(async move {
3588    ///             let _ = VectorCore.send_dm(&to, &reply).await;
3589    ///         });
3590    ///     }
3591    /// }
3592    ///
3593    /// # async fn example() -> vector_core::Result<()> {
3594    /// let core = VectorCore::init(CoreConfig {
3595    ///     data_dir: "/tmp/bot-data".into(),
3596    ///     event_emitter: None,
3597    /// })?;
3598    /// core.login("nsec1...", None).await?;
3599    /// core.listen(Arc::new(MyBot)).await?;
3600    /// # Ok(())
3601    /// # }
3602    /// ```
3603    pub async fn listen(&self, handler: Arc<dyn InboundEventHandler>) -> Result<()> {
3604        use nostr_sdk::prelude::*;
3605
3606        let client = state::nostr_client()
3607            .ok_or(VectorError::Other("Not connected".into()))?;
3608        let my_pk = state::my_public_key()
3609            .ok_or(VectorError::Other("Not logged in".into()))?;
3610
3611        // Start the stream-AUTH responder BEFORE any relay interaction: a gating
3612        // relay issues its NIP-42 challenge ONCE per connection, and the DM
3613        // subscribe below consumes it via nostr-sdk's user auto-auth — if the
3614        // responder isn't already watching, that challenge is never remembered
3615        // and the stream keys registered later can NEVER authenticate (the relay
3616        // won't re-challenge an authed connection; the v2 sub dies silently).
3617        community::v2::streamauth::ensure_responder(&client);
3618
3619        // Outage resilience — catch up on connect, then re-sync periodically.
3620        //
3621        // Catch up BEFORE going realtime so a bot that was offline folds any missed re-foundings /
3622        // metadata / banlist changes (and recent messages) into local state, and subscribes at the
3623        // CURRENT epoch pseudonyms. This is state-only: historical messages are not replayed to the
3624        // handler (matches the gateway model) — query them via `get_messages`.
3625        // Spawn the single per-community follow worker for this session; the v2
3626        // follow queue (fed by dispatch, catch-up, and sync) drains through it.
3627        community::v2::realtime::spawn_follow_worker(handler.clone());
3628        let _ = self.sync_communities().await;
3629        let _ = self.sync_dms(None, &NoOpEventHandler).await;
3630
3631        // Subscribe to DMs (GiftWraps) AND Community channel events — one loop dispatches both
3632        // through the same handler, so `on_dm_received`/`on_community_message` share a sink.
3633        let dm_sub_id = self.subscribe_dms().await?;
3634        community::realtime::refresh_subscription(&client).await;
3635        community::v2::realtime::refresh_subscription(&client).await;
3636
3637        // Outage resilience via the relay Monitor — event-driven, not polling.
3638        //
3639        // (1) Reconnect-driven catch-up: a `limit(0)` realtime sub never replays what was published
3640        // while we were down, so a relay (re)connecting is exactly when we must catch up. On each
3641        // Connected transition we refold consensus + reconcile DMs (NIP-77 negentropy → only the
3642        // diff) and re-track the realtime sub at the current epochs. Idle when healthy. Stops on swap.
3643        if let Some(monitor) = client.monitor() {
3644            let mut rx = monitor.subscribe();
3645            let session = state::SessionGuard::capture();
3646            tokio::spawn(async move {
3647                // Debounce reconnect bursts: StatusChanged is per-relay, but one catch-up queries the
3648                // whole pool — so coalesce Connected transitions within a short window into one resync.
3649                let mut last_resync: Option<std::time::Instant> = None;
3650                while let Ok(notification) = rx.recv().await {
3651                    if !session.is_valid() {
3652                        return;
3653                    }
3654                    let MonitorNotification::StatusChanged { status, .. } = notification;
3655                    if status == RelayStatus::Connected {
3656                        if last_resync.is_some_and(|t| t.elapsed() < std::time::Duration::from_secs(3)) {
3657                            continue;
3658                        }
3659                        let _ = VectorCore.sync_communities().await;
3660                        let _ = VectorCore.sync_dms(None, &NoOpEventHandler).await;
3661                        if let Some(c) = state::nostr_client() {
3662                            community::realtime::refresh_subscription(&c).await;
3663                            community::v2::realtime::refresh_subscription(&c).await;
3664                        }
3665                        last_resync = Some(std::time::Instant::now());
3666                    }
3667                }
3668            });
3669        }
3670
3671        // (2) Health probe: a relay can report Connected while silently dead. Every 60s probe each
3672        // with a tiny query + timeout; a zombie is force-reconnected (which fires the monitor above
3673        // → catch-up), and Disconnected/Terminated relays are reconnected directly.
3674        {
3675            let client_health = client.clone();
3676            let session = state::SessionGuard::capture();
3677            tokio::spawn(async move {
3678                tokio::time::sleep(std::time::Duration::from_secs(30)).await; // warm-up
3679                loop {
3680                    if !session.is_valid() {
3681                        return;
3682                    }
3683                    for (url, relay) in client_health.relays().await {
3684                        match relay.status() {
3685                            RelayStatus::Connected => {
3686                                let probe = tokio::time::timeout(
3687                                    std::time::Duration::from_secs(10),
3688                                    client_health
3689                                        .fetch_events(nostr_sdk::prelude::ReqTarget::single(
3690                                            url.to_string(),
3691                                            [Filter::new().kind(Kind::Metadata).limit(1)],
3692                                        ))
3693                                        .timeout(std::time::Duration::from_secs(8)),
3694                                )
3695                                .await;
3696                                if !matches!(probe, Ok(Ok(_))) {
3697                                    let _ = relay.disconnect();
3698                                    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
3699                                    let _ = relay.try_connect().timeout(crate::relay_connect_timeout(std::time::Duration::from_secs(10))).await;
3700                                }
3701                            }
3702                            RelayStatus::Terminated | RelayStatus::Disconnected => {
3703                                let _ = relay.try_connect().timeout(crate::relay_connect_timeout(std::time::Duration::from_secs(10))).await;
3704                            }
3705                            _ => {}
3706                        }
3707                    }
3708                    tokio::time::sleep(std::time::Duration::from_secs(60)).await;
3709                }
3710            });
3711        }
3712
3713        let client_for_closure = client.clone();
3714
3715        // 0.45 removed `handle_notifications`; drive the stream directly. It ends when
3716        // the client shuts down, which is what stops this loop on `swap_session`.
3717        let mut notifications = client.notifications();
3718        while let Some(notification) = notifications.next().await {
3719            let handler = handler.clone();
3720            let c = client_for_closure.clone();
3721            let dm_sid = dm_sub_id.clone();
3722            {
3723                // Relay OKs feed the send pipeline: an OK that outlives the
3724                // per-attempt wait still confirms delivery, and can rescue a
3725                // message already marked Failed.
3726                if let nostr_sdk::prelude::ClientNotification::Message { message, .. } = &notification {
3727                    if let nostr_sdk::prelude::RelayMessage::Ok { event_id, status, .. } = &**message {
3728                        sending::note_relay_ok(event_id, *status);
3729                    }
3730                }
3731                if let nostr_sdk::prelude::ClientNotification::Event { event, subscription_id, .. } = notification {
3732                    if subscription_id == dm_sid {
3733                        // DMs, files, reactions
3734                        let prepared = event_handler::prepare_event(*event, &c, my_pk).await;
3735                        event_handler::commit_prepared_event(prepared, true, &*handler).await;
3736                    } else if community::realtime::subscription_id().await.as_ref() == Some(&subscription_id)
3737                        || community::realtime::poolwide_subscription_id().await.as_ref() == Some(&subscription_id)
3738                    {
3739                        // Community (v1) channel messages / reactions / edits / control editions.
3740                        // OR the pool-wide sub (the path that streams on Android) — else v1 events
3741                        // arriving under it match no branch and are silently dropped.
3742                        let session = state::SessionGuard::capture();
3743                        community::realtime::dispatch_event(&session, *event, handler.clone()).await;
3744                    } else if community::v2::realtime::subscription_id().await.as_ref() == Some(&subscription_id)
3745                        || community::v2::realtime::poolwide_subscription_id().await.as_ref() == Some(&subscription_id)
3746                    {
3747                        // Concord v2 plane events (authors-addressed kind-1059/21059).
3748                        let session = state::SessionGuard::capture();
3749                        community::v2::realtime::dispatch_event(&session, *event, handler.clone()).await;
3750                    }
3751                }
3752            }
3753        }
3754
3755        Ok(())
3756    }
3757
3758    /// Disconnect and clean up.
3759    pub async fn logout(&self) {
3760        if let Some(client) = state::nostr_client() {
3761            let _ = client.disconnect().await;
3762        }
3763        db::close_database();
3764    }
3765
3766    /// Tear down the current session for an in-process account swap — the account-agnostic core of
3767    /// the app's `reset_session()`. Advances the session generation FIRST so any background task
3768    /// holding a `SessionGuard` short-circuits before it can touch the next account's storage; shuts
3769    /// the client down (which ends any `listen()` notification loop bound to it, so the old account's
3770    /// events can't land in the new account's DB); closes the DB pool; and clears the key vaults plus
3771    /// all in-memory per-account state. Follow with `login()` to bind the next account, then re-attach
3772    /// `listen()`. (The app's `reset_session()` additionally clears Tauri-only caches it owns.)
3773    pub async fn swap_session(&self) {
3774        // FIRST — invalidate every captured guard before any teardown begins.
3775        state::bump_session_generation();
3776
3777        // Shut the client down before anything else: this detaches relay subscriptions and ends the
3778        // prior `listen()` loop, so it stops firing the old account's events into the new session.
3779        if let Some(client) = state::take_nostr_client() {
3780            let _ = client.shutdown().await;
3781        }
3782        db::close_database();
3783
3784        // Key vaults + transient secrets.
3785        state::ENCRYPTION_KEY.clear(&[&state::MY_SECRET_KEY]);
3786        state::MY_SECRET_KEY.clear(&[&state::ENCRYPTION_KEY]);
3787        {
3788            use zeroize::Zeroize;
3789            if let Ok(mut g) = state::MNEMONIC_SEED.lock() {
3790                if let Some(s) = g.as_mut() { s.zeroize(); }
3791                *g = None;
3792            }
3793            if let Ok(mut g) = state::PENDING_NSEC.lock() {
3794                if let Some(s) = g.as_mut() { s.zeroize(); }
3795                *g = None;
3796            }
3797        }
3798
3799        // In-memory per-account state owned by vector-core's globals.
3800        {
3801            let mut st = state::STATE.lock().await;
3802            st.profiles.clear();
3803            st.chats.clear();
3804            st.db_loaded = false;
3805            st.is_syncing = false;
3806        }
3807        state::WRAPPER_ID_CACHE.lock().await.clear();
3808        state::PENDING_EVENTS.lock().await.clear();
3809        state::set_active_chat(None);
3810        crate::profile::sync::clear_profile_sync_queue();
3811        crate::inbox_relays::clear_inbox_relay_cache();
3812        // In-flight wrap confirmations carry the prior account's chat and
3813        // message ids — a late OK must not "rescue" into the new session.
3814        crate::sending::clear_wrap_confirms();
3815        crate::emoji_packs::clear_nip65_cache();
3816        // Chat/user row-id caches are PER-ACCOUNT (row ids belong to the prior account's DB). Not clearing
3817        // them here let a swapped-in account resolve a channel/npub to the WRONG (prior-account) row id →
3818        // saves FK-failed silently + reads hit the wrong row (e.g. a community member vanished post-swap).
3819        crate::db::clear_id_caches();
3820        // Community sync RAM cache (page cursors, history-start, in-flight, invite preload) is
3821        // account-scoped — drop it so the next account can't read A's cursors/warmed pages. The
3822        // generation stamp self-invalidates too, but clear explicitly for parity with the GUI swap.
3823        crate::community::cache::clear();
3824        // Community realtime route/subscription state is account-scoped (channel keys + banned sets);
3825        // drop it so a swapped-in account can't listen on the prior account's pseudonyms.
3826        crate::community::realtime::clear().await;
3827        crate::community::v2::realtime::clear().await;
3828        // Pooled plane connections are authed as the prior account's plane secret keys.
3829        crate::community::transport::clear_plane_pool();
3830        // Theme-pack emoji tags are account-scoped; leaving the prior account's set active would tag the
3831        // next account's outbound messages with A's theme shortcodes (leaking A's pack Blossom URLs). The
3832        // frontend re-registers the new account's theme, but only if it HAS one — clear to be safe.
3833        crate::emoji_packs::set_theme_emoji_tags(Vec::new());
3834    }
3835}
3836
3837#[cfg(all(test, feature = "tor", not(target_arch = "wasm32")))]
3838mod transport_policy_tests {
3839    use std::time::Duration;
3840
3841    /// ONE test covering proxy + budgets: the Tor preference is a process-global
3842    /// atomic, so separate `#[test]` fns would race under the parallel runner.
3843    #[test]
3844    fn tor_transport_policy() {
3845        let short = Duration::from_secs(5);
3846        let long = Duration::from_secs(300);
3847
3848        // Tor off: connections may go direct, and every caller's clearnet budget
3849        // passes through untouched so the common path is never slowed down.
3850        crate::tor::set_tor_enabled_pref(false);
3851        assert_eq!(super::tor_proxy_target(), None);
3852        assert_eq!(super::relay_connect_timeout(short), short);
3853        assert_eq!(super::relay_request_timeout(short), short);
3854
3855        // `RequiredButInactive` (Tor chosen, proxy not up yet) must raise the floor
3856        // just like `Active`: that window is when connects are slowest, and treating
3857        // it as clearnet is what tore relays down mid-handshake.
3858        crate::tor::set_tor_enabled_pref(true);
3859        assert!(matches!(
3860            crate::tor::transport_state(),
3861            crate::tor::TorTransportState::RequiredButInactive
3862        ));
3863        // THE leak invariant: `None` here means "connect direct". While Tor is the
3864        // chosen transport it must never be None — least of all during bootstrap,
3865        // which is exactly when a naive implementation falls through to direct.
3866        // Silent failure with an IP disclosure as the cost, so it gets a permanent
3867        // guard rather than a one-off manual check.
3868        assert_eq!(
3869            super::tor_proxy_target(),
3870            Some(crate::tor::blackhole_proxy_addr()),
3871            "Tor enabled but inactive must blackhole, never connect direct"
3872        );
3873        assert_eq!(super::relay_connect_timeout(short), super::TOR_RELAY_CONNECT_FLOOR);
3874        assert_eq!(super::relay_request_timeout(short), super::TOR_RELAY_REQUEST_FLOOR);
3875
3876        // The floor only ever raises. A caller asking for longer than the floor has
3877        // a reason to, and shortening it would abort operations that used to finish.
3878        for tor in [true, false] {
3879            crate::tor::set_tor_enabled_pref(tor);
3880            assert_eq!(super::relay_connect_timeout(long), long, "connect, tor={tor}");
3881            assert_eq!(super::relay_request_timeout(long), long, "request, tor={tor}");
3882        }
3883    }
3884}
3885
3886#[cfg(test)]
3887mod facade_tests {
3888    use super::*;
3889
3890    /// SSRF regression: `download_attachment` must reject a private/link-local URL via
3891    /// `validate_url_not_private` BEFORE any network fetch (the URL is attacker-controlled).
3892    #[tokio::test]
3893    async fn download_attachment_rejects_private_url() {
3894        let att = crate::types::Attachment {
3895            url: "http://169.254.169.254/latest/meta-data/".to_string(),
3896            ..Default::default()
3897        };
3898        match VectorCore.download_attachment(&att).await {
3899            Err(VectorError::Other(msg)) => {
3900                assert!(msg.contains("Private/internal"), "expected SSRF rejection, got: {msg}")
3901            }
3902            other => panic!("expected SSRF rejection, got {other:?}"),
3903        }
3904    }
3905
3906    #[tokio::test]
3907    async fn download_attachment_rejects_empty_url() {
3908        let att = crate::types::Attachment::default();
3909        assert!(VectorCore.download_attachment(&att).await.is_err());
3910    }
3911
3912    /// The facade dual-stack dispatch: a v2 community surfaces in `list_communities`
3913    /// with `version: 2`, and `v2_community_for_channel` routes its channels to the
3914    /// v2 send path — while a v1 community is untouched (version 1).
3915    #[tokio::test]
3916    async fn list_communities_and_channel_routing_are_protocol_aware() {
3917        use crate::community::transport::memory::MemoryRelay;
3918        use nostr_sdk::prelude::Keys;
3919
3920        let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
3921        crate::db::close_database();
3922        crate::db::clear_id_caches();
3923        let tmp = tempfile::tempdir().unwrap();
3924        // A valid bech32-charset, npub-length account dir name.
3925        let acct = {
3926            const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
3927            let mut s = String::from("npub1");
3928            for i in 0..58 {
3929                s.push(B[(i * 7 + 3) % 32] as char);
3930            }
3931            s
3932        };
3933        std::fs::create_dir_all(tmp.path().join(&acct)).unwrap();
3934        crate::db::set_app_data_dir(tmp.path().to_path_buf());
3935        crate::db::set_current_account(acct.clone()).unwrap();
3936        crate::db::init_database(&acct).unwrap();
3937        let _ = crate::state::take_nostr_client();
3938        let me = Keys::generate();
3939        crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
3940        crate::state::set_my_public_key(me.public_key());
3941
3942        // Create a v2 community directly through the v2 service (offline).
3943        let relay = MemoryRelay::new();
3944        let community = crate::community::v2::service::create_community(&relay, "V2 Guild", vec!["wss://r".into()], None)
3945            .await
3946            .unwrap();
3947        let channel_hex = crate::simd::hex::bytes_to_hex_32(&community.channels[0].id.0);
3948
3949        // The facade lists it as version 2, owned by me.
3950        let listed = VectorCore.list_communities().await;
3951        let v2 = listed.iter().find(|c| c["version"] == 2).expect("the v2 community is listed");
3952        assert_eq!(v2["name"], "V2 Guild");
3953        assert_eq!(v2["is_owner"], true);
3954        assert_eq!(v2["channels"][0]["channel_id"], channel_hex);
3955
3956        // The channel routes to the v2 send path.
3957        assert_eq!(
3958            VectorCore.v2_community_for_channel(&channel_hex).unwrap(),
3959            Some(community.identity.community_id),
3960            "a v2 channel is routed to v2"
3961        );
3962        // An unknown channel routes nowhere (would fall through to v1).
3963        assert_eq!(VectorCore.v2_community_for_channel(&"00".repeat(32)).unwrap(), None);
3964    }
3965
3966    /// The facade builds a v2 invite URL by trimming `/invite` off the v1
3967    /// constant (v2's `build_invite_url` re-appends its own `/invite/<naddr>`).
3968    /// Lock that the derived URL is v2-shaped and round-trips through the v2
3969    /// parser — a stale constant or a double-`/invite` would silently break joins.
3970    #[test]
3971    fn v2_invite_url_base_derivation_round_trips() {
3972        use crate::community::v2::derive::TOKEN_LEN;
3973        use crate::community::v2::invite::{build_invite_url, parse_invite_link};
3974        use nostr_sdk::prelude::Keys;
3975        let base = crate::community::public_invite::INVITE_URL_BASE.trim_end_matches("/invite");
3976        assert!(!base.ends_with("/invite"), "the bare domain must not carry /invite");
3977        let signer = Keys::generate();
3978        let token = [0x07u8; TOKEN_LEN];
3979        let url = build_invite_url(base, &signer.public_key(), &token, &[]).unwrap();
3980        assert!(url.contains("/invite/"), "a v2 URL carries the naddr path");
3981        assert!(!url.contains("/invite/invite/"), "no doubled /invite from the base");
3982        let parsed = parse_invite_link(&url).unwrap();
3983        assert_eq!(parsed.link_signer, signer.public_key());
3984        assert_eq!(parsed.token, token);
3985    }
3986}