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 is used by:
5//! - **src-tauri**: the desktop and mobile app (a thin command shell)
6//! - **Vector Web**: the same frontend in a browser, over this crate compiled to wasm32
7//! - **vector_sdk**: bots and clients, with **vector-media** for voice without devices
8//! - **vector-cli**, **concord-cli** and the **vector-agent** MCP server
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 rt;
33pub mod files;
34#[cfg(target_arch = "wasm32")]
35pub mod webfiles;
36pub mod logging;
37pub mod error;
38pub mod traits;
39
40// Nostr SDK trait imports needed for bech32 operations
41use crate::event_ext::FinalizeUnsignedWithId;
42use nostr_sdk::prelude::{FinalizeEventAsync, ToBech32};
43
44// === Core Types ===
45pub mod event_ext;
46pub mod event_json;
47pub mod tags;
48pub mod types;
49pub mod profile;
50pub mod chat;
51pub mod clock;
52pub mod boot_payload;
53pub mod compact;
54
55// === State ===
56pub mod state;
57
58// === Debug Stats ===
59#[cfg(any(debug_assertions, feature = "bench"))]
60pub mod stats;
61
62// === Crypto ===
63pub mod crypto;
64
65// === Signer (polymorphic: local vault vs. NIP-46 remote bunker) ===
66pub mod signer;
67
68// === NIP-55 offline signer (on-device Amber over Android IPC) ===
69pub mod nip55;
70
71// === NIP-07 browser signer (a `window.nostr` extension, web builds) ===
72pub mod nip07;
73
74// === Database ===
75pub mod db;
76/// The "every task carries its account" check, run by this crate's suite and
77/// by every crate that spawns per-account work against vector-core.
78pub mod spawn_audit;
79#[cfg(test)]
80mod vault_audit;
81
82// === Network ===
83pub mod net;
84pub mod fasthash;
85pub mod event_size;
86#[cfg(not(target_arch = "wasm32"))]
87pub mod tls;
88pub mod events_tracker;
89pub mod proxy;
90pub mod negentropy;
91pub mod dm_catchup;
92pub mod live_subs;
93pub mod news;
94pub mod blossom;
95pub mod media;
96pub mod blossom_servers;
97pub mod blossom_capabilities;
98pub mod blossom_error;
99pub mod blossom_info;
100pub mod blossom_stats;
101pub mod inbox_relays;
102pub mod relay_info;
103pub mod emoji_packs;
104pub mod text_color;
105pub mod text_time;
106pub mod text_spans;
107pub mod secrets;
108pub mod emoji_usage;
109pub mod nostr_embed;
110pub mod video_poster;
111pub mod image_crop;
112pub mod image_prep;
113pub mod deep_link;
114pub mod golink;
115pub mod badges;
116pub mod history_gaps;
117pub mod bot_interface;
118pub mod webxdc;
119pub mod webxdc_permissions;
120#[cfg(feature = "xdc")]
121pub mod xdc;
122#[cfg(feature = "tor")]
123pub mod tor;
124#[cfg(all(feature = "i2p", not(target_arch = "wasm32")))]
125pub mod i2p;
126pub mod transport;
127pub mod svg;
128#[cfg(not(target_arch = "wasm32"))]
129pub mod vcache;
130
131/// NIP-42 authenticator.
132///
133/// Many Concord/Armada communities live on AUTH-gating relays (Ditto's default
134/// gates kind-1059), where an unauthenticated client silently reads back ZERO
135/// events — a join's control-plane verify then fails closed and every community
136/// fetch comes up empty. Registering this is what unlocks those reads; a relay
137/// that doesn't challenge is unaffected.
138///
139/// The signer is resolved per challenge rather than captured at client
140/// construction, so a bunker that connects later (or an account swap) authks
141/// under the identity that is live *now*.
142#[derive(Debug)]
143pub struct VectorAuthenticator;
144
145impl nostr_sdk::prelude::Authenticator for VectorAuthenticator {
146    fn make_auth_event<'a>(
147        &'a self,
148        relay_url: &'a nostr_sdk::prelude::RelayUrl,
149        challenge: &'a str,
150    ) -> signer::BoxedFuture<'a, std::result::Result<nostr_sdk::prelude::Event, nostr_sdk::prelude::Error>>
151    {
152        Box::pin(async move {
153            let signer =
154                signer::active_signer().map_err(nostr_sdk::prelude::Error::other)?;
155            Ok(
156                nostr_sdk::prelude::ClientAuthentication::new(challenge, relay_url.clone())
157                    .finalize_async(&signer)
158                    .await?,
159            )
160        })
161    }
162}
163
164/// A `ClientBuilder` carrying Vector's client-wide policy: NIP-42 auth plus the transport.
165///
166/// Callers should start from this rather than `ClientBuilder::new()` so both come along. The
167/// transport decides per connection attempt, so relays added later follow the network in use.
168pub fn nostr_client_builder() -> nostr_sdk::prelude::ClientBuilder {
169    transport::ws::apply_transport(
170        nostr_sdk::prelude::ClientBuilder::new().authenticator(VectorAuthenticator),
171        transport::Lane::Account,
172    )
173}
174
175pub use transport::ws::{apply_transport, transport_relay_options};
176
177/// Register a relay with the pool's own auto-reconnect disabled.
178///
179/// Vector drives every reconnect from its reconcile loop, because it needs the
180/// connection lifecycle to be observable and to sequence with health checks and
181/// the Tor transport switch. The pool's retry is invisible to all of that, so two
182/// schedules end up fighting over one socket.
183///
184/// This exists as a helper rather than a per-call `.reconnect(false)` because
185/// `reconnect` is the one relay option `ClientBuilder` cannot default: it lives
186/// only on `RelayOptions`, so every registration site has to opt out by hand, and
187/// most of them silently didn't.
188pub trait ClientRelayExt {
189    /// `Client::add_relay` with `reconnect(false)` already applied.
190    fn add_managed_relay<'client, 'url, U>(
191        &'client self,
192        url: U,
193    ) -> nostr_sdk::prelude::AddRelay<'client, 'url>
194    where
195        U: Into<nostr_sdk::prelude::RelayUrlArg<'url>>;
196}
197
198impl ClientRelayExt for nostr_sdk::prelude::Client {
199    fn add_managed_relay<'client, 'url, U>(
200        &'client self,
201        url: U,
202    ) -> nostr_sdk::prelude::AddRelay<'client, 'url>
203    where
204        U: Into<nostr_sdk::prelude::RelayUrlArg<'url>>,
205    {
206        self.add_relay(url).reconnect(false)
207    }
208}
209
210/// Re-send every live subscription this relay is supposed to carry, after VECTOR
211/// reconnected it.
212///
213/// Vector owns every reconnect (`add_managed_relay` ⇒ `reconnect(false)`), and the
214/// pool re-applies live subs only inside its own retry path — which is exactly the
215/// path that was turned off. So a dropped socket comes back carrying NOTHING, and a
216/// catch-up fetch is not a subscription: the data lands once and then the stream is
217/// silent forever. Only an AUTH-gating relay healed, via its post-challenge re-send.
218///
219/// Driven off the pool's own subscription table rather than a list of known
220/// subscriptions, so a future subscription is covered without touching this. Only
221/// ids the pool already associates with `relay` are re-sent, so a relay-targeted
222/// subscription is never widened onto a relay it deliberately excluded. Same-id
223/// REQs are idempotent. Sent as raw REQs: the pool refuses to subscribe an id it
224/// already holds.
225pub async fn resubscribe_relay_after_reconnect(
226    client: &nostr_sdk::prelude::Client,
227    relay: &nostr_sdk::prelude::RelayUrl,
228) {
229    use std::borrow::Cow;
230    crate::community::v2::realtime::note_resubscribe();
231    let Ok(Some(handle)) = client.relay(relay).await else { return };
232    let (mut sent, mut failed) = (0usize, 0usize);
233    for (id, per_relay) in client.subscriptions().await {
234        let Some(filters) = per_relay.get(relay) else { continue };
235        if filters.is_empty() {
236            continue;
237        }
238        let req = nostr_sdk::prelude::ClientMessage::Req {
239            subscription_id: Cow::Borrowed(&id),
240            filters: filters.iter().map(Cow::Borrowed).collect(),
241        };
242        match handle.send_msg(req).await {
243            Ok(()) => sent += 1,
244            Err(_) => failed += 1,
245        }
246    }
247    println!("[subs] {relay}: re-sent {sent} live sub(s), {failed} refused");
248    // What a relay closed was never in the pool to re-send.
249    live_subs::heal(client).await;
250}
251
252/// A relay connect budget for the transport in use: the caller's clearnet value, raised to the
253/// chosen kind's floor.
254///
255/// Clearnet TCP+TLS settles in well under a second, so the tight per-call budgets are right
256/// there. Under an anonymity network those budgets expire mid-circuit, and because the
257/// health-check and reconcile loops treat a timeout as "unhealthy" they disconnect and retry,
258/// so a relay would churn and never connect.
259pub fn relay_connect_timeout(clearnet: std::time::Duration) -> std::time::Duration {
260    transport::budget(transport::Op::RelayConnect, clearnet)
261}
262
263/// A relay round-trip budget for the transport in use. A relay that answers a probe in 200ms
264/// direct can take many seconds through three hops.
265pub fn relay_request_timeout(clearnet: std::time::Duration) -> std::time::Duration {
266    transport::budget(transport::Op::RelayRequest, clearnet)
267}
268
269/// The transport for any `ClientBuilder`, as the user's own lane.
270#[deprecated(note = "use vector_core::apply_transport(builder, lane)")]
271pub fn apply_tor_proxy(
272    builder: nostr_sdk::prelude::ClientBuilder,
273) -> nostr_sdk::prelude::ClientBuilder {
274    apply_transport(builder, transport::Lane::Account)
275}
276
277/// A publish waiting on the transport's budget for its OK and NIP-42 challenge: the SDK's
278/// fixed 10 s marks a Tor-slow publish failed while the relay is still answering.
279pub fn transport_aware<'c, 'e, 'u>(
280    send: nostr_sdk::client::SendEvent<'c, 'e, 'u>,
281) -> nostr_sdk::client::SendEvent<'c, 'e, 'u> {
282    let wait = relay_request_timeout(std::time::Duration::from_secs(10));
283    send.ok_timeout(wait).authentication_timeout(wait)
284}
285
286/// Relay options carrying the transport, for clients the SDK builds itself (NIP-46).
287#[deprecated(note = "use vector_core::transport_relay_options()")]
288pub fn tor_relay_options() -> nostr_sdk::prelude::RelayOptions {
289    transport_relay_options()
290}
291
292/// Sign an `EventBuilder` with the session signer, refusing an event no relay would store.
293///
294/// Stands in for 0.44's `Client::sign_event_builder`, which went away when the
295/// client stopped owning a signer.
296pub async fn sign_builder(
297    builder: nostr_sdk::prelude::EventBuilder,
298) -> std::result::Result<nostr_sdk::prelude::Event, String> {
299    let signer = signer::active_signer()?;
300    let event = builder
301        .finalize_async(&signer)
302        .await
303        .map_err(|e| e.to_string())?;
304    event_size::check(&event)?;
305    Ok(event)
306}
307
308/// Sign an `EventBuilder` with the session signer and publish it.
309///
310/// Stands in for 0.44's `Client::send_event_builder`.
311pub async fn sign_and_send(
312    client: &nostr_sdk::prelude::Client,
313    builder: nostr_sdk::prelude::EventBuilder,
314) -> std::result::Result<nostr_sdk::prelude::SendEventOutput, String> {
315    let event = sign_builder(builder).await?;
316    transport_aware(client.send_event(&event))
317        .await
318        .map_err(|e| e.to_string())
319}
320
321/// Read `filter` from the user's read relays, or `Err` unless at least one relay reached EOSE.
322///
323/// The SDK's fetch reports a timeout, a disconnect and a refusal as an empty success, so it
324/// cannot tell "you hold none" from "nobody answered". A read-modify-write needs the difference.
325pub async fn fetch_answered(
326    client: &nostr_sdk::prelude::Client,
327    filter: nostr_sdk::prelude::Filter,
328    timeout: std::time::Duration,
329) -> std::result::Result<Vec<nostr_sdk::prelude::Event>, String> {
330    use community::transport::{fetch_relay_eose_filters, EoseFail};
331    use nostr_sdk::prelude::RelayStatus;
332    let relays = client.relays().with_capabilities(nostr_sdk::prelude::RelayCapabilities::READ).await;
333    // Reconnects are ours, so a terminated relay would only burn the whole timeout.
334    let live: Vec<_> = relays
335        .iter()
336        .filter(|(_, r)| !matches!(r.status(), RelayStatus::Terminated | RelayStatus::Shutdown | RelayStatus::Banned))
337        .map(|(url, _)| url)
338        .collect();
339    if live.is_empty() {
340        return Err("no relays to read from".to_string());
341    }
342    let reads = live.into_iter().map(|url| {
343        let url = url.to_string();
344        let filter = filter.clone();
345        async move {
346            match fetch_relay_eose_filters(client, &url, vec![filter.clone()], timeout).await {
347                // A CLOSED is usually auth-required; the authenticator answers it, so ask once more.
348                Err(EoseFail::Closed) => {
349                    crate::rt::time::sleep(std::time::Duration::from_millis(800)).await;
350                    fetch_relay_eose_filters(client, &url, vec![filter], timeout).await
351                }
352                other => other,
353            }
354        }
355    });
356    let mut answered = false;
357    let mut seen = std::collections::HashSet::new();
358    let mut events = Vec::new();
359    for read in futures_util::future::join_all(reads).await.into_iter().flatten() {
360        answered = true;
361        events.extend(read.into_iter().filter(|e| seen.insert(e.id)));
362    }
363    if !answered {
364        return Err("none of your relays answered".to_string());
365    }
366    Ok(events)
367}
368
369/// The newest of a replaceable event's copies: highest `created_at`, then lowest id, as relays keep.
370pub fn newest_replaceable(events: Vec<nostr_sdk::prelude::Event>) -> Option<nostr_sdk::prelude::Event> {
371    events.into_iter().min_by(|a, b| b.created_at.cmp(&a.created_at).then_with(|| a.id.cmp(&b.id)))
372}
373
374/// Seal, wrap and publish a rumor to `receiver`.
375///
376/// Stands in for 0.44's `Client::gift_wrap` / `gift_wrap_to`, which went away
377/// with the client's signer. An empty `relays` publishes pool-wide, matching
378/// `gift_wrap`; a non-empty one targets those relays, matching `gift_wrap_to`.
379pub async fn send_gift_wrap<'u, I, U, T>(
380    client: &nostr_sdk::prelude::Client,
381    relays: I,
382    receiver: &nostr_sdk::prelude::PublicKey,
383    rumor: nostr_sdk::prelude::UnsignedEvent,
384    extra_tags: T,
385) -> std::result::Result<nostr_sdk::prelude::SendEventOutput, String>
386where
387    I: IntoIterator<Item = U>,
388    U: Into<nostr_sdk::prelude::RelayUrlArg<'u>>,
389    T: IntoIterator<Item = nostr_sdk::prelude::Tag>,
390{
391    let wrap = signer::gift_wrap(receiver, rumor, extra_tags).await?;
392    let targets: Vec<nostr_sdk::prelude::RelayUrlArg<'u>> =
393        relays.into_iter().map(Into::into).collect();
394    if targets.is_empty() {
395        crate::transport_aware(client.send_event(&wrap)).await.map_err(|e| e.to_string())
396    } else {
397        transport_aware(client.send_event(&wrap))
398            .to(targets)
399            .await
400            .map_err(|e| e.to_string())
401    }
402}
403
404/// Capabilities for a Community / "external" relay: GOSSIP only.
405///
406/// GOSSIP is read/write-capable when TARGETED — `can_read()` is
407/// `READ|GOSSIP|DISCOVERY` and `can_write()` is `WRITE|GOSSIP`, so per-relay
408/// targeted ops pass. But pool-wide ops select READ-only / WRITE-only relays, so
409/// the DM/giftwrap subscription and the user's outbox skip GOSSIP relays — the
410/// user's own traffic never touches relays they don't own.
411///
412/// No PING counterpart any more: 0.45 demoted PING from a capability flag to a
413/// per-relay option (`AddRelay::ping`) that already defaults to true, with
414/// `sleep_when_idle` defaulting to false. The 24/7 keepalive this used to buy is
415/// now the default, so it doesn't belong in the capability set.
416pub fn community_relay_capabilities() -> nostr_sdk::prelude::RelayCapabilities {
417    nostr_sdk::prelude::RelayCapabilities::GOSSIP
418}
419
420/// Relay options for a Discovery Relay (see `state::DISCOVERY_RELAYS`): the same
421/// GOSSIP|PING targeted-only isolation as Community relays — reachable via
422/// `fetch_events_from` / `send_event_to`, invisible to pool-wide DM/profile ops.
423/// An overlap with a user relay keeps the user's READ+WRITE flags (`add_relay`
424/// no-ops on an already-pooled url).
425pub fn discovery_relay_capabilities() -> nostr_sdk::prelude::RelayCapabilities {
426    community_relay_capabilities()
427}
428
429// === Event Storage ===
430pub mod stored_event;
431
432// === Rumor Processing ===
433pub mod rumor;
434
435// === Messaging ===
436pub mod sending;
437
438// === Per-DM Wallpapers ===
439pub mod pinned_chats;
440pub mod rail_layout;
441pub mod start_menu;
442pub mod synced_prefs;
443pub mod notify;
444pub mod push;
445pub mod wallpaper;
446pub mod requests;
447
448// === Message Deletion (NIP-09 against retained gift-wraps) ===
449pub mod deletion;
450pub mod early;
451pub mod self_destruct;
452pub mod transfer;
453
454// === SIMD Operations ===
455pub mod simd;
456
457/// Calls: the platform-free half from `vector-calls`, and with `calls` the session itself.
458pub mod calls;
459
460// === Community protocol (GROUP_PROTOCOL.md) ===
461pub mod community;
462
463// === Event Handler ===
464pub mod event_handler;
465
466// === Re-exports for convenience ===
467pub use types::{Message, Attachment, Reaction, EditEntry, ImageMetadata, SiteMetadata, LoginResult, AttachmentFile, mention, extract_mentions};
468pub use profile::{Profile, ProfileFlags, SlimProfile, Status};
469pub use chat::{Chat, ChatType, ChatMetadata, SerializableChat};
470pub use compact::{CompactMessage, CompactMessageVec, NpubInterner};
471pub use state::{
472    ChatState, MY_SECRET_KEY, STATE, ENCRYPTION_KEY,
473    nostr_client, my_public_key, has_active_session,
474    set_nostr_client, set_my_public_key,
475    take_nostr_client, clear_my_public_key,
476    set_pending_bunker_setup, pending_bunker_setup, clear_pending_bunker_setup,
477    set_pending_nip55_setup, pending_nip55_setup, clear_pending_nip55_setup,
478};
479pub use crypto::{GuardedKey, GuardedSigner};
480pub use signer::{
481    SignerKind, signer_kind, set_signer_kind, is_bunker, is_keyless,
482    BUNKER_SIGNER, bunker_signer, set_bunker_signer, take_bunker_signer,
483    build_bunker_signer, prewarm_bunker, drain_bunker_state,
484    parse_bunker_remote_pubkey, parse_bunker_relays,
485    BunkerConnectionState, bunker_state, set_bunker_state,
486    VectorAuthUrlHandler, attempt_bunker_login, WatchedBunkerSigner,
487    vector_metadata, build_nostrconnect_uri, build_nostrconnect_session,
488    VECTOR_APP_NAME, VECTOR_APP_URL, VECTOR_APP_ICON,
489};
490pub use nip55::{
491    Nip55Backend, Nip55Error, Nip55ResolverOutcome, Nip55Signer, Nip55State,
492    set_nip55_backend, nip55_backend, nip55_state, set_nip55_state, drain_nip55_state,
493    nip55_is_installed, nip55_pair, nip55_perms_json,
494    VECTOR_NIP55_SIGN_KINDS, VECTOR_NIP55_ENCRYPT_TYPES,
495};
496pub use nip07::{Nip07Backend, Nip07Signer, set_nip07_backend, nip07_backend, nip07_get_public_key};
497pub use error::{DownloadError, VectorError, Result};
498
499/// What [`VectorCore::download_attachment_reporting`] is doing, as it happens.
500#[derive(Debug, Clone, Copy)]
501pub enum DownloadStep {
502    /// Ciphertext received so far from the current source, and the length it declared.
503    /// A source that fails over starts the count again.
504    Received { bytes: u64, total: Option<u64> },
505    /// Every byte is in; it is being decrypted, or checked against its hash.
506    Opening,
507}
508pub use traits::{EventEmitter, NoOpEmitter, set_event_emitter, emit_event};
509pub use db::{set_app_data_dir, get_app_data_dir};
510pub use sending::{SendCallback, NoOpSendCallback, SendConfig, SendResult};
511pub use deletion::{delete_own_dm, delete_received_dm, DeleteOutcome};
512pub use stored_event::{StoredEvent, StoredEventBuilder, SystemEventType};
513pub use rumor::{RumorEvent, RumorContext, ConversationType, RumorProcessingResult, process_rumor};
514pub use profile::{SyncPriority, ProfileSyncHandler, NoOpProfileSyncHandler};
515pub use event_handler::{InboundEventHandler, LiveOnly, NoOpEventHandler, PreparedEvent, process_event};
516
517use std::path::PathBuf;
518use std::sync::Arc;
519
520// ============================================================================
521// VectorCore — High-level API
522// ============================================================================
523
524/// Configuration for initializing VectorCore.
525pub struct CoreConfig {
526    /// Path to the app data directory (e.g., ~/.local/share/io.vectorapp/data/)
527    pub data_dir: PathBuf,
528    /// Optional event emitter for UI integration
529    pub event_emitter: Option<Box<dyn EventEmitter>>,
530}
531
532/// The main entry point for Vector Core.
533///
534/// Provides a high-level API for all Vector operations. Internally uses
535/// global state (same pattern as the Tauri backend) for compatibility.
536///
537/// ```no_run
538/// use vector_core::{VectorCore, CoreConfig};
539/// use std::path::PathBuf;
540///
541/// # async fn example() -> vector_core::Result<()> {
542/// let core = VectorCore::init(CoreConfig {
543///     data_dir: PathBuf::from("/tmp/vector-data"),
544///     event_emitter: None,
545/// })?;
546///
547/// // Login with nsec
548/// let result = core.login("nsec1...", None).await?;
549/// println!("Logged in as {}", result.npub);
550/// # Ok(())
551/// # }
552/// ```
553#[derive(Clone, Copy)]
554pub struct VectorCore;
555
556/// How a post goes out. The default is a plain post, with pictures compressed.
557///
558/// ```
559/// let opts = vector_core::PostOptions::default().reply_to("ab12…").expires_in(600);
560/// let original = vector_core::PostOptions::default().compress(false);
561/// ```
562#[derive(Debug, Clone)]
563#[non_exhaustive]
564pub struct PostOptions {
565    /// The message this one replies to.
566    pub reply_to: Option<String>,
567    /// Seconds until it deletes itself for everyone (NIP-40).
568    pub expires_in_secs: Option<u64>,
569    /// The one bot (npub or hex) a command is meant for, when several answer the same name.
570    pub bot: Option<String>,
571    /// The text under a file. Ignored for a text post, whose content is the text.
572    pub caption: Option<String>,
573    /// A picture sent as a file is fitted to 2560px and re-encoded first, which also strips its
574    /// metadata (camera, GPS). Off sends the file's bytes as they are.
575    pub compress: bool,
576}
577
578impl Default for PostOptions {
579    fn default() -> Self {
580        PostOptions { reply_to: None, expires_in_secs: None, bot: None, caption: None, compress: true }
581    }
582}
583
584impl PostOptions {
585    pub fn compress(mut self, on: bool) -> Self {
586        self.compress = on;
587        self
588    }
589
590    pub fn reply_to(mut self, message_id: impl Into<String>) -> Self {
591        self.reply_to = Some(message_id.into());
592        self
593    }
594
595    pub fn expires_in(mut self, secs: u64) -> Self {
596        self.expires_in_secs = Some(secs);
597        self
598    }
599
600    pub fn to_bot(mut self, bot: impl Into<String>) -> Self {
601        self.bot = Some(bot.into());
602        self
603    }
604
605    pub fn caption(mut self, text: impl Into<String>) -> Self {
606        self.caption = Some(text.into());
607        self
608    }
609}
610
611/// A file as it goes out: a picture compressed when `compress` says so, its name following
612/// the format it became. One too large to compress goes with its metadata cut out instead, and
613/// one that can't be stripped either is refused: compressing promises no metadata leaves.
614/// Anything that isn't a picture goes as it is.
615pub(crate) async fn ready_to_send(bytes: Vec<u8>, filename: &str, compress: bool) -> Result<(Vec<u8>, String)> {
616    if !compress || image::guess_format(&bytes).is_err() || crate::svg::looks_like_svg(&bytes) {
617        return Ok((bytes, filename.to_string()));
618    }
619    let prepared = crate::rt::spawn_blocking(move || {
620        crate::image_prep::prepare(&bytes, crate::image_prep::ImageUse::Photo).or_else(|e| crate::image_prep::strip(&bytes).ok_or(e))
621    })
622    .await
623    .map_err(|e| VectorError::Other(format!("image: {e}")))?
624    .map_err(|e| VectorError::Other(format!("{e}; send it uncompressed to share it as it is")))?;
625    let path = std::path::Path::new(filename);
626    let same = path.extension().and_then(|e| e.to_str()).is_some_and(|e| {
627        let e = e.to_ascii_lowercase();
628        e == prepared.extension || (prepared.extension == "jpg" && e == "jpeg")
629    });
630    let name = if same { filename.to_string() } else { path.with_extension(prepared.extension).to_string_lossy().into_owned() };
631    Ok((prepared.bytes, name))
632}
633
634/// How a new Community starts. The default is one `#general` Channel on the active relays.
635#[derive(Debug, Clone, Default)]
636#[non_exhaustive]
637pub struct NewCommunity {
638    pub description: Option<String>,
639    /// The first Channel's name, `general` when unset.
640    pub first_channel: Option<String>,
641    /// Where it lives; empty means the account's active relays.
642    pub relays: Vec<String>,
643}
644
645impl NewCommunity {
646    pub fn description(mut self, text: impl Into<String>) -> Self {
647        self.description = Some(text.into());
648        self
649    }
650
651    pub fn first_channel(mut self, name: impl Into<String>) -> Self {
652        self.first_channel = Some(name.into());
653        self
654    }
655
656    pub fn relays(mut self, relays: impl IntoIterator<Item = impl Into<String>>) -> Self {
657        self.relays = relays.into_iter().map(Into::into).collect();
658        self
659    }
660}
661
662/// How a new Channel starts. The default is a public chat Channel at the top level.
663#[derive(Debug, Clone, Default)]
664#[non_exhaustive]
665pub struct NewChannel {
666    /// A key of its own: only those let in can read it.
667    pub private: bool,
668    pub category_id: Option<String>,
669    /// `chat` (the default), `forum` or `voice`.
670    pub view: Option<String>,
671    pub topic: Option<String>,
672}
673
674impl NewChannel {
675    pub fn private(mut self) -> Self {
676        self.private = true;
677        self
678    }
679
680    pub fn in_category(mut self, category_id: impl Into<String>) -> Self {
681        self.category_id = Some(category_id.into());
682        self
683    }
684
685    pub fn view(mut self, view: impl Into<String>) -> Self {
686        self.view = Some(view.into());
687        self
688    }
689
690    pub fn topic(mut self, topic: impl Into<String>) -> Self {
691        self.topic = Some(topic.into());
692        self
693    }
694}
695
696/// What a public invite link shows before joining.
697#[derive(Debug, Clone, serde::Serialize)]
698#[non_exhaustive]
699pub struct LinkPreview {
700    pub community_id: String,
701    pub name: String,
702    pub description: Option<String>,
703    /// The icon's encrypted blob reference.
704    pub icon: Option<crate::community::CommunityImage>,
705    /// Already a member: the preview is what this device holds.
706    pub joined: bool,
707    /// Read from the Community itself. When false, the name, description and icon are what the
708    /// link's creator wrote, unproven: show them as a claim, if at all.
709    pub verified: bool,
710}
711
712/// Which live subscription an event came in on.
713enum LiveRoute {
714    Dm,
715    CommunityV2,
716}
717
718/// Stands for every relay in what a listener's catch-up owes.
719const EVERY_RELAY: &str = "*";
720
721/// What a listener's catch-up runner owes, by session: see [`VectorCore::owe_catch_up`].
722#[derive(Default)]
723struct Owed {
724    session: u64,
725    communities: bool,
726    dms: bool,
727    relays: std::collections::HashMap<String, u64>,
728    running: bool,
729}
730
731// Keyed by session id, as `news` is: the runner and its callers may hold different Session objects.
732static CATCH_UPS: std::sync::LazyLock<std::sync::Mutex<Owed>> = std::sync::LazyLock::new(Default::default);
733
734/// Who fetches what was published while a `listen` client was offline.
735#[derive(Debug, Clone, Copy, PartialEq, Eq)]
736pub enum CatchUp {
737    /// `listen` folds state, back-fills every channel and syncs DMs before its
738    /// Community subscriptions go live (DMs go live first, so nothing sent during
739    /// the sync is missed), and again on each reconnect: a bot starts from a
740    /// complete picture.
741    Inline,
742    /// `listen` goes live at once and leaves the gap to the caller, which pages
743    /// it behind the live subscriptions (a UI that paints as history lands).
744    External,
745}
746
747/// A community image no edition names any more, off its media server. Only its uploader's delete
748/// is honoured there, so another admin's upload stays, encrypted, under a key only members held.
749fn drop_community_image(url: Option<String>, kept: Option<&str>) {
750    let Some(url) = url.filter(|u| Some(u.as_str()) != kept) else { return };
751    if let Ok(signer) = crate::signer::active_signer() {
752        crate::blossom::delete_blobs_best_effort(signer, vec![url]);
753    }
754}
755
756/// How many times a count-only backfill pages on from where the relay walk stopped.
757const BACKFILL_CONTINUATIONS: usize = 3;
758
759/// Epochs below the live one a catch-up with no proof reads.
760const UNPROVEN_EPOCHS: u64 = 2;
761
762/// What one catch-up page cost and what it yielded.
763///
764/// `fetched` is the relay's answer — zero means there is genuinely nothing
765/// further back, which is the only sound "reached the start" signal.
766/// `new_messages` counts what this client had never seen, which is what a UI
767/// reports; a page of entirely-known history is 0 new with a non-empty fetch.
768#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
769pub struct BackfillCount {
770    pub fetched: usize,
771    pub new_messages: usize,
772    /// Where an older page goes on from (Unix seconds) when this one stopped with relay history
773    /// still unread; `None` when it reached what it was after.
774    pub next_before: Option<u64>,
775    /// No relay answered: nothing is known about what lies past the cursor.
776    pub unreachable: bool,
777}
778
779impl VectorCore {
780    /// Initialize Vector Core with the given configuration.
781    pub fn init(config: CoreConfig) -> Result<Self> {
782        // Set data directory
783        db::set_app_data_dir(config.data_dir);
784
785        // Set event emitter (or no-op)
786        if let Some(emitter) = config.event_emitter {
787            traits::set_event_emitter(emitter);
788        }
789
790        // Install rustls ring provider
791        #[cfg(not(target_arch = "wasm32"))]
792        let _ = rustls::crypto::ring::default_provider().install_default();
793
794        net::raise_fd_limit();
795
796        Ok(VectorCore)
797    }
798
799    /// Get all available accounts.
800    pub fn accounts(&self) -> Result<Vec<String>> {
801        db::get_accounts().map_err(VectorError::from)
802    }
803
804    /// Login with an nsec key or mnemonic seed phrase.
805    pub async fn login(&self, key: &str, password: Option<&str>) -> Result<LoginResult> {
806        use nostr_sdk::prelude::*;
807
808        // Parse the key
809        let keys = if key.starts_with("nsec1") {
810            let secret = SecretKey::from_bech32(key)
811                .map_err(|e| VectorError::Nostr(format!("Invalid nsec: {}", e)))?;
812            Keys::new(secret)
813        } else {
814            // Treat as mnemonic (NIP-06: derive from BIP-39 seed)
815            Keys::from_mnemonic(key, None)
816                .map_err(|e| VectorError::Nostr(format!("Key derivation failed: {}", e)))?
817        };
818
819        let public_key = keys.public_key();
820        let npub = public_key.to_bech32()
821            .map_err(|e| VectorError::Nostr(format!("Failed to encode npub: {}", e)))?;
822
823        // Store in GuardedKey vault (pass other vaults to protect during decoy writes)
824        let secret_bytes = keys.secret_key().to_secret_bytes();
825        state::MY_SECRET_KEY.set(secret_bytes, &[&state::ENCRYPTION_KEY]);
826        state::set_my_public_key(public_key);
827
828        // Initialize database for this account
829        db::set_current_account(npub.clone())?;
830        db::init_database(&npub)?;
831
832        // Store nsec for encryption setup
833        {
834            let nsec = keys.secret_key().to_bech32()
835                .map_err(|e| VectorError::Nostr(format!("Failed to encode nsec: {}", e)))?;
836            *state::PENDING_NSEC.lock().unwrap() = Some(nsec.clone());
837
838            // NEVER clobber an existing encrypted key with the plaintext nsec. An account with encryption
839            // enabled keeps its key encrypted-at-rest (PIN-derived); overwriting it with the raw nsec — e.g.
840            // a no-password headless/diagnostic login (the concord CLI) — would leave the GUI deriving the
841            // right key from the correct PIN but trying to decrypt a value that's no longer ciphertext, i.e.
842            // "incorrect pin" with the real key effectively lost. MY_SECRET_KEY is already set in-memory above,
843            // so login works regardless; only persist the raw key when there's no encrypted key to protect.
844            let existing_encrypted = db::get_pkey().ok().flatten().is_some_and(|v| !v.starts_with("nsec1"));
845            if !(state::resolve_encryption_enabled_from_db() && existing_encrypted) {
846                db::set_pkey(&nsec)?;
847            }
848        }
849
850        // Use the canonical resolver so this high-level API agrees with
851        // crypto::is_encryption_enabled and the Android bg-sync probe.
852        let has_encryption = state::resolve_encryption_enabled_from_db();
853
854        if has_encryption {
855            if let Some(pwd) = password {
856                // The vault takes the key only once it proves against this account's material:
857                // a wrong password here would seal everything this session writes under it.
858                // No salt upgrade here: a tool can share a data dir with a running app, which
859                // upgrades at its own unlock.
860                let kdf = crate::crypto::Kdf::of_account().map_err(VectorError::Crypto)?;
861                let key = zeroize::Zeroizing::new(crate::crypto::derive_key(pwd, &kdf).await);
862                crate::crypto::install_unlocked_key(&key, &kdf).map_err(VectorError::Crypto)?;
863            }
864        }
865        // Seed the atomic unconditionally — `is_encryption_enabled_fast()`
866        // must agree with the DB regardless of branch.
867        state::init_encryption_enabled();
868
869        // Build Nostr client — tor-aware options so a headless consumer with
870        // the Tor pref ON proxies (or blackholes) instead of dialing direct.
871        let client = crate::nostr_client_builder()
872            // Relay health monitor — powers the reconnect-driven catch-up in `listen()`.
873            .monitor(Monitor::new(1024))
874            .build();
875
876        // Add trusted relays
877        for relay in state::TRUSTED_RELAYS {
878            client.add_managed_relay(*relay).await.ok();
879        }
880
881        // Connect
882        client.connect().await;
883
884        let _ = { state::set_nostr_client(client); Ok::<(), ()>(()) };
885
886        Ok(LoginResult { npub, has_encryption })
887    }
888
889    /// Generate a fresh random account secret key (bech32 nsec). Lets a headless client spin up a
890    /// brand-new identity (`add_account` with no key) without depending on nostr-sdk directly.
891    pub fn generate_nsec(&self) -> Result<String> {
892        use nostr_sdk::prelude::*;
893        Keys::generate().secret_key().to_bech32()
894            .map_err(|e| VectorError::Nostr(format!("Failed to encode nsec: {}", e)))
895    }
896
897    /// Send a NIP-17 gift-wrapped text DM using the full pipeline. Retries a
898    /// transient publish miss (headless preset, 3 attempts) so an SDK/CLI bot rides
899    /// out a relay blip instead of silently dropping the message on the first miss;
900    /// `self_send: false` keeps it a plain send (no inbox self-copy).
901    pub async fn send_dm(&self, to_npub: &str, content: &str) -> Result<sending::SendResult> {
902        let config = SendConfig { self_send: false, ..SendConfig::headless() };
903        sending::send_dm(to_npub, content, None, &config, Arc::new(NoOpSendCallback)).await
904            .map_err(VectorError::Other)
905    }
906
907    /// Send a DM as a threaded reply to `replied_to` (an existing message's event id).
908    pub async fn send_dm_reply(&self, to_npub: &str, replied_to: &str, content: &str) -> Result<sending::SendResult> {
909        let config = SendConfig { self_send: false, ..SendConfig::headless() };
910        sending::send_dm(to_npub, content, Some(replied_to), &config, Arc::new(NoOpSendCallback)).await
911            .map_err(VectorError::Other)
912    }
913
914    /// Download a received attachment and decrypt it to plaintext bytes. Fetches the encrypted blob
915    /// from its Blossom URL (SSRF/Tor-aware client, size-capped) and AES-decrypts with the
916    /// attachment's embedded key + nonce. Walks the primary URL then any BUD-04 `fallback`
917    /// mirrors (same ciphertext on other hosts) until one serves. Prefer
918    /// [`download_attachment_from`](Self::download_attachment_from) when the message author is
919    /// known — it adds the BUD-03 hash-swap over the author's advertised servers.
920    pub async fn download_attachment(&self, attachment: &Attachment) -> Result<Vec<u8>> {
921        self.download_attachment_from(attachment, None).await
922    }
923
924    /// [`download_attachment`](Self::download_attachment) with the full source walk: primary URL →
925    /// embedded `fallback` mirrors → BUD-03 hash-swap (the same content-address on each of the
926    /// author's kind-10063 servers). `author_npub` is the message author (your own npub for your
927    /// own messages); `None` skips the hash-swap stage.
928    pub async fn download_attachment_from(
929        &self,
930        attachment: &Attachment,
931        author_npub: Option<&str>,
932    ) -> Result<Vec<u8>> {
933        self.download_attachment_within(attachment, author_npub, 256 * 1024 * 1024)
934            .await
935            .map_err(|e| VectorError::Other(e.to_string()))
936    }
937
938    /// [`download_attachment_from`](Self::download_attachment_from), refusing more
939    /// than `max_bytes` of ciphertext: the size an attachment declares is the
940    /// sender's word, so the cap holds on the bytes actually received.
941    pub async fn download_attachment_within(
942        &self,
943        attachment: &Attachment,
944        author_npub: Option<&str>,
945        max_bytes: usize,
946    ) -> std::result::Result<Vec<u8>, DownloadError> {
947        self.download_attachment_reporting(attachment, author_npub, max_bytes, |_| true).await
948    }
949
950    /// [`download_attachment_within`](Self::download_attachment_within), telling `step` what the
951    /// walk is doing as it happens. `step` returning false stops it with
952    /// [`DownloadError::Cancelled`] at the next chunk.
953    pub async fn download_attachment_reporting<F: FnMut(DownloadStep) -> bool>(
954        &self,
955        attachment: &Attachment,
956        author_npub: Option<&str>,
957        max_bytes: usize,
958        mut step: F,
959    ) -> std::result::Result<Vec<u8>, DownloadError> {
960        use futures_util::StreamExt;
961        let max_download = max_bytes;
962        if attachment.url.is_empty() {
963            return Err(DownloadError::Unusable("attachment has no URL".into()));
964        }
965        // Bounded by progress, not by a deadline: any rate finishes, a stall fails over.
966        let client = crate::net::build_http_client_with_options(
967            None,
968            Some(crate::net::transfer_stall()),
969            true,
970        )
971        .map_err(DownloadError::Unreachable)?;
972        let mut last_err = String::from("download failed");
973        // Waits for the network to come back after a switch; bounded so a flapping network can't
974        // hold the download forever.
975        let mut network_waits = 0u8;
976        // Whether every source answered: only then is a failure the message's own.
977        let mut all_answered = true;
978        let mut candidates: Vec<String> = vec![attachment.url.clone()];
979        candidates.extend(attachment.fallback_urls.iter().cloned());
980        let mut hash_swap_tried = false;
981        let mut i = 0;
982        'sources: while i < candidates.len() {
983            let url = candidates[i].clone();
984            i += 1;
985            // One-time last resort once every embedded source has failed: the author's advertised
986            // servers may hold the blob under the same content-address.
987            let extend_with_swap = |candidates: &mut Vec<String>, servers: &[String]| {
988                let extra = crate::blossom::hash_swap_candidates(&attachment.url, servers);
989                for c in extra {
990                    if !candidates.contains(&c) {
991                        candidates.push(c);
992                    }
993                }
994            };
995            macro_rules! next_source {
996                () => {{
997                    log_net_fail!("[Download] source failed ({}): {}", url, last_err);
998                    if i == candidates.len() && !hash_swap_tried {
999                        hash_swap_tried = true;
1000                        let servers = crate::blossom_servers::author_swap_servers(author_npub, false).await;
1001                        extend_with_swap(&mut candidates, &servers);
1002                    }
1003                    continue 'sources;
1004                }};
1005            }
1006            // SSRF guard: URLs are attacker-controlled (off an inbound message). build_http_client
1007            // only validates redirect HOPS, not the initial request — so validate each source here
1008            // (matches the native download path). With Tor off this is the only egress guard.
1009            if let Err(e) = crate::net::validate_url_not_private(&url) {
1010                last_err = e.to_string();
1011                next_source!();
1012            }
1013            macro_rules! network_changed {
1014                ($e:expr) => {{
1015                    if $e.is_transient() && network_waits < 8 {
1016                        network_waits += 1;
1017                        match crate::net::wait_after(&$e).await {
1018                            Ok(()) => {
1019                                i -= 1;
1020                                continue 'sources;
1021                            }
1022                            // Every other source sits behind the same network: none would fare better.
1023                            Err(text) => return Err(DownloadError::Unreachable(text)),
1024                        }
1025                    }
1026                }};
1027            }
1028            let resp = match crate::net::proxied_request(&client, reqwest::Method::GET, &url).await.send().await {
1029                Ok(r) => r,
1030                Err(e) => {
1031                    network_changed!(e);
1032                    last_err = format!("download: {e}");
1033                    all_answered = false;
1034                    next_source!();
1035                }
1036            };
1037            if !resp.status().is_success() {
1038                last_err = format!("download failed: HTTP {}", resp.status());
1039                all_answered = false;
1040                next_source!();
1041            }
1042            // Stream with a cap so a hostile/oversized blob can't OOM the process. The cap is
1043            // permanent — every mirror serves the same blob, so don't bother trying the next.
1044            let mut encrypted: Vec<u8> = Vec::with_capacity(
1045                // The declared length is the server's word: reserve no more than a few MiB on it.
1046                resp.content_length().map(|l| usize::try_from(l).unwrap_or(usize::MAX).min(max_download).min(4 * 1024 * 1024)).unwrap_or(64 * 1024),
1047            );
1048            let total = resp.content_length();
1049            if !step(DownloadStep::Received { bytes: 0, total }) {
1050                return Err(DownloadError::Cancelled);
1051            }
1052            let mut stream = resp.bytes_stream();
1053            loop {
1054                // Every declared byte is here: done, without waiting on an end of body WebKit can hold back.
1055                if total.is_some_and(|t| encrypted.len() as u64 >= t) {
1056                    break;
1057                }
1058                // A browser's fetch has no read timeout: a body that goes silent fails over here instead.
1059                #[cfg(target_arch = "wasm32")]
1060                let next = match crate::rt::time::timeout(crate::transport::budget(crate::transport::Op::HttpRead, crate::net::transfer_stall()), stream.next()).await {
1061                    Ok(next) => next,
1062                    Err(_) => {
1063                        last_err = "read body: stalled".to_string();
1064                        all_answered = false;
1065                        next_source!();
1066                    }
1067                };
1068                #[cfg(not(target_arch = "wasm32"))]
1069                let next = stream.next().await;
1070                let Some(chunk) = next else { break };
1071                let chunk = match chunk {
1072                    Ok(c) => c,
1073                    Err(e) => {
1074                        network_changed!(e);
1075                        last_err = format!("read body: {e}");
1076                        all_answered = false;
1077                        next_source!();
1078                    }
1079                };
1080                if encrypted.len() + chunk.len() > max_download {
1081                    return Err(DownloadError::TooLarge(max_download));
1082                }
1083                encrypted.extend_from_slice(&chunk);
1084                if !step(DownloadStep::Received { bytes: encrypted.len() as u64, total }) {
1085                    return Err(DownloadError::Cancelled);
1086                }
1087            }
1088            if !step(DownloadStep::Opening) {
1089                return Err(DownloadError::Cancelled);
1090            }
1091            // Plaintext public blob (no decryption tags): its content address and the sender's
1092            // claim are the only integrity checks there are.
1093            if attachment.key.is_empty() || attachment.nonce.is_empty() {
1094                let hash = crate::crypto::sha256_hex(&encrypted);
1095                if crate::blossom::plaintext_matches(&url, attachment.original_hash.as_deref(), &hash) {
1096                    return Ok(encrypted);
1097                }
1098                last_err = "plaintext blob fails its hash claim".to_string();
1099                next_source!();
1100            }
1101            match crate::crypto::decrypt_data_owned(encrypted, &attachment.key, &attachment.nonce) {
1102                Ok(plain) => {
1103                    if i > 1 {
1104                        log_net_info!("[Download] fallback source {}/{} served {}", i, candidates.len(), url);
1105                    }
1106                    return Ok(plain);
1107                }
1108                Err(e) => {
1109                    // A host serving wrong bytes under the right URL must not
1110                    // veto sources still holding the real ciphertext.
1111                    last_err = format!("decrypt: {e}");
1112                    next_source!();
1113                }
1114            }
1115        }
1116        log_net_fail!("[Download] all {} source(s) failed for {}: {}", candidates.len(), attachment.url, last_err);
1117        Err(if all_answered { DownloadError::Unusable(last_err) } else { DownloadError::Unreachable(last_err) })
1118    }
1119
1120    /// The size of an attachment that arrived without one, asked of its server as a download
1121    /// would ask it, and recorded on the message so auto-download can weigh it. `None` when the
1122    /// server won't say, or the message is a request not yet answered.
1123    pub async fn probe_attachment_size(&self, message_id: &str, attachment_id: &str) -> Option<u64> {
1124        crate::db::scoped(async move {
1125            let (chat_id, message) = self.get_message(message_id).await?;
1126            let att = message.attachments.iter().find(|a| a.id == attachment_id)?;
1127            if att.size > 0 {
1128                return Some(att.size);
1129            }
1130            if !(att.url.starts_with("https://") || att.url.starts_with("http://")) {
1131                return None;
1132            }
1133            if !message.mine && crate::requests::shielded() && state::STATE.lock().await.dm_unanswered(&chat_id) {
1134                return None;
1135            }
1136            let probe = crate::net::get_remote_file_size(&att.url);
1137            let size = crate::rt::time::timeout(crate::net::tor_http_timeout(std::time::Duration::from_secs(5)), probe).await.ok().flatten()?;
1138            if let Err(e) = db::attachments::set_attachment_size(message_id, attachment_id, size) {
1139                crate::log_warn!("[Attachments] could not record a probed size: {e}");
1140            }
1141            state::STATE.lock().await.update_attachment(&chat_id, message_id, attachment_id, |a| a.size = size);
1142            Some(size)
1143        })
1144        .await
1145    }
1146
1147    /// Send a NIP-17 gift-wrapped file attachment DM.
1148    pub async fn send_file(&self, to_npub: &str, file_path: &str) -> Result<sending::SendResult> {
1149        let path = std::path::Path::new(file_path);
1150        let bytes = std::fs::read(path)
1151            .map_err(VectorError::Io)?;
1152        let filename = path.file_name()
1153            .and_then(|n| n.to_str())
1154            .unwrap_or("file");
1155        let extension = path.extension()
1156            .and_then(|e| e.to_str())
1157            .unwrap_or("bin");
1158
1159        sending::send_file_dm(
1160            to_npub,
1161            std::sync::Arc::new(bytes),
1162            filename,
1163            extension,
1164            None,
1165            None,
1166            &SendConfig::default(),
1167            Arc::new(NoOpSendCallback),
1168        ).await.map_err(VectorError::Other)
1169    }
1170
1171    /// Send bytes held in memory as a DM file named `filename`, whose extension sets its type.
1172    /// `opts` carries the caption, the reply, and whether a picture is compressed; a DM has no
1173    /// per-message expiry, so one set there is refused.
1174    pub async fn send_file_bytes(&self, to_npub: &str, bytes: Vec<u8>, filename: &str, opts: &PostOptions) -> Result<sending::SendResult> {
1175        if opts.expires_in_secs.is_some() {
1176            return Err(VectorError::Other("DMs have no per-message expiry".into()));
1177        }
1178        let (bytes, filename) = ready_to_send(bytes, filename, opts.compress).await?;
1179        let extension = std::path::Path::new(&filename).extension().and_then(|e| e.to_str()).unwrap_or("bin").to_lowercase();
1180        let config = SendConfig { self_send: false, ..SendConfig::headless() };
1181        let sent = sending::send_file_dm(to_npub, std::sync::Arc::new(bytes), &filename, &extension, None, opts.reply_to.as_deref(), &config, Arc::new(NoOpSendCallback))
1182            .await
1183            .map_err(VectorError::Other)?;
1184        // A DM file carries no text: the caption follows as a reply to it.
1185        if let Some(caption) = opts.caption.as_deref().filter(|c| !c.trim().is_empty()) {
1186            let file_id = sent.event_id.clone().unwrap_or_else(|| sent.pending_id.clone());
1187            self.send_dm_reply(to_npub, &file_id, caption).await?;
1188        }
1189        Ok(sent)
1190    }
1191
1192    /// Withdraw one of our own reactions, in a DM or a Community, by the reaction's id.
1193    pub async fn remove_reaction(&self, reaction_id: &str) -> Result<()> {
1194        crate::db::scoped(async move {
1195            use nostr_sdk::prelude::{EventId, PublicKey, ToBech32};
1196            let session = crate::db::current_session();
1197            let (chat_id, message_id, author_npub, is_community) =
1198                Self::locate_reaction(reaction_id).await.ok_or_else(|| VectorError::NotFound(format!("reaction {reaction_id}")))?;
1199            let me = state::my_public_key().ok_or_else(|| VectorError::NotInitialized("not logged in".into()))?;
1200            if me.to_bech32().ok().as_deref() != Some(author_npub.as_str()) {
1201                return Err(VectorError::Other("only its own author can withdraw a reaction".into()));
1202            }
1203            // Off this device first, as the app does, so the relay's echo of the delete changes nothing.
1204            // The kind-7 row goes explicitly: a message save adds reactions, never drops them.
1205            let updated = state::STATE.lock().await.remove_reaction_from_message(&message_id, reaction_id);
1206            let _ = crate::db::events::delete_event(reaction_id).await;
1207            if let Some((_, mut message)) = updated {
1208                traits::emit_message_update(&chat_id, &message_id, &mut message).await;
1209            }
1210            // The delete signs as whoever is live: never as the account that took over.
1211            if !session.is_live() {
1212                return Err(VectorError::Other("account changed while withdrawing the reaction".into()));
1213            }
1214            if is_community {
1215                use crate::community::transport::LiveTransport;
1216                let id = self.v2_community_for_channel(&chat_id)?.ok_or_else(|| VectorError::NotFound("community channel".into()))?;
1217                let community = crate::db::community::load_community_v2(&id)
1218                    .map_err(VectorError::Db)?
1219                    .ok_or_else(|| VectorError::NotFound("community".into()))?;
1220                let ch = crate::community::ChannelId(Self::id32(&chat_id, "channel_id")?);
1221                let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
1222                crate::community::v2::service::delete_own(&transport, &community, &ch, reaction_id, crate::community::v2::kind::REACTION)
1223                    .await
1224                    .map_err(VectorError::Other)?;
1225            } else {
1226                let rid = EventId::from_hex(reaction_id).map_err(|e| VectorError::Nostr(e.to_string()))?;
1227                let recipient = PublicKey::parse(&chat_id).map_err(|e| VectorError::Nostr(e.to_string()))?;
1228                crate::deletion::delete_own_reaction(&rid, recipient).await.map_err(VectorError::Other)?;
1229            }
1230            Ok(())
1231        })
1232        .await
1233    }
1234
1235    /// Where a reaction sits: `(chat id, message id, reactor npub, in a Community)`. Memory first,
1236    /// then the database, since memory holds only a window of each chat.
1237    async fn locate_reaction(reaction_id: &str) -> Option<(String, String, String, bool)> {
1238        if let Some(found) = state::STATE.lock().await.find_reaction(reaction_id) {
1239            return Some(found);
1240        }
1241        let parent = crate::db::events::reaction_target(reaction_id).ok().flatten()?;
1242        let (chat_id, message) = crate::db::events::get_message_by_id(&parent).await.ok().flatten()?;
1243        let author = message.reactions.iter().find(|r| r.id == reaction_id)?.author_id.clone();
1244        let community = crate::db::community::community_id_for_channel(&chat_id).ok().flatten().is_some();
1245        Some((chat_id, parent, author, community))
1246    }
1247
1248    /// Withdraw our own `emoji` reaction to `message_id`, if we hold one. `Ok(false)` when there is none.
1249    pub async fn remove_my_reaction(&self, message_id: &str, emoji: &str) -> Result<bool> {
1250        match Self::own_reaction_id(message_id, emoji).await {
1251            Some(id) => self.remove_reaction(&id).await.map(|_| true),
1252            None => Ok(false),
1253        }
1254    }
1255
1256    /// The id of our own reaction to `message_id` with `emoji`, if we already have
1257    /// one. A reaction set is keyed by (author, emoji), so a repeat is something
1258    /// every receiver collapses anyway: refusing it here spends no publish, no
1259    /// gift-wrap and no relay round-trip on an event that changes nothing.
1260    async fn own_reaction_id(message_id: &str, emoji: &str) -> Option<String> {
1261        use nostr_sdk::prelude::ToBech32;
1262        let me = state::my_public_key()?.to_bech32().ok()?;
1263        let resident = state::STATE.lock().await.find_message(message_id).map(|(_, m)| m);
1264        let message = match resident {
1265            Some(m) => m,
1266            None => crate::db::events::get_message_by_id(message_id).await.ok().flatten()?.1,
1267        };
1268        message.reactions.iter().find(|r| r.author_id == me && r.emoji == emoji).map(|r| r.id.clone())
1269    }
1270
1271    /// Send a NIP-25 reaction to a DM message. `emoji_url` carries the NIP-30
1272    /// image URL when reacting with a custom-pack emoji (content stays
1273    /// `:shortcode:`). Returns the reaction's rumor id. Local echo + persistence
1274    /// are best-effort — the gift-wrap send is the source of truth.
1275    pub async fn send_reaction(
1276        &self,
1277        to_npub: &str,
1278        reference_id: &str,
1279        emoji: &str,
1280        emoji_url: Option<&str>,
1281    ) -> Result<String> {
1282        use nostr_sdk::prelude::*;
1283
1284        let client = state::nostr_client().ok_or(VectorError::Other("Not connected".into()))?;
1285        let my_public_key = state::my_public_key().ok_or(VectorError::Other("Not logged in".into()))?;
1286
1287        // Already ours: hand back the reaction we hold rather than minting a second.
1288        if let Some(existing) = Self::own_reaction_id(reference_id, emoji).await {
1289            return Ok(existing);
1290        }
1291
1292        // Group ceiling + per-tier fresh-reaction allowance (joins always pass)
1293        badges::check_new_reaction_allowance(reference_id, emoji)
1294            .await
1295            .map_err(VectorError::Other)?;
1296
1297        let reference_event = EventId::from_hex(reference_id)
1298            .map_err(|e| VectorError::Nostr(e.to_string()))?;
1299        let receiver_pubkey = PublicKey::from_bech32(to_npub)
1300            .map_err(|e| VectorError::Nostr(e.to_string()))?;
1301
1302        // NIP-30 custom-emoji tag — only when content is `:shortcode:` and a URL is present.
1303        let custom_emoji_tag = emoji_url.and_then(|url| {
1304            if !emoji.starts_with(':') || !emoji.ends_with(':') || emoji.len() < 3 || url.is_empty() {
1305                return None;
1306            }
1307            let shortcode = &emoji[1..emoji.len() - 1];
1308            if shortcode.is_empty() { return None; }
1309            Some(Tag::custom("emoji", [shortcode.to_string(), url.to_string()]))
1310        });
1311
1312        let reaction_target = nostr_sdk::prelude::nip25::ReactionTarget {
1313            event_id: reference_event,
1314            public_key: receiver_pubkey,
1315            coordinate: None,
1316            kind: Some(Kind::PrivateDirectMessage),
1317            relay_hint: None,
1318        };
1319        let mut builder =
1320            nostr_sdk::prelude::nip25::ReactionBuilder::new(reaction_target, emoji)
1321                .into_event_builder();
1322        if let Some(tag) = custom_emoji_tag {
1323            builder = builder.tag(tag);
1324        }
1325        let rumor = builder.finalize_unsigned_with_id(my_public_key);
1326        let inner_rumor_id = rumor.id;
1327        let rumor_id = inner_rumor_id.ok_or(VectorError::Other("Failed to get rumor ID".into()))?.to_hex();
1328
1329        // Retain the recipient wrap's ephemeral key + targeted relays so the
1330        // reaction can later be revoked with a NIP-09 relay nuke (mirrors the
1331        // DM message send path). Without retention the reaction is undeletable.
1332        let outcome = inbox_relays::send_gift_wrap_retained(&client, &receiver_pubkey, rumor.clone(), [])
1333            .await.map_err(VectorError::Other)?;
1334        if !outcome.output.success.is_empty() {
1335            if let Some(rid) = inner_rumor_id {
1336                if let Err(e) = db::nip17_keys::store_wrap_key(
1337                    &outcome.wrap_event_id, &rid, &receiver_pubkey,
1338                    db::nip17_keys::WrapRole::Recipient,
1339                    &outcome.wrap_secret, &outcome.targeted_relays,
1340                ) {
1341                    crate::log_warn!("[Reaction] failed to persist wrap key: {}", e);
1342                }
1343            }
1344        }
1345
1346        // Self-wrap for multi-device recovery + retain its key too, so another
1347        // device (or this one) can later revoke. Bail on account swap.
1348        let self_wrap_client = client.clone();
1349        db::spawn_bound(async move {
1350            if let Ok(self_outcome) = inbox_relays::send_gift_wrap_retained(
1351                &self_wrap_client, &my_public_key, rumor, [],
1352            ).await {
1353                if !self_outcome.output.success.is_empty() {
1354                    if let Some(rid) = inner_rumor_id {
1355                        let _ = db::nip17_keys::store_wrap_key(
1356                            &self_outcome.wrap_event_id, &rid, &my_public_key,
1357                            db::nip17_keys::WrapRole::SelfSend,
1358                            &self_outcome.wrap_secret, &self_outcome.targeted_relays,
1359                        );
1360                    }
1361                }
1362            }
1363        });
1364
1365        // Best-effort optimistic local echo + persistence.
1366        let reaction = Reaction {
1367            id: rumor_id.clone(),
1368            reference_id: reference_id.to_string(),
1369            author_id: my_public_key.to_bech32().unwrap_or_else(|_| my_public_key.to_hex()),
1370            emoji: emoji.to_string(),
1371            emoji_url: emoji_url.map(|s| s.to_string()),
1372        };
1373        let msg_for_save = {
1374            let mut st = state::STATE.lock().await;
1375            match st.add_reaction_to_message(reference_id, reaction) {
1376                Some((cid, true)) => st.find_message(reference_id).map(|(_, m)| (cid, m)),
1377                _ => None,
1378            }
1379        };
1380        if let Some((cid, mut msg)) = msg_for_save {
1381            let _ = db::events::save_message(&cid, &msg).await;
1382            traits::emit_message_update(&cid, reference_id, &mut msg).await;
1383        }
1384
1385        Ok(rumor_id)
1386    }
1387
1388    /// Send an ephemeral typing indicator to a DM recipient. Fire-and-forget
1389    /// with a 30-second NIP-40 expiry so relays purge it quickly.
1390    pub async fn send_typing(&self, to_npub: &str) -> Result<()> {
1391        use nostr_sdk::prelude::*;
1392
1393        let client = state::nostr_client().ok_or(VectorError::Other("Not connected".into()))?;
1394        let my_public_key = state::my_public_key().ok_or(VectorError::Other("Not logged in".into()))?;
1395        let pubkey = PublicKey::from_bech32(to_npub).map_err(|e| VectorError::Nostr(e.to_string()))?;
1396        // Notes: nobody to tell.
1397        if pubkey == my_public_key {
1398            return Ok(());
1399        }
1400
1401        let expiry = Timestamp::from_secs(crate::clock::timestamp().as_secs() + 30);
1402        let rumor = EventBuilder::new(Kind::ApplicationSpecificData, "typing")
1403            .tag(Tag::public_key(pubkey))
1404            .tag(Tag::custom("d", vec!["vector"]))
1405            .tag(Tag::expiration(expiry))
1406            .finalize_unsigned_with_id(my_public_key);
1407
1408        // No usable signer stays VectorError::Other, as SDK callers match it; resolving a local
1409        // key reads a cached owner, not the vault.
1410        signer::active_signer().map_err(VectorError::Other)?;
1411        // Client no longer wraps: build the wrap, then publish it to the target relays.
1412        let wrap = signer::gift_wrap(&pubkey, rumor, [Tag::expiration(expiry)])
1413            .await
1414            .map_err(VectorError::Nostr)?;
1415        transport_aware(client.send_event(&wrap))
1416            .to(state::active_trusted_relays().await)
1417            .await
1418            .map_err(|e| VectorError::Nostr(e.to_string()))?;
1419        Ok(())
1420    }
1421
1422    /// Edit a DM you previously sent (kind-16 edit) with an optimistic local
1423    /// echo. Returns the edit event id. Persistence is best-effort and only
1424    /// happens when the chat already exists locally.
1425    pub async fn edit_dm(&self, to_npub: &str, message_id: &str, new_content: &str) -> Result<String> {
1426        crate::db::scoped(async move {
1427            use nostr_sdk::prelude::*;
1428
1429            let client = state::nostr_client().ok_or(VectorError::Other("Not connected".into()))?;
1430            let my_public_key = state::my_public_key().ok_or(VectorError::Other("Not logged in".into()))?;
1431            let my_npub = my_public_key.to_bech32().map_err(|e| VectorError::Nostr(e.to_string()))?;
1432            let receiver_pubkey = PublicKey::from_bech32(to_npub).map_err(|e| VectorError::Nostr(e.to_string()))?;
1433            let reference_event = EventId::from_hex(message_id).map_err(|e| VectorError::Nostr(e.to_string()))?;
1434
1435            let (plain, text_spans) = crate::text_spans::extract_own(new_content);
1436            let new_content = plain.as_str();
1437            // NIP-30: resolve `:shortcode:` so the edit carries emoji image tags.
1438            let emoji_tags = emoji_packs::resolve_outbound_emoji_tags(new_content);
1439            // On the rumor and the wrap alike, so relays drop the edit with its message.
1440            let expiry_tags: Vec<Tag> = crate::self_destruct::edit_expiry(message_id)
1441                .await
1442                .map_err(VectorError::Other)?
1443                .map(|exp| Tag::expiration(Timestamp::from_secs(exp)))
1444                .into_iter()
1445                .collect();
1446
1447            let mut builder = EventBuilder::new(
1448                Kind::from_u16(stored_event::event_kind::MESSAGE_EDIT),
1449                new_content,
1450            ).tag(Tag::event(reference_event));
1451            for et in &emoji_tags {
1452                builder = builder.tag(Tag::custom(
1453                    "emoji",
1454                    [et.shortcode.clone(), et.url.clone()],
1455                ));
1456            }
1457            builder = builder.tags(crate::text_spans::to_nostr_tags(&text_spans));
1458            let rumor = builder.tags(expiry_tags.clone()).finalize_unsigned_with_id(my_public_key);
1459            let edit_id = rumor.id.ok_or(VectorError::Other("Failed to get edit rumor ID".into()))?.to_hex();
1460            let edit_ts_ms = rumor.created_at.as_secs() * 1000;
1461
1462            // Optimistic local echo + best-effort persistence.
1463            let msg_for_emit = {
1464                let mut st = state::STATE.lock().await;
1465                st.update_message_in_chat_with(to_npub, message_id, |msg, i| {
1466                    msg.apply_edit(new_content.to_string(), edit_ts_ms, emoji_tags.clone(), text_spans.clone(), i);
1467                    msg.set_preview_metadata(None);
1468                })
1469            };
1470            if let Some(mut msg) = msg_for_emit {
1471                traits::emit_message_update(to_npub, message_id, &mut msg).await;
1472                if let Ok(db_chat_id) = db::id_cache::get_chat_id_by_identifier(to_npub) {
1473                    let _ = db::events::save_edit_event(
1474                        &edit_id, message_id, new_content, &emoji_tags, &text_spans, db_chat_id, None, &my_npub,
1475                    ).await;
1476                }
1477            }
1478
1479            inbox_relays::send_gift_wrap(&client, &receiver_pubkey, rumor.clone(), expiry_tags.clone())
1480                .await.map_err(VectorError::Other)?;
1481
1482            let self_wrap_client = client.clone();
1483            let self_wrap_session = crate::db::current_session();
1484            db::spawn_bound(async move {
1485                if !self_wrap_session.is_live() { return; }
1486                if let Ok(wrap) = signer::gift_wrap(&my_public_key, rumor, expiry_tags).await {
1487                    let _ = crate::transport_aware(self_wrap_client.send_event(&wrap)).await;
1488                }
1489            });
1490
1491            Ok(edit_id)
1492        })
1493        .await
1494    }
1495
1496    /// Delete a DM from the network: one you sent ([`deletion::delete_own_dm`]), or your copy of
1497    /// one you received ([`deletion::delete_received_dm`]). Drops it here too.
1498    pub async fn delete_dm(&self, message_id: &str) -> Result<deletion::DeleteOutcome> {
1499        use nostr_sdk::prelude::*;
1500        let rumor_id = EventId::from_hex(message_id).map_err(|e| VectorError::Nostr(e.to_string()))?;
1501        let (chat_id, msg) = self.get_message(message_id).await.ok_or_else(|| VectorError::Other("message not found".into()))?;
1502        if !chat_id.starts_with("npub1") {
1503            return Err(VectorError::Other("not a DM".into()));
1504        }
1505        let outcome = if msg.mine { deletion::delete_own_dm(&rumor_id).await } else { deletion::delete_received_dm(&rumor_id).await }
1506            .map_err(VectorError::Other)?;
1507        state::STATE.lock().await.remove_message(message_id);
1508        let _ = crate::db::events::delete_event(message_id).await;
1509        traits::emit_event_json("message_removed", serde_json::json!({ "id": message_id, "chat_id": chat_id, "reason": "deleted" }));
1510        Ok(outcome)
1511    }
1512
1513    /// Get chats from the in-memory state.
1514    pub async fn get_chats(&self) -> Vec<SerializableChat> {
1515        let state = state::STATE.lock().await;
1516        state.chats.iter()
1517            .map(|c| c.to_serializable_with_last_n(1, &state.interner))
1518            .collect()
1519    }
1520
1521    /// Get messages for a chat (paginated).
1522    pub async fn get_messages(&self, chat_id: &str, limit: usize, offset: usize) -> Vec<Message> {
1523        let state = state::STATE.lock().await;
1524        let Some(chat) = state.get_chat(chat_id) else { return Vec::new() };
1525        let msgs = chat.messages.messages();
1526        let start = offset.min(msgs.len());
1527        let end = offset.saturating_add(limit).min(msgs.len());
1528        msgs[start..end].iter().map(|m| m.to_message(&state.interner)).collect()
1529    }
1530
1531    /// One message by id, with the chat it was said in. Reads STATE first, then
1532    /// the store for a row that has paged out of the loaded window.
1533    ///
1534    /// This is what a moderation citation needs: it names a message id and
1535    /// nothing else, so the room has to come back with it. `None` is an
1536    /// ordinary answer — a citation outlives its message (a delete, a hide, an
1537    /// expiry, history never synced), and callers must read absence as absence
1538    /// rather than as a fault.
1539    pub async fn get_message(&self, message_id: &str) -> Option<(String, Message)> {
1540        {
1541            let state = state::STATE.lock().await;
1542            if let Some((chat, msg)) = state.find_message(message_id) {
1543                return Some((chat.id.clone(), msg));
1544            }
1545        }
1546        db::events::get_message_by_id(message_id).await.ok().flatten()
1547    }
1548
1549    /// Every message carrying an attachment with this content hash, newest
1550    /// first. `Attachment.id` IS that hash, and so is a citation's
1551    /// `content_hash`, so a classifier verdict about a blob resolves straight
1552    /// back to what carried it.
1553    ///
1554    /// A list, not one answer: one blob rides many messages — a forward, a
1555    /// re-post, or forty accounts posting the same image, which is exactly the
1556    /// case worth being able to see whole.
1557    pub async fn get_messages_with_attachment(&self, content_hash: &str) -> Vec<(String, Message)> {
1558        let Ok(ids) = db::attachments::events_with_attachment_hash(content_hash) else { return Vec::new() };
1559        let mut out = Vec::with_capacity(ids.len());
1560        for id in ids {
1561            if let Some(found) = self.get_message(&id).await {
1562                out.push(found);
1563            }
1564        }
1565        out
1566    }
1567
1568    /// Cursor-paged local read: up to `limit` messages strictly before the
1569    /// `(at_ms, id)` cursor, chronological. `None` returns the newest `limit`.
1570    ///
1571    /// The cursor is compared BY VALUE, never resolved to a stored row, so it
1572    /// keeps working after its message is gone (NIP-09 delete, moderation hide,
1573    /// a self-destruct timer) — a persisted cursor must not wedge the walk. The
1574    /// id tiebreaks inside a same-millisecond burst, giving a total order that
1575    /// can't skip or re-serve across pages. Local only: sync older history in
1576    /// from relays first.
1577    pub async fn get_messages_before(
1578        &self,
1579        chat_id: &str,
1580        before: Option<(u64, &str)>,
1581        limit: usize,
1582    ) -> Vec<Message> {
1583        let state = state::STATE.lock().await;
1584        let Some(chat) = state.get_chat(chat_id) else {
1585            return Vec::new();
1586        };
1587        page_before(chat.messages.messages(), &state.interner, before, limit)
1588    }
1589
1590    /// Get a profile by npub.
1591    pub async fn get_profile(&self, npub: &str) -> Option<SlimProfile> {
1592        let state = state::STATE.lock().await;
1593        state.get_profile(npub)
1594            .map(|p| SlimProfile::from_profile(p, &state.interner))
1595    }
1596
1597    /// Fetch a profile's metadata and status from relays.
1598    pub async fn load_profile(&self, npub: &str) -> bool {
1599        profile::sync::load_profile(npub.to_string(), &NoOpProfileSyncHandler).await
1600    }
1601
1602    /// Update the current user's profile metadata and broadcast to relays.
1603    pub async fn update_profile(&self, name: &str, avatar: &str, banner: &str, about: &str) -> bool {
1604        profile::sync::update_profile(
1605            name.to_string(), avatar.to_string(), banner.to_string(), about.to_string(),
1606            &NoOpProfileSyncHandler,
1607        ).await
1608    }
1609
1610    /// Like [`update_profile`](Self::update_profile) but marks the profile as a bot (`bot: true` in
1611    /// the metadata). The SDK uses this for every bot; build human clients on `update_profile`.
1612    pub async fn update_bot_profile(&self, name: &str, avatar: &str, banner: &str, about: &str) -> bool {
1613        profile::sync::update_bot_profile(
1614            name.to_string(), avatar.to_string(), banner.to_string(), about.to_string(),
1615            &NoOpProfileSyncHandler,
1616        ).await
1617    }
1618
1619    /// Publish whether the current user consents to being shown on other people's streams.
1620    /// Returns the value now in effect.
1621    pub async fn set_stream_consent(&self, on: bool) -> Result<bool> {
1622        db::scoped_result(profile::sync::set_stream_consent(on, &NoOpProfileSyncHandler))
1623            .await
1624            .map_err(VectorError::Other)
1625    }
1626
1627    /// Update the current user's status and broadcast to relays.
1628    pub async fn update_status(&self, status: &str) -> bool {
1629        profile::sync::update_status(status.to_string()).await
1630    }
1631
1632    /// Upload an image file to Blossom **unencrypted** and return its public URL — for avatars,
1633    /// banners, and other images other clients must fetch directly. (The opposite of
1634    /// [`send_file`](Self::send_file)'s encrypted attachments.) Pass the URL to [`update_profile`].
1635    ///
1636    /// [`update_profile`]: Self::update_profile
1637    pub async fn upload_public_image(&self, file_path: &str) -> Result<String> {
1638        let path = std::path::Path::new(file_path);
1639        let bytes = std::fs::read(path).map_err(VectorError::Io)?;
1640        if bytes.is_empty() {
1641            return Err(VectorError::Other("Empty image file".into()));
1642        }
1643        let extension = path.extension().and_then(|e| e.to_str()).unwrap_or("bin").to_lowercase();
1644        let mime = crate::crypto::mime_from_extension(&extension);
1645        let _client = state::nostr_client().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
1646        let signer = crate::signer::active_signer()
1647            .map_err(|e| VectorError::Other(format!("Signer unavailable: {e}")))?;
1648        let servers = crate::blossom_servers::compute_enabled_servers();
1649        if servers.is_empty() {
1650            return Err(VectorError::Other("No Blossom servers configured".into()));
1651        }
1652        // Avatars/banners run larger than emojis (up to ~1MB): a server may accept
1653        // nothing for 20s before it is treated as dead and failover moves on.
1654        crate::blossom::upload_blob_with_failover(
1655            signer,
1656            servers,
1657            std::sync::Arc::new(bytes),
1658            Some(mime),
1659            Some(crate::net::tor_http_timeout(std::time::Duration::from_secs(20))),
1660        )
1661        .await
1662        .map_err(VectorError::Other)
1663    }
1664
1665    /// Block a user by npub.
1666    pub async fn block_user(&self, npub: &str) -> bool {
1667        profile::sync::block_user(npub.to_string(), &NoOpProfileSyncHandler).await
1668    }
1669
1670    /// Unblock a user by npub.
1671    pub async fn unblock_user(&self, npub: &str) -> bool {
1672        profile::sync::unblock_user(npub.to_string(), &NoOpProfileSyncHandler).await
1673    }
1674
1675    /// Set a nickname for a profile.
1676    pub async fn set_nickname(&self, npub: &str, nickname: &str) -> bool {
1677        profile::sync::set_nickname(npub.to_string(), nickname.to_string(), &NoOpProfileSyncHandler).await
1678    }
1679
1680    /// Get all blocked profiles.
1681    pub async fn get_blocked_users(&self) -> Vec<SlimProfile> {
1682        profile::sync::get_blocked_users().await
1683    }
1684
1685    /// Queue a profile for background sync.
1686    pub fn queue_profile_sync(&self, npub: &str, priority: SyncPriority) {
1687        profile::sync::queue_profile_sync(npub.to_string(), priority, false);
1688    }
1689
1690    /// Get the current user's npub.
1691    pub fn my_npub(&self) -> Option<String> {
1692        state::my_public_key()
1693            .and_then(|pk| ToBech32::to_bech32(&pk).ok())
1694    }
1695
1696    // === Communities (headless) ===
1697    // The GUI's Tauri commands carry optimistic-echo + emit machinery a headless client
1698    // doesn't need; these are the lean equivalents over the same `community::service` layer,
1699    // so a CLI / agent can join, read, post, and sync a Community.
1700
1701    /// List every Community held locally (owned or joined), each with its channels.
1702    pub async fn list_communities(&self) -> Vec<serde_json::Value> {
1703        let ids = crate::db::community::list_community_ids().unwrap_or_default();
1704        let me = state::my_public_key();
1705        let mut out = Vec::new();
1706        for id in ids {
1707            let Ok(Some(c)) = crate::db::community::load_community_v2(&id) else { continue };
1708            let is_owner = me.is_some_and(|m| c.owner().is_ok_and(|o| o == m));
1709            out.push(serde_json::json!({
1710                "community_id": crate::simd::hex::bytes_to_hex_32(&c.identity.community_id.0),
1711                "version": 2,
1712                "name": c.name,
1713                "description": c.description,
1714                "is_owner": is_owner,
1715                // A dissolved community is SEALED: the row survives (history
1716                // is never auto-deleted) but no write is ever accepted again.
1717                // Without this a bot cannot tell it from a live one and
1718                // retries sends into a tombstone forever.
1719                "dissolved": c.dissolved,
1720                // `readable` is the field a bot needs and could never
1721                // compute: a private channel we've been told about but
1722                // hold no key for is enumerable-but-unreadable, which
1723                // is what distinguishes "not a member" from "member
1724                // awaiting the key vend".
1725                "channels": c.layout().1.into_iter()
1726                    .map(|(ch, cat)| serde_json::json!({
1727                        "channel_id": crate::simd::hex::bytes_to_hex_32(&ch.id.0),
1728                        "name": ch.name,
1729                        "private": ch.private,
1730                        "readable": !(ch.private && ch.key.is_none()),
1731                        "epoch": ch.epoch.0,
1732                        "category_id": cat.map(|k| crate::simd::hex::bytes_to_hex_32(&k.id)),
1733                        "topic": ch.topic(),
1734                        "view": ch.view().as_str(),
1735                    }))
1736                    .collect::<Vec<_>>(),
1737                "categories": Self::categories_json(&c),
1738            }));
1739        }
1740        out
1741    }
1742
1743    /// Create a fresh **Concord v2** community owned by the local identity. Mints the
1744    /// self-certifying id + genesis, persists, publishes, and registers each channel
1745    /// as a chat. Returns a `version: 2` JSON summary.
1746    pub async fn create_community_v2(&self, name: &str) -> Result<serde_json::Value> {
1747        self.create_community_with(name, &NewCommunity::default()).await
1748    }
1749
1750    /// Create a Community as [`NewCommunity`] shapes it. Returns the same summary as
1751    /// [`create_community_v2`](Self::create_community_v2).
1752    pub async fn create_community_with(&self, name: &str, opts: &NewCommunity) -> Result<serde_json::Value> {
1753        use crate::community::{v2::service as v2, transport::LiveTransport};
1754        let relays: Vec<String> = if opts.relays.is_empty() {
1755            crate::state::active_trusted_relays().await.iter().map(|s| s.to_string()).collect()
1756        } else {
1757            crate::community::v2::service::clean_relays(&[], &opts.relays).map_err(VectorError::Other)?
1758        };
1759        if relays.is_empty() {
1760            return Err(VectorError::Other("no relays available to host the Community".into()));
1761        }
1762        let session = crate::db::current_session();
1763        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
1764        let mut community = v2::create_community_on_roles_v2(&transport, name, relays, opts.description.clone())
1765            .await
1766            .map_err(VectorError::Other)?;
1767        if !session.is_live() {
1768            return Err(VectorError::Other("account changed while creating the community".into()));
1769        }
1770        self.register_v2_chats(&community, &session).await;
1771        // Genesis names the first Channel `general`. The Community stands either way, so a
1772        // failed rename is logged rather than returned: a retry would found a second one.
1773        if let Some(first) = opts.first_channel.as_deref().map(str::trim).filter(|n| !n.is_empty() && *n != "general") {
1774            if let Some(ch) = community.channels.first().cloned() {
1775                // From the held document: a rename keeps every vsk-2 field it doesn't touch.
1776                let mut meta = ch.metadata();
1777                meta.name = first.to_string();
1778                match v2::edit_channel_metadata(&transport, &community, &ch.id, &meta).await {
1779                    Ok(()) => {
1780                        if let Ok(Some(fresh)) = crate::db::community::load_community_v2(community.id()) {
1781                            community = fresh;
1782                            if session.is_live() {
1783                                self.register_v2_chats(&community, &session).await;
1784                            }
1785                        }
1786                    }
1787                    Err(e) => crate::log_warn!("[v2:create] the first channel keeps the name general: {e}"),
1788                }
1789            }
1790        }
1791        // Start streaming this community's planes right away.
1792        if let Some(client) = state::nostr_client() {
1793            crate::community::v2::realtime::refresh_subscription(&client).await;
1794        }
1795        Ok(Self::v2_summary(&community))
1796    }
1797
1798    /// If `channel_id` belongs to a locally-held **v2** community, its
1799    /// `CommunityId`; `Ok(None)` for an unknown channel. A DB read error PROPAGATES
1800    /// (fail-closed) rather than reading as "unknown" on a transient failure.
1801    fn v2_community_for_channel(&self, channel_id: &str) -> Result<Option<crate::community::CommunityId>> {
1802        let Some(cid_hex) = crate::db::community::community_id_for_channel(channel_id).map_err(VectorError::Other)? else {
1803            return Ok(None);
1804        };
1805        let cid = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&cid_hex));
1806        Ok(crate::db::community::community_held(&cid).map_err(VectorError::Other)?.then_some(cid))
1807    }
1808
1809    /// The `version: 2` JSON summary the SDK/facade hands back for a v2 community.
1810    fn v2_summary(community: &crate::community::v2::community::CommunityV2) -> serde_json::Value {
1811        let me = state::my_public_key();
1812        let is_owner = me.is_some_and(|m| community.owner().is_ok_and(|o| o == m));
1813        serde_json::json!({
1814            "community_id": crate::simd::hex::bytes_to_hex_32(&community.identity.community_id.0),
1815            "version": 2,
1816            "name": community.name,
1817            "description": community.description,
1818            "is_owner": is_owner,
1819            // The primary channel id, so the frontend can stamp every grafted chat row
1820            // the way `register_v2_chats` stamps the persisted ones. Without it each
1821            // channel claimed primary via the render fallback and a multi-channel
1822            // community drew one list row per channel until the next full reload.
1823            "primary_channel": community.primary_channel().map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0)),
1824            "channels": community.layout().1.into_iter()
1825                .map(|(c, cat)| serde_json::json!({
1826                    "channel_id": crate::simd::hex::bytes_to_hex_32(&c.id.0),
1827                    "name": c.name,
1828                    "private": c.private,
1829                    "category_id": cat.map(|k| crate::simd::hex::bytes_to_hex_32(&k.id)),
1830                    "topic": c.topic(),
1831                    "view": c.view().as_str(),
1832                }))
1833                .collect::<Vec<_>>(),
1834            "categories": Self::categories_json(community),
1835        })
1836    }
1837
1838    /// What the local user may do in each channel, on Roles v2 (CORD-04 §8): `None` on the
1839    /// legacy roster, where channels carry no permissions of their own.
1840    pub fn my_channel_permissions(community: &crate::community::v2::community::CommunityV2) -> std::collections::HashMap<[u8; 32], u64> {
1841        let Some(me) = state::my_public_key() else { return Default::default() };
1842        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
1843        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
1844        if roster.everyone.is_none() {
1845            return Default::default();
1846        }
1847        let owner = community.owner().ok().map(|o| o.to_hex());
1848        community
1849            .channels
1850            .iter()
1851            .map(|c| (c.id.0, roster.channel_permissions(owner.as_deref(), &me.to_hex(), &crate::simd::hex::bytes_to_hex_32(&c.id.0), c.private).0))
1852            .collect()
1853    }
1854
1855    /// A community's Categories in sidebar order, as the summaries carry them.
1856    pub fn categories_json(community: &crate::community::v2::community::CommunityV2) -> serde_json::Value {
1857        community
1858            .layout()
1859            .0
1860            .into_iter()
1861            .map(|k| serde_json::json!({ "category_id": crate::simd::hex::bytes_to_hex_32(&k.id), "name": k.name }))
1862            .collect()
1863    }
1864
1865    /// Register each of a v2 community's channels as a chat row (so it surfaces in
1866    /// the chat list / `communities()`). `session`
1867    /// is captured by the caller BEFORE its network I/O, so this STATE write is
1868    /// skipped if the account swapped mid-flight (else we'd write A's community
1869    /// into B's in-memory chats).
1870    pub async fn register_v2_chats(&self, community: &crate::community::v2::community::CommunityV2, __session: &std::sync::Arc<crate::db::Session>) {
1871        register_v2_chats_inner(community).await
1872    }
1873}
1874
1875/// Free-function body of [`VectorCore::register_v2_chats`] — also the migration finalize's
1876/// chat stamp (it runs from a spawned task with no facade handle; only globals are touched).
1877pub(crate) async fn register_v2_chats_inner(community: &crate::community::v2::community::CommunityV2) {
1878    // A Community joined or founded while listening: what stands now is its baseline, so its
1879    // first changes are news rather than the baseline itself.
1880    crate::community::v2::changes::prime(community);
1881    crate::db::scoped(async move {
1882        let owner_npub = community.owner().ok().and_then(|p| ToBech32::to_bech32(&p).ok());
1883            let me = state::my_public_key();
1884            let is_owner = me.is_some_and(|m| community.owner().is_ok_and(|o| o == m));
1885            let id_hex = crate::simd::hex::bytes_to_hex_32(&community.identity.community_id.0);
1886            // The chat list shows ONE row per community — the primary channel under the
1887            // community's metadata.
1888            let Some(primary) = community.primary_channel() else { return };
1889            let primary_hex = crate::simd::hex::bytes_to_hex_32(&primary.id.0);
1890            // Every channel gets a real chat row carrying its own name plus the community's
1891            // primary id. The chat list still shows ONE row per community (it renders only the
1892            // primary), but the sibling rows are now addressable, which is what lets the UI
1893            // reach a multi-channel community's other channels.
1894            let slims = {
1895                let mut st = state::STATE.lock().await;
1896                let mut slims = Vec::new();
1897                for ch in &community.channels {
1898                    let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
1899                    st.upsert_community_chat(
1900                        &ch_hex,
1901                        &community.name,
1902                        community.description.as_deref().unwrap_or(""),
1903                        &id_hex,
1904                        is_owner,
1905                        community.icon.is_some(),
1906                        owner_npub.as_deref(),
1907                        Some(community.created_at_ms),
1908                        community.dissolved,
1909                        &ch.name,
1910                        &primary_hex,
1911                    );
1912                    if let Some(chat) = st.chats.iter().find(|c| c.id == ch_hex) {
1913                        slims.push(crate::db::chats::SlimChatDB::from_chat(chat, &st.interner));
1914                    }
1915                }
1916                slims
1917            };
1918            // Persist the rows so a fresh boot reloads each channel's name/metadata
1919            for slim in &slims {
1920                let _ = crate::db::chats::save_slim_chat(slim);
1921            }
1922    })
1923    .await
1924}
1925
1926/// How long a community's raid verdict stays warm. Long enough that opening the panel
1927/// right after seeing its badge is instant, short enough that a wave arriving now shows
1928/// up without the moderator reloading anything.
1929const RAID_REPORT_TTL_SECS: u64 = 90;
1930
1931/// Per-account: the verdict is derived from this account's database and its roster.
1932struct RaidReportCache;
1933
1934struct PolicyReportCache;
1935struct PolicyReportGate;
1936
1937type ReportCache<T> = std::sync::Arc<std::sync::Mutex<std::collections::HashMap<String, (u64, std::sync::Arc<T>)>>>;
1938
1939/// The engine's console report, memoised like the assessor's was: evaluating
1940/// decrypts a four-thousand-message window and clusters every author, so a
1941/// header badge asking on every render would be a real cost.
1942fn policy_report_cache() -> ReportCache<serde_json::Value> {
1943    crate::db::current_session().scoped::<PolicyReportCache, _>()
1944}
1945
1946fn policy_report_gate() -> std::sync::Arc<std::sync::Mutex<()>> {
1947    crate::db::current_session().scoped::<PolicyReportGate, _>()
1948}
1949
1950fn raid_report_cache() -> ReportCache<crate::community::raid::RaidReport> {
1951    crate::db::current_session().scoped::<RaidReportCache, _>()
1952}
1953
1954/// A fresh memoised report. Expired entries go on every touch, so a community looked at
1955/// once is not held for the rest of the session.
1956fn report_get<T>(cache: &ReportCache<T>, cid_hex: &str, now_secs: u64) -> Option<std::sync::Arc<T>> {
1957    let mut map = cache.lock().unwrap_or_else(|e| e.into_inner());
1958    map.retain(|_, (at, _)| now_secs.saturating_sub(*at) < RAID_REPORT_TTL_SECS);
1959    map.get(cid_hex).map(|(_, report)| report.clone())
1960}
1961
1962fn report_put<T>(cache: &ReportCache<T>, cid_hex: &str, now_secs: u64, report: std::sync::Arc<T>) {
1963    let mut map = cache.lock().unwrap_or_else(|e| e.into_inner());
1964    map.retain(|_, (at, _)| now_secs.saturating_sub(*at) < RAID_REPORT_TTL_SECS);
1965    map.insert(cid_hex.to_string(), (now_secs, report));
1966}
1967
1968/// A memoised report, evaluated at most once per expiry: callers that miss together (a
1969/// badge, a menu and a panel asking on one render) wait for the first and take its report.
1970fn report_once<T>(
1971    cache: &ReportCache<T>,
1972    gate: &std::sync::Mutex<()>,
1973    cid_hex: &str,
1974    now_secs: u64,
1975    compute: impl FnOnce() -> Result<std::sync::Arc<T>>,
1976) -> Result<std::sync::Arc<T>> {
1977    if let Some(hit) = report_get(cache, cid_hex, now_secs) {
1978        return Ok(hit);
1979    }
1980    let _turn = gate.lock().unwrap_or_else(|e| e.into_inner());
1981    if let Some(hit) = report_get(cache, cid_hex, now_secs) {
1982        return Ok(hit);
1983    }
1984    let report = compute()?;
1985    report_put(cache, cid_hex, now_secs, report.clone());
1986    Ok(report)
1987}
1988
1989#[cfg(test)]
1990mod report_cache_tests {
1991    use super::*;
1992
1993    #[test]
1994    fn an_expired_report_goes_on_the_next_touch() {
1995        let cache: ReportCache<u32> = Default::default();
1996        report_put(&cache, "a", 1_000, std::sync::Arc::new(1));
1997        report_put(&cache, "b", 1_050, std::sync::Arc::new(2));
1998        assert_eq!(report_get(&cache, "a", 1_000 + RAID_REPORT_TTL_SECS - 1).as_deref(), Some(&1));
1999        assert_eq!(report_get(&cache, "a", 1_000 + RAID_REPORT_TTL_SECS), None, "a report is fresh for the TTL, no longer");
2000        assert_eq!(cache.lock().unwrap().len(), 1, "the lookup dropped it");
2001        report_put(&cache, "c", 1_050 + RAID_REPORT_TTL_SECS, std::sync::Arc::new(3));
2002        let map = cache.lock().unwrap();
2003        assert!(!map.contains_key("b") && map.contains_key("c"), "and so does an insert");
2004    }
2005
2006    #[test]
2007    fn callers_that_miss_together_share_one_evaluation() {
2008        let cache: ReportCache<u32> = Default::default();
2009        let gate = std::sync::Mutex::new(());
2010        let runs = std::sync::atomic::AtomicU32::new(0);
2011        std::thread::scope(|s| {
2012            for _ in 0..4 {
2013                s.spawn(|| {
2014                    let got = report_once(&cache, &gate, "a", 1_000, || {
2015                        runs.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2016                        std::thread::sleep(std::time::Duration::from_millis(50));
2017                        Ok(std::sync::Arc::new(7))
2018                    });
2019                    assert_eq!(got.unwrap().as_ref(), &7);
2020                });
2021            }
2022        });
2023        assert_eq!(runs.load(std::sync::atomic::Ordering::SeqCst), 1);
2024        let again = report_once(&cache, &gate, "a", 1_000 + RAID_REPORT_TTL_SECS, || Ok(std::sync::Arc::new(8)));
2025        assert_eq!(again.unwrap().as_ref(), &8, "an expired report is evaluated afresh");
2026    }
2027}
2028
2029impl VectorCore {
2030    /// Join a Community from a public invite URL (`vectorapp.io/invite/<naddr>#...`). Fetches the
2031    /// token-encrypted bundle, persists the member-view Community, and registers its channels
2032    /// as chats. Returns a JSON summary.
2033    pub async fn join_community(&self, invite_url: &str) -> Result<serde_json::Value> {
2034        use crate::community::transport::LiveTransport;
2035        crate::community::v2::invite::parse_invite_link(invite_url)
2036            .map_err(|_| VectorError::Other("not a Vector invite link".into()))?;
2037        let session = crate::db::current_session();
2038        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2039        let community = crate::community::v2::service::accept_public_link(&transport, invite_url)
2040            .await
2041            .map_err(VectorError::Other)?;
2042        self.register_v2_chats(&community, &session).await;
2043        if let Some(client) = state::nostr_client() {
2044            crate::community::v2::realtime::refresh_subscription(&client).await;
2045        }
2046        // Seed the membership store post-join. With a live listen the follow
2047        // worker does it (and SURFACES the folded joins as presence lines —
2048        // the joiner sees the room's history, own join included); headless
2049        // callers seed directly (membership only, no feed to surface).
2050        if crate::community::v2::realtime::follow_worker_running() {
2051            crate::community::v2::realtime::enqueue_follow(community.id());
2052        } else {
2053            let seed_community = community.clone();
2054            db::spawn_bound(async move {
2055                let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(20));
2056                if matches!(
2057                    crate::community::v2::service::sync_guestbook(&transport, &seed_community).await,
2058                    Ok(fresh) if !fresh.is_empty()
2059                ) {
2060                    let cid_hex = crate::simd::hex::bytes_to_hex_32(&seed_community.id().0);
2061                    emit_event("community_refreshed", &serde_json::json!({ "community_id": cid_hex }));
2062                }
2063            });
2064        }
2065        Ok(Self::v2_summary(&community))
2066    }
2067
2068    /// List the parked private invites (giftwrapped) awaiting acceptance. Each entry is the
2069    /// community id, its name (from the stored bundle), and the inviter's npub.
2070    pub fn list_pending_invites(&self) -> Result<Vec<serde_json::Value>> {
2071        let rows = crate::db::community::list_pending_invites().map_err(VectorError::Other)?;
2072        Ok(rows
2073            .iter()
2074            .filter_map(|p| {
2075                let v2 = crate::community::v2::invite::CommunityInvite::from_bundle_json(&p.bundle_json).ok()?;
2076                Some(serde_json::json!({
2077                    "community_id": p.community_id,
2078                    "name": v2.name,
2079                    "inviter_npub": p.inviter_npub,
2080                    "version": 2,
2081                }))
2082            })
2083            .collect())
2084    }
2085
2086    /// Accept a PARKED private invite by community id: rebuild the member-view Community from the stored
2087    /// bundle, finalize the join exactly like a public link, then drop the pending row. Mirrors the
2088    /// desktop's consent-then-join for an invite delivered over a gift wrap.
2089    pub async fn accept_pending_invite(&self, community_id: &str) -> Result<serde_json::Value> {
2090        crate::db::scoped(async move {
2091            use crate::community::transport::LiveTransport;
2092            let bundle_json = crate::db::community::get_pending_invite(community_id)
2093                .map_err(VectorError::Other)?
2094                .ok_or_else(|| VectorError::Other(format!("no pending invite for {community_id}")))?;
2095            let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2096            let session = crate::db::current_session();
2097            // The inviter's hex (parked at receive) attributes the Guestbook Join.
2098            let inviter = crate::db::community::list_pending_invites()
2099                .ok()
2100                .and_then(|rows| rows.into_iter().find(|p| p.community_id == community_id).map(|p| p.inviter_npub));
2101            // On failure the parked row is LEFT INTACT for retry — we must NOT auto-delete
2102            // on a verify failure: the multi-relay transport launders an unreachable-relay
2103            // error into an empty fetch, which yields the same "could not verify" as a
2104            // forged root (and a control-plane flood does too), so an auto-delete would
2105            // erase a GENUINE invite on a transient blip or an attacker's flood. A
2106            // pre-planted forged-root bundle (deferred protocol residual) is instead
2107            // cleared by the user declining it.
2108            //
2109            // ONE exception: a verified dissolution is a verdict, not a maybe — an
2110            // owner-signed grave has no undo (§9), so that invite can never succeed
2111            // and is retired everywhere instead of parking a permanent error loop.
2112            let community = match crate::community::v2::service::accept_parked_invite(&transport, &bundle_json, inviter.as_deref()).await {
2113                Ok(c) => c,
2114                Err(e) if e == crate::community::v2::service::ERR_DISSOLVED => {
2115                    let relays = crate::community::v2::invite::CommunityInvite::from_bundle_json(&bundle_json)
2116                        .map(|i| i.relays)
2117                        .unwrap_or_default();
2118                    crate::community::v2::service::retire_dead_invite(&transport, community_id, &relays).await;
2119                    return Err(VectorError::Other("this community has been dissolved — the invite was removed".into()));
2120                }
2121                Err(e) => return Err(VectorError::Other(e)),
2122            };
2123            self.register_v2_chats(&community, &session).await;
2124            if let Some(client) = state::nostr_client() {
2125                crate::community::v2::realtime::refresh_subscription(&client).await;
2126            }
2127            crate::community::v2::realtime::enqueue_follow(community.id());
2128            let _ = crate::db::community::delete_pending_invite(community_id);
2129            Ok(Self::v2_summary(&community))
2130        })
2131        .await
2132    }
2133
2134
2135    // ── Channels (CORD-03) ───────────────────────────────────────────────────
2136
2137    /// Resolve a v2 community by id, or explain why it isn't one.
2138    fn v2_community(community_id: &str) -> Result<crate::community::v2::community::CommunityV2> {
2139        use crate::community::CommunityId;
2140        if community_id.len() != 64 {
2141            return Err(VectorError::Other("malformed community id".into()));
2142        }
2143        let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
2144        crate::db::community::load_community_v2(&cid)
2145            .map_err(VectorError::Other)?
2146            .ok_or_else(|| VectorError::Other("community not found".into()))
2147    }
2148
2149    fn channel_id_of(channel_id: &str) -> Result<crate::community::ChannelId> {
2150        crate::simd::hex::hex_to_bytes_32_checked(channel_id)
2151            .map(crate::community::ChannelId)
2152            .ok_or_else(|| VectorError::Other("malformed channel id".into()))
2153    }
2154
2155    /// Create a channel. A private one mints its own key plus the channel-scoped
2156    /// access Role that is its access list (CORD-03/04); grant that role with
2157    /// [`grant_channel_access`](Self::grant_channel_access) to let someone read it.
2158    /// Returns the new channel id (32-byte hex).
2159    pub async fn create_channel(&self, community_id: &str, name: &str, private: bool) -> Result<String> {
2160        use crate::community::{v2::service, transport::LiveTransport};
2161        let community = Self::v2_community(community_id)?;
2162        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2163        let id = if private {
2164            service::create_private_channel(&transport, &community, name).await
2165        } else {
2166            service::create_public_channel(&transport, &community, name).await
2167        }
2168        .map_err(VectorError::Other)?;
2169        // Subscribe the new channel's chat plane now — waiting on the round-trip of
2170        // our own vsk-2 edition would leave the creator deaf to first replies.
2171        if let Some(client) = state::nostr_client() {
2172            crate::community::v2::realtime::refresh_subscription(&client).await;
2173        }
2174        Ok(crate::simd::hex::bytes_to_hex_32(&id.0))
2175    }
2176
2177    /// Create a Channel as [`NewChannel`] shapes it. Returns the channel id.
2178    pub async fn create_channel_with(&self, community_id: &str, name: &str, opts: &NewChannel) -> Result<String> {
2179        use crate::community::{v2::service, transport::LiveTransport};
2180        let name = name.trim();
2181        if name.is_empty() {
2182            return Err(VectorError::Other("a channel needs a name".into()));
2183        }
2184        let view = opts.view.as_deref().map(Self::view_named).transpose()?;
2185        let session = crate::db::current_session();
2186        let community = Self::v2_community(community_id)?;
2187        let category = opts.category_id.as_deref().map(|c| Self::id32(c, "category_id")).transpose()?;
2188        // A private Channel rekeys every member it admits, which takes longer.
2189        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(20));
2190        let id = service::create_channel_in(&transport, &community, name, opts.private, category).await.map_err(VectorError::Other)?;
2191        let channel_id = crate::simd::hex::bytes_to_hex_32(&id.0);
2192        // From the held document: the create wrote the Channel there, not onto our copy.
2193        if let Ok(Some(fresh)) = crate::db::community::load_community_v2(community.id()) {
2194            if session.is_live() {
2195                self.register_v2_chats(&fresh, &session).await;
2196            }
2197        }
2198        // The view and topic are a second edition. The Channel stands either way, so a failure
2199        // is logged rather than returned: a retry would make a second Channel.
2200        if view.is_some() || opts.topic.is_some() {
2201            let view = view.unwrap_or(crate::community::v2::community::ChannelView::Chat).as_str();
2202            if let Err(e) = self.edit_channel_details(community_id, &channel_id, name, opts.topic.as_deref(), view).await {
2203                crate::log_warn!("[v2:create] channel {} stands without its view or topic: {e}", &channel_id[..12]);
2204            }
2205        }
2206        if let Some(client) = state::nostr_client() {
2207            crate::community::v2::realtime::refresh_subscription(&client).await;
2208        }
2209        Ok(channel_id)
2210    }
2211
2212    /// What a public invite link shows before joining: name, description and icon, read from the
2213    /// Community's own Control Plane when its owner's root verifies (`verified`). Read-only.
2214    pub async fn preview_public_link(&self, url: &str) -> Result<LinkPreview> {
2215        use crate::community::{transport::LiveTransport, CommunityId};
2216        crate::community::v2::invite::parse_invite_link(url).map_err(|_| VectorError::Other("not a Vector invite link".into()))?;
2217        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2218        let bundle = crate::community::v2::service::fetch_public_bundle(&transport, url).await.map_err(VectorError::Other)?;
2219        // Self-certifying: verified as the bundle decrypts, so it names the Community unfolded.
2220        let community_id = bundle.community_id.clone();
2221        if let Ok(id) = Self::id32(&community_id, "community_id") {
2222            if let Ok(Some(local)) = crate::db::community::load_community_v2(&CommunityId(id)) {
2223                return Ok(LinkPreview {
2224                    community_id,
2225                    name: local.name.clone(),
2226                    description: local.description.clone(),
2227                    icon: local.icon.as_ref().map(|i| i.to_community_image()),
2228                    joined: true,
2229                    verified: true,
2230                });
2231            }
2232        }
2233        let (folded, verified) = crate::community::v2::service::preview_bundle_checked(&transport, &bundle).await.map_err(VectorError::Other)?;
2234        Ok(LinkPreview {
2235            community_id,
2236            name: folded.name.clone(),
2237            description: folded.description.clone(),
2238            icon: folded.icon.as_ref().map(|i| i.to_community_image()),
2239            joined: false,
2240            verified,
2241        })
2242    }
2243
2244    /// Rename a channel (a versioned edit of the same entity, so its history and
2245    /// id survive). Other folded fields are carried through untouched.
2246    pub async fn rename_channel(&self, community_id: &str, channel_id: &str, name: &str) -> Result<()> {
2247        use crate::community::{v2::service, transport::LiveTransport};
2248        let community = Self::v2_community(community_id)?;
2249        let id = Self::channel_id_of(channel_id)?;
2250        let mut meta = community
2251            .channel(&id)
2252            .ok_or_else(|| VectorError::Other("unknown channel".into()))?
2253            .metadata();
2254        meta.name = name.to_string();
2255        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2256        service::edit_channel_metadata(&transport, &community, &id, &meta)
2257            .await
2258            .map_err(VectorError::Other)
2259    }
2260
2261    /// Tombstone a channel. Deletion is terminal and the id is never reused;
2262    /// history stays readable to anyone who already holds its keys.
2263    pub async fn delete_channel(&self, community_id: &str, channel_id: &str) -> Result<()> {
2264        use crate::community::{v2::service, transport::LiveTransport};
2265        let community = Self::v2_community(community_id)?;
2266        let id = Self::channel_id_of(channel_id)?;
2267        let name = community.channel(&id).map(|c| c.name.clone()).unwrap_or_default();
2268        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2269        service::delete_channel(&transport, &community, &id, &name)
2270            .await
2271            .map_err(VectorError::Other)
2272    }
2273
2274    /// Grant `npub` read access to a private channel: adds the channel's access
2275    /// role and vends the key to them (CORD-03 "delivered on grant").
2276    pub async fn grant_channel_access(&self, community_id: &str, channel_id: &str, npub: &str) -> Result<()> {
2277        use crate::community::{v2::service, transport::LiveTransport};
2278        let community = Self::v2_community(community_id)?;
2279        let id = Self::channel_id_of(channel_id)?;
2280        let member = nostr_sdk::prelude::PublicKey::parse(npub)
2281            .map_err(|e| VectorError::Other(format!("bad npub: {e}")))?;
2282        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2283        service::grant_channel_access(&transport, &community, &id, &member)
2284            .await
2285            .map_err(VectorError::Other)
2286    }
2287
2288    /// Revoke `npub`'s read access: drops the access role and rekeys the channel
2289    /// so the removal actually severs them (CORD-06). They keep whatever history
2290    /// they already read — a rekey protects the future, never the past.
2291    pub async fn revoke_channel_access(&self, community_id: &str, channel_id: &str, npub: &str) -> Result<()> {
2292        use crate::community::{v2::service, transport::LiveTransport};
2293        let community = Self::v2_community(community_id)?;
2294        let id = Self::channel_id_of(channel_id)?;
2295        let member = nostr_sdk::prelude::PublicKey::parse(npub)
2296            .map_err(|e| VectorError::Other(format!("bad npub: {e}")))?;
2297        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2298        service::revoke_channel_access(&transport, &community, &id, &member)
2299            .await
2300            .map_err(VectorError::Other)
2301    }
2302
2303    /// Who may read a private channel: the channel-scoped Roles that are its
2304    /// access list (CORD-04 §2) and the members holding them.
2305    ///
2306    /// Sync read off the folded roster. `members` is exactly the access-role
2307    /// holders; `owner` is reported alongside because the owner is entitled
2308    /// whether or not they hold one (a channel's creator is granted the role, so
2309    /// an owner-created channel lists them in both).
2310    /// Whether `npub` may READ `channel_id` here.
2311    ///
2312    /// A PUBLIC channel is readable by the community; a PRIVATE one only by the
2313    /// holders of one of its channel-scoped access roles (CORD-03), plus the
2314    /// owner. Community-level power is NOT the question and must not be
2315    /// substituted for it: BAN says what someone may do to people, never which
2316    /// rooms they may see, and an access role commonly carries no powers at all.
2317    ///
2318    /// The reason this exists: a moderation report quotes what was said. Sending
2319    /// one built from a private channel to a moderator who holds no key there
2320    /// would launder the content out of the room, using the bot as the bypass —
2321    /// so anything that forwards evidence asks this first.
2322    ///
2323    /// Fails closed. A banned member reads nothing, and an unknown channel is an
2324    /// error rather than a permissive default.
2325    pub fn member_can_read_channel(&self, community_id: &str, channel_id: &str, npub: &str) -> Result<bool> {
2326        use nostr_sdk::prelude::PublicKey;
2327        let community = Self::v2_community(community_id)?;
2328        let id = Self::channel_id_of(channel_id)?;
2329        let ch = community.channel(&id).ok_or_else(|| VectorError::Other("unknown channel".into()))?;
2330        let who = PublicKey::parse(npub).map_err(|_| VectorError::Other(format!("invalid npub: {npub}")))?.to_hex();
2331        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
2332        if crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default().contains(&who) {
2333            return Ok(false);
2334        }
2335        if !ch.private {
2336            return Ok(true);
2337        }
2338        if community.owner().map(|o| o.to_hex()) == Ok(who.clone()) {
2339            return Ok(true);
2340        }
2341        let roster = crate::db::community::get_community_roles(&cid_hex).map_err(VectorError::Other)?;
2342        let access_ids = roster.channel_role_ids(&crate::simd::hex::bytes_to_hex_32(&id.0));
2343        Ok(roster
2344            .grants
2345            .iter()
2346            .filter(|g| g.member == who)
2347            .any(|g| g.role_ids.iter().any(|rid| access_ids.contains(rid))))
2348    }
2349
2350    pub fn channel_access(&self, community_id: &str, channel_id: &str) -> Result<serde_json::Value> {
2351        use nostr_sdk::prelude::{PublicKey, ToBech32};
2352        let community = Self::v2_community(community_id)?;
2353        let id = Self::channel_id_of(channel_id)?;
2354        let ch = community
2355            .channel(&id)
2356            .ok_or_else(|| VectorError::Other("unknown channel".into()))?;
2357        // Normalised id, not the caller's string: an uppercase-hex argument loads
2358        // the community but would miss the roster row and silently report nobody.
2359        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
2360        let roster = crate::db::community::get_community_roles(&cid_hex).map_err(VectorError::Other)?;
2361        let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
2362        let chan_hex = crate::simd::hex::bytes_to_hex_32(&id.0);
2363        let owner_hex = community.owner().ok().map(|o| o.to_hex());
2364        let (roles, members): (Vec<serde_json::Value>, Vec<String>) = if roster.everyone.is_some() {
2365            // Roles v2: whoever the Channel resolves View for, through Roles or their own overwrite.
2366            use crate::community::roles::{OverwriteTarget, Permissions};
2367            let scope = roster.syncs.get(&chan_hex).cloned().unwrap_or_else(|| chan_hex.clone());
2368            let roles = roster
2369                .overwrites
2370                .iter()
2371                .filter(|o| o.scope == scope && o.allow.contains(Permissions::VIEW_CHANNEL))
2372                .filter_map(|o| match &o.target {
2373                    OverwriteTarget::Role(id) => roster.role(id).map(|r| serde_json::json!({ "role_id": r.role_id, "name": r.name })),
2374                    _ => None,
2375                })
2376                .collect();
2377            let mut named: Vec<String> = roster.grants.iter().map(|g| g.member.clone()).collect();
2378            named.extend(roster.overwrites.iter().filter_map(|o| match &o.target {
2379                OverwriteTarget::Member(m) => Some(m.clone()),
2380                _ => None,
2381            }));
2382            named.sort();
2383            named.dedup();
2384            let members = named
2385                .into_iter()
2386                .filter(|m| !banned.contains(m) && Some(m) != owner_hex.as_ref() && roster.is_entitled(owner_hex.as_deref(), m, &chan_hex, &[], &[]))
2387                .filter_map(|m| PublicKey::from_hex(&m).ok().and_then(|pk| pk.to_bech32().ok()))
2388                .collect();
2389            (roles, members)
2390        } else {
2391            let access_ids = roster.channel_role_ids(&chan_hex);
2392            let roles = roster
2393                .channel_roles(&chan_hex)
2394                .into_iter()
2395                .map(|r| serde_json::json!({ "role_id": r.role_id, "name": r.name }))
2396                .collect();
2397            let members = roster
2398                .grants
2399                .iter()
2400                .filter(|g| !banned.contains(&g.member))
2401                .filter(|g| g.role_ids.iter().any(|rid| access_ids.contains(rid)))
2402                .filter_map(|g| PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok()))
2403                .collect();
2404            (roles, members)
2405        };
2406        Ok(serde_json::json!({
2407            "channel_id": chan_hex,
2408            "private": ch.private,
2409            "readable": !(ch.private && ch.key.is_none()),
2410            "owner": community.owner().ok().and_then(|o| o.to_bech32().ok()),
2411            "roles": roles,
2412            "members": members,
2413        }))
2414    }
2415
2416    /// Mint a public invite link for a Community this identity owns. Returns the shareable URL.
2417    /// `expires_at_ms` is an ABSOLUTE unix timestamp in MILLISECONDS (v2's native unit and the
2418    /// `InviteEntry` wire's). `label` is the attribution bucket shown as `"joined via <label>"`.
2419    pub async fn create_public_invite(
2420        &self,
2421        community_id: &str,
2422        expires_at_ms: Option<u64>,
2423        label: Option<String>,
2424    ) -> Result<String> {
2425        use crate::community::CommunityId;
2426        if community_id.len() != 64 {
2427            return Err(VectorError::Other("malformed community id".into()));
2428        }
2429        let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
2430        let community = crate::db::community::load_community_v2(&cid)
2431            .map_err(VectorError::Other)?
2432            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2433        // `build_invite_url` appends its own `/invite/<naddr>`, so pass the bare domain.
2434        let base = crate::community::v2::invite::INVITE_URL_BASE.trim_end_matches("/invite");
2435        let label = Some(crate::community::v2::invite::resolve_invite_label(community_id, label).map_err(VectorError::Other)?);
2436        let minted = crate::community::v2::service::mint_public_link_sync_later(&community, base, expires_at_ms, label)
2437            .await
2438            .map_err(VectorError::Other)?;
2439        Ok(minted.url)
2440    }
2441
2442    /// Send a PRIVATE invite: gift-wrap a Direct Invite bundle (3313) to an npub's inbox relays. The
2443    /// invitee parks it pending consent (accept_pending_invite). Any member may extend one.
2444    pub async fn invite_to_community(&self, community_id: &str, invitee_npub: &str) -> Result<serde_json::Value> {
2445        crate::db::scoped(async move {
2446            use crate::community::CommunityId;
2447
2448            let my_pk = crate::state::my_public_key()
2449                .ok_or_else(|| VectorError::Other("Public key not set".into()))?;
2450
2451            if community_id.len() != 64 {
2452                return Err(VectorError::Other("malformed community id".into()));
2453            }
2454            let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
2455            // A Direct Invite (3313 giftwrap), DELIBERATELY ungated: a Direct Invite is an ungateable key handoff (CORD-05 §6 — "any keyholder
2456            // can whisper keys"), so any member may extend one; the real access cut is
2457            // the rekey, not a permission on inviting.
2458            let recipient = nostr_sdk::prelude::PublicKey::parse(invitee_npub)
2459                .map_err(|e| VectorError::Other(format!("bad invitee npub: {e}")))?;
2460            let client = crate::state::nostr_client().ok_or_else(|| VectorError::Other("Not connected".into()))?;
2461            // Gift-wrap the 3313 Direct-Invite rumor (the bundle JSON) to the RECIPIENT'S
2462            // inbox relays (kind-10050) — a not-yet-member sees it on their DM sub;
2463            // the community relays wouldn't reach them. `#k=3313` per CORD-05 §6.
2464            //
2465            // Load + snapshot UNDER the rotation lock: a bundle minted while a Ban's
2466            // refound is mid-rotation carries the root being buried, and its joiner
2467            // lands on a dead epoch only to self-evict on the rekey exclusion.
2468            let bundle = {
2469                let lock = crate::community::v2::realtime::follow_lock(&cid);
2470                let _rotation = lock.lock().await;
2471                let community = crate::db::community::load_community_v2(&cid)
2472                    .map_err(VectorError::Other)?
2473                    .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2474                crate::community::v2::service::bundle_of(
2475                    &community,
2476                    crate::community::v2::service::BundleAudience::Member(recipient),
2477                    Some(my_pk),
2478                    None,
2479                    None,
2480                )
2481            };
2482            let bundle_json = serde_json::to_string(&bundle).map_err(|e| VectorError::Other(e.to_string()))?;
2483            // A 24h NIP-40 expiry (DIRECT_INVITE_EXPIRY_SECS): a bundle is live key material for a community that keeps rotating, so it must not linger.
2484            let expires_at = crate::clock::timestamp().as_secs()
2485                + crate::community::v2::invite::DIRECT_INVITE_EXPIRY_SECS;
2486            let expiry_tag = nostr_sdk::prelude::Tag::expiration(nostr_sdk::prelude::Timestamp::from_secs(expires_at));
2487            let rumor = nostr_sdk::prelude::EventBuilder::new(
2488                nostr_sdk::prelude::Kind::Custom(crate::community::v2::kind::DIRECT_INVITE),
2489                bundle_json,
2490            )
2491            .tag(expiry_tag.clone())
2492            .finalize_unsigned_with_id(my_pk);
2493            let k_tag = nostr_sdk::prelude::Tag::custom(
2494                "k",
2495                [crate::community::v2::kind::DIRECT_INVITE.to_string()],
2496            );
2497            crate::inbox_relays::send_gift_wrap(&client, &recipient, rumor, [k_tag, expiry_tag])
2498                .await
2499                .map_err(VectorError::Other)?;
2500            Ok(serde_json::json!({ "invited": invitee_npub, "version": 2 }))
2501        })
2502        .await
2503    }
2504
2505    /// The public invite links this account minted for a Community (to list + revoke). Each carries
2506    /// the hex `token` (the link secret) needed by [`Self::revoke_public_invite`]. A local read of
2507    /// the links minted on this device (a mint also syncs the cross-device 13303 record).
2508    /// `join_count` comes from the Guestbook.
2509    pub fn list_public_invites(&self, community_id: &str) -> Result<Vec<crate::db::community::PublicInviteRecord>> {
2510        crate::db::community::list_public_invites(community_id).map_err(VectorError::Other)
2511    }
2512
2513    /// Bring [`list_public_invites`](Self::list_public_invites) up to date with the links this
2514    /// account minted or retired on its other devices. Returns whether it changed.
2515    pub async fn sync_public_invites(&self, community_id: &str) -> Result<bool> {
2516        let held = Self::held_v2(community_id)?;
2517        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2518        crate::community::v2::service::adopt_invite_list(&transport, &held).await.map_err(VectorError::Other)
2519    }
2520
2521    /// Revoke a public invite link by its hex token. Retiring the LAST active link flips the Community to
2522    /// Private, which re-founds (rotates the base key + every channel key) to cut link-joined lurkers.
2523    /// Idempotent: a token this account doesn't hold is a no-op. Needs a local key when the revoke triggers
2524    /// the privatize rekey (a bunker account can't rotate).
2525    pub async fn revoke_public_invite(&self, community_id: &str, token: &str) -> Result<()> {
2526        use crate::community::{transport::LiveTransport, CommunityId};
2527        if community_id.len() != 64 {
2528            return Err(VectorError::Other("malformed community id".into()));
2529        }
2530        let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
2531        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(20));
2532        // A link is retired by its 16-byte token hex (re-post the coordinate as a
2533        // tombstone + tombstone the 13303 entry + refresh the Registry).
2534        let community = crate::db::community::load_community_v2(&cid)
2535            .map_err(VectorError::Other)?
2536            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2537        crate::community::v2::service::revoke_public_link(&transport, &community, token)
2538            .await
2539            .map_err(VectorError::Other)
2540    }
2541
2542    /// Post a text message to a Community channel. Returns the message id (the inner id).
2543    pub async fn send_community_message(
2544        &self,
2545        channel_id: &str,
2546        content: &str,
2547        replied_to: Option<&str>,
2548    ) -> Result<String> {
2549        self.send_community_message_expiring(channel_id, content, replied_to, None).await
2550    }
2551
2552    /// Post a message that deletes itself after `expires_in_secs`.
2553    ///
2554    /// A NIP-40 `expiration` tag on the rumor, which is what relays drop on and
2555    /// every member's client purges against — the same mechanism as the
2556    /// per-channel Self-Destruct Timer, decided per message instead of per
2557    /// channel. For a bot posting a public moderation notice: the warning is
2558    /// seen, then it stops being a permanent monument to somebody's worst day.
2559    ///
2560    pub async fn send_community_message_expiring(
2561        &self,
2562        channel_id: &str,
2563        content: &str,
2564        replied_to: Option<&str>,
2565        expires_in_secs: Option<u64>,
2566    ) -> Result<String> {
2567        let opts = PostOptions { reply_to: replied_to.map(str::to_string), expires_in_secs, ..Default::default() };
2568        self.post_community_message(channel_id, content, &opts).await
2569    }
2570
2571    /// Post a text message to a Community channel, as [`PostOptions`] shapes it. Returns the
2572    /// message id (the inner id).
2573    pub async fn post_community_message(&self, channel_id: &str, content: &str, opts: &PostOptions) -> Result<String> {
2574        self.post_community(channel_id, content, Vec::new(), opts, std::time::Duration::from_secs(12)).await
2575    }
2576
2577    /// The text half of every Community post: mentions, text spans and custom emoji resolved,
2578    /// the reply's author found, and the options' tags added.
2579    async fn post_community(
2580        &self,
2581        channel_id: &str,
2582        content: &str,
2583        mut extra_tags: Vec<nostr_sdk::prelude::Tag>,
2584        opts: &PostOptions,
2585        timeout: std::time::Duration,
2586    ) -> Result<String> {
2587        use crate::community::transport::LiveTransport;
2588        let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2589        let community = crate::db::community::load_community_v2(&id)
2590            .map_err(VectorError::Other)?
2591            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2592        let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
2593        let transport = LiveTransport::with_timeout(timeout);
2594        // The NIP-C7 q tag's author slot is a SHOULD — best-effort from the
2595        // held message, empty (= unknown) when the parent isn't in memory.
2596        let reply = match opts.reply_to.as_deref().filter(|r| !r.is_empty()) {
2597            Some(parent_id) => {
2598                let author_hex = {
2599                    let st = state::STATE.lock().await;
2600                    st.find_message(parent_id)
2601                        .and_then(|(_, m)| m.npub.as_deref().and_then(|n| nostr_sdk::prelude::PublicKey::parse(n).ok()))
2602                        .map(|pk| pk.to_hex())
2603                        .unwrap_or_default()
2604                };
2605                Some((parent_id.to_string(), author_hex))
2606            }
2607            None => None,
2608        };
2609        let reply_ref = reply.as_ref().map(|(id, author)| (id.as_str(), author.as_str()));
2610        let (named, role_mentions) = crate::community::mentions::resolve_in(&crate::simd::hex::bytes_to_hex_32(&id.0), content);
2611        // NIP-30: resolve `:shortcode:` against subscribed packs so the rumor
2612        // carries `["emoji", ...]` pairs.
2613        let (plain, text_spans) = crate::text_spans::extract_own(&named);
2614        let content = plain.as_str();
2615        let emoji_owned = crate::emoji_packs::resolve_outbound_emoji_tags(content);
2616        let emoji_pairs: Vec<(&str, &str)> = emoji_owned.iter().map(|t| (t.shortcode.as_str(), t.url.as_str())).collect();
2617        extra_tags.extend(crate::text_spans::to_nostr_tags(&text_spans).chain(crate::community::mentions::to_tags(&role_mentions)));
2618        if let Some(bot) = opts.bot.as_deref().filter(|b| !b.is_empty()) {
2619            let pk = nostr_sdk::prelude::PublicKey::parse(bot).map_err(|_| VectorError::Other(format!("{bot} isn't an npub or hex pubkey")))?;
2620            extra_tags.push(crate::bot_interface::bot_tag(&pk));
2621        }
2622        if let Some(secs) = opts.expires_in_secs.filter(|s| *s > 0) {
2623            let at = crate::clock::now_secs().saturating_add(secs);
2624            extra_tags.push(nostr_sdk::prelude::Tag::expiration(nostr_sdk::prelude::Timestamp::from_secs(at)));
2625        }
2626        crate::community::v2::service::send_chat_message(&transport, &community, &ch, content, reply_ref, &emoji_pairs, extra_tags)
2627            .await
2628            .map_err(VectorError::Other)
2629    }
2630
2631    /// Send a file to a Community channel as an encrypted attachment. Returns the message id.
2632    /// Mirrors the DM file pipeline (encrypt → Blossom upload → NIP-92 `imeta`) but publishes
2633    /// over the community transport.
2634    pub async fn send_community_file(&self, channel_id: &str, file_path: &str) -> Result<String> {
2635        self.post_community_file(channel_id, file_path, &PostOptions::default().compress(false)).await
2636    }
2637
2638    /// [`send_community_file`](Self::send_community_file) with a caption, a reply, an expiry or a bot address.
2639    pub async fn post_community_file(&self, channel_id: &str, file_path: &str, opts: &PostOptions) -> Result<String> {
2640        let path = std::path::Path::new(file_path);
2641        let bytes = std::fs::read(path).map_err(VectorError::Io)?;
2642        let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("file").to_string();
2643        self.post_community_bytes(channel_id, bytes, &filename, opts).await
2644    }
2645
2646    /// Send bytes held in memory to a Community channel as a file named `filename`, whose
2647    /// extension sets its type. Returns the message id.
2648    pub async fn post_community_bytes(&self, channel_id: &str, bytes: Vec<u8>, filename: &str, opts: &PostOptions) -> Result<String> {
2649        crate::db::scoped(async move {
2650            use crate::community::attachments;
2651            if bytes.is_empty() {
2652                return Err(VectorError::Other("Empty file".into()));
2653            }
2654            let (bytes, filename) = ready_to_send(bytes, filename, opts.compress).await?;
2655            let filename = filename.as_str();
2656            let extension = std::path::Path::new(filename).extension().and_then(|e| e.to_str()).unwrap_or("bin").to_lowercase();
2657
2658            // Resolve the destination BEFORE the upload so a bad channel fails fast, and refuse a
2659            // sealed community (CORD-02 §9) here: the send's own gate is too late to save the upload.
2660            let id = self
2661                .v2_community_for_channel(channel_id)?
2662                .ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2663            let community = crate::db::community::load_community_v2(&id)
2664                .map_err(VectorError::Other)?
2665                .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2666            if community.dissolved {
2667                return Err(VectorError::Other("this community has been dissolved".into()));
2668            }
2669            let author_pk = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
2670
2671            let file_hash = crate::crypto::sha256_hex(&bytes);
2672            let mime = crate::crypto::mime_from_extension(&extension);
2673            let img_meta = crate::crypto::generate_image_metadata(&bytes);
2674
2675            // Encrypt → upload to Blossom.
2676            let params = crate::crypto::generate_encryption_params();
2677            let encrypted = crate::crypto::encrypt_data(&bytes, &params)?;
2678            let encrypted_size = encrypted.len() as u64;
2679
2680            let _client = state::nostr_client().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
2681            let signer = crate::signer::active_signer().map_err(|e| VectorError::Other(format!("Signer unavailable: {e}")))?;
2682            let servers = crate::blossom_servers::compute_enabled_servers();
2683            if servers.is_empty() {
2684                return Err(VectorError::Other("No Blossom servers configured".into()));
2685            }
2686            let noop_progress: crate::blossom::ProgressCallback = std::sync::Arc::new(|_, _| Ok(()));
2687            let accepted = crate::blossom::upload_blob_with_progress_and_failover(
2688                signer.clone(),
2689                servers,
2690                std::sync::Arc::new(encrypted),
2691                Some(mime),
2692                /* is_encrypted */ true,
2693                noop_progress,
2694                Some(3),
2695                Some(std::time::Duration::from_secs(2)),
2696                None,
2697            ).await.map_err(VectorError::Other)?;
2698            // This flow never mirrors, so only the descriptor matters.
2699            let url = accepted.url;
2700
2701            let attachment = crate::types::Attachment {
2702                id: file_hash.clone(),
2703                key: params.key.clone(),
2704                nonce: params.nonce.clone(),
2705                extension: extension.clone(),
2706                name: filename.to_string(),
2707                url,
2708                // The caller's own file is the only plaintext copy there is.
2709                path: String::new(),
2710                size: encrypted_size,
2711                img_meta,
2712                downloading: false,
2713                downloaded: false,
2714                verified: true,
2715                // Mini Apps: one topic minted at send, so every member joins the same session.
2716                webxdc_topic: extension
2717                    .eq_ignore_ascii_case("xdc")
2718                    .then(|| crate::webxdc::mint_topic_id(&file_hash, &author_pk.to_hex())),
2719                ..Default::default()
2720            };
2721            // The imeta rides the kind-9 rumor verbatim (NIP-92); the caption is its content.
2722            let imeta = vec![attachments::attachment_to_imeta(&attachment)];
2723            let caption = opts.caption.clone().unwrap_or_default();
2724            self.post_community(channel_id, &caption, imeta, opts, std::time::Duration::from_secs(30)).await
2725        })
2726        .await
2727    }
2728
2729    /// Send an ephemeral typing indicator to a Community channel.
2730    pub async fn send_community_typing(&self, channel_id: &str) -> Result<()> {
2731        use crate::community::transport::LiveTransport;
2732        let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2733        let community = crate::db::community::load_community_v2(&id)
2734            .map_err(VectorError::Other)?
2735            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2736        let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
2737        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(8));
2738        crate::community::v2::service::send_typing(&transport, &community, &ch)
2739            .await
2740            .map_err(VectorError::Other)
2741    }
2742
2743    /// React to a Community message. `emoji_url` carries the NIP-30 image URL for a custom
2744    /// `:shortcode:` reaction (parity with DMs).
2745    pub async fn send_community_reaction(
2746        &self,
2747        channel_id: &str,
2748        message_id: &str,
2749        emoji: &str,
2750        emoji_url: Option<&str>,
2751    ) -> Result<()> {
2752        crate::db::scoped(async move {
2753            // Already ours — nothing to publish; the set can't hold it twice.
2754            if Self::own_reaction_id(message_id, emoji).await.is_some() {
2755                return Ok(());
2756            }
2757            let emoji_tags: Vec<crate::types::EmojiTag> = match emoji_url {
2758                Some(url) if emoji.starts_with(':') && emoji.ends_with(':') && emoji.len() >= 3 && !url.is_empty() => {
2759                    vec![crate::types::EmojiTag { shortcode: emoji[1..emoji.len() - 1].to_string(), url: url.to_string() }]
2760                }
2761                _ => Vec::new(),
2762            };
2763            let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2764            let community = crate::db::community::load_community_v2(&id)
2765                .map_err(VectorError::Other)?
2766                .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2767            let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
2768            let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2769            // NIP-25 names the reacted-to author (a required `p`). STATE first, then
2770            // the persisted row (v2 history + the send echo live in the shared events
2771            // store, so this almost always resolves locally); the channel-page fetch
2772            // is the last resort for a target this device never saw.
2773            let held = {
2774                let st = state::STATE.lock().await;
2775                st.find_message(message_id)
2776                    .and_then(|(_, m)| m.npub.as_deref().and_then(|n| nostr_sdk::prelude::PublicKey::parse(n).ok()))
2777            };
2778            let held = held.or_else(|| {
2779                crate::db::events::event_author(message_id)
2780                    .ok()
2781                    .flatten()
2782                    .and_then(|n| nostr_sdk::prelude::PublicKey::parse(&n).ok())
2783            });
2784            let target_author = match held {
2785                Some(pk) => pk,
2786                None => crate::community::v2::service::fetch_channel(&transport, &community, &ch, 500)
2787                    .await
2788                    .map_err(VectorError::Other)?
2789                    .iter()
2790                    .find(|f| f.event.opened().rumor_id.to_hex() == message_id)
2791                    .map(|f| f.event.opened().author)
2792                    .ok_or_else(|| VectorError::Other("reacted-to message not found".into()))?,
2793            };
2794            // The author lookup straddled awaits against THIS account's community.
2795            let pair = emoji_tags.first().map(|t| (t.shortcode.as_str(), t.url.as_str()));
2796            // The NIP-25 `k` names the target's rumor kind. Stored rows don't keep
2797            // wire-kind fidelity yet, so a reaction to a received kind-1111 thread
2798            // reply claims `9` — Armada's fold ignores reaction `k`, and exact
2799            // threading lands with the thread-aware GUI.
2800            crate::community::v2::service::send_reaction(
2801                &transport, &community, &ch, message_id, &target_author.to_hex(), crate::community::v2::kind::MESSAGE, emoji, pair,
2802            )
2803            .await
2804            .map(|_| ())
2805            .map_err(VectorError::Other)
2806        })
2807        .await
2808    }
2809
2810    /// Edit one of your own Community messages.
2811    pub async fn edit_community_message(&self, channel_id: &str, message_id: &str, new_content: &str) -> Result<()> {
2812        let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2813        // An edit names a Role in text only: it pings nobody anew.
2814        let (named, _) = crate::community::mentions::resolve_in(&crate::simd::hex::bytes_to_hex_32(&id.0), new_content);
2815        let (plain, text_spans) = crate::text_spans::extract_own(&named);
2816        let new_content = plain.as_str();
2817        let span_tags: Vec<nostr_sdk::prelude::Tag> = crate::text_spans::to_nostr_tags(&text_spans).collect();
2818        let emoji_tags = emoji_packs::resolve_outbound_emoji_tags(new_content);
2819        let community = crate::db::community::load_community_v2(&id)
2820            .map_err(VectorError::Other)?
2821            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2822        let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
2823        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2824        let emoji_pairs: Vec<(&str, &str)> = emoji_tags.iter().map(|t| (t.shortcode.as_str(), t.url.as_str())).collect();
2825        crate::community::v2::service::send_edit_tagged(&transport, &community, &ch, message_id, new_content, &emoji_pairs, span_tags)
2826            .await
2827            .map(|_| ())
2828            .map_err(VectorError::Other)
2829    }
2830
2831    /// Delete one of your own Community messages, resolving its channel from local
2832    /// history (the GUI path). A headless v2 consumer holds no local history — use
2833    /// [`Self::delete_community_message_in`] with the channel id instead.
2834    pub async fn delete_community_message(&self, message_id: &str) -> Result<()> {
2835        let channel_id = self.message_chat(message_id).await?;
2836        self.delete_community_message_in(&channel_id, message_id).await
2837    }
2838
2839    /// The chat a message on this device was said in: memory first, then the store, which
2840    /// holds the rows a page served without loading them into memory.
2841    pub async fn message_chat(&self, message_id: &str) -> Result<String> {
2842        if let Some((_, chat)) = state::STATE.lock().await.find_chat_for_message(message_id) {
2843            return Ok(chat);
2844        }
2845        crate::db::events::locate_message(message_id)
2846            .map_err(VectorError::Other)?
2847            .chat
2848            .ok_or_else(|| VectorError::Other("message not found (already deleted?)".into()))
2849    }
2850
2851    /// Delete one of your own Community messages (or reactions) in `channel_id`: its wraps off
2852    /// the relays by every key kept for them, then the in-plane kind-5 so peers drop it, plus
2853    /// best-effort attachment cleanup.
2854    pub async fn delete_community_message_in(&self, channel_id: &str, message_id: &str) -> Result<()> {
2855        use crate::community::transport::LiveTransport;
2856        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2857
2858        // Attachment URLs come from local history when held (a headless v2 consumer
2859        // has none — blob cleanup is then the receiving peers' concern, not ours).
2860        let attachment_urls: Vec<String> = self
2861            .get_message(message_id)
2862            .await
2863            .map(|(_, msg)| msg.attachments.iter().flat_map(|a| a.all_urls().map(str::to_string)).collect())
2864            .unwrap_or_default();
2865        // Smart-forward gate: scrub only urls no OTHER message still references.
2866        let attachment_urls =
2867            crate::db::attachments::urls_unreferenced_elsewhere(&attachment_urls, message_id).unwrap_or_default();
2868
2869        let id = self
2870            .v2_community_for_channel(channel_id)?
2871            .ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2872        let community = crate::db::community::load_community_v2(&id)
2873            .map_err(VectorError::Other)?
2874            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2875        let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
2876        crate::community::v2::service::delete_own(&transport, &community, &ch, message_id, crate::community::v2::kind::MESSAGE)
2877            .await
2878            .map_err(VectorError::Other)?;
2879        // Best-effort attachment blob delete.
2880        if !attachment_urls.is_empty() {
2881            if let Some(_client) = state::nostr_client() {
2882                if let Ok(signer) = crate::signer::active_signer() {
2883                    crate::blossom::delete_blobs_best_effort(signer, attachment_urls);
2884                }
2885            }
2886        }
2887        let removed_chat = {
2888            let mut st = state::STATE.lock().await;
2889            st.remove_message(message_id).map(|(cid, _)| cid)
2890        };
2891        let _ = crate::db::events::delete_event(message_id).await;
2892        traits::emit_event_json("message_removed", serde_json::json!({
2893            "id": message_id, "chat_id": removed_chat.as_deref().unwrap_or(channel_id), "reason": "deleted",
2894        }));
2895        Ok(())
2896    }
2897
2898    /// Moderation-hide someone ELSE's community message under `MANAGE_MESSAGES`
2899    /// (CORD-04 §3/§5). Seals the same kind-5 its authors use; peers re-derive the
2900    /// actor's authority from the signed inner against the folded Roster, so this is
2901    /// an authority claim peers verify, never a local suppression.
2902    pub async fn hide_community_message(&self, channel_id: &str, message_id: &str) -> Result<()> {
2903        use crate::community::transport::LiveTransport;
2904        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2905
2906        // You can only moderate a message you can see: the author resolves from
2907        // STATE, then the store for a row that has paged out of the window.
2908        let author_npub = {
2909            let st = state::STATE.lock().await;
2910            st.find_message(message_id).and_then(|(_, m)| m.npub)
2911        };
2912        let author_npub = match author_npub {
2913            Some(n) => n,
2914            None => crate::db::events::event_author(message_id)
2915                .ok()
2916                .flatten()
2917                .ok_or_else(|| VectorError::Other("can't resolve the target message's author".into()))?,
2918        };
2919        let author = nostr_sdk::prelude::PublicKey::parse(&author_npub)
2920            .map_err(|_| VectorError::Other("target message has an unreadable author".into()))?;
2921
2922        let id = self
2923            .v2_community_for_channel(channel_id)?
2924            .ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2925        let community = crate::db::community::load_community_v2(&id)
2926            .map_err(VectorError::Other)?
2927            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2928        let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
2929        crate::community::v2::service::moderation_delete(
2930            &transport, &community, &ch, message_id, crate::community::v2::kind::MESSAGE, &author,
2931        )
2932        .await
2933        .map_err(VectorError::Other)?;
2934
2935        let removed_chat = {
2936            let mut st = state::STATE.lock().await;
2937            st.remove_message(message_id).map(|(cid, _)| cid)
2938        };
2939        let _ = crate::db::events::delete_event(message_id).await;
2940        traits::emit_event_json("message_removed", serde_json::json!({
2941            "id": message_id, "chat_id": removed_chat.as_deref().unwrap_or(channel_id), "reason": "hidden",
2942        }));
2943        Ok(())
2944    }
2945
2946    /// Catch a Community channel up from relays: the consensus catch-up (rekeys + control refold)
2947    /// plus a chat backfill. Returns `(new_message_count, warnings)`; `warnings` are NON-FATAL
2948    /// errors hit during the sync — surfaced rather than swallowed so a headless caller is never
2949    /// blind to "the sync ran but a catch-up failed."
2950    pub async fn sync_community_channel(&self, channel_id: &str, limit: usize) -> Result<(usize, Vec<String>)> {
2951        self.sync_community_channel_before(channel_id, limit, None).await
2952    }
2953
2954    /// One page of a channel catch-up: what the relay served, and how much of it
2955    /// this client had never seen.
2956    pub async fn sync_community_channel_page(
2957        &self,
2958        channel_id: &str,
2959        limit: usize,
2960        before_secs: Option<u64>,
2961        since_secs: Option<u64>,
2962    ) -> Result<(BackfillCount, Vec<String>)> {
2963        let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2964        let warnings = if community::v2::realtime::follow_worker_running() {
2965            community::v2::realtime::enqueue_follow(&id);
2966            Vec::new()
2967        } else {
2968            Self::v2_inline_follow(&id).await
2969        };
2970        let count = Self::v2_backfill_channel_counted(
2971            &id, channel_id, limit, 8, since_secs, before_secs,
2972            crate::community::transport::Evidence::Fast, 12,
2973        ).await;
2974        Ok((count, warnings))
2975    }
2976
2977    /// Fill the hole in a channel's held history that a scroll up from `before_ms` is about to
2978    /// cross, with the relay pages from its top down. The count of messages that arrived; 0 when
2979    /// there is no hole there, or the relays can't be reached (it stays for the next scroll).
2980    pub async fn fill_community_gap(&self, channel_id: &str, before_ms: u64) -> Result<usize> {
2981        let Some(gap) = history_gaps::gap_at(channel_id, before_ms / 1000) else {
2982            return Ok(0);
2983        };
2984        // From the hole's top: a reader can step into it lower down, past rows it held.
2985        let before = gap.hi + 1;
2986        let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2987        let count = Self::v2_backfill_channel_counted(
2988            &id, channel_id, 50, 2, None, Some(before),
2989            crate::community::transport::Evidence::Fast, 12,
2990        ).await;
2991        // A walk that can't step below where it began (a second holding more than its pages)
2992        // would be asked again on every scroll: let the hole go.
2993        if count.next_before.is_some_and(|n| n >= before) {
2994            history_gaps::abandon(channel_id, before);
2995        }
2996        Ok(count.new_messages)
2997    }
2998
2999    /// [`sync_community_channel`](Self::sync_community_channel) with a back-paging
3000    /// cursor: `before_secs` bounds the fetch to messages at or older than it.
3001    ///
3002    /// The cursor is what reaches a v2 channel's PRE-ROTATION history. An
3003    /// uncursored catch-up reads the live epoch only (rotations move the
3004    /// conversation, so that is where it is); each epoch keeps its own plane
3005    /// address, and a bounded fetch spans all of them at once because messages are
3006    /// selected by time, not by epoch.
3007    pub async fn sync_community_channel_before(
3008        &self,
3009        channel_id: &str,
3010        limit: usize,
3011        before_secs: Option<u64>,
3012    ) -> Result<(usize, Vec<String>)> {
3013        // Consensus catch-up (rekeys then control refold) + chat backfill. With a
3014        // running listen() the coalescing worker owns the follow (never run inline beside
3015        // it — two concurrent follows can whole-row clobber); headless, walk it inline.
3016        // The chat page is fetched + persisted either way, so get_messages backfills.
3017        let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
3018        let warnings = if community::v2::realtime::follow_worker_running() {
3019            community::v2::realtime::enqueue_follow(&id);
3020            Vec::new()
3021        } else {
3022            Self::v2_inline_follow(&id).await
3023        };
3024        // Deepest catch-up walk: pages × page-size bounds one reconnect's fetch.
3025        // Chat plane = fetch ASAP. NOTE: fetch_plane does not consult the
3026        // evidence tier yet (#370) — until it does, the transport-seconds
3027        // bound is the effective limit; the declared Fast records intent.
3028        let new = Self::v2_backfill_channel(
3029            &id, channel_id, limit, 8, None, before_secs,
3030            crate::community::transport::Evidence::Fast, 12,
3031        ).await;
3032        Ok((new, warnings))
3033    }
3034
3035    /// Cursor-paged relay sync: fetch ONE page of up to `max_events` events from
3036    /// the channel's relays (per relay — divergent relays can push the union
3037    /// higher), ingest it, and return how many MESSAGES were new. A return of 0
3038    /// means the page held nothing new, not that the channel is empty.
3039    ///
3040    /// `until_s` / `since_s` are unix-seconds bounds (the back-paging cursor and
3041    /// the time floor). Depth comes from looping, not from a bigger page:
3042    /// `max_events` is clamped to 500 (relays clamp theirs anyway) and values
3043    /// under 50 behave as 50 on v2 (the shared pager's floor).
3044    ///
3045    /// Consensus (root rotations, control folds, ban checks) is the FULL sync's
3046    /// job — [`sync_community_channel`](Self::sync_community_channel) — so a
3047    /// hundred-page walk doesn't re-fold control a hundred times. Run one full
3048    /// sync (or be listening) before deep walks.
3049    pub async fn sync_channel_events(
3050        &self,
3051        channel_id: &str,
3052        max_events: usize,
3053        until_s: Option<u64>,
3054        since_s: Option<u64>,
3055    ) -> Result<usize> {
3056        let max = max_events.clamp(1, 500);
3057        let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
3058        let community = crate::db::community::load_community_v2(&id)
3059            .map_err(VectorError::Other)?
3060            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
3061        if community.dissolved {
3062            return Err(VectorError::Other("this community has been dissolved".into()));
3063        }
3064        let ch_id = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
3065        let ch = community
3066            .channel(&ch_id)
3067            .ok_or_else(|| VectorError::Other("no such channel in this community".into()))?;
3068        // Err, not a silent 0 — "granted but the key hasn't arrived" must be
3069        // distinguishable from "nothing new" or the caller diagnoses a mute bot.
3070        if ch.private && ch.key.is_none() {
3071            return Err(VectorError::Other(
3072                "this private channel has no key yet (awaiting rekey delivery)".into(),
3073            ));
3074        }
3075        let new = Self::v2_backfill_channel(
3076            &id, channel_id, max, 1, since_s, until_s,
3077            crate::community::transport::Evidence::Fast, 12,
3078        )
3079        .await;
3080        Ok(new)
3081    }
3082
3083    /// The composer's `/` picker snapshot for `chat_id`, answered INSTANTLY
3084    /// from local state: the chat's bot-flagged members (kind-0 `bot: true` —
3085    /// the SDK sets it on every bot it builds) and their last-known manifests
3086    /// from the persistent store. When the last refresh is older than a minute
3087    /// (or the bot set changed), ONE background REQ re-fetches every bot's
3088    /// manifest together (5s unification window), persists newer editions, and
3089    /// emits `chat_commands_updated` — the UI swaps the list in when it lands.
3090    /// Works for BOTH community protocols (an invocation is plain content; only
3091    /// the optional routing tag is v2-only) and DMs. The manifest REQ always
3092    /// includes the discovery indexers beside the chat's own relays, so an
3093    /// unreachable or stranger-dropping community relay can't blind the picker.
3094    pub async fn get_chat_commands(&self, chat_id: &str) -> crate::bot_interface::ChatCommandsSnapshot {
3095        use crate::bot_interface::{self, ChatCommandsSnapshot};
3096        use nostr_sdk::prelude::ToBech32;
3097
3098        let mut bots: Vec<nostr_sdk::prelude::PublicKey> = Vec::new();
3099        let mut relays: Vec<String> = Vec::new();
3100        let community_hex = crate::db::community::community_id_for_channel(chat_id).ok().flatten();
3101        if let Some(cid_hex) = community_hex {
3102            let Ok(Some(community)) = Self::load_held(&cid_hex) else {
3103                return ChatCommandsSnapshot { bots: 0, commands: Vec::new(), fresh: true };
3104            };
3105            let members = community::v2::service::stored_memberlist(&community).unwrap_or_default();
3106            relays = community.relays.clone();
3107            let state = crate::state::STATE.lock().await;
3108            for pk in members {
3109                let Ok(npub) = pk.to_bech32();
3110                if state.get_profile(&npub).map(|p| p.flags.is_bot()).unwrap_or(false) {
3111                    bots.push(pk);
3112                }
3113            }
3114        } else if chat_id.starts_with("npub1") {
3115            if let Ok(pk) = nostr_sdk::prelude::PublicKey::parse(chat_id) {
3116                let is_bot = {
3117                    let state = crate::state::STATE.lock().await;
3118                    state.get_profile(chat_id).map(|p| p.flags.is_bot()).unwrap_or(false)
3119                };
3120                if is_bot {
3121                    bots.push(pk);
3122                    // The counterpart published its manifest to its own login
3123                    // relays/indexers — our connected pool is the read set.
3124                    if let Some(client) = crate::state::nostr_client() {
3125                        relays = client.relays().await.keys().map(|u| u.to_string()).collect();
3126                    }
3127                }
3128            }
3129        }
3130
3131        if bots.is_empty() {
3132            return ChatCommandsSnapshot { bots: 0, commands: Vec::new(), fresh: true };
3133        }
3134        // The chat's own relays PLUS the discovery indexers, one REQ across the
3135        // union — a room whose relays refuse kind 10304 still resolves.
3136        relays.extend(bot_interface::DISCOVERY_RELAYS.iter().map(|s| s.to_string()));
3137        relays.sort();
3138        relays.dedup();
3139        // Deterministic order: the freshness check compares the exact bot set,
3140        // and picker sections stay stable across refreshes.
3141        bots.sort_by_key(|p| p.to_hex());
3142        let bot_hexes: Vec<String> = bots.iter().map(|p| p.to_hex()).collect();
3143        let commands = bot_interface::assemble_from_store(&bot_hexes);
3144        let fresh = bot_interface::commands_fresh(chat_id, &bot_hexes);
3145        if !fresh {
3146            bot_interface::spawn_commands_refresh(chat_id.to_string(), bots.clone(), relays);
3147        }
3148        ChatCommandsSnapshot { bots: bots.len(), commands, fresh }
3149    }
3150
3151    /// Members of a Community: the Complete Memberlist, each entry `{npub}` (it carries no
3152    /// activity time). One only seen posting, outside the Guestbook's members, also carries
3153    /// `unlisted` (`"no_join"` or `"departed"`): listed, but never counted, since what this
3154    /// client has seen depends on how much history it holds. Best-effort throughout: a
3155    /// transport failure yields an empty list, never an error.
3156    pub async fn get_community_members(&self, community_id: &str) -> Vec<serde_json::Value> {
3157        use nostr_sdk::prelude::ToBech32;
3158        // The Complete Memberlist from LOCAL state (persisted guestbook +
3159        // observed authors + roster grantees − banlist). The store is seeded
3160        // post-join and cursor-caught-up by the follow worker (boot/reconnect) +
3161        // live ingest; a cold store (a hold predating the store) seeds in the
3162        // background and refreshes the UI when it lands.
3163        let Ok(Some(community)) = Self::load_held(community_id) else { return Vec::new() };
3164        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3165        let (events, cursor) = crate::db::community::get_guestbook_shared(&cid_hex).unwrap_or_default();
3166        if cursor == 0 {
3167            if crate::community::v2::realtime::follow_worker_running() {
3168                crate::community::v2::realtime::enqueue_follow(community.id());
3169            } else {
3170                let c2 = community.clone();
3171                db::spawn_bound(async move {
3172                    let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(20));
3173                    if matches!(crate::community::v2::service::sync_guestbook(&transport, &c2).await, Ok(fresh) if !fresh.is_empty()) {
3174                        emit_event("community_refreshed", &serde_json::json!({ "community_id": cid_hex }));
3175                    }
3176                });
3177            }
3178        }
3179        let parts = crate::community::v2::service::stored_member_parts(&community, &events).unwrap_or_default();
3180        let counted = parts.counted.into_iter().filter_map(|pk| pk.to_bech32().ok()).map(|npub| serde_json::json!({ "npub": npub }));
3181        let unlisted = parts
3182            .unlisted
3183            .into_iter()
3184            .filter_map(|(pk, why)| pk.to_bech32().ok().map(|npub| serde_json::json!({ "npub": npub, "unlisted": why })));
3185        counted.chain(unlisted).collect()
3186    }
3187
3188    /// A Community's banlist, as npubs.
3189    ///
3190    /// The counterpart to [`Self::set_member_banned`], which had none: setting a
3191    /// ban succeeds identically whether or not one was already in place, so a
3192    /// caller lifting a ban could not tell whether it changed anything, and
3193    /// anything reporting on it was guessing.
3194    ///
3195    /// Read from local state, so it reflects the last banlist edition this
3196    /// client folded rather than a fresh fetch.
3197    pub fn get_community_banned(&self, community_id: &str) -> Vec<String> {
3198        use nostr_sdk::prelude::{PublicKey, ToBech32};
3199        // Resolve the id the same way the moderation panel does: a caller may
3200        // hold a logical id that is not the row key.
3201        let cid_hex = match Self::load_held(community_id) {
3202            Ok(Some(c)) => crate::simd::hex::bytes_to_hex_32(&c.id().0),
3203            _ => community_id.to_string(),
3204        };
3205        crate::db::community::get_community_banlist(&cid_hex)
3206            .unwrap_or_default()
3207            .iter()
3208            .filter_map(|hex| PublicKey::parse(hex).ok())
3209            .filter_map(|pk| pk.to_bech32().ok())
3210            .collect()
3211    }
3212
3213    /// Everything the moderation panel needs about one Community, read once so the
3214    /// parts agree with each other: every member scored against the raid evidence
3215    /// ([`crate::community::raid`]), the duplicate-text cohorts behind those verdicts,
3216    /// the live invite links, and what the caller may actually do about it.
3217    ///
3218    /// v2 only — the containment this feeds (batch ban, refounding) are v2 verbs.
3219    pub fn community_moderation_intel(&self, community_id: &str) -> Result<serde_json::Value> {
3220        let community = Self::load_held(community_id)?
3221            .ok_or_else(|| VectorError::Other("moderation tools require a Concord v2 community".into()))?;
3222        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3223        let report = Self::policy_console_report(&cid_hex, &community)?;
3224        let invites = crate::db::community::list_public_invites(&cid_hex).unwrap_or_default();
3225        let banlist = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
3226        let caps = self.community_capabilities(community_id).unwrap_or_else(|_| serde_json::json!({}));
3227        let owner_b32 = community.owner().map_err(VectorError::Other)?.to_bech32().unwrap_or_default();
3228        // Who the member list marks as only seen posting: assessed like everyone, never counted.
3229        let unlisted: Vec<String> = crate::db::community::get_guestbook_shared(&cid_hex)
3230            .ok()
3231            .and_then(|(events, _)| crate::community::v2::service::stored_member_parts(&community, &events).ok())
3232            .map(|p| p.unlisted.into_keys().filter_map(|pk| pk.to_bech32().ok()).collect())
3233            .unwrap_or_default();
3234
3235        Ok(serde_json::json!({
3236            "community_id": cid_hex,
3237            "name": community.name,
3238            "owner_npub": owner_b32,
3239            "epoch": community.root_epoch.0,
3240            "report": &*report,
3241            "unlisted": unlisted,
3242            "invites": invites.iter().map(|i| serde_json::json!({
3243                "token": i.token,
3244                "label": i.label,
3245                "created_at": i.created_at,
3246                "expires_at": i.expires_at,
3247                "join_count": i.join_count,
3248            })).collect::<Vec<_>>(),
3249            "banlist_count": banlist.len(),
3250            "banlist_max": crate::community::v2::roles::MAX_BANLIST,
3251            "capabilities": caps,
3252            // The designer offers per-channel exemptions, and this is the
3253            // console's own data source — one place to ask, one answer.
3254            "channels": community.channels.iter().map(|c| serde_json::json!({
3255                "id": crate::simd::hex::bytes_to_hex_32(&c.id.0),
3256                "name": c.name,
3257            })).collect::<Vec<_>>(),
3258        }))
3259    }
3260
3261    /// Screen ONE message immediately, without waiting for a sweep.
3262    ///
3263    /// Runs only the stateless rules — words, links, regex, mentions — because
3264    /// those are the only ones a single message can answer. Rate, repetition
3265    /// and cohorts describe a window and stay with the periodic evaluation.
3266    ///
3267    /// Costs no corpus read and no cache: the whole point is that a word filter
3268    /// should answer in milliseconds, not on the next 90-second tick.
3269    pub fn screen_community_message(
3270        &self,
3271        channel_id: &str,
3272        author_npub: &str,
3273        text: &str,
3274    ) -> Result<serde_json::Value> {
3275        use nostr_sdk::prelude::PublicKey;
3276        let Some(id) = self.v2_community_for_channel(channel_id)? else {
3277            return Ok(serde_json::json!({ "findings": [] }));
3278        };
3279        let community = crate::db::community::load_community_v2(&id)
3280            .map_err(VectorError::Other)?
3281            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
3282        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3283        let owner = community.owner().map_err(VectorError::Other)?;
3284        let author = PublicKey::parse(author_npub).map_err(|_| VectorError::Other("unreadable author".into()))?;
3285
3286        // Same staff definition the console uses: a role carrying a moderation
3287        // permission bit, never mere role membership.
3288        use crate::community::roles::Permissions;
3289        const MOD_MASK: u64 = Permissions::MANAGE_ROLES
3290            | Permissions::MANAGE_CHANNELS
3291            | Permissions::MANAGE_METADATA
3292            | Permissions::KICK
3293            | Permissions::BAN
3294            | Permissions::MANAGE_MESSAGES;
3295        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
3296        let hex = author.to_hex();
3297        let roles: Vec<String> =
3298            roster.grants.iter().find(|g| g.member == hex).map(|g| g.role_ids.clone()).unwrap_or_default();
3299        let is_staff = roles
3300            .iter()
3301            .any(|rid| roster.roles.iter().any(|r| &r.role_id == rid && (r.permissions.0 & MOD_MASK) != 0));
3302
3303        let now_ms = crate::clock::now_ms();
3304        let findings = crate::community::policy::harness::screen_message(
3305            &cid_hex, &owner, &author, &roles, is_staff, channel_id, text, now_ms,
3306        );
3307        Ok(serde_json::json!({ "findings": findings }))
3308    }
3309
3310    /// The raid verdict alone, for the badge on a community header. Same assessment as
3311    /// the panel and served from the same cache, so surfacing the alert costs nothing
3312    /// once and then nothing at all until it expires.
3313    pub fn check_community_raid(&self, community_id: &str) -> Result<serde_json::Value> {
3314        let Some(community) = Self::load_held(community_id)? else {
3315            return Ok(serde_json::json!({ "detected": false }));
3316        };
3317        // A raid alarm is a call to act, and only BAN can answer it (the console's
3318        // containment verbs all need it). Anyone else would be alarmed with nothing
3319        // to do, and would pay for a four-thousand-message scan to get there.
3320        let caps = self.community_capabilities(community_id)?;
3321        if caps["ban"].as_bool() != Some(true) {
3322            return Ok(serde_json::json!({ "detected": false }));
3323        }
3324        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3325        let report = Self::policy_console_report(&cid_hex, &community)?;
3326        let biggest = report["cohorts"].get(0);
3327        Ok(serde_json::json!({
3328            "detected": report["raid_detected"].as_bool().unwrap_or(false),
3329            "suspects": report["suspects"].as_u64().unwrap_or(0),
3330            "cohort": biggest.and_then(|c| c["size"].as_u64()).unwrap_or(0),
3331            "sample": biggest
3332                .and_then(|c| c["sample"].as_str())
3333                .map(|s| s.chars().take(60).collect::<String>())
3334                .unwrap_or_default(),
3335        }))
3336    }
3337
3338    /// Assess a community, memoised for [`RAID_REPORT_TTL_SECS`]. The read decrypts a
3339    /// four-thousand-message window, so a header badge asking on every render would be a
3340    /// real cost; the panel opening moments later reuses the same answer.
3341    fn raid_report(cid_hex: &str) -> Result<std::sync::Arc<crate::community::raid::RaidReport>> {
3342        use crate::community::raid;
3343        use crate::community::v2::guestbook::GuestbookEntry;
3344        use nostr_sdk::prelude::PublicKey;
3345        use std::collections::{HashMap, HashSet};
3346
3347        let now_secs = crate::clock::now_secs();
3348        if let Some(report) = report_get(&raid_report_cache(), cid_hex, now_secs) {
3349            return Ok(report);
3350        }
3351        let community = crate::db::community::load_community_v2(&crate::community::CommunityId(
3352            crate::simd::hex::hex_to_bytes_32(cid_hex),
3353        ))
3354        .map_err(VectorError::Other)?
3355        .ok_or_else(|| VectorError::Other("moderation tools require a Concord v2 community".into()))?;
3356        let owner_b32 = community.owner().map_err(VectorError::Other)?.to_bech32().unwrap_or_default();
3357        let me_b32 = state::my_public_key().and_then(|p| p.to_bech32().ok()).unwrap_or_default();
3358
3359        // Anyone holding a live grant is staff, whatever the role is called.
3360        let roster = crate::db::community::get_community_roles(cid_hex).unwrap_or_default();
3361        let staff: HashSet<String> = roster
3362            .grants
3363            .iter()
3364            .filter(|g| !g.role_ids.is_empty())
3365            .filter_map(|g| PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok()))
3366            .collect();
3367
3368        // The same fold the member list paints, so the panel can't disagree with it.
3369        let members: Vec<String> = crate::community::v2::service::stored_memberlist(&community)
3370            .unwrap_or_default()
3371            .into_iter()
3372            .filter_map(|pk| pk.to_bech32().ok())
3373            .collect();
3374
3375        // Guestbook: authoritative joins, with the invite each one came through.
3376        let (events, _cursor) = crate::db::community::get_guestbook(cid_hex).unwrap_or_default();
3377        let mut joined_at: HashMap<String, u64> = HashMap::new();
3378        let mut invite_label: HashMap<String, String> = HashMap::new();
3379        for e in &events {
3380            let GuestbookEntry::Join { member, invited_by, at_ms } = &e.entry else { continue };
3381            let Ok(b32) = member.to_bech32();
3382            // Earliest join wins: a rejoin must not erase real tenure.
3383            let slot = joined_at.entry(b32.clone()).or_insert(*at_ms);
3384            *slot = (*slot).min(*at_ms);
3385            if let Some((_creator, label)) = invited_by {
3386                invite_label.entry(b32).or_insert_with(|| label.clone());
3387            }
3388        }
3389
3390        let footprints: HashMap<String, crate::db::community::AuthorFootprint> =
3391            crate::db::community::community_author_footprints(cid_hex)
3392                .unwrap_or_default()
3393                .into_iter()
3394                .map(|f| (f.npub.clone(), f))
3395                .collect();
3396
3397        // Cohort evidence comes from the recent window only — a raid is by definition
3398        // recent, and the whole history would cost a vault decrypt per row.
3399        const TEXT_WINDOW: usize = 4_000;
3400        let mut texts: HashMap<String, (Vec<String>, Vec<u64>)> = HashMap::new();
3401        for (npub, at, text) in crate::db::community::community_recent_texts(cid_hex, TEXT_WINDOW).unwrap_or_default() {
3402            let slot = texts.entry(npub).or_default();
3403            slot.0.push(text);
3404            slot.1.push(at);
3405        }
3406
3407        let signals: Vec<raid::MemberSignals> = members
3408            .iter()
3409            .map(|npub| {
3410                let f = footprints.get(npub);
3411                raid::MemberSignals {
3412                    npub: npub.clone(),
3413                    joined_at_ms: joined_at.get(npub).copied().unwrap_or(0),
3414                    invite_label: invite_label.get(npub).cloned(),
3415                    messages: f.map(|f| f.messages).unwrap_or(0),
3416                    first_secs: f.map(|f| f.first_secs).unwrap_or(0),
3417                    last_secs: f.map(|f| f.last_secs).unwrap_or(0),
3418                    texts: texts.get(npub).map(|t| t.0.clone()).unwrap_or_default(),
3419                    text_secs: texts.get(npub).map(|t| t.1.clone()).unwrap_or_default(),
3420                    is_owner: *npub == owner_b32,
3421                    is_admin: staff.contains(npub),
3422                    is_me: *npub == me_b32,
3423                }
3424            })
3425            .collect();
3426
3427        let params = raid::RaidParams {
3428            known_shortcodes: crate::emoji_packs::known_shortcodes(),
3429            ..Default::default()
3430        };
3431        let report = std::sync::Arc::new(raid::assess(&signals, now_secs, &params));
3432        report_put(&raid_report_cache(), cid_hex, now_secs, report.clone());
3433        Ok(report)
3434    }
3435
3436    /// The preset library: what a designer offers instead of a blank document.
3437    pub fn policy_presets(&self) -> Result<serde_json::Value> {
3438        let presets: Vec<serde_json::Value> = crate::community::policy::presets::all()
3439            .into_iter()
3440            .map(|p| {
3441                serde_json::json!({
3442                    "id": p.id,
3443                    "name": p.name,
3444                    "description": p.description,
3445                    "example": p.example,
3446                    "caveat": p.caveat,
3447                    "dials": p.dials,
3448                    // Every rule in plain language: a template whose behaviour
3449                    // you can only infer from its name is the same black box
3450                    // the shipped defaults used to be.
3451                    "rules": crate::community::policy::presets::describe(&p.policy),
3452                    "bytes": serde_json::to_string(&p.policy).unwrap_or_default(),
3453                })
3454            })
3455            .collect();
3456        // The from-scratch builder's catalogue rides along: it is fetched at the
3457        // same moment, and its numbers must come from the same place the
3458        // presets' do.
3459        let rule_kinds: Vec<serde_json::Value> = crate::community::policy::presets::rule_kinds()
3460            .into_iter()
3461            .map(|k| {
3462                serde_json::json!({
3463                    "id": k.id,
3464                    "label": k.label,
3465                    "description": k.description,
3466                    "input": k.input,
3467                    "input_label": k.input_label,
3468                    "input_hint": k.input_hint,
3469                    "rule": k.rule,
3470                })
3471            })
3472            .collect();
3473        Ok(serde_json::json!({ "presets": presets, "rule_kinds": rule_kinds }))
3474    }
3475
3476    /// What a candidate policy WOULD do, against real history. Stores nothing,
3477    /// publishes nothing, removes nobody — the designer never enables a policy
3478    /// from a form alone, only from a preview that named who it would catch.
3479    pub fn preview_community_policy(&self, community_id: &str, bytes: &str) -> Result<serde_json::Value> {
3480        use crate::community::v2::guestbook::GuestbookEntry;
3481        let community = Self::load_held(community_id)?
3482            .ok_or_else(|| VectorError::Other("policies require a Concord v2 community".into()))?;
3483        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3484        let owner = community.owner().map_err(VectorError::Other)?;
3485        let me = state::my_public_key();
3486
3487        use crate::community::roles::Permissions;
3488        const MOD_MASK: u64 = Permissions::MANAGE_ROLES
3489            | Permissions::MANAGE_CHANNELS
3490            | Permissions::MANAGE_METADATA
3491            | Permissions::KICK
3492            | Permissions::BAN
3493            | Permissions::MANAGE_MESSAGES;
3494        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
3495        let staff: std::collections::HashSet<String> = roster
3496            .grants
3497            .iter()
3498            .filter(|g| {
3499                g.role_ids
3500                    .iter()
3501                    .any(|rid| roster.roles.iter().any(|r| &r.role_id == rid && (r.permissions.0 & MOD_MASK) != 0))
3502            })
3503            .map(|g| g.member.clone())
3504            .collect();
3505        let roles_of: std::collections::HashMap<String, Vec<String>> =
3506            roster.grants.iter().map(|g| (g.member.clone(), g.role_ids.clone())).collect();
3507
3508        let (events, _cursor) = crate::db::community::get_guestbook_shared(&cid_hex).unwrap_or_default();
3509        let mut joined_at: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
3510        let mut invite_label: std::collections::HashMap<String, String> = std::collections::HashMap::new();
3511        for e in events.iter() {
3512            let GuestbookEntry::Join { member, invited_by, at_ms } = &e.entry else { continue };
3513            let hex = member.to_hex();
3514            let slot = joined_at.entry(hex.clone()).or_insert(*at_ms);
3515            *slot = (*slot).min(*at_ms);
3516            if let Some((_c, label)) = invited_by {
3517                invite_label.entry(hex).or_insert_with(|| label.clone());
3518            }
3519        }
3520        let members: Vec<crate::community::policy::harness::MemberRow> =
3521            crate::community::v2::service::stored_memberlist(&community)
3522                .unwrap_or_default()
3523                .into_iter()
3524                .map(|pk| {
3525                    let hex = pk.to_hex();
3526                    (
3527                        pk,
3528                        joined_at.get(&hex).copied(),
3529                        staff.contains(&hex),
3530                        roles_of.get(&hex).cloned().unwrap_or_default(),
3531                        invite_label.get(&hex).cloned(),
3532                    )
3533                })
3534                .collect();
3535
3536        let now_ms = crate::clock::now_ms();
3537        let assembled =
3538            crate::community::policy::harness::assemble(&cid_hex, &owner, me.as_ref(), &members, now_ms)
3539                .map_err(VectorError::Other)?;
3540        let preview = crate::community::policy::harness::preview_policy(&assembled, bytes, now_ms);
3541        serde_json::to_value(preview).map_err(|e| VectorError::Other(e.to_string()))
3542    }
3543
3544    /// A community's policies, as stored. Returns the exact bytes, so an editor
3545    /// round-trips what was written rather than a re-serialization of it.
3546    pub fn list_community_policies(&self, community_id: &str) -> Result<serde_json::Value> {
3547        let community = Self::load_held(community_id)?
3548            .ok_or_else(|| VectorError::Other("policies require a Concord v2 community".into()))?;
3549        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3550        let stored = crate::db::community::get_community_policies(&cid_hex).map_err(VectorError::Other)?;
3551        let rows: Vec<serde_json::Value> = stored
3552            .iter()
3553            .map(|p| {
3554                // Report what the validator says NOW: a policy stored under an
3555                // older engine can stop validating, and a moderator must see
3556                // that rather than assume their rules are running.
3557                let verdict = serde_json::from_str::<crate::community::policy::document::Policy>(&p.bytes)
3558                    .map_err(|e| e.to_string())
3559                    .and_then(|doc| doc.validate().map_err(|r| format!("{r:?}")));
3560                serde_json::json!({
3561                    "policy_id": p.policy_id,
3562                    "hash": p.hash,
3563                    "enabled": p.enabled,
3564                    "updated_at": p.updated_at,
3565                    "bytes": p.bytes,
3566                    "valid": verdict.is_ok(),
3567                    "error": verdict.err(),
3568                })
3569            })
3570            .collect();
3571        Ok(serde_json::json!({
3572            "community_id": cid_hex,
3573            "policies": rows,
3574            // Must agree with `select_policies`, which is the thing that
3575            // actually decides: the shipped defaults run unless the community
3576            // has forked them. A flag derived any other way tells a moderator
3577            // their cover is on while the engine has stood it down.
3578            "using_builtin": !stored
3579                .iter()
3580                .any(|p| p.policy_id == crate::community::policy::harness::DEFAULTS_POLICY_ID),
3581        }))
3582    }
3583
3584    /// Store a policy, validating FIRST. An invalid policy is a rejected edit,
3585    /// never a stored one that quietly evaluates to nothing.
3586    pub fn set_community_policy(&self, community_id: &str, policy_id: &str, bytes: &str, enabled: bool) -> Result<serde_json::Value> {
3587        let community = Self::load_held(community_id)?
3588            .ok_or_else(|| VectorError::Other("policies require a Concord v2 community".into()))?;
3589        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3590        if bytes.len() > crate::community::policy::types::caps::MAX_POLICY_BYTES {
3591            return Err(VectorError::Other("policy exceeds the maximum document size".into()));
3592        }
3593        let doc: crate::community::policy::document::Policy =
3594            serde_json::from_str(bytes).map_err(|e| VectorError::Other(format!("policy is not valid JSON: {e}")))?;
3595        doc.validate().map_err(|r| VectorError::Other(format!("policy rejected: {r:?}")))?;
3596
3597        let hash = crate::community::policy::harness::hash_policy_bytes(bytes.as_bytes());
3598        let hash_hex = crate::simd::hex::bytes_to_hex_32(&hash.0);
3599        let now_secs = crate::clock::now_secs();
3600        crate::db::community::set_community_policy(&cid_hex, policy_id, bytes, &hash_hex, enabled, now_secs)
3601            .map_err(VectorError::Other)?;
3602        // The console must not keep serving verdicts from the rules that were
3603        // in force a minute ago.
3604        Self::invalidate_raid_report(&cid_hex);
3605        Ok(serde_json::json!({ "policy_id": policy_id, "hash": hash_hex, "enabled": enabled }))
3606    }
3607
3608    pub fn delete_community_policy(&self, community_id: &str, policy_id: &str) -> Result<()> {
3609        let community = Self::load_held(community_id)?
3610            .ok_or_else(|| VectorError::Other("policies require a Concord v2 community".into()))?;
3611        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3612        crate::db::community::delete_community_policy(&cid_hex, policy_id).map_err(VectorError::Other)?;
3613        Self::invalidate_raid_report(&cid_hex);
3614        Ok(())
3615    }
3616
3617    /// The built-in policy, as editable bytes — the starting point an editor
3618    /// offers instead of a blank document.
3619    pub fn builtin_policy_json(&self) -> Result<String> {
3620        serde_json::to_string_pretty(&crate::community::policy::harness::default_policy())
3621            .map_err(|e| VectorError::Other(e.to_string()))
3622    }
3623
3624    /// The moderation console's report, from the POLICY ENGINE. Memoised for
3625    /// [`RAID_REPORT_TTL_SECS`], same as the assessor it replaces.
3626    ///
3627    /// `raid.rs` still runs — [`Self::policy_side_by_side`] diffs the two — but
3628    /// the panel reads this. The engine earned it on live data: it clustered a
3629    /// real raid out of local storage and stayed silent on a healthy community
3630    /// across six runs.
3631    fn policy_console_report(cid_hex: &str, community: &crate::community::v2::community::CommunityV2) -> Result<std::sync::Arc<serde_json::Value>> {
3632        let now_secs = crate::clock::now_secs();
3633        report_once(&policy_report_cache(), &policy_report_gate(), cid_hex, now_secs, || {
3634            Self::evaluate_policy_console(cid_hex, community, now_secs)
3635        })
3636    }
3637
3638    fn evaluate_policy_console(
3639        cid_hex: &str,
3640        community: &crate::community::v2::community::CommunityV2,
3641        now_secs: u64,
3642    ) -> Result<std::sync::Arc<serde_json::Value>> {
3643        use crate::community::v2::guestbook::GuestbookEntry;
3644        let owner = community.owner().map_err(VectorError::Other)?;
3645        let me = state::my_public_key();
3646
3647        // Staff = a role carrying moderation permissions. NOT mere role
3648        // membership: a cosmetic or self-serve role must never confer immunity
3649        // from the rules this engine exists to enforce.
3650        use crate::community::roles::Permissions;
3651        const MOD_MASK: u64 = Permissions::MANAGE_ROLES
3652            | Permissions::MANAGE_CHANNELS
3653            | Permissions::MANAGE_METADATA
3654            | Permissions::KICK
3655            | Permissions::BAN
3656            | Permissions::MANAGE_MESSAGES;
3657        let roster = crate::db::community::get_community_roles(cid_hex).unwrap_or_default();
3658        let staff: std::collections::HashSet<String> = roster
3659            .grants
3660            .iter()
3661            .filter(|g| {
3662                g.role_ids
3663                    .iter()
3664                    .any(|rid| roster.roles.iter().any(|r| &r.role_id == rid && (r.permissions.0 & MOD_MASK) != 0))
3665            })
3666            .map(|g| g.member.clone())
3667            .collect();
3668        let roles_of: std::collections::HashMap<String, Vec<String>> =
3669            roster.grants.iter().map(|g| (g.member.clone(), g.role_ids.clone())).collect();
3670
3671        let (events, _cursor) = crate::db::community::get_guestbook(cid_hex).unwrap_or_default();
3672        let mut joined_at: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
3673        let mut invite_label: std::collections::HashMap<String, String> = std::collections::HashMap::new();
3674        for e in &events {
3675            let GuestbookEntry::Join { member, invited_by, at_ms } = &e.entry else { continue };
3676            let hex = member.to_hex();
3677            // Earliest join wins: a rejoin must not erase real tenure.
3678            let slot = joined_at.entry(hex.clone()).or_insert(*at_ms);
3679            *slot = (*slot).min(*at_ms);
3680            if let Some((_creator, label)) = invited_by {
3681                invite_label.entry(hex).or_insert_with(|| label.clone());
3682            }
3683        }
3684
3685        let members: Vec<crate::community::policy::harness::MemberRow> =
3686            crate::community::v2::service::stored_memberlist(community)
3687                .unwrap_or_default()
3688                .into_iter()
3689                .map(|pk| {
3690                    let hex = pk.to_hex();
3691                    (
3692                        pk,
3693                        joined_at.get(&hex).copied(),
3694                        staff.contains(&hex),
3695                        roles_of.get(&hex).cloned().unwrap_or_default(),
3696                        invite_label.get(&hex).cloned(),
3697                    )
3698                })
3699                .collect();
3700
3701        let now_ms = now_secs.saturating_mul(1000);
3702        let assembled =
3703            crate::community::policy::harness::assemble(cid_hex, &owner, me.as_ref(), &members, now_ms)
3704                .map_err(VectorError::Other)?;
3705        Ok(std::sync::Arc::new(
3706            crate::community::policy::harness::evaluate_for_console(cid_hex, &assembled, now_ms)
3707                .map_err(VectorError::Other)?,
3708        ))
3709    }
3710
3711    /// Run the policy engine beside the shipped assessor and report where they
3712    /// disagree. Diagnostic only: the engine convicts nothing in production
3713    /// until this diff has been read against real data.
3714    pub fn policy_side_by_side(&self, community_id: &str) -> Result<serde_json::Value> {
3715        use crate::community::v2::guestbook::GuestbookEntry;
3716        use nostr_sdk::prelude::PublicKey;
3717        let community = Self::load_held(community_id)?
3718            .ok_or_else(|| VectorError::Other("moderation tools require a Concord v2 community".into()))?;
3719        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3720        let owner = community.owner().map_err(VectorError::Other)?;
3721
3722        // The moderation permission bits: holding one of these is staff. Mere
3723        // role membership is NOT — a cosmetic role must not confer immunity.
3724        use crate::community::roles::Permissions;
3725        const MOD_MASK: u64 = Permissions::MANAGE_ROLES
3726            | Permissions::MANAGE_CHANNELS
3727            | Permissions::MANAGE_METADATA
3728            | Permissions::KICK
3729            | Permissions::BAN
3730            | Permissions::MANAGE_MESSAGES;
3731        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
3732        let staff: std::collections::HashSet<String> = roster
3733            .grants
3734            .iter()
3735            .filter(|g| {
3736                g.role_ids.iter().any(|rid| {
3737                    roster.roles.iter().any(|r| &r.role_id == rid && (r.permissions.0 & MOD_MASK) != 0)
3738                })
3739            })
3740            .map(|g| g.member.clone())
3741            .collect();
3742        let roles_of: std::collections::HashMap<String, Vec<String>> =
3743            roster.grants.iter().map(|g| (g.member.clone(), g.role_ids.clone())).collect();
3744
3745        let (events, _cursor) = crate::db::community::get_guestbook_shared(&cid_hex).unwrap_or_default();
3746        let mut joined_at: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
3747        for e in events.iter() {
3748            let GuestbookEntry::Join { member, at_ms, .. } = &e.entry else { continue };
3749            let hex = member.to_hex();
3750            let slot = joined_at.entry(hex).or_insert(*at_ms);
3751            *slot = (*slot).min(*at_ms);
3752        }
3753
3754        let members: Vec<(PublicKey, Option<u64>, bool, Vec<String>)> =
3755            crate::community::v2::service::stored_memberlist(&community)
3756                .unwrap_or_default()
3757                .into_iter()
3758                .map(|pk| {
3759                    let hex = pk.to_hex();
3760                    (pk, joined_at.get(&hex).copied(), staff.contains(&hex), roles_of.get(&hex).cloned().unwrap_or_default())
3761                })
3762                .collect();
3763
3764        // The assessor's own verdicts, for the diff.
3765        let assessments: Vec<(String, String)> = Self::raid_report(&cid_hex)
3766            .map(|r| {
3767                r.members
3768                    .iter()
3769                    .map(|m| (m.npub.clone(), format!("{:?}", m.verdict).to_lowercase()))
3770                    .collect()
3771            })
3772            .unwrap_or_default();
3773
3774        let now_ms = crate::clock::now_ms();
3775        let diff = crate::community::policy::harness::run_side_by_side(
3776            &cid_hex, &owner, &members, &assessments, now_ms,
3777        )
3778        .map_err(VectorError::Other)?;
3779        serde_json::to_value(diff).map_err(|e| VectorError::Other(e.to_string()))
3780    }
3781
3782    /// Drop a community's memoised verdict. Every moderation action changes who is a
3783    /// member, so serving the pre-action answer would leave the badge accusing people
3784    /// who are already gone.
3785    pub fn invalidate_raid_report(community_id: &str) {
3786        policy_report_cache().lock().unwrap_or_else(|e| e.into_inner()).remove(community_id);
3787        raid_report_cache().lock().unwrap_or_else(|e| e.into_inner()).remove(community_id);
3788    }
3789
3790    /// Rotate the Community's keys with no banlist edit: mint a new root epoch that
3791    /// only `retain` can follow. This is the containment that scales — a wave of
3792    /// thousands cannot fit in a 500-entry banlist, but it can be locked out of the
3793    /// next epoch in one publish. `retain` is a keep-list; everyone else is cut.
3794    ///
3795    /// Passing an empty `retain` rotates without removing anyone, which is what you
3796    /// want when the invite link leaked but the members are all real.
3797    pub async fn refound_community(&self, community_id: &str, retain: &[&str]) -> Result<()> {
3798        let community = Self::load_held(community_id)?
3799            .ok_or_else(|| VectorError::Other("re-founding requires a Concord v2 community".into()))?;
3800        let removed = Self::members_to_remove(&community, retain)?;
3801        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(30));
3802        crate::community::v2::service::refound_community(&transport, &community, &removed)
3803            .await
3804            .map_err(VectorError::Other)?;
3805        // The cut changed who is a member; the memoised verdict still names them.
3806        Self::invalidate_raid_report(community_id);
3807        Ok(())
3808    }
3809
3810    /// The members a `retain` keep-list would cut.
3811    ///
3812    /// Folded from the LOCAL store, and that is not an oversight. The network memberlist
3813    /// is epoch-scoped — its Guestbook plane holds only the current epoch's snapshot, and
3814    /// its channel reads only return what is decryptable now — so members stranded on a
3815    /// buried epoch are already absent from it. Those are precisely the phantoms this
3816    /// panel exists to clear: they survive ONLY in the local store, which accumulates
3817    /// across epochs. Folding the network list here returns an empty removal set and the
3818    /// sweep does nothing.
3819    ///
3820    /// The two lists answer different questions and must not be unified. "Who receives a
3821    /// new key" is the rotation's own network fold, which it does for itself. "Who is a
3822    /// phantom to evict" is this one, and being local-only is the definition of it.
3823    ///
3824    /// An empty `retain` removes nobody — a rotation for its own sake. You and the owner
3825    /// are never in the result: a keep-list omitting either is a caller mistake, and
3826    /// honouring it would lock the community's own staff out of an epoch they just minted.
3827    fn members_to_remove(
3828        community: &crate::community::v2::community::CommunityV2,
3829        retain: &[&str],
3830    ) -> Result<Vec<nostr_sdk::prelude::PublicKey>> {
3831        use nostr_sdk::prelude::PublicKey;
3832        let keep: std::collections::HashSet<PublicKey> =
3833            retain.iter().filter_map(|n| PublicKey::parse(n).ok()).collect();
3834        if keep.is_empty() {
3835            return Ok(Vec::new());
3836        }
3837        let me = state::my_public_key();
3838        let owner = community.owner().ok();
3839        Ok(crate::community::v2::service::stored_memberlist(community)
3840            .map_err(VectorError::Other)?
3841            .into_iter()
3842            .filter(|pk| !keep.contains(pk))
3843            .filter(|pk| Some(*pk) != me && Some(*pk) != owner)
3844            .collect())
3845    }
3846
3847    /// Rotate the keys around the survivors, then kick the removed off the roster.
3848    ///
3849    /// The order is load-bearing, and it is ROTATE FIRST. A Guestbook plane is derived
3850    /// per epoch, so kicks published before the rotation land on a plane the rotation
3851    /// immediately buries: every reader then has to receive them in the window before it
3852    /// follows the rekey, and whatever is still in flight is never folded by anyone.
3853    /// Publishing onto the NEW epoch instead puts the departures on the plane every
3854    /// survivor will read from now on, so a client that catches up an hour later still
3855    /// folds them. It also closes the re-admission window — the removed hold no key at
3856    /// the new epoch, so they cannot post their way back into the memberlist between
3857    /// their own kick and the rotation.
3858    ///
3859    /// The rotation alone would not clear the roster: the guestbook store is keyed by
3860    /// community and appended across epochs, and the memberlist re-admits observed
3861    /// authors from local history regardless of epoch. The kicks are what evict them.
3862    pub async fn purge_and_refound(
3863        &self,
3864        community_id: &str,
3865        retain: &[&str],
3866        on_progress: &(dyn Fn(usize, usize) + Sync),
3867    ) -> Result<serde_json::Value> {
3868        let community = Self::load_held(community_id)?
3869            .ok_or_else(|| VectorError::Other("re-founding requires a Concord v2 community".into()))?;
3870        let removed = Self::members_to_remove(&community, retain)?;
3871        // The operator's list IS the recipient set. `removed` is derived from the
3872        // memberlist at THIS instant and only drives the kick sweep below; the refound
3873        // fetches its own, later. Passing removal alone let an account that appeared in
3874        // between be vended a key by default — implicitly retained by the purge.
3875        let keep: Vec<nostr_sdk::prelude::PublicKey> = retain
3876            .iter()
3877            .filter_map(|n| nostr_sdk::prelude::PublicKey::parse(n).ok())
3878            .collect();
3879        log_info!("[Moderation] purge: {} to remove, {} retained", removed.len(), keep.len());
3880        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(30));
3881        // An EMPTY retain means "cut nobody", not "keep nobody".
3882        //
3883        // The two lines above read the same empty list in opposite directions:
3884        // `members_to_remove` correctly removes nobody, while `keep` becomes an empty
3885        // ALLOW-LIST — and an allow-list keeps only this device and the owner, so a
3886        // plain "Rotate keys" vended to two people and stranded everyone else at the
3887        // previous epoch, permanently. It presented as members vanishing from the
3888        // list some time later, nowhere near the button that did it.
3889        //
3890        // A purge is the caller NAMING who stays. Nobody named is not a purge.
3891        if keep.is_empty() {
3892            crate::community::v2::service::refound_community(&transport, &community, &removed)
3893                .await
3894                .map_err(VectorError::Other)?;
3895        } else {
3896            crate::community::v2::service::refound_community_retaining(&transport, &community, &removed, &keep)
3897                .await
3898                .map_err(VectorError::Other)?;
3899        }
3900        // Re-load onto the epoch the rotation just minted: kicking against the stale
3901        // struct would address the plane we just buried, which is the whole bug this
3902        // ordering exists to avoid.
3903        let fresh = Self::load_held(community_id)?
3904            .ok_or_else(|| VectorError::Other("community gone during the purge".into()))?;
3905        let sweep = crate::community::v2::service::kick_members(&transport, &fresh, &removed, on_progress)
3906            .await
3907            .map_err(VectorError::Other)?;
3908        // Fold our own directives back. Without this the local roster only shows what
3909        // the live subscription happened to echo before the sweep finished.
3910        let _ = crate::community::v2::service::sync_guestbook(&transport, &fresh).await;
3911        log_info!(
3912            "[Moderation] purge: rotated to epoch {}, kicked {}/{} ({} refused, {} failed)",
3913            fresh.root_epoch.0,
3914            sweep.kicked.len(),
3915            removed.len(),
3916            sweep.refused.len(),
3917            sweep.failed.len()
3918        );
3919        Ok(serde_json::json!({
3920            "kicked": sweep.kicked.len(),
3921            "refused": sweep.refused.len(),
3922            "failed": sweep.failed.len(),
3923            "rotated": true,
3924        }))
3925    }
3926
3927    /// Kick many members without rotating. Exposed for callers that want the roster
3928    /// cleaned but the keys left alone.
3929    pub async fn kick_community_members(
3930        &self,
3931        community_id: &str,
3932        npubs: &[&str],
3933        on_progress: &(dyn Fn(usize, usize) + Sync),
3934    ) -> Result<serde_json::Value> {
3935        let community = Self::load_held(community_id)?
3936            .ok_or_else(|| VectorError::Other("kicking requires a Concord v2 community".into()))?;
3937        use nostr_sdk::prelude::PublicKey;
3938        let targets: Vec<PublicKey> = npubs.iter().filter_map(|n| PublicKey::parse(n).ok()).collect();
3939        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(30));
3940        let sweep = crate::community::v2::service::kick_members(&transport, &community, &targets, on_progress)
3941            .await
3942            .map_err(VectorError::Other)?;
3943        let _ = crate::community::v2::service::sync_guestbook(&transport, &community).await;
3944        log_info!(
3945            "[Moderation] kick sweep: {}/{} kicked ({} refused, {} failed)",
3946            sweep.kicked.len(),
3947            targets.len(),
3948            sweep.refused.len(),
3949            sweep.failed.len()
3950        );
3951        Self::invalidate_raid_report(community_id);
3952        Ok(serde_json::json!({
3953            "kicked": sweep.kicked.len(),
3954            "refused": sweep.refused.iter().map(|(_, why)| why.clone()).collect::<Vec<_>>(),
3955            "failed": sweep.failed.len(),
3956        }))
3957    }
3958
3959    /// Retire every public invite link this Community holds. A raid arrives through a
3960    /// link, and revoking them one at a time loses the race — the whole set has to go
3961    /// in one pass before the rotation, or the next wave walks in through the survivor.
3962    /// Returns `(revoked, failed)`.
3963    pub async fn revoke_all_public_invites(&self, community_id: &str) -> Result<(usize, usize)> {
3964        let tokens: Vec<String> = crate::db::community::list_public_invites(community_id)
3965            .map_err(VectorError::Other)?
3966            .into_iter()
3967            .map(|i| i.token)
3968            .collect();
3969        let mut revoked = 0usize;
3970        let mut failed = 0usize;
3971        for token in &tokens {
3972            match self.revoke_public_invite(community_id, token).await {
3973                Ok(()) => revoked += 1,
3974                Err(_) => failed += 1,
3975            }
3976        }
3977        Ok((revoked, failed))
3978    }
3979
3980    /// One synchronous v2 follow pass — rekeys first (a base adopt moves the
3981    /// control address), then a control refold on the FRESH state, the same order
3982    /// the live follow worker runs. Returns non-fatal warnings.
3983    /// Walk one community's rekeys + control fold NOW, serialized against the live
3984    /// follow worker by the per-community lock. Public so boot can converge a community
3985    /// the probe saw move BEFORE paging its content — content read at a superseded
3986    /// epoch is wasted work, and may not open at all.
3987    pub async fn v2_inline_follow(id: &crate::community::CommunityId) -> Vec<String> {
3988        crate::db::scoped(async move {
3989            use crate::community::transport::LiveTransport;
3990            let session = crate::db::current_session();
3991            // Serialize with the live follow worker: `follow_worker_running` is
3992            // check-then-act, so a worker can spawn right after a caller saw `false` —
3993            // this shared per-community lock is what actually prevents two follows of
3994            // one community interleaving their whole-row saves.
3995            let lock = crate::community::v2::realtime::follow_lock(id);
3996            let _guard = lock.lock().await;
3997            let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
3998            let mut warnings: Vec<String> = Vec::new();
3999            let Ok(Some(community)) = crate::db::community::load_community_v2(id) else {
4000                warnings.push("v2 community not found".to_string());
4001                return warnings;
4002            };
4003            let cid_hex = crate::simd::hex::bytes_to_hex_32(&id.0);
4004            match crate::community::v2::service::follow_rekeys(&transport, &community, &session).await {
4005                // A tombstone surfaced during catch-up — sealed read-only; stop here.
4006                Ok(f) if f.dissolved => return warnings,
4007                Ok(f) if f.self_removed => {
4008                    // An authorized rotation that excluded us IS a removal — but keep the
4009                    // epoch keys, exactly as every other self-removal path does. They grant
4010                    // no future read (post-removal keys are never delivered); dropping them
4011                    // only destroys the ability to author a 3305 self-delete of our OWN past
4012                    // messages, each sealed under the epoch it was sent at. That is the one
4013                    // thing a removed member should still be able to do — and doubly so if
4014                    // the removal turns out to have been a false positive.
4015                    let _ = crate::db::community::delete_community_retain_keys(&cid_hex);
4016                    return warnings;
4017                }
4018                Ok(_) => {}
4019                Err(e) => warnings.push(format!("v2 rekey follow failed: {e}")),
4020            }
4021            if let Ok(Some(fresh)) = crate::db::community::load_community_v2(id) {
4022                match crate::community::v2::service::follow_control(&transport, &fresh).await {
4023                    // Walk the rekeys once more whenever the control fold moved ANYTHING.
4024                    // The document half reveals rekey work that predates it (a just-announced
4025                    // private channel's key crate already sits on its rekey plane). The
4026                    // AUTHORITY half is the one that strands: the walk above gates every
4027                    // rotation on the roster and citation heads this fold just wrote, so a
4028                    // promote-then-rotate is refused on pass 1 and, without this, never
4029                    // reconsidered. Re-read from the DB — the authority half moves columns
4030                    // the returned document does not carry.
4031                    Ok(control) if control.moved() => {
4032                        if let Ok(Some(latest)) = crate::db::community::load_community_v2(id) {
4033                            if let Err(e) = crate::community::v2::service::follow_rekeys(&transport, &latest, &session).await {
4034                                warnings.push(format!("v2 rekey follow failed: {e}"));
4035                            }
4036                        }
4037                    }
4038                    Ok(_) => {}
4039                    Err(e) => warnings.push(format!("v2 control follow failed: {e}")),
4040                }
4041            }
4042            // Banned by the freshly-folded banlist: a removal just like the rotation
4043            // exclusion above, and it arrives FIRST (CORD-04 §6 orders the Banlist edition
4044            // before the Refounding), so keying removal solely off the rotation leaves a
4045            // banned headless client running against a community that already dropped it.
4046            if let Some(me) = crate::my_public_key() {
4047                if crate::db::community::is_author_banned(&cid_hex, &me) {
4048                    let _ = crate::db::community::delete_community_retain_keys(&cid_hex);
4049                    return warnings;
4050                }
4051            }
4052            // As the live follow does: what a fold here undid is taken back, and what waited is judged again.
4053            let quiet = crate::event_handler::NoOpEventHandler;
4054            if let Ok(Some(folded)) = crate::db::community::load_community_v2(id) {
4055                crate::community::v2::service::owe_new_departures(&folded);
4056            }
4057            crate::community::v2::realtime::settle_owed_retractions(id, &transport, &quiet).await;
4058            if let Ok(Some(folded)) = crate::db::community::load_community_v2(id) {
4059                crate::community::v2::service::rejudge_held(&folded, &quiet).await;
4060            }
4061            warnings
4062        })
4063        .await
4064    }
4065
4066    /// Fetch a channel's recent chat history and PERSIST it into the shared events
4067    /// tables, so `get_messages`/`get_new_messages` backfill. PAGES backwards until it reaches messages it already holds
4068    /// (bounded), so a reconnecting bot that slept through more than one page of traffic
4069    /// still catches the whole gap instead of only the newest `limit`. Reuses the v2
4070    /// inbound bridge (dedup + STATE aggregate) + the shared save path. Returns the count of
4071    /// brand-new messages applied. Best-effort: a fetch failure is 0.
4072    /// Reconnect/boot catch-up for one v2 channel: fetches the newest pages
4073    /// and PAGES backwards until it reaches messages it already holds, then
4074    /// ingests through the shared pipeline. The boot volley fetches its own
4075    /// batches and shares only [`Self::v2_ingest_chat_page`].
4076    #[allow(clippy::too_many_arguments)]
4077    pub(crate) async fn v2_backfill_channel(
4078        id: &crate::community::CommunityId,
4079        channel_id: &str,
4080        limit: usize,
4081        max_pages: usize,
4082        since: Option<u64>,
4083        until: Option<u64>,
4084        evidence: crate::community::transport::Evidence,
4085        transport_secs: u64,
4086    ) -> usize {
4087        // A caller that takes only a count can't page on from where the relay walk stopped: go on
4088        // from there a few times, or what a quieter address held below it would wait for a scroll.
4089        let (mut new, mut until) = (0, until);
4090        let mut waiting = Vec::new();
4091        for _ in 0..BACKFILL_CONTINUATIONS {
4092            let (count, still) = Self::v2_backfill_window(id, channel_id, limit, max_pages, since, until, evidence, transport_secs).await;
4093            new += count.new_messages;
4094            waiting.extend(still);
4095            match count.next_before {
4096                Some(next) if until.is_none_or(|u| next < u) => until = Some(next),
4097                _ => break,
4098            }
4099        }
4100        // Newest first, so a reaction, edit or delete can arrive a window before its target: once
4101        // every window has landed, it lands too.
4102        if !waiting.is_empty() {
4103            if let Some(me) = state::my_public_key() {
4104                Self::v2_ingest_chat_page_waiting(channel_id, me, crate::db::current_session(), waiting).await;
4105            }
4106        }
4107        new
4108    }
4109
4110    /// [`v2_backfill_channel`](Self::v2_backfill_channel) reporting what the RELAY
4111    /// served as well as what was new. A back-page over history we already hold is
4112    /// new-count 0 with a non-empty fetch, so only `fetched` can answer "is there
4113    /// anything older" — new-count alone stops a scroll at the first known page.
4114    #[allow(clippy::too_many_arguments)]
4115    pub(crate) async fn v2_backfill_channel_counted(
4116        id: &crate::community::CommunityId,
4117        channel_id: &str,
4118        limit: usize,
4119        max_pages: usize,
4120        since: Option<u64>,
4121        until: Option<u64>,
4122        evidence: crate::community::transport::Evidence,
4123        transport_secs: u64,
4124    ) -> BackfillCount {
4125        Self::v2_backfill_window(id, channel_id, limit, max_pages, since, until, evidence, transport_secs).await.0
4126    }
4127
4128    /// [`v2_backfill_channel_counted`](Self::v2_backfill_channel_counted), with the reactions,
4129    /// edits and deletes whose target the window didn't hold.
4130    #[allow(clippy::too_many_arguments)]
4131    async fn v2_backfill_window(
4132        id: &crate::community::CommunityId,
4133        channel_id: &str,
4134        limit: usize,
4135        max_pages: usize,
4136        since: Option<u64>,
4137        until: Option<u64>,
4138        evidence: crate::community::transport::Evidence,
4139        transport_secs: u64,
4140    ) -> (BackfillCount, Vec<crate::community::v2::service::FetchedEvent>) {
4141        // Guard straddles the fetch: a swap mid-fetch must not persist account A's chat
4142        // into account B's STATE/DB (the message ids are global).
4143        let session = crate::db::current_session();
4144        let Some(my_pk) = state::my_public_key() else { return (BackfillCount::default(), Vec::new()) };
4145        // CORD-02 §9: a dissolved community honors no NEW events — old history reads
4146        // through the explicit paths, but a catch-up sweep must not ingest anything
4147        // authored into the grave.
4148        if crate::db::community::get_community_dissolved(&crate::simd::hex::bytes_to_hex_32(&id.0)).unwrap_or(false) {
4149            return (BackfillCount::default(), Vec::new());
4150        }
4151        let Ok(Some(community)) = crate::db::community::load_community_v2(id) else { return (BackfillCount::default(), Vec::new()) };
4152        let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
4153        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(transport_secs));
4154        let held = std::sync::atomic::AtomicUsize::new(0);
4155        let began = crate::clock::now_secs();
4156        let floor = crate::history_gaps::floor(channel_id, until, began);
4157        let reach = crate::history_gaps::reach(since, floor);
4158        let live = community.channel(&ch).map_or(community.root_epoch, |c| community.channel_secret(c).1);
4159        // Epochs adopted since the proof are read whole. Unproven, the last few from the floor:
4160        // a week rarely holds more rotations.
4161        let past = until.is_none().then(|| match crate::history_gaps::proven_epoch(channel_id) {
4162            Some(e) => (crate::community::Epoch(e), since),
4163            None => (crate::community::Epoch(live.0.saturating_sub(UNPROVEN_EPOCHS)), reach),
4164        });
4165        // Published planes, and past epochs delivered read-only, that nothing here read: what they
4166        // hold predates everything this device has, so they are read whole.
4167        let unread: Vec<nostr_sdk::prelude::PublicKey> = match community.channel(&ch).filter(|_| until.is_none()) {
4168            Some(c) => {
4169                let read = crate::history_gaps::history_read(channel_id);
4170                let cid_hex = crate::simd::hex::bytes_to_hex_32(&id.0);
4171                let views = crate::db::community::history_views(&cid_hex, channel_id).unwrap_or_default().into_iter().filter_map(|(_, v)| nostr_sdk::prelude::PublicKey::from_slice(&v.address).ok());
4172                c.published_history().into_iter().map(|(_, g)| g.pk()).chain(views).filter(|pk| !read.contains(&pk.to_hex())).collect()
4173            }
4174            None => Vec::new(),
4175        };
4176        let Ok((page, next_before, complete)) = crate::community::v2::service::fetch_channel_history_since_epoch(
4177            &transport,
4178            &community,
4179            &ch,
4180            limit.max(50),
4181            max_pages,
4182            reach,
4183            until,
4184            evidence,
4185            // A settled wrap is a held row, which decides the page like a held message.
4186            |page, settled, next| {
4187                crate::community::v2::service::catch_up_pages_on(page, settled, next, floor, |id| crate::db::events::event_exists(id).unwrap_or(false))
4188            },
4189            // Only a catch-up skips what it holds: a back-page feeds the reader what it scrolled to.
4190            |wraps| {
4191                if until.is_some() {
4192                    return Default::default();
4193                }
4194                let hex: Vec<String> = wraps.iter().map(|w| w.to_hex()).collect();
4195                let settled = crate::db::events::community_wraps_settled(&hex);
4196                let skip: std::collections::HashSet<_> = wraps.iter().zip(&hex).filter(|(_, h)| settled.contains(*h)).map(|(w, _)| *w).collect();
4197                held.fetch_add(skip.len(), std::sync::atomic::Ordering::Relaxed);
4198                skip
4199            },
4200            past,
4201            &unread,
4202        )
4203        .await
4204        else {
4205            return (BackfillCount { unreachable: true, ..Default::default() }, Vec::new());
4206        };
4207        let fetched = page.len() + held.into_inner();
4208        let (new_messages, waiting) = Self::v2_ingest_chat_page_keeping(channel_id, my_pk, session, page).await;
4209        // A walk that stops while still finding new messages leaves a hole above what it held.
4210        crate::history_gaps::note_walk(channel_id, until, next_before, floor, |t| crate::db::events::newest_message_before(channel_id, t));
4211        // From the top, everything down to the floor is now read or in the ledger: proven once every
4212        // relay answered, so one that didn't is read from the old floor next time.
4213        if until.is_none() && since.is_none() && complete {
4214            crate::history_gaps::prove(channel_id, began, live.0);
4215        }
4216        // Read to their end or to where an older page goes on from: either way, read.
4217        if complete && !unread.is_empty() {
4218            crate::history_gaps::mark_history_read(channel_id, unread.iter().map(|pk| pk.to_hex()));
4219        }
4220        (BackfillCount { fetched, new_messages, next_before, unreachable: false }, waiting)
4221    }
4222
4223    /// Ingest a fetched chat page: STATE apply, batched persist with delete
4224    /// barriers, then UI surfacing — shared by the reconnect backfill and the
4225    /// boot volley's batched paint path.
4226    pub(crate) async fn v2_ingest_chat_page(
4227        channel_id: &str,
4228        my_pk: nostr_sdk::prelude::PublicKey,
4229        session: std::sync::Arc<crate::db::Session>,
4230        page: Vec<crate::community::v2::service::FetchedEvent>,
4231    ) -> usize {
4232        Self::v2_ingest_chat_page_keeping(channel_id, my_pk, session, page).await.0
4233    }
4234
4235    /// Ingest reactions, edits and deletes kept back by [`v2_ingest_chat_page_keeping`] once more.
4236    async fn v2_ingest_chat_page_waiting(
4237        channel_id: &str,
4238        my_pk: nostr_sdk::prelude::PublicKey,
4239        session: std::sync::Arc<crate::db::Session>,
4240        page: Vec<crate::community::v2::service::FetchedEvent>,
4241    ) {
4242        Self::v2_ingest_chat_page_keeping(channel_id, my_pk, session, page).await;
4243    }
4244
4245    /// [`v2_ingest_chat_page`](Self::v2_ingest_chat_page), returning as well the reactions, edits
4246    /// and deletes that wait on a target nothing holds yet.
4247    async fn v2_ingest_chat_page_keeping(
4248        channel_id: &str,
4249        my_pk: nostr_sdk::prelude::PublicKey,
4250        session: std::sync::Arc<crate::db::Session>,
4251        page: Vec<crate::community::v2::service::FetchedEvent>,
4252    ) -> (usize, Vec<crate::community::v2::service::FetchedEvent>) {
4253        crate::db::scoped(async move {
4254            use crate::community::v2::inbound::ChatPersist;
4255            let judged_on = crate::community::v2::service::writers_head(channel_id);
4256            let page = crate::community::v2::service::rejudge_page(channel_id, page);
4257            let since = page.iter().map(|f| f.event.opened().at_ms).min();
4258            let posted: Vec<(nostr_sdk::prelude::PublicKey, u64)> = page.iter().filter(|f| matches!(f.event, crate::community::v2::chat::ChatEvent::Message { .. } | crate::community::v2::chat::ChatEvent::Edit { .. })).map(|f| (f.event.opened().author, f.event.opened().at_ms)).collect();
4259            let mut new = 0usize;
4260            let mut unapplied: Vec<usize> = Vec::new();
4261            // Pass 1 — apply to STATE (per-item lock) and COLLECT outcomes in wire order.
4262            let mut outcomes: Vec<ChatPersist> = Vec::with_capacity(page.len());
4263            // The page index each outcome came from.
4264            let mut sources: Vec<usize> = Vec::with_capacity(page.len());
4265            let stored = crate::db::events::existing_event_ids(&crate::community::v2::inbound::page_event_ids(page.iter().map(|f| &f.event))).unwrap_or_default();
4266            for (i, f) in page.iter().enumerate() {
4267                // A backfilled WebXDC peer ad persists through the shared 30078 row
4268                // (recency-gated at read) so a reopening lobby lists peers who
4269                // advertised while this device was closed. Own
4270                // echoes drop; the ad is not a chat row.
4271                if let crate::community::v2::chat::ChatEvent::Webxdc { opened } = &f.event {
4272                    if opened.author != my_pk {
4273                        if let Some((topic, addr)) = crate::webxdc::parse_peer_signal(&opened.rumor.content) {
4274                            let Ok(npub) = ToBech32::to_bech32(&opened.author);
4275                            crate::community::v2::inbound::persist_webxdc_signal(
4276                                channel_id,
4277                                &npub,
4278                                &topic,
4279                                addr.as_deref(),
4280                                &opened.rumor_id.to_hex(),
4281                                opened.at_ms / 1000,
4282                            )
4283                            .await;
4284                        }
4285                    }
4286                    continue;
4287                }
4288                crate::community::v2::inbound::hydrate_target(&f.event, channel_id).await;
4289                let outcome = {
4290                    let mut st = state::STATE.lock().await;
4291                    crate::community::v2::inbound::apply_page_event_to_state(&mut st, &f.event, channel_id, &my_pk, &stored)
4292                };
4293                match outcome {
4294                    Some(outcome) => {
4295                        if matches!(outcome, ChatPersist::New(_)) {
4296                            new += 1;
4297                        }
4298                        outcomes.push(outcome);
4299                        sources.push(i);
4300                    }
4301                    None if matches!(f.event, crate::community::v2::chat::ChatEvent::Reaction { .. } | crate::community::v2::chat::ChatEvent::Edit { .. } | crate::community::v2::chat::ChatEvent::Delete { .. }) => unapplied.push(i),
4302                    None => {}
4303                }
4304            }
4305            // Pass 2 — persist: message saves COLLECT into batched transactions; deletes are
4306            // flush barriers (a save committing after a delete it preceded on the wire would
4307            // resurrect the deleted row). One tx per page in the common no-delete case.
4308            // Bytes we already hold verify at arrival (indexed probe first, hash
4309            // only on a plausible candidate), mirroring the DM ingest — the batch
4310            // below borrows, so claims convert here while outcomes are still owned.
4311            for o in &mut outcomes {
4312                if let ChatPersist::New(m) | ChatPersist::Updated { message: m, .. } = o {
4313                    crate::db::attachments::verify_message_attachments(m, Some(channel_id)).await;
4314                }
4315            }
4316            crate::community::v2::inbound::persist_chat_page(channel_id, &outcomes, &session).await;
4317            if let Some(since) = since {
4318                crate::community::v2::service::owe_if_moved(channel_id, judged_on, since);
4319            }
4320            crate::community::v2::service::owe_if_departed(channel_id, &posted);
4321            // Resolve each reply's quote before the emit: the renderer has no other source
4322            // for a parent outside its window and never retries. Placed AFTER the persists
4323            // so a parent carried by this same page resolves too. One query per page.
4324            {
4325                let quoted: Vec<&mut crate::types::Message> = outcomes
4326                    .iter_mut()
4327                    .filter_map(|o| match o {
4328                        ChatPersist::New(m)
4329                        | ChatPersist::Updated { message: m, .. }
4330                        | ChatPersist::ReactionRemoved { message: m, .. } => Some(m),
4331                        ChatPersist::Removed { .. } => None,
4332                    })
4333                    .collect();
4334                let _ = crate::db::events::populate_reply_contexts(quoted).await;
4335            }
4336            // Pass 3 — surface to the live UI, mirroring the live dispatch handler:
4337            // a silent DB-only backfill left the chat-list preview, unread badge, and sort order
4338            // stale until the channel was opened. Raw emits (no notification ping) — a boot
4339            // catch-up must not fire an OS ping per message. Headless consumers register no
4340            // emitter, so these are a no-op there. After the persists so nothing surfaces unsaved.
4341            for outcome in &outcomes {
4342                match outcome {
4343                    ChatPersist::New(msg) => crate::traits::emit_message_new(channel_id, msg),
4344                    ChatPersist::Updated { message, .. }
4345                    | ChatPersist::ReactionRemoved { message, .. } => {
4346                        let mut message = message.clone();
4347                        let target_id = message.id.clone();
4348                        crate::traits::emit_message_update(channel_id, &target_id, &mut message).await;
4349                    }
4350                    ChatPersist::Removed { id: target_id, .. } => crate::traits::emit_event(
4351                        "message_removed",
4352                        &serde_json::json!({ "id": target_id, "chat_id": channel_id, "reason": "deleted" }),
4353                    ),
4354                }
4355            }
4356            // A listener hears what it hadn't yet: a page can be the only path a message sent
4357            // while this device was away, or still subscribing, ever takes.
4358            if let Some(listener) = crate::news::listener() {
4359                for (outcome, i) in outcomes.into_iter().zip(sources) {
4360                    let event = &page[i].event;
4361                    let at = match &outcome {
4362                        ChatPersist::New(m) => m.at,
4363                        _ => event.opened().at_ms,
4364                    };
4365                    if crate::news::is_news(at) {
4366                        crate::community::v2::inbound::notify_chat_outcome(&*listener, channel_id, event, outcome, true).await;
4367                    }
4368                }
4369            }
4370            let mut waiting = Vec::new();
4371            for i in unapplied {
4372                let f = &page[i];
4373                if crate::community::v2::inbound::awaits_target(&f.event).await {
4374                    waiting.push(crate::community::v2::service::FetchedEvent { event: f.event.clone(), epoch: f.epoch, wrap: f.wrap.clone() });
4375                }
4376            }
4377            (new, waiting)
4378        })
4379        .await
4380    }
4381
4382    /// The held community `community_id` names, or `Ok(None)`. A DB read error
4383    /// PROPAGATES (fail-closed) rather than reading as "unknown".
4384    /// A community id read from the caller, for one this device no longer holds.
4385    fn unheld_id(community_id: &str) -> Result<crate::community::CommunityId> {
4386        crate::simd::hex::hex_to_bytes_32_checked(community_id)
4387            .map(crate::community::CommunityId)
4388            .ok_or_else(|| VectorError::Other("malformed community id".into()))
4389    }
4390
4391    fn load_held(community_id: &str) -> Result<Option<crate::community::v2::community::CommunityV2>> {
4392        if community_id.len() != 64 {
4393            return Ok(None);
4394        }
4395        let cid = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
4396        crate::db::community::load_community_v2(&cid).map_err(VectorError::Other)
4397    }
4398
4399    // ── Community admin actions ── role-gated; vector-core re-checks authority on every action and peers
4400    // re-verify against the owner-rooted roster, so these can't forge standing. A bunker account can't ban
4401    // in a private community (the rekey needs a raw local key).
4402
4403    /// My effective management capabilities in a community (role engine — owner is just position 0). Use to
4404    /// confirm a promotion/demotion landed. A local read: the roster is folded + persisted by the control
4405    /// follow, never fetched here.
4406    pub fn community_capabilities(&self, community_id: &str) -> Result<serde_json::Value> {
4407        let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
4408        use crate::community::roles::Permissions;
4409        let me = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?.to_hex();
4410        let owner_hex = v2.owner().map_err(VectorError::Other)?.to_hex();
4411        let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
4412        // A banned member holds no standing (CORD-04 §4), even if a since-skipped
4413        // roster persist still lists their grant — the banlist advances on its own gate.
4414        let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
4415        if banned.contains(&me) && me != owner_hex {
4416            return Ok(serde_json::json!({
4417                "manage_metadata": false, "manage_channels": false, "create_invite": false, "kick": false,
4418                "ban": false, "manage_messages": false, "manage_roles": false, "manage_admin_role": false,
4419                "pin_messages": false, "control_write": false, "moderate_members": false, "view_audit_log": false,
4420                "manage_nicknames": false, "change_nickname": false,
4421            }));
4422        }
4423        // Actions that land as Control editions additionally need the plane's
4424        // write key (CORD-02 §2): a role-authorized staffer whose control_wrap
4425        // hasn't arrived yet factually cannot publish, and an honest false here
4426        // beats a bot retry-looping a publish every reader drops. KICK
4427        // (Guestbook) and MANAGE_MESSAGES (Chat planes) never need it.
4428        let control_write = crate::community::v2::control::ControlPlane::of(&v2).can_write();
4429        let has = |p: u64| roster.is_authorized(&me, Some(&owner_hex), p);
4430        let has_ctl = |p: u64| control_write && has(p);
4431        Ok(serde_json::json!({
4432            "manage_metadata": has_ctl(Permissions::MANAGE_METADATA), "manage_channels": has_ctl(Permissions::MANAGE_CHANNELS),
4433            "create_invite": has_ctl(Permissions::CREATE_INVITE), "kick": has(Permissions::KICK), "ban": has_ctl(Permissions::BAN),
4434            "manage_messages": has(Permissions::MANAGE_MESSAGES), "manage_roles": has_ctl(Permissions::MANAGE_ROLES),
4435            // Only the owner (position 0) strictly outranks the position-1 Admin role.
4436            "manage_admin_role": me == owner_hex && control_write,
4437            "pin_messages": has_ctl(Permissions::PIN_MESSAGES),
4438            "control_write": control_write,
4439            // A Timeout rides the Guestbook, so it needs no Control write key.
4440            "moderate_members": has(Permissions::MODERATE_MEMBERS),
4441            "view_audit_log": has(Permissions::VIEW_AUDIT_LOG),
4442            // Nicknames ride the Guestbook too.
4443            "manage_nicknames": has(Permissions::MANAGE_NICKNAMES),
4444            "change_nickname": roster.may_name(&me, Some(&owner_hex), &me),
4445        }))
4446    }
4447
4448    /// Check each relay `relays` would add to a v2 community before moving it there: whether it
4449    /// holds what a community needs, and whether it throttles.
4450    pub async fn check_community_relays(&self, community_id: &str, relays: &[String]) -> Result<Vec<crate::community::v2::service::RelayCheck>> {
4451        let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
4452        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(15));
4453        crate::community::v2::service::check_relays(&transport, &v2, relays).await.map_err(VectorError::Other)
4454    }
4455
4456    /// Move a v2 community to `relays`, copying what its members need onto each new relay first
4457    /// (see [`crate::community::v2::service::move_relays`]).
4458    pub async fn move_community_relays(&self, community_id: &str, relays: &[String]) -> Result<crate::community::v2::service::RelayMove> {
4459        let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
4460        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(15));
4461        crate::community::v2::service::move_relays(&transport, &v2, relays).await.map_err(VectorError::Other)
4462    }
4463
4464    /// A v2 community's Audit Log, newest first: who changed what, and when. Any member can read
4465    /// the chain it comes from; showing it is for the owner and View Audit Log holders.
4466    pub async fn community_audit_log(&self, community_id: &str) -> Result<crate::community::v2::service::AuditLog> {
4467        let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
4468        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(15));
4469        crate::community::v2::service::audit_log(&transport, &v2).await.map_err(VectorError::Other)
4470    }
4471
4472    /// Pin a message in a v2 community channel (CORD-04 §7). The proof is
4473    /// rebuilt from the message's recovered wrap; see `service::pin_message`.
4474    pub async fn pin_community_message(&self, community_id: &str, channel_id: &str, message_id: &str) -> Result<()> {
4475        use crate::community::{transport::LiveTransport, ChannelId};
4476        let v2 = Self::load_held(community_id)?
4477            .ok_or_else(|| VectorError::Other("pins are only available in Concord v2 communities".into()))?;
4478        let ch = ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
4479        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
4480        crate::community::v2::service::pin_message(&transport, &v2, &ch, message_id)
4481            .await
4482            .map_err(VectorError::Other)
4483    }
4484
4485    /// Unpin a message: the next Pin List edition without the entry.
4486    pub async fn unpin_community_message(&self, community_id: &str, channel_id: &str, message_id: &str) -> Result<()> {
4487        use crate::community::{transport::LiveTransport, ChannelId};
4488        let v2 = Self::load_held(community_id)?
4489            .ok_or_else(|| VectorError::Other("pins are only available in Concord v2 communities".into()))?;
4490        let ch = ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
4491        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
4492        crate::community::v2::service::unpin_message(&transport, &v2, &ch, message_id)
4493            .await
4494            .map_err(VectorError::Other)
4495    }
4496
4497    /// Fetch a pinned attachment FROM THE PIN ALONE (CORD-04 §7's whole point:
4498    /// the proof carries the rumor, whose imeta carries the blob URL and the
4499    /// file's decryption material — no chat history and no old epoch key
4500    /// needed). Serves the already-downloaded copy when its content hash
4501    /// verifies; otherwise runs the full download walk (mirrors + hash-swap),
4502    /// decrypts, verifies, and caches at the same content-addressed path the
4503    /// chat pipeline uses. Returns `{ path, mime, name }`.
4504    pub async fn fetch_pinned_attachment(
4505        &self,
4506        community_id: &str,
4507        channel_id: &str,
4508        rumor_id: &str,
4509    ) -> Result<serde_json::Value> {
4510        crate::db::scoped(async move {
4511            use crate::community::ChannelId;
4512            let v2 = Self::load_held(community_id)?
4513                .ok_or_else(|| VectorError::Other("pins are only available in Concord v2 communities".into()))?;
4514            let ch = ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
4515            let pins = crate::community::v2::service::read_channel_pins(&v2, &ch).map_err(VectorError::Other)?;
4516            let pin = pins
4517                .pins
4518                .iter()
4519                .find(|p| p.rumor_id == rumor_id)
4520                .ok_or_else(|| VectorError::Other("that message is not pinned".into()))?;
4521            let dir = crate::db::get_download_dir();
4522            let tag = pin
4523                .tags
4524                .iter()
4525                .find(|t| t.first().map(String::as_str) == Some("imeta"))
4526                .map(|t| nostr_sdk::prelude::Tag::custom("imeta", t[1..].to_vec()))
4527                .ok_or_else(|| VectorError::Other("this pin carries no attachment".into()))?;
4528            let attachment = crate::community::attachments::attachment_from_imeta(&tag, &dir)
4529                .ok_or_else(|| VectorError::Other("this pin's attachment metadata is malformed".into()))?;
4530
4531            let respond = |path: &str| {
4532                serde_json::json!({
4533                    "path": path,
4534                    "name": attachment.name.to_string(),
4535                    "extension": attachment.extension.to_string(),
4536                })
4537            };
4538
4539            // The author-committed content address (the pin verified the rumor, so
4540            // `ox` carries the author's signature-weight claim — the same trust the
4541            // chat pipeline extends). Reuse and fresh downloads both verify it.
4542            let expected = attachment.original_hash.as_deref();
4543            // A pin is held in memory like a chat's file; kept too when the account keeps files,
4544            // or when it is too large to hold.
4545            let in_memory = crate::media::ram::cache().admits(attachment.size);
4546            let keep = !in_memory || crate::media::keep_media();
4547            if let Some(hash) = expected.and_then(crate::simd::hex::hex_to_bytes_32_checked).filter(|h| crate::media::resident(h)) {
4548                return Ok(respond(&crate::media::MediaRef::held(&hash)));
4549            }
4550            let path = std::path::PathBuf::from(&*attachment.path);
4551            if let Ok(bytes) = std::fs::read(&path) {
4552                match expected {
4553                    Some(want) if crate::crypto::sha256_hex(&bytes) == want => return Ok(respond(&path.to_string_lossy())),
4554                    None => return Ok(respond(&path.to_string_lossy())),
4555                    _ => {} // stale or foreign bytes at the path: re-download
4556                }
4557            }
4558
4559            let author_npub = nostr_sdk::prelude::PublicKey::from_hex(&pin.author)
4560                .ok()
4561                .and_then(|pk| nostr_sdk::prelude::ToBech32::to_bech32(&pk).ok());
4562            let bytes = self.download_attachment_from(&attachment, author_npub.as_deref()).await?;
4563            let hash = crate::crypto::sha256_hex(&bytes);
4564            if expected.is_some_and(|want| hash != want) {
4565                return Err(VectorError::Other("downloaded bytes do not match the pinned content hash".into()));
4566            }
4567            let held = crate::simd::hex::hex_to_bytes_32(&hash);
4568            let mime = crate::crypto::mime_from_extension(&attachment.extension.to_ascii_lowercase());
4569            // Kept the way a chat keeps it: sealed in the store, never plain.
4570            if keep {
4571                #[cfg(not(target_arch = "wasm32"))]
4572                crate::media::store::keep_sealed(&bytes, held, mime, crate::db::media_store::Origin::Sealed)
4573                    .map_err(|e| VectorError::Other(format!("could not keep the attachment: {e}")))?;
4574                #[cfg(target_arch = "wasm32")]
4575                crate::media::store::keep_sealed(&bytes, held, mime, crate::db::media_store::Origin::Sealed)
4576                    .await
4577                    .map_err(|e| VectorError::Other(format!("could not keep the attachment: {e}")))?;
4578            }
4579            if in_memory {
4580                match crate::media::ram::insert(held, bytes, mime) {
4581                    Ok(_) => {}
4582                    Err(_) if keep => {}
4583                    Err(_) => return Err(VectorError::Other("too much media is open to show this one".into())),
4584                }
4585            }
4586            Ok(respond(&crate::media::MediaRef::held(&held)))
4587        })
4588        .await
4589    }
4590
4591    /// A channel's verified pins from the locally folded head — local-only read.
4592    /// `sealed: true` means the list exists but is unreadable on this device;
4593    /// render it as unavailable, never as empty.
4594    pub fn get_channel_pins(&self, community_id: &str, channel_id: &str) -> Result<serde_json::Value> {
4595        use crate::community::ChannelId;
4596        let Some(v2) = Self::load_held(community_id)? else {
4597            return Ok(serde_json::json!({ "pins": [], "sealed": false, "version": 0 }));
4598        };
4599        let ch = ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
4600        let pins = crate::community::v2::service::read_channel_pins(&v2, &ch).map_err(VectorError::Other)?;
4601        serde_json::to_value(&pins).map_err(|e| VectorError::Other(e.to_string()))
4602    }
4603
4604    /// The whole role graph: every role with its position and colour, and who
4605    /// holds what.
4606    ///
4607    /// `community_roles` above answers only "who is an admin", which is all the
4608    /// crown ever needed. A member list that groups people by rank needs the
4609    /// hierarchy itself, and npubs rather than hex so it can match a roster it
4610    /// already holds.
4611    pub fn community_role_graph(&self, community_id: &str) -> Result<serde_json::Value> {
4612        use nostr_sdk::prelude::{PublicKey, ToBech32};
4613        let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
4614        // A banned member is gone from every read (§4), roles included.
4615        let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
4616        let roles: Vec<serde_json::Value> = roster
4617            .roles
4618            .iter()
4619            .map(|r| {
4620                // A channel-scoped role is that channel's access list (CORD-04 §2), which
4621                // is what a Private Channel's member list is drawn from.
4622                let channel_id = match &r.scope {
4623                    crate::community::roles::RoleScope::Channel(c) => Some(c.to_ascii_lowercase()),
4624                    crate::community::roles::RoleScope::Server => None,
4625                };
4626                serde_json::json!({
4627                    "role_id": r.role_id,
4628                    "name": r.name,
4629                    "position": r.position,
4630                    "color": r.color,
4631                    "channel_id": channel_id,
4632                    "display": r.display,
4633                })
4634            })
4635            .collect();
4636        let grants: Vec<serde_json::Value> = roster
4637            .grants
4638            .iter()
4639            .filter(|g| !banned.contains(&g.member))
4640            .filter_map(|g| {
4641                let npub = PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok())?;
4642                Some(serde_json::json!({ "npub": npub, "role_ids": g.role_ids }))
4643            })
4644            .collect();
4645        // On Roles v2 a Private Channel's readers are whoever it resolves View Channel for.
4646        let activated = roster.everyone.is_some();
4647        let mut readers = serde_json::Map::new();
4648        if activated {
4649            if let Some(v2) = Self::load_held(community_id)? {
4650                let owner_hex = v2.owner().ok().map(|o| o.to_hex());
4651                let mut candidates: std::collections::BTreeSet<PublicKey> =
4652                    crate::community::v2::service::stored_memberlist(&v2).unwrap_or_default().into_iter().collect();
4653                candidates.extend(roster.grants.iter().filter_map(|g| PublicKey::from_hex(&g.member).ok()));
4654                for ch in v2.channels.iter().filter(|c| c.private) {
4655                    let chan = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
4656                    let npubs: Vec<String> = candidates
4657                        .iter()
4658                        .filter(|pk| !banned.contains(&pk.to_hex()) && roster.is_entitled(owner_hex.as_deref(), &pk.to_hex(), &chan, &[], &[]))
4659                        .filter_map(|pk| pk.to_bech32().ok())
4660                        .collect();
4661                    readers.insert(chan, npubs.into());
4662                }
4663            }
4664        }
4665        Ok(serde_json::json!({ "roles": roles, "grants": grants, "activated": activated, "readers": readers }))
4666    }
4667
4668    /// Everything a role editor needs, in one local read: every role in display order
4669    /// (CORD-04 §3: position, then the lower role_id), who holds each, what the caller
4670    /// may touch, and the channels a role can be scoped to. Permissions ride as decimal
4671    /// strings, the wire's own rule, since a JS number corrupts past 2^53.
4672    pub fn community_roles_view(&self, community_id: &str) -> Result<serde_json::Value> {
4673        use crate::community::roles::{Permissions, RoleScope};
4674        let v2 = Self::load_held(community_id)?
4675            .ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
4676        let me = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?.to_hex();
4677        let owner_hex = v2.owner().map_err(VectorError::Other)?.to_hex();
4678        let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
4679        let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
4680        let is_owner = me == owner_hex;
4681        let can_manage = is_owner
4682            || (!banned.contains(&me) && roster.is_authorized(&me, Some(&owner_hex), Permissions::MANAGE_ROLES));
4683        let rank = if is_owner { Some(0) } else { roster.highest_position(&me) };
4684        let grantable = if is_owner { u64::MAX } else { roster.effective_permissions(&me).0 };
4685        let mut roles: Vec<&crate::community::roles::Role> = roster.roles.iter().collect();
4686        roles.sort_by(|a, b| a.position.cmp(&b.position).then_with(|| a.role_id.cmp(&b.role_id)));
4687        let activated = Self::roles_v2_active(community_id, &roster);
4688        let roles: Vec<serde_json::Value> = roles
4689            .into_iter()
4690            .map(|r| {
4691                let holders: Vec<String> = roster
4692                    .grants
4693                    .iter()
4694                    .filter(|g| !banned.contains(&g.member) && g.role_ids.iter().any(|id| id == &r.role_id))
4695                    .filter_map(|g| nostr_sdk::prelude::PublicKey::from_hex(&g.member).ok())
4696                    .filter_map(|pk| nostr_sdk::prelude::ToBech32::to_bech32(&pk).ok())
4697                    .collect();
4698                serde_json::json!({
4699                    "role_id": r.role_id,
4700                    "name": r.name,
4701                    "position": r.position,
4702                    "color": r.color,
4703                    "permissions": r.permissions.0.to_string(),
4704                    "channel_id": match &r.scope { RoleScope::Channel(c) => Some(c.to_ascii_lowercase()), RoleScope::Server => None },
4705                    "holders": holders,
4706                    "display": r.display,
4707                    "mentionable": r.mentionable,
4708                    "manageable": can_manage && (is_owner || {
4709                        let support = roster.permissions_above(&me, r.position);
4710                        support.contains(Permissions::MANAGE_ROLES) && r.permissions.0 & !support.0 == 0
4711                    }),
4712                })
4713            })
4714            .collect();
4715        let channels: Vec<serde_json::Value> = v2
4716            .channels
4717            .iter()
4718            .map(|c| serde_json::json!({
4719                "channel_id": crate::simd::hex::bytes_to_hex_32(&c.id.0),
4720                "name": c.name,
4721                "private": c.private,
4722            }))
4723            .collect();
4724        Ok(serde_json::json!({
4725            "is_owner": is_owner,
4726            "can_manage": can_manage,
4727            "rank": rank,
4728            "grantable": grantable.to_string(),
4729            // Roles v2 (CORD-04 §2): deletable Roles, `@everyone`, and the channel bits.
4730            "activated": activated,
4731            "everyone": roster.everyone.map(|p| p.0.to_string()),
4732            "everyone_editable": activated && (is_owner || roster.permissions_above(&me, u32::MAX).contains(Permissions::MANAGE_ROLES)),
4733            "everyone_default": crate::community::v2::roles::EVERYONE_DEFAULT.to_string(),
4734            "roles": roles,
4735            "channels": channels,
4736            "max_roles": crate::community::v2::roles::MAX_ROLES_PER_COMMUNITY,
4737            "max_per_member": crate::community::v2::roles::MAX_ROLES_PER_MEMBER,
4738        }))
4739    }
4740
4741    fn parse_permissions(s: &str) -> Result<u64> {
4742        if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {
4743            return Err(VectorError::Other(format!("permissions must be a decimal string, got {s:?}")));
4744        }
4745        s.parse::<u64>().map_err(|_| VectorError::Other("permissions out of range".into()))
4746    }
4747
4748    fn role_scope(channel_id: Option<&str>) -> Result<crate::community::roles::RoleScope> {
4749        use crate::community::roles::RoleScope;
4750        match channel_id {
4751            None => Ok(RoleScope::Server),
4752            Some(c) if c.len() == 64 && c.bytes().all(|b| b.is_ascii_hexdigit()) => Ok(RoleScope::Channel(c.to_ascii_lowercase())),
4753            Some(_) => Err(VectorError::Other("channel_id must be 32-byte hex".into())),
4754        }
4755    }
4756
4757    /// Create a Role at the bottom of the list. Returns its id.
4758    pub async fn create_role(&self, community_id: &str, name: &str, color: u32, permissions: &str, channel_id: Option<&str>) -> Result<String> {
4759        let v2 = Self::load_held(community_id)?
4760            .ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
4761        let perms = Self::parse_permissions(permissions)?;
4762        let scope = Self::role_scope(channel_id)?;
4763        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
4764        let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
4765        let id = if Self::roles_v2_active(community_id, &roster) {
4766            if channel_id.is_some() {
4767                return Err(VectorError::Other("on the new roles, channel access is set on the channel".into()));
4768            }
4769            crate::community::v2::service::create_role_v2(&transport, &v2, name, color, perms).await
4770        } else {
4771            crate::community::v2::service::create_role(&transport, &v2, name, color, perms, scope).await
4772        }
4773        .map_err(VectorError::Other)?;
4774        Self::converge_v2_authority(&transport, community_id).await;
4775        Ok(id)
4776    }
4777
4778    /// Edit a Role's name, colour, permissions and scope.
4779    pub async fn edit_role(&self, community_id: &str, role_id: &str, name: &str, color: u32, permissions: &str, channel_id: Option<&str>) -> Result<()> {
4780        self.edit_role_shown(community_id, role_id, name, color, permissions, channel_id, None, None).await
4781    }
4782
4783    /// [`Self::edit_role`], plus whether a Roles v2 Role shows apart in the member list and
4784    /// can be mentioned (`None` keeps what it has).
4785    #[allow(clippy::too_many_arguments)]
4786    pub async fn edit_role_shown(
4787        &self,
4788        community_id: &str,
4789        role_id: &str,
4790        name: &str,
4791        color: u32,
4792        permissions: &str,
4793        channel_id: Option<&str>,
4794        display: Option<bool>,
4795        mentionable: Option<bool>,
4796    ) -> Result<()> {
4797        let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
4798        if Self::roles_v2_active(community_id, &roster) {
4799            let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
4800            let perms = Self::parse_permissions(permissions)?;
4801            let current = roster.role(role_id).ok_or_else(|| VectorError::Other("no such role".into()))?;
4802            let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
4803            crate::community::v2::service::edit_role_v2(
4804                &transport,
4805                &v2,
4806                role_id,
4807                name,
4808                color,
4809                perms,
4810                display.unwrap_or(current.display),
4811                mentionable.unwrap_or(current.mentionable),
4812            )
4813            .await
4814            .map_err(VectorError::Other)?;
4815            Self::converge_v2_authority(&transport, community_id).await;
4816            return Ok(());
4817        }
4818        let v2 = Self::load_held(community_id)?
4819            .ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
4820        let perms = Self::parse_permissions(permissions)?;
4821        let scope = Self::role_scope(channel_id)?;
4822        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
4823        crate::community::v2::service::edit_role(&transport, &v2, role_id, name, color, perms, scope)
4824            .await
4825            .map_err(VectorError::Other)?;
4826        Self::converge_v2_authority(&transport, community_id).await;
4827        Ok(())
4828    }
4829
4830    /// Reorder the roles beneath the caller, top to bottom. Returns how many moved.
4831    pub async fn reorder_roles(&self, community_id: &str, ordered: &[String]) -> Result<usize> {
4832        let v2 = Self::load_held(community_id)?
4833            .ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
4834        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
4835        let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
4836        if Self::roles_v2_active(community_id, &roster) {
4837            let moved = crate::community::v2::service::reorder_roles_v2(&transport, &v2, ordered).await.map_err(VectorError::Other)?;
4838            if moved > 0 {
4839                Self::converge_v2_authority(&transport, community_id).await;
4840            }
4841            return Ok(moved);
4842        }
4843        let moved = crate::community::v2::service::reorder_roles(&transport, &v2, ordered)
4844            .await
4845            .map_err(VectorError::Other)?;
4846        if moved > 0 {
4847            Self::converge_v2_authority(&transport, community_id).await;
4848        }
4849        Ok(moved)
4850    }
4851
4852    /// Roles v2 is active here (CORD-04 §2), by what this device has folded.
4853    fn roles_v2_active(community_id: &str, roster: &crate::community::roles::CommunityRoles) -> bool {
4854        if roster.everyone.is_some() {
4855            return true;
4856        }
4857        let Some(cid) = crate::simd::hex::hex_to_bytes_32_checked(community_id) else { return false };
4858        let everyone = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::everyone_locator(&crate::community::CommunityId(cid)));
4859        crate::db::community::get_edition_head(community_id, &everyone).ok().flatten().is_some()
4860    }
4861
4862    fn held_v2(community_id: &str) -> Result<crate::community::v2::community::CommunityV2> {
4863        Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("this needs a Concord v2 community".into()))
4864    }
4865
4866    fn short_transport() -> crate::community::transport::LiveTransport {
4867        crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12))
4868    }
4869
4870    /// A Channel view by name: `chat`, `forum` or `voice`.
4871    fn view_named(view: &str) -> Result<crate::community::v2::community::ChannelView> {
4872        crate::community::v2::community::ChannelView::try_parse(view)
4873            .ok_or_else(|| VectorError::Other(format!("no channel view named {view:?}: chat, forum or voice")))
4874    }
4875
4876    fn id32(hex: &str, what: &str) -> Result<[u8; 32]> {
4877        crate::simd::hex::hex_to_bytes_32_checked(hex).ok_or_else(|| VectorError::Other(format!("{what} must be 32-byte hex")))
4878    }
4879
4880    /// A channel's permission overwrites and what an editor needs to change them, read
4881    /// locally. Bits ride as decimal strings.
4882    pub fn channel_permissions_view(&self, community_id: &str, channel_id: &str) -> Result<serde_json::Value> {
4883        use crate::community::roles::{OverwriteTarget, Permissions};
4884        let v2 = Self::held_v2(community_id)?;
4885        let me = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?.to_hex();
4886        let owner_hex = v2.owner().map_err(VectorError::Other)?.to_hex();
4887        let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
4888        let is_owner = me == owner_hex;
4889        let chan = channel_id.to_ascii_lowercase();
4890        let mut roles: Vec<&crate::community::roles::Role> = roster.roles.iter().collect();
4891        roles.sort_by(|a, b| a.position.cmp(&b.position).then_with(|| a.role_id.cmp(&b.role_id)));
4892        let overwrites: Vec<serde_json::Value> = roster
4893            .overwrites
4894            .iter()
4895            .filter(|o| o.scope == chan)
4896            .map(|o| {
4897                let (kind, id) = match &o.target {
4898                    OverwriteTarget::Everyone => ("everyone", None),
4899                    OverwriteTarget::Role(id) => ("role", Some(id.clone())),
4900                    OverwriteTarget::Member(m) => ("member", Some(m.clone())),
4901                };
4902                let npub = (kind == "member").then(|| id.as_deref().and_then(|m| nostr_sdk::prelude::PublicKey::from_hex(m).ok()).and_then(|pk| ToBech32::to_bech32(&pk).ok())).flatten();
4903                serde_json::json!({ "kind": kind, "id": id, "npub": npub, "allow": o.allow.0.to_string(), "deny": o.deny.0.to_string() })
4904            })
4905            .collect();
4906        let category = crate::simd::hex::hex_to_bytes_32_checked(&chan)
4907            .and_then(|b| v2.channel(&crate::community::ChannelId(b)))
4908            .and_then(|c| c.category())
4909            .filter(|k| v2.categories.iter().any(|x| x.id == *k))
4910            .map(|k| crate::simd::hex::bytes_to_hex_32(&k));
4911        Ok(serde_json::json!({
4912            "activated": Self::roles_v2_active(community_id, &roster),
4913            // The Category the channel files under, and whether it takes that Category's rules.
4914            "category": category,
4915            "synced": roster.syncs.get(&chan),
4916            "can_manage": is_owner || roster.is_authorized(&me, Some(&owner_hex), Permissions::MANAGE_ROLES),
4917            "grantable": if is_owner { u64::MAX.to_string() } else { roster.effective_permissions(&me).0.to_string() },
4918            "roles": roles.iter().map(|r| serde_json::json!({ "role_id": r.role_id, "name": r.name, "color": r.color, "position": r.position })).collect::<Vec<_>>(),
4919            "overwrites": overwrites,
4920            // Who a member overwrite can name: everyone this device knows, but the owner.
4921            "members": crate::community::v2::service::stored_memberlist(&v2)
4922                .unwrap_or_default()
4923                .into_iter()
4924                .filter(|pk| pk.to_hex() != owner_hex)
4925                .map(|pk| serde_json::json!({ "id": pk.to_hex(), "npub": ToBech32::to_bech32(&pk).ok() }))
4926                .collect::<Vec<_>>(),
4927        }))
4928    }
4929
4930    /// Set, or with no bits clear, one overwrite on a Channel or Category. `kind` is
4931    /// `everyone`, `role` (a role id) or `member` (an npub or hex key).
4932    pub async fn set_channel_overwrite(&self, community_id: &str, scope_id: &str, kind: &str, target_id: Option<&str>, allow: &str, deny: &str) -> Result<()> {
4933        use crate::community::roles::OverwriteTarget;
4934        let v2 = Self::held_v2(community_id)?;
4935        let target = match (kind, target_id) {
4936            ("everyone", _) => OverwriteTarget::Everyone,
4937            ("role", Some(id)) => OverwriteTarget::Role(crate::simd::hex::bytes_to_hex_32(&Self::id32(id, "role_id")?)),
4938            ("member", Some(m)) => OverwriteTarget::Member(
4939                nostr_sdk::prelude::PublicKey::parse(m).map_err(|_| VectorError::Other("invalid member key".into()))?.to_hex(),
4940            ),
4941            _ => return Err(VectorError::Other("an overwrite targets everyone, a role or a member".into())),
4942        };
4943        let (allow, deny) = (Self::parse_permissions(allow)?, Self::parse_permissions(deny)?);
4944        let transport = Self::short_transport();
4945        crate::community::v2::service::set_overwrite(&transport, &v2, Self::id32(scope_id, "scope_id")?, target, allow, deny)
4946            .await
4947            .map_err(VectorError::Other)?;
4948        Self::converge_v2_authority(&transport, community_id).await;
4949        Ok(())
4950    }
4951
4952    /// Sync a channel to a Category's permissions, or (`None`) back to its own.
4953    pub async fn set_channel_sync(&self, community_id: &str, channel_id: &str, category_id: Option<&str>) -> Result<()> {
4954        let v2 = Self::held_v2(community_id)?;
4955        let channel = crate::community::ChannelId(Self::id32(channel_id, "channel_id")?);
4956        let category = category_id.map(|c| Self::id32(c, "category_id")).transpose()?;
4957        let transport = Self::short_transport();
4958        crate::community::v2::service::set_channel_sync(&transport, &v2, &channel, category).await.map_err(VectorError::Other)?;
4959        Self::converge_v2_authority(&transport, community_id).await;
4960        Ok(())
4961    }
4962
4963    /// Of `npubs`, those who can't send in a channel by the roster as it stands (CORD-04 §8):
4964    /// a reader collapses their posts there. Empty on the legacy roster.
4965    pub fn channel_send_denied(&self, community_id: &str, channel_id: &str, npubs: &[String]) -> Result<Vec<String>> {
4966        Self::channel_denied(community_id, channel_id, npubs, crate::community::roles::Permissions::SEND_MESSAGES)
4967    }
4968
4969    /// Of `npubs`, those who can't react in a channel by the roster as it stands: a reader
4970    /// doesn't count their reactions there. Empty on the legacy roster.
4971    pub fn channel_react_denied(&self, community_id: &str, channel_id: &str, npubs: &[String]) -> Result<Vec<String>> {
4972        Self::channel_denied(community_id, channel_id, npubs, crate::community::roles::Permissions::ADD_REACTIONS)
4973    }
4974
4975    fn channel_denied(community_id: &str, channel_id: &str, npubs: &[String], perm: u64) -> Result<Vec<String>> {
4976        let v2 = Self::held_v2(community_id)?;
4977        let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
4978        if roster.everyone.is_none() {
4979            return Ok(Vec::new());
4980        }
4981        let owner = v2.owner().ok().map(|o| o.to_hex());
4982        let chan = channel_id.to_ascii_lowercase();
4983        let ch = Self::id32(channel_id, "channel_id").ok().and_then(|b| v2.channel(&crate::community::ChannelId(b)));
4984        let private = ch.is_some_and(|c| c.private);
4985        Ok(npubs
4986            .iter()
4987            .filter(|n| {
4988                nostr_sdk::prelude::PublicKey::parse(n.as_str())
4989                    .is_ok_and(|pk| !roster.channel_permissions(owner.as_deref(), &pk.to_hex(), &chan, private).contains(perm))
4990            })
4991            .cloned()
4992            .collect())
4993    }
4994
4995    /// What mentions in a community need (CORD-04 §8): who may mention everyone, and so any
4996    /// Role (`anyone` when `@everyone` itself may), and its Roles top first, each with
4997    /// whether any member may mention it and whether I hold it.
4998    pub fn community_mentions(&self, community_id: &str) -> Result<serde_json::Value> {
4999        use crate::community::roles::Permissions;
5000        use nostr_sdk::prelude::PublicKey;
5001        let v2 = Self::held_v2(community_id)?;
5002        let owner = v2.owner().map_err(VectorError::Other)?.to_hex();
5003        let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
5004        let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
5005        let me = crate::state::my_public_key().map(|pk| pk.to_hex()).unwrap_or_default();
5006        let members: std::collections::BTreeSet<&str> = std::iter::once(owner.as_str()).chain(roster.grants.iter().map(|g| g.member.as_str())).collect();
5007        let pingers: Vec<String> = members
5008            .into_iter()
5009            .filter(|m| !banned.iter().any(|b| b == m) && roster.is_authorized(m, Some(&owner), Permissions::MENTION_EVERYONE))
5010            .filter_map(|m| PublicKey::from_hex(m).ok()?.to_bech32().ok())
5011            .collect();
5012        let held: std::collections::HashSet<&str> = roster.roles_of(&me).map(|r| r.role_id.as_str()).collect();
5013        let mut roles: Vec<&crate::community::roles::Role> = roster.roles.iter().filter(|r| crate::community::mentions::is_role_id(&r.role_id)).collect();
5014        roles.sort_by_key(|r| r.position);
5015        let roles: Vec<serde_json::Value> = roles
5016            .into_iter()
5017            .map(|r| serde_json::json!({ "id": r.role_id, "name": r.name, "color": r.color, "mentionable": r.mentionable, "held": held.contains(r.role_id.as_str()) }))
5018            .collect();
5019        Ok(serde_json::json!({
5020            "anyone": roster.everyone.is_some_and(|e| e.contains(Permissions::MENTION_EVERYONE)),
5021            "pingers": pingers,
5022            "roles": roles,
5023        }))
5024    }
5025
5026    /// Whether a message's Role mentions ping me (CORD-04 §8). False on any read failure.
5027    pub fn role_mentions_ping_me(&self, community_id: &str, author_npub: &str, content: &str, role_ids: &[String]) -> bool {
5028        if role_ids.is_empty() {
5029            return false;
5030        }
5031        let (Some(me), Ok(author), Ok(Some(held))) = (
5032            crate::state::my_public_key(),
5033            nostr_sdk::prelude::PublicKey::parse(author_npub),
5034            Self::load_held(community_id),
5035        ) else {
5036            return false;
5037        };
5038        let (Ok(owner), Ok(roster)) = (held.owner(), crate::db::community::get_community_roles(community_id)) else { return false };
5039        let author = author.to_hex();
5040        if crate::db::community::get_community_banlist(community_id).unwrap_or_default().contains(&author) {
5041            return false;
5042        }
5043        crate::community::mentions::pings(&roster, Some(&owner.to_hex()), &author, &me.to_hex(), content, role_ids)
5044    }
5045
5046    /// Whether a fresh post by `author_npub` in a channel stays silent (CORD-04 §8): they can't
5047    /// send there, or a Timeout of theirs is running, whatever date they put on the post.
5048    pub fn post_silenced(&self, community_id: &str, channel_id: &str, author_npub: &str) -> bool {
5049        if self.channel_send_denied(community_id, channel_id, &[author_npub.to_string()]).is_ok_and(|d| !d.is_empty()) {
5050            return true;
5051        }
5052        let (Ok(v2), Ok(author)) = (Self::held_v2(community_id), nostr_sdk::prelude::PublicKey::parse(author_npub)) else { return false };
5053        crate::community::v2::service::community_timeouts(&v2).is_ok_and(|t| t.contains_key(&author))
5054    }
5055
5056    /// The Timeouts running in a community: npub → { from, until } (unix seconds).
5057    pub fn community_timeouts(&self, community_id: &str) -> Result<serde_json::Value> {
5058        let v2 = Self::held_v2(community_id)?;
5059        let running = crate::community::v2::service::community_timeouts(&v2).map_err(VectorError::Other)?;
5060        Ok(running
5061            .into_iter()
5062            .filter_map(|(pk, (from, until))| Some((pk.to_bech32().ok()?, serde_json::json!({ "from": from, "until": until }))))
5063            .collect::<serde_json::Map<_, _>>()
5064            .into())
5065    }
5066
5067    /// Time a member out for `seconds` (at most 28 days); 0 lifts a running Timeout.
5068    pub async fn timeout_member(&self, community_id: &str, npub: &str, seconds: u64) -> Result<()> {
5069        let v2 = Self::held_v2(community_id)?;
5070        let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
5071        crate::community::v2::service::timeout_member(&Self::short_transport(), &v2, &member, seconds).await.map_err(VectorError::Other)
5072    }
5073
5074    /// What members are called in a community, for those with a Nickname there: npub → nickname.
5075    pub fn community_nicknames(&self, community_id: &str) -> Result<serde_json::Value> {
5076        let v2 = Self::held_v2(community_id)?;
5077        let named = crate::community::v2::service::community_nicknames(&v2).map_err(VectorError::Other)?;
5078        Ok(named
5079            .into_iter()
5080            .filter_map(|(pk, nick)| Some((pk.to_bech32().ok()?, serde_json::Value::String(nick))))
5081            .collect::<serde_json::Map<_, _>>()
5082            .into())
5083    }
5084
5085    /// A member's Nickname in a community, when they have one there.
5086    pub fn member_nickname(&self, community_id: &str, npub: &str) -> Option<String> {
5087        let v2 = Self::held_v2(community_id).ok()?;
5088        let member = nostr_sdk::prelude::PublicKey::parse(npub).ok()?;
5089        crate::community::v2::service::community_nicknames(&v2).ok()?.remove(&member)
5090    }
5091
5092    /// Set a member's Nickname in a community (`""` clears it): your own, or one beneath you.
5093    pub async fn set_community_nickname(&self, community_id: &str, npub: &str, nickname: &str) -> Result<()> {
5094        let v2 = Self::held_v2(community_id)?;
5095        let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
5096        crate::community::v2::service::set_nickname(&Self::short_transport(), &v2, &member, nickname).await.map_err(VectorError::Other)
5097    }
5098
5099    /// Delete a Role (Roles v2 only): terminal, it leaves every holder.
5100    pub async fn delete_role(&self, community_id: &str, role_id: &str) -> Result<()> {
5101        let v2 = Self::held_v2(community_id)?;
5102        let transport = Self::short_transport();
5103        crate::community::v2::service::delete_role_v2(&transport, &v2, role_id).await.map_err(VectorError::Other)?;
5104        Self::converge_v2_authority(&transport, community_id).await;
5105        Ok(())
5106    }
5107
5108    /// Set what `@everyone` holds. `permissions` is a decimal string.
5109    pub async fn set_everyone_permissions(&self, community_id: &str, permissions: &str) -> Result<()> {
5110        let v2 = Self::held_v2(community_id)?;
5111        let perms = Self::parse_permissions(permissions)?;
5112        let transport = Self::short_transport();
5113        crate::community::v2::service::set_everyone(&transport, &v2, perms).await.map_err(VectorError::Other)?;
5114        Self::converge_v2_authority(&transport, community_id).await;
5115        Ok(())
5116    }
5117
5118    /// Move the community to Roles v2 (owner only). Returns how many Roles it carried over.
5119    pub async fn activate_roles_v2(&self, community_id: &str, everyone: &str) -> Result<usize> {
5120        let v2 = Self::held_v2(community_id)?;
5121        let perms = Self::parse_permissions(everyone)?;
5122        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(30));
5123        let carried = crate::community::v2::service::activate_roles_v2(&transport, &v2, perms).await.map_err(VectorError::Other)?;
5124        Self::converge_v2_authority(&transport, community_id).await;
5125        Ok(carried)
5126    }
5127
5128    /// Create a Category at the bottom of the sidebar. Returns its id.
5129    pub async fn create_category(&self, community_id: &str, name: &str) -> Result<String> {
5130        let v2 = Self::held_v2(community_id)?;
5131        let id = crate::community::v2::service::create_category(&Self::short_transport(), &v2, name).await.map_err(VectorError::Other)?;
5132        Ok(crate::simd::hex::bytes_to_hex_32(&id))
5133    }
5134
5135    pub async fn rename_category(&self, community_id: &str, category_id: &str, name: &str) -> Result<()> {
5136        let v2 = Self::held_v2(community_id)?;
5137        crate::community::v2::service::rename_category(&Self::short_transport(), &v2, Self::id32(category_id, "category_id")?, name).await.map_err(VectorError::Other)
5138    }
5139
5140    /// Delete a Category; its Channels render uncategorized.
5141    pub async fn delete_category(&self, community_id: &str, category_id: &str) -> Result<()> {
5142        let v2 = Self::held_v2(community_id)?;
5143        crate::community::v2::service::delete_category(&Self::short_transport(), &v2, Self::id32(category_id, "category_id")?).await.map_err(VectorError::Other)
5144    }
5145
5146    /// Move a Category to `index` among the Categories (0 is the top).
5147    pub async fn move_category(&self, community_id: &str, category_id: &str, index: usize) -> Result<()> {
5148        let v2 = Self::held_v2(community_id)?;
5149        crate::community::v2::service::move_category(&Self::short_transport(), &v2, Self::id32(category_id, "category_id")?, index).await.map_err(VectorError::Other)
5150    }
5151
5152    /// Move a Channel into a Category (`None` = uncategorized) at `index` among its Channels.
5153    pub async fn move_channel(&self, community_id: &str, channel_id: &str, category_id: Option<&str>, index: usize) -> Result<()> {
5154        let v2 = Self::held_v2(community_id)?;
5155        let channel = crate::community::ChannelId(Self::id32(channel_id, "channel_id")?);
5156        let category = category_id.map(|c| Self::id32(c, "category_id")).transpose()?;
5157        crate::community::v2::service::move_channel(&Self::short_transport(), &v2, &channel, category, index).await.map_err(VectorError::Other)
5158    }
5159
5160    /// Edit a Channel's name, topic and view (`chat`, `forum` or `voice`).
5161    pub async fn edit_channel_details(&self, community_id: &str, channel_id: &str, name: &str, topic: Option<&str>, view: &str) -> Result<()> {
5162        let view = Self::view_named(view)?;
5163        let v2 = Self::held_v2(community_id)?;
5164        let channel = crate::community::ChannelId(Self::id32(channel_id, "channel_id")?);
5165        crate::community::v2::service::edit_channel_details(&Self::short_transport(), &v2, &channel, name, topic, view).await.map_err(VectorError::Other)
5166    }
5167
5168    /// Make a Channel private (a key of its own, CORD-03 §2) or public again.
5169    pub async fn set_channel_private(&self, community_id: &str, channel_id: &str, private: bool) -> Result<()> {
5170        let v2 = Self::held_v2(community_id)?;
5171        let channel = crate::community::ChannelId(Self::id32(channel_id, "channel_id")?);
5172        let transport = Self::short_transport();
5173        if private {
5174            return crate::community::v2::service::privatize_channel(&transport, &v2, &channel).await.map_err(VectorError::Other);
5175        }
5176        crate::community::v2::service::publicize_channel(&transport, &v2, &channel).await.map_err(VectorError::Other)
5177    }
5178
5179    /// Set exactly which Roles a member holds.
5180    pub async fn set_member_roles(&self, community_id: &str, npub: &str, role_ids: Vec<String>) -> Result<()> {
5181        let v2 = Self::load_held(community_id)?
5182            .ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
5183        let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
5184        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5185        crate::community::v2::service::set_member_roles(&transport, &v2, &member, role_ids)
5186            .await
5187            .map_err(VectorError::Other)?;
5188        Self::converge_v2_authority_soon(community_id);
5189        Ok(())
5190    }
5191
5192    /// Give a member `add` and take `remove`, against the Roles they hold by the freshest
5193    /// view, so a Role another moderator granted or took meanwhile stays as they left it.
5194    pub async fn modify_member_roles(&self, community_id: &str, npub: &str, add: &[String], remove: &[String]) -> Result<()> {
5195        let v2 = Self::load_held(community_id)?
5196            .ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
5197        let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
5198        let (add, remove): (Vec<String>, Vec<String>) =
5199            (add.iter().map(|r| r.to_ascii_lowercase()).collect(), remove.iter().map(|r| r.to_ascii_lowercase()).collect());
5200        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5201        crate::community::v2::service::change_member_roles(&transport, &v2, &member, move |current| {
5202            let mut next: Vec<String> = current.iter().map(|r| r.to_ascii_lowercase()).filter(|r| !remove.contains(r)).collect();
5203            next.extend(add.into_iter().filter(|r| !remove.contains(r)));
5204            next
5205        })
5206        .await
5207        .map_err(VectorError::Other)?;
5208        Self::converge_v2_authority_soon(community_id);
5209        Ok(())
5210    }
5211
5212    /// Whether `npub` holds `permission` in this community, per the folded roster.
5213    ///
5214    /// The roster IS the ACL (CORD-04), so this is the same question every
5215    /// enforcement path asks — a bot gating a chat command on it refuses exactly
5216    /// what the protocol would, instead of inventing a second permission model
5217    /// that can disagree with the first.
5218    ///
5219    /// Deliberately NOT [`community_capabilities`](Self::community_capabilities): that answers "could I publish
5220    /// this", which additionally needs the Control Plane write key. Here the
5221    /// caller is asking *someone else* for authority while the bot does the
5222    /// publishing, so the write key is the bot's problem, not theirs.
5223    ///
5224    /// Fails CLOSED. A banned member holds nothing; an unreadable or not-yet-folded
5225    /// roster answers `false` for everyone but the owner, because `has_permission`
5226    /// finds no grant. Authority must never be granted by an absence of data.
5227    pub fn member_has_permission(&self, community_id: &str, npub: &str, permission: u64) -> Result<bool> {
5228        use nostr_sdk::prelude::PublicKey;
5229        let who = PublicKey::parse(npub).map_err(|_| VectorError::Other(format!("invalid npub: {npub}")))?.to_hex();
5230        let owner_hex = Self::load_held(community_id)?
5231            .ok_or_else(|| VectorError::Other("community not found".into()))?
5232            .owner()
5233            .map_err(VectorError::Other)?
5234            .to_hex();
5235        if who != owner_hex && crate::db::community::get_community_banlist(community_id).unwrap_or_default().contains(&who) {
5236            return Ok(false);
5237        }
5238        let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
5239        Ok(roster.is_authorized(&who, Some(&owner_hex), permission))
5240    }
5241
5242    /// The community's owner npub + the admin npubs (role overview). A local read,
5243    /// like [`Self::community_capabilities`].
5244    pub fn community_roles(&self, community_id: &str) -> Result<serde_json::Value> {
5245        use nostr_sdk::prelude::{PublicKey, ToBech32};
5246        let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
5247        let owner = v2.owner().map_err(VectorError::Other)?;
5248        let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
5249        // Exclude banned members from the admin list (a banned npub vanishes, §4).
5250        let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
5251        let admins: Vec<String> = roster.grants.iter()
5252            .filter(|g| roster.is_admin(&g.member) && !banned.contains(&g.member))
5253            .filter_map(|g| PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok()))
5254            .collect();
5255        Ok(serde_json::json!({ "owner": owner.to_bech32().ok(), "admins": admins }))
5256    }
5257
5258    /// [`converge_v2_authority`](Self::converge_v2_authority) without holding the caller. A Role
5259    /// change is in this device's own fold the moment it publishes, so the re-read only catches
5260    /// what others changed meanwhile, and a bot handing out Roles answers as soon as the keys are out.
5261    fn converge_v2_authority_soon(community_id: &str) {
5262        let Some(id) = crate::simd::hex::hex_to_bytes_32_checked(community_id).map(crate::community::CommunityId) else { return };
5263        // A listening client's worker runs the same re-read, one at a time however many ask.
5264        if crate::community::v2::realtime::follow_worker_running() {
5265            crate::community::v2::realtime::enqueue_follow(&id);
5266            return;
5267        }
5268        let community_id = community_id.to_string();
5269        crate::db::spawn_bound(async move {
5270            let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5271            Self::converge_v2_authority(&transport, &community_id).await;
5272        });
5273    }
5274
5275    /// Fold the v2 control plane back in right after publishing an authority change, so the
5276    /// LOCAL roster/banlist — which is what every read is served from (crowns, in-chat tags,
5277    /// capabilities, moderation gates) — is current by the time the call returns. `publish`
5278    /// only returns once a relay ACKed, so this refetch sees our own edition; the fold
5279    /// announces `community_refreshed` itself when the roster actually moved.
5280    ///
5281    /// Best-effort: the edition is already published, so a failed refold is a stale local
5282    /// cache the next follow repairs, never a failed action.
5283    async fn converge_v2_authority(
5284        transport: &crate::community::transport::LiveTransport,
5285        community_id: &str,
5286    ) {
5287        crate::db::scoped(async move {
5288            // Reload rather than reuse the caller's clone: the publish advanced edition floors,
5289            // and a rekey/refound may have moved the control address under us.
5290            if let Ok(Some(fresh)) = Self::load_held(community_id) {
5291                let _ = crate::community::v2::service::follow_control(transport, &fresh).await;
5292                // Membership is part of the view being converged: an unban must
5293                // re-fetch the Guestbook, because a Join that legally raced the ban
5294                // window may exist only on the relays — and our own just-published
5295                // edition doesn't echo back to trigger a follow.
5296                if let Ok(added) = crate::community::v2::service::sync_guestbook(transport, &fresh).await {
5297                    if !added.is_empty() {
5298                        traits::emit_event_json(
5299                            "community_refreshed",
5300                            serde_json::json!({ "community_id": community_id }),
5301                        );
5302                    }
5303                }
5304            }
5305        })
5306        .await
5307    }
5308
5309    /// Grant a member the @admin role. Requires MANAGE_ROLES + outranking the role's position.
5310    pub async fn grant_admin(&self, community_id: &str, npub: &str) -> Result<()> {
5311        use crate::community::transport::LiveTransport;
5312        let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
5313        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5314        let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
5315        crate::community::v2::service::grant_admin(&transport, &v2, &member)
5316            .await
5317            .map_err(VectorError::Other)?;
5318        Self::converge_v2_authority(&transport, community_id).await;
5319        Ok(())
5320    }
5321
5322    /// Revoke a member's @admin role.
5323    pub async fn revoke_admin(&self, community_id: &str, npub: &str) -> Result<()> {
5324        use crate::community::transport::LiveTransport;
5325        let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
5326        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5327        let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
5328        crate::community::v2::service::revoke_admin(&transport, &v2, &member)
5329            .await
5330            .map_err(VectorError::Other)?;
5331        Self::converge_v2_authority(&transport, community_id).await;
5332        Ok(())
5333    }
5334
5335    /// Cooperatively kick a member — they self-remove but can rejoin. Requires KICK + outrank.
5336    pub async fn kick_member(&self, community_id: &str, npub: &str) -> Result<()> {
5337        crate::db::scoped(async move {
5338            use crate::community::transport::LiveTransport;
5339            let pk = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
5340            let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5341            let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
5342            crate::community::v2::service::kick_member(&transport, &v2, &pk)
5343                .await
5344                .map_err(VectorError::Other)?;
5345            // Catch the local Guestbook up on our own Kick, so the memberlist read
5346            // (which folds the STORE, not the network) drops them before this returns
5347            // instead of waiting on the relay echo. The control fold follows because a
5348            // Kick strips roles first (CORD-04 §6), which moves the roster too.
5349            if let Ok(fresh) = crate::community::v2::service::sync_guestbook(&transport, &v2).await {
5350                if !fresh.is_empty() {
5351                    emit_event("community_refreshed", &serde_json::json!({ "community_id": community_id }));
5352                }
5353            }
5354            Self::converge_v2_authority(&transport, community_id).await;
5355            Ok(())
5356        })
5357        .await
5358    }
5359
5360    /// Ban (`true`) or unban (`false`) a member. Ban is terminal (no rejoin). The read cut:
5361    /// a private community re-founds (full rotation); a public one rotates just the private
5362    /// channels the member could read (CORD-05 §5 — no refound, the link refresh would
5363    /// re-hand them the root). Requires BAN + outrank, checked against the folded roster
5364    /// BEFORE any publish.
5365    pub async fn set_member_banned(&self, community_id: &str, npub: &str, banned: bool) -> Result<()> {
5366        self.set_members_banned(community_id, &[npub], banned).await
5367    }
5368
5369    /// Ban (`true`) or unban (`false`) a whole batch as ONE moderation unit: one
5370    /// Banlist edition, one grant-strip pass, one read cut — a private community
5371    /// re-founds ONCE with every target removed, however many there are. Additive
5372    /// on ban, reductive on unban, over the freshest folded list either way.
5373    ///
5374    /// Serialized per community (with every other ban/unban) so concurrent
5375    /// moderation composes in arrival order instead of the last write erasing
5376    /// its siblings. The wire caps a Banlist at 500 entries — a batch that would
5377    /// exceed it fails before anything publishes.
5378    pub async fn set_members_banned(&self, community_id: &str, npubs: &[&str], banned: bool) -> Result<()> {
5379        use crate::community::{transport::LiveTransport, CommunityId};
5380        if npubs.is_empty() {
5381            return Ok(());
5382        }
5383        // Parse every target up front — one bad npub fails the batch before any publish.
5384        let mut pks: Vec<nostr_sdk::prelude::PublicKey> = Vec::with_capacity(npubs.len());
5385        for n in npubs {
5386            let pk = nostr_sdk::prelude::PublicKey::parse(n).map_err(|_| VectorError::Other(format!("invalid npub: {n}")))?;
5387            if !pks.contains(&pk) {
5388                pks.push(pk);
5389            }
5390        }
5391        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5392        // A v2 Ban is the CORD-04 §6 three-removal composition, in order — the Banlist
5393        // edition first (instant silence), then the Grant strip (authority removal), then
5394        // the Refounding read-cut (cryptographic severance).
5395        if community_id.len() != 64 {
5396            return Err(VectorError::Other("malformed community id".into()));
5397        }
5398        let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
5399        crate::community::v2::service::set_members_banned(&transport, &cid, &pks, banned)
5400            .await
5401            .map_err(VectorError::Other)?;
5402        // A ban removes them from the memberlist; the memoised verdict still counts them as
5403        // present and keeps flagging a raid nobody is running any more.
5404        Self::invalidate_raid_report(community_id);
5405        Self::announce_ban_change(community_id);
5406        Ok(())
5407    }
5408
5409    /// Our own ban never reaches the fold as a change (the publish already wrote the
5410    /// list locally), so announce it: the UI re-reads its filtered history, which takes
5411    /// their messages and their join/leave lines with it.
5412    fn announce_ban_change(community_id: &str) {
5413        emit_event("community_refreshed", &serde_json::json!({ "community_id": community_id }));
5414    }
5415
5416    /// Re-vend the epoch chain to members a past rotation forgot.
5417    ///
5418    /// A client follows rekeys hop by hop and can only ever derive `held + 1`, so
5419    /// a member missed at one hop is stranded there permanently — no later
5420    /// rotation can reach them, and re-inviting does not help because they are
5421    /// already a member. This publishes the blobs that should have existed, keyed
5422    /// exactly like the original rotation so they merge into it.
5423    ///
5424    /// Requires rotation authority (owner or BAN) and the archived roots, which
5425    /// the rotator holds. Publishing nothing else and touching no membership.
5426    pub async fn rescue_stranded_members(&self, community_id: &str, npubs: &[&str]) -> Result<serde_json::Value> {
5427        use nostr_sdk::prelude::PublicKey;
5428        let community = Self::load_held(community_id)?
5429            .ok_or_else(|| VectorError::Other("rescuing requires a Concord v2 community".into()))?;
5430        let mut targets: Vec<PublicKey> = Vec::with_capacity(npubs.len());
5431        for n in npubs {
5432            let pk = PublicKey::parse(n).map_err(|_| VectorError::Other(format!("invalid npub: {n}")))?;
5433            if !targets.contains(&pk) {
5434                targets.push(pk);
5435            }
5436        }
5437        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(30));
5438        let report = crate::community::v2::service::rescue_stranded_members(&transport, &community, &targets)
5439            .await
5440            .map_err(VectorError::Other)?;
5441        serde_json::to_value(report).map_err(|e| VectorError::Other(e.to_string()))
5442    }
5443
5444    /// Repair a v2 community's roster cache: keep what is stored, but reset its
5445    /// PROVENANCE to zero so the next control fold is allowed to replace it.
5446    ///
5447    /// The completeness guard retains the cached roster whenever a stored entity is
5448    /// floored but folds no head — protection against a relay quietly stripping
5449    /// admins. If the cache itself is wrong, that same guard pins the wrong data in
5450    /// place: the fold can see the real roster and still be refused. Zeroing the
5451    /// provenance marks the cache a seed — a guess, not evidence — which the fold may
5452    /// overwrite. It publishes nothing and touches no key material; worst case the
5453    /// next fold writes what it can see, which is what a fresh join would get.
5454    pub async fn repair_community_roster(&self, community_id: &str) -> Result<serde_json::Value> {
5455        use crate::community::CommunityId;
5456        if community_id.len() != 64 {
5457            return Err(VectorError::Other("malformed community id".into()));
5458        }
5459        let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
5460        if crate::db::community::load_community_v2(&cid).map_err(VectorError::Other)?.is_none() {
5461            return Err(VectorError::Other("not a held Concord v2 community".into()));
5462        }
5463        let before = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
5464        let before_at = crate::db::community::get_community_roles_at(community_id).map_err(VectorError::Other)?;
5465        crate::db::community::set_community_roles(community_id, &before, 0).map_err(VectorError::Other)?;
5466        // Fold immediately so the repair is one step, not two.
5467        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(20));
5468        let community = crate::db::community::load_community_v2(&cid)
5469            .map_err(VectorError::Other)?
5470            .ok_or_else(|| VectorError::Other("community vanished mid-repair".into()))?;
5471        let follow = crate::community::v2::service::follow_control(&transport, &community).await;
5472        let after = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
5473        Ok(serde_json::json!({
5474            "provenance_before": before_at,
5475            "provenance_after": crate::db::community::get_community_roles_at(community_id).unwrap_or(0),
5476            "roles_before": before.roles.len(),
5477            "grants_before": before.grants.len(),
5478            "roles_after": after.roles.len(),
5479            "grants_after": after.grants.len(),
5480            "fold_error": follow.as_ref().err().cloned(),
5481            "repaired": after.grants.len() > before.grants.len(),
5482        }))
5483    }
5484
5485    /// Explain this account's epoch state for a v2 community: what it holds, what
5486    /// the next-epoch rekey plane offers, and why each rotation there was or was not
5487    /// adopted.
5488    ///
5489    /// This is the answer to "is this client stranded, and why" — a question that is
5490    /// otherwise unanswerable, because a stranded client sees only silence and
5491    /// silence looks exactly like a quiet community. Run it from two clients on one
5492    /// community to compare their views; the `held` block is where they diverge
5493    /// first. Read-only; returns public keys and verdicts, never key material.
5494    pub async fn explain_epoch_state(&self, community_id: &str) -> Result<serde_json::Value> {
5495        use crate::community::{transport::LiveTransport, CommunityId};
5496        if community_id.len() != 64 {
5497            return Err(VectorError::Other("malformed community id".into()));
5498        }
5499        let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
5500        let community = crate::db::community::load_community_v2(&cid)
5501            .map_err(VectorError::Other)?
5502            .ok_or_else(|| VectorError::Other("not a held Concord v2 community".into()))?;
5503        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(15));
5504        crate::community::v2::service::explain_epoch_state(&transport, &community)
5505            .await
5506            .map_err(VectorError::Other)
5507    }
5508
5509    /// Contain a raid (v2 only): ban the named raiders, cut everyone who joined
5510    /// through the door during the raid window, and perform a SEVERING Refounding
5511    /// — the rotation that REVOKES the public invite links instead of carrying
5512    /// them into the new epoch.
5513    ///
5514    /// This is the raid lane. An ordinary ban keeps its shipped behaviour, where a
5515    /// Public community deliberately does not roll the root (the stable-URL refresh
5516    /// would undo it). Here the link IS the attack surface, so it closes.
5517    ///
5518    /// `window_start_secs` is the raid's opening edge (unix seconds); pass 0 to cut
5519    /// only the convicted. Returns an honest report — a failed refound is reported,
5520    /// never dressed up as a closed door.
5521    pub async fn contain_raid(
5522        &self,
5523        community_id: &str,
5524        npubs: &[&str],
5525        window_start_secs: u64,
5526        cut_also: &[&str],
5527    ) -> Result<crate::community::v2::service::ContainmentReport> {
5528        use crate::community::{transport::LiveTransport, CommunityId};
5529        if community_id.len() != 64 {
5530            return Err(VectorError::Other("malformed community id".into()));
5531        }
5532        let mut pks: Vec<nostr_sdk::prelude::PublicKey> = Vec::with_capacity(npubs.len());
5533        for n in npubs {
5534            let pk = nostr_sdk::prelude::PublicKey::parse(n).map_err(|_| VectorError::Other(format!("invalid npub: {n}")))?;
5535            if !pks.contains(&pk) {
5536                pks.push(pk);
5537            }
5538        }
5539        let mut extra: Vec<nostr_sdk::prelude::PublicKey> = Vec::with_capacity(cut_also.len());
5540        for n in cut_also {
5541            let pk = nostr_sdk::prelude::PublicKey::parse(n).map_err(|_| VectorError::Other(format!("invalid npub: {n}")))?;
5542            if !extra.contains(&pk) {
5543                extra.push(pk);
5544            }
5545        }
5546        let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
5547        if !crate::db::community::community_held(&cid).map_err(VectorError::Other)? {
5548            return Err(VectorError::Other("community not found".into()));
5549        }
5550        // Unbound caller (SDK/command): a swap mid-containment would ban in one
5551        // account and rotate in another.
5552        let session = crate::db::current_session();
5553        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(20));
5554        let report = crate::community::v2::service::contain_raid(&transport, &cid, &pks, window_start_secs, &extra)
5555            .await
5556            .map_err(VectorError::Other)?;
5557        if !session.is_live() {
5558            return Err(VectorError::Other("account changed during raid containment".into()));
5559        }
5560        Self::invalidate_raid_report(community_id);
5561        Ok(report)
5562    }
5563
5564    /// Owner dissolution / "Delete Community": publish the terminal GroupDissolved tombstone (and
5565    /// retire the owner's own invite links, no rekey), sealing the community permanently. Owner-only
5566    /// (re-verified cryptographically in `service::dissolve_community`); irreversible.
5567    pub async fn dissolve_community(&self, community_id: &str) -> Result<()> {
5568        use crate::community::{transport::LiveTransport, CommunityId};
5569        if community_id.len() != 64 {
5570            return Err(VectorError::Other("malformed community id".into()));
5571        }
5572        let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
5573        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5574        // Dissolves at the `community_id`-derived dissolved plane (CORD-02 §9).
5575        let community = crate::db::community::load_community_v2(&cid)
5576            .map_err(VectorError::Other)?
5577            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
5578        crate::community::v2::service::dissolve_community(&transport, &community)
5579            .await
5580            .map_err(VectorError::Other)?;
5581        // Its icon and banner have nothing left to show on: off the media server too.
5582        drop_community_image(community.icon.as_ref().map(|i| i.url.clone()), None);
5583        drop_community_image(community.banner.as_ref().map(|i| i.url.clone()), community.icon.as_ref().map(|i| i.url.as_str()));
5584        Ok(())
5585    }
5586
5587    /// Edit community metadata (name / description) as an authorized member (MANAGE_METADATA). `None` leaves
5588    /// a field unchanged; an empty description clears it.
5589    pub async fn edit_community_metadata(&self, community_id: &str, name: Option<&str>, description: Option<&str>) -> Result<()> {
5590        use crate::community::{transport::LiveTransport, CommunityId};
5591        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5592        // An authorized vsk-0 control edition, overlaid onto the FULL held document
5593        // (`CommunityV2::metadata()`): an edition replaces the entity, so a bare name edit
5594        // would otherwise wipe the icon/banner for every member (CORD-02 §6).
5595        if community_id.len() != 64 {
5596            return Err(VectorError::Other("malformed community id".into()));
5597        }
5598        let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
5599        let community = crate::db::community::load_community_v2(&cid)
5600            .map_err(VectorError::Other)?
5601            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
5602        let mut meta = community.metadata();
5603        if let Some(n) = name {
5604            meta.name = n.to_string();
5605        }
5606        if let Some(d) = description {
5607            meta.description = if d.is_empty() { None } else { Some(d.to_string()) };
5608        }
5609        crate::community::v2::service::edit_community_metadata(&transport, &community, &meta)
5610            .await
5611            .map_err(VectorError::Other)
5612    }
5613
5614    /// Take a Community's logo or banner away (MANAGE_METADATA). An edition is the whole
5615    /// document, so one without the image removes it for every member.
5616    pub async fn remove_community_image(&self, community_id: &str, is_banner: bool) -> Result<()> {
5617        use crate::community::{transport::LiveTransport, CommunityId};
5618        let session = crate::db::current_session();
5619        let cid = CommunityId(Self::id32(community_id, "community_id")?);
5620        let community = crate::db::community::load_community_v2(&cid)
5621            .map_err(VectorError::Other)?
5622            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
5623        let mut meta = community.metadata();
5624        let gone = if is_banner { meta.banner.take() } else { meta.icon.take() };
5625        let kept = if is_banner { meta.icon.as_ref() } else { meta.banner.as_ref() }.map(|i| i.url.clone());
5626        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5627        crate::community::v2::service::edit_community_metadata(&transport, &community, &meta)
5628            .await
5629            .map_err(VectorError::Other)?;
5630        // Unbound caller: the edition is out, but the account on screen may no longer be its own.
5631        if !session.is_live() {
5632            return Err(VectorError::Other("account changed while removing the image".into()));
5633        }
5634        drop_community_image(gone.map(|i| i.url), kept.as_deref());
5635        if let Some(updated) = crate::community::v2::service::persist_community_image(&cid, None, is_banner).await {
5636            self.register_v2_chats(&updated, &session).await;
5637        }
5638        Ok(())
5639    }
5640
5641    /// Set a Community's icon, or its banner when `is_banner`, from image bytes (MANAGE_METADATA).
5642    /// The image is stripped of metadata and fitted first, then encrypted so only members can
5643    /// open it. Returns the uploaded blob's URL.
5644    pub async fn set_community_image(&self, community_id: &str, bytes: &[u8], is_banner: bool) -> Result<String> {
5645        let usage = if is_banner { crate::image_prep::ImageUse::Banner } else { crate::image_prep::ImageUse::Icon };
5646        let raw = bytes.to_vec();
5647        let prepared = crate::rt::spawn_blocking(move || crate::image_prep::prepare(&raw, usage))
5648            .await
5649            .map_err(|e| VectorError::Other(format!("image preparation stopped: {e}")))?
5650            .map_err(VectorError::Other)?;
5651        self.publish_community_image(community_id, prepared.bytes, prepared.extension, is_banner, None).await
5652    }
5653
5654    /// [`set_community_image`](Self::set_community_image) for bytes already prepared, which
5655    /// are published as given. `progress` hears the upload.
5656    pub async fn publish_community_image(
5657        &self,
5658        community_id: &str,
5659        bytes: Vec<u8>,
5660        extension: &str,
5661        is_banner: bool,
5662        progress: Option<crate::blossom::ProgressCallback>,
5663    ) -> Result<String> {
5664        use crate::community::{transport::LiveTransport, CommunityId};
5665        let session = crate::db::current_session();
5666        let cid = CommunityId(Self::id32(community_id, "community_id")?);
5667        crate::db::community::load_community_v2(&cid)
5668            .map_err(VectorError::Db)?
5669            .ok_or_else(|| VectorError::NotFound("community".into()))?;
5670        if crate::svg::looks_like_svg(&bytes) {
5671            return Err(VectorError::Other(crate::community::SVG_REFUSED.to_string()));
5672        }
5673        let hash = crate::crypto::sha256_hex(&bytes);
5674        // A fresh key per image: it rides the members-only metadata edition.
5675        let params = crate::crypto::generate_encryption_params();
5676        let encrypted = crate::crypto::encrypt_data(&bytes, &params).map_err(VectorError::Other)?;
5677        let signer = crate::signer::active_signer().map_err(|e| VectorError::Other(format!("signer: {e}")))?;
5678        let servers = state::get_blossom_servers();
5679        if servers.is_empty() {
5680            return Err(VectorError::Other("no Blossom servers configured".into()));
5681        }
5682        let progress = progress.unwrap_or_else(|| std::sync::Arc::new(|_, _| Ok(())));
5683        let url = crate::blossom::upload_blob_with_progress_and_failover(
5684            signer,
5685            servers,
5686            std::sync::Arc::new(encrypted),
5687            Some("application/octet-stream"),
5688            true,
5689            progress,
5690            None,
5691            None,
5692            None,
5693        )
5694        .await
5695        .map_err(VectorError::Other)?
5696        .url;
5697        let mut extra = serde_json::Map::new();
5698        extra.insert("ext".into(), serde_json::Value::String(extension.to_string()));
5699        let image = crate::community::v2::control::ImageRef { url: url.clone(), key: params.key.clone(), nonce: params.nonce.clone(), hash, extra };
5700        // The edition signs as whoever is live: never as the account that took over mid-upload.
5701        if !session.is_live() {
5702            return Err(VectorError::Other("account changed while setting the image".into()));
5703        }
5704        // Overlaid onto the document as it stands after the upload, so an edit made meanwhile
5705        // survives; an edition replaces the whole of it.
5706        let community = crate::db::community::load_community_v2(&cid)
5707            .map_err(VectorError::Db)?
5708            .ok_or_else(|| VectorError::NotFound("community".into()))?;
5709        let mut meta = community.metadata();
5710        let replaced = if is_banner { meta.banner.replace(image.clone()) } else { meta.icon.replace(image.clone()) };
5711        let kept = if is_banner { meta.icon.as_ref() } else { meta.banner.as_ref() }.map(|i| i.url.clone());
5712        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5713        crate::community::v2::service::edit_community_metadata(&transport, &community, &meta)
5714            .await
5715            .map_err(VectorError::Other)?;
5716        if !session.is_live() {
5717            return Err(VectorError::Other("account changed while setting the image".into()));
5718        }
5719        drop_community_image(replaced.map(|i| i.url).filter(|u| *u != url), kept.as_deref());
5720        if let Some(updated) = crate::community::v2::service::persist_community_image(&cid, Some(image), is_banner).await {
5721            self.register_v2_chats(&updated, &session).await;
5722        }
5723        Ok(url)
5724    }
5725
5726    /// A Community's icon, or its banner when `is_banner`, as a member sees it: downloaded,
5727    /// decrypted and checked against the hash the metadata commits to. `None` when it has none.
5728    pub async fn community_image(&self, community_id: &str, is_banner: bool) -> Result<Option<Vec<u8>>> {
5729        use crate::community::CommunityId;
5730        let cid = CommunityId(Self::id32(community_id, "community_id")?);
5731        let community = crate::db::community::load_community_v2(&cid)
5732            .map_err(VectorError::Other)?
5733            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
5734        let Some(image) = (if is_banner { community.banner } else { community.icon }) else {
5735            return Ok(None);
5736        };
5737        let cap: usize = if is_banner { 16 } else { 10 } * 1024 * 1024;
5738        // The URL is the editor's to write: refuse one aimed inside this machine's network.
5739        crate::net::validate_url_not_private(&image.url).map_err(|e| VectorError::Network(format!("community image URL refused: {e}")))?;
5740        let client = crate::net::build_http_client(std::time::Duration::from_secs(30)).map_err(VectorError::Network)?;
5741        let resp = crate::net::proxied_request(&client, reqwest::Method::GET, &image.url)
5742            .await
5743            .send()
5744            .await
5745            .map_err(|e| VectorError::Network(format!("download: {e}")))?;
5746        if !resp.status().is_success() {
5747            return Err(VectorError::Network(format!("download failed: HTTP {}", resp.status())));
5748        }
5749        let mut encrypted: Vec<u8> = Vec::with_capacity(resp.content_length().map_or(64 * 1024, |l| (l as usize).min(cap)));
5750        let mut body = resp.bytes_stream();
5751        while let Some(chunk) = futures_util::StreamExt::next(&mut body).await {
5752            let chunk = chunk.map_err(|e| VectorError::Network(format!("read body: {e}")))?;
5753            if encrypted.len() + chunk.len() > cap {
5754                return Err(VectorError::Other("community image too large".into()));
5755            }
5756            encrypted.extend_from_slice(&chunk);
5757        }
5758        let plain = crate::crypto::decrypt_data_owned(encrypted, &image.key, &image.nonce).map_err(VectorError::Crypto)?;
5759        if crate::crypto::sha256_hex(&plain) != image.hash {
5760            return Err(VectorError::Crypto("community image failed its integrity check".into()));
5761        }
5762        if crate::svg::looks_like_svg(&plain) {
5763            return Err(VectorError::Other(crate::community::SVG_REFUSED.to_string()));
5764        }
5765        Ok(Some(plain))
5766    }
5767
5768    /// Set the iroh relays a Community's voice channels use (CORD-07 §8): at most eight, https
5769    /// only; none means iroh's defaults. Overlaid onto the held document like any metadata edit.
5770    pub async fn set_voice_relays(&self, community_id: &str, relays: &[String]) -> Result<Vec<String>> {
5771        use crate::community::{transport::LiveTransport, CommunityId};
5772        let cid = CommunityId(Self::id32(community_id, "community_id")?);
5773        let community = crate::db::community::load_community_v2(&cid)
5774            .map_err(VectorError::Other)?
5775            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
5776        let mut clean: Vec<String> = Vec::new();
5777        for r in relays.iter().map(|r| r.trim().trim_end_matches('/').to_string()).filter(|r| !r.is_empty()) {
5778            let parsed = url::Url::parse(&r).map_err(|_| VectorError::Other(format!("{r} isn't a relay address")))?;
5779            if parsed.scheme() != "https" || parsed.host_str().is_none() {
5780                return Err(VectorError::Other(format!("{r}: a voice relay is an https:// address")));
5781            }
5782            let normal = format!("{}/", parsed.as_str().trim_end_matches('/'));
5783            if !clean.contains(&normal) {
5784                clean.push(normal);
5785            }
5786        }
5787        if clean.len() > crate::community::v2::community::MAX_VOICE_RELAYS {
5788            return Err(VectorError::Other(format!("at most {} voice relays", crate::community::v2::community::MAX_VOICE_RELAYS)));
5789        }
5790        let mut meta = community.metadata();
5791        if clean.is_empty() {
5792            meta.extra.remove("voice_relays");
5793        } else {
5794            meta.extra.insert("voice_relays".into(), serde_json::json!(clean));
5795        }
5796        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5797        crate::community::v2::service::edit_community_metadata(&transport, &community, &meta).await.map_err(VectorError::Other)?;
5798        Ok(clean)
5799    }
5800
5801    /// Leave a Community: announce a best-effort "left" presence (before dropping keys), then
5802    /// drop the held keys + local channel chats. You need a fresh invite to rejoin.
5803    pub async fn leave_community(&self, community_id: &str) -> Result<()> {
5804        crate::db::scoped(async move {
5805            use crate::community::transport::LiveTransport;
5806            if community_id.len() != 64 {
5807                return Err(VectorError::Other("malformed community id".into()));
5808            }
5809            use crate::community::v2::service;
5810            let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5811            let Some(v2) = Self::load_held(community_id)? else {
5812                let cid = Self::unheld_id(community_id)?;
5813                let at_ms = service::leave_unheld_locally(&cid).await.ok_or_else(|| VectorError::Other("community not found".into()))?;
5814                service::announce_unheld_leave(&transport, &cid, at_ms).await;
5815                return Ok(());
5816            };
5817            // Guestbook Leave + cross-device List tombstone + local delete, in the service.
5818            let channel_ids: Vec<String> =
5819                v2.channels.iter().map(|ch| crate::simd::hex::bytes_to_hex_32(&ch.id.0)).collect();
5820            service::leave_community(&transport, &v2).await.map_err(VectorError::Other)?;
5821            service::forget_community_chats(&crate::simd::hex::bytes_to_hex_32(&v2.id().0), &channel_ids).await;
5822            Ok(())
5823        })
5824        .await
5825    }
5826
5827    /// [`Self::leave_community`] for a caller that repaints at once: the community is gone
5828    /// here when this returns, and the announcements publish behind it. The List
5829    /// tombstone is kept pending first, so a leave survives a restart before it lands.
5830    pub async fn leave_community_now(&self, community_id: &str) -> Result<()> {
5831        crate::db::scoped(async move {
5832            use crate::community::v2::service;
5833            let Some(v2) = Self::load_held(community_id)? else {
5834                let cid = Self::unheld_id(community_id)?;
5835                let at_ms = service::leave_unheld_locally(&cid).await.ok_or_else(|| VectorError::Other("community not found".into()))?;
5836                crate::db::spawn_bound(async move {
5837                    let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5838                    service::announce_unheld_leave(&transport, &cid, at_ms).await;
5839                });
5840                return Ok(());
5841            };
5842            let channel_ids: Vec<String> =
5843                v2.channels.iter().map(|ch| crate::simd::hex::bytes_to_hex_32(&ch.id.0)).collect();
5844            let at_ms = service::leave_locally(&v2).map_err(VectorError::Other)?;
5845            service::forget_community_chats(&crate::simd::hex::bytes_to_hex_32(&v2.id().0), &channel_ids).await;
5846            crate::db::spawn_bound(async move {
5847                let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5848                service::announce_leave(&transport, &v2, at_ms).await;
5849                if let Some(client) = state::nostr_client() {
5850                    crate::community::v2::realtime::refresh_subscription(&client).await;
5851                }
5852                // After the announcements, which still need these relays.
5853                crate::community::transport::prune_unneeded_community_relays(&v2.relays).await;
5854            });
5855            Ok(())
5856        })
5857        .await
5858    }
5859
5860    /// Decline a parked invite: dropped here, tombstoned in the Community List so no device parks
5861    /// it again, the wraps that delivered it deleted from our relays, and the relays its bundle
5862    /// named shed.
5863    pub async fn decline_community_invite(&self, community_id: &str) -> Result<()> {
5864        crate::db::scoped(async move {
5865            use crate::db::community as db;
5866            // A bundle this build can't parse names no community the List could ever hold: only drop it.
5867            let bundle = db::get_pending_invite(community_id)
5868                .ok()
5869                .flatten()
5870                .and_then(|j| crate::community::v2::invite::CommunityInvite::from_bundle_json(&j).ok());
5871            let relays: Vec<String> = bundle.as_ref().map(|b| b.relays.clone()).unwrap_or_default();
5872            let wraps = db::pending_invite_wraps(community_id).unwrap_or_default();
5873            db::delete_pending_invite(community_id).map_err(VectorError::Other)?;
5874            if let Some(cid) = bundle.and_then(|_| crate::simd::hex::hex_to_bytes_32_checked(community_id)) {
5875                let removed_at = crate::clock::now_ms();
5876                crate::community::v2::service::tombstone_community_list_durable(crate::community::CommunityId(cid), relays.clone(), removed_at);
5877            }
5878            for wrap in wraps.iter().filter_map(|w| nostr_sdk::prelude::EventId::from_hex(w).ok()) {
5879                crate::deletion::delete_received_wrap(wrap);
5880            }
5881            if !relays.is_empty() {
5882                crate::community::transport::prune_unneeded_community_relays(&relays).await;
5883            }
5884            Ok(())
5885        })
5886        .await
5887    }
5888
5889    /// Sync DM history from relays using NIP-77 negentropy set reconciliation.
5890    ///
5891    /// Reconciles local wrapper history with relay state, fetches missing events,
5892    /// and processes them through the standard prepare → commit pipeline.
5893    ///
5894    /// Returns (total_events, new_messages).
5895    ///
5896    /// ```no_run
5897    /// # async fn example() -> vector_core::Result<()> {
5898    /// let core = vector_core::VectorCore;
5899    /// // Sync last 7 days of DMs
5900    /// let (events, new) = core.sync_dms(Some(7), &vector_core::NoOpEventHandler).await?;
5901    /// println!("Processed {} events, {} new messages", events, new);
5902    /// # Ok(())
5903    /// # }
5904    /// ```
5905    pub async fn sync_dms(
5906        &self,
5907        since_days: Option<u64>,
5908        handler: &dyn InboundEventHandler,
5909    ) -> Result<(u32, u32)> {
5910        crate::db::scoped(async move {
5911            use futures_util::StreamExt;
5912            use nostr_sdk::prelude::*;
5913
5914            let client = state::nostr_client()
5915                .ok_or(VectorError::Other("Not connected".into()))?;
5916            let my_pk = state::my_public_key()
5917                .ok_or(VectorError::Other("Not logged in".into()))?;
5918
5919            // Load known wrapper IDs + timestamps for negentropy fingerprinting.
5920            // A windowed sync bounds the read in SQL: materialising all of
5921            // history to keep a few days of it is most of this function's cost
5922            // on an established account.
5923            let (items, filter) = if let Some(days) = since_days {
5924                let since_ts = crate::clock::timestamp().as_secs().saturating_sub(days * 24 * 3600);
5925                let items = db::wrappers::load_negentropy_items_since(since_ts)
5926                    .unwrap_or_default();
5927                let filter = Filter::new()
5928                    .pubkey(my_pk)
5929                    .kind(Kind::GiftWrap)
5930                    .since(Timestamp::from_secs(since_ts));
5931                (items, filter)
5932            } else {
5933                let items = db::wrappers::load_negentropy_items().unwrap_or_default();
5934                let filter = Filter::new()
5935                    .pubkey(my_pk)
5936                    .kind(Kind::GiftWrap);
5937                (items, filter)
5938            };
5939
5940            log_info!("[SyncDMs] {} negentropy items, since_days={:?}", items.len(), since_days);
5941            let items = std::sync::Arc::new(items);
5942
5943            // Dry-run negentropy: exchange fingerprints to identify missing events
5944            let sync_opts = nostr_sdk::prelude::SyncOptions::new()
5945                .direction(nostr_sdk::prelude::SyncDirection::Down)
5946                .initial_timeout(relay_request_timeout(std::time::Duration::from_secs(10)))
5947                .dry_run();
5948
5949            // Race all relays — first to reconcile drives the fetch. Relays with a
5950            // fresh no-NIP-77 verdict skip the doomed reconcile and get a bounded
5951            // REQ pass below instead.
5952            let relay_map = client.relays().await;
5953            let (all_relays, no_neg_relays): (Vec<_>, Vec<_>) =
5954                relay_map.iter()
5955                    .map(|(url, relay)| (url.clone(), relay.clone()))
5956                    .partition(|(url, _)| negentropy::neg_supported_cached(url.as_str()) != Some(false));
5957            drop(relay_map);
5958            let skipped_no_neg: Vec<String> = no_neg_relays.iter().map(|(u, _)| u.to_string()).collect();
5959            if !skipped_no_neg.is_empty() {
5960                log_info!("[SyncDMs] {} relay(s) on REQ path (no NIP-77)", skipped_no_neg.len());
5961            }
5962
5963            // Tor-aware like the GUI path — a fixed clearnet budget over Tor makes
5964            // a healthy relay's slow first frame look like connected-silence and
5965            // earns it a false 24h no-NEG verdict in the shared account KV.
5966            let neg_budget = relay_request_timeout(std::time::Duration::from_secs(10));
5967            let neg_outer = neg_budget + std::time::Duration::from_secs(5);
5968            let connect_allowance = relay_request_timeout(std::time::Duration::from_secs(3))
5969                .min(neg_outer);
5970            let mut relay_futs = futures_util::stream::FuturesUnordered::new();
5971            for (url, relay) in &all_relays {
5972                let url = url.clone();
5973                let relay = relay.clone();
5974                let f = filter.clone();
5975                let i = items.clone();
5976                let o = sync_opts.clone();
5977                relay_futs.push(async move {
5978                    if !negentropy::wait_connected(&relay, connect_allowance).await {
5979                        return (url, None, false);
5980                    }
5981                    // Outer slack over the initial_timeout so the SDK's error
5982                    // (which distinguishes refusal from silence) surfaces first.
5983                    let result = crate::rt::time::timeout(
5984                        neg_outer,
5985                        relay.sync(f).items(i.iter().copied()).opts(o),
5986                    ).await;
5987                    let connected = relay.status() == RelayStatus::Connected;
5988                    (url, Some(result), connected)
5989                });
5990            }
5991
5992            // Collect missing IDs from all relays
5993            let cap_session = crate::db::current_session();
5994            let mut all_missing: std::collections::HashSet<EventId> = std::collections::HashSet::new();
5995            while let Some((url, result, connected)) = relay_futs.next().await {
5996                let Some(result) = result else {
5997                    log_warn!("[SyncDMs] {} skipped: not connected", url);
5998                    continue;
5999                };
6000                match result {
6001                    Ok(Ok(recon)) => {
6002                        let count = recon.remote.len();
6003                        all_missing.extend(recon.remote);
6004                        log_info!("[SyncDMs] {} reconciled: {} missing", url, count);
6005                        negentropy::record_neg_support(url.as_str(), true);
6006                    }
6007                    Ok(Err(e)) => {
6008                        log_warn!("[SyncDMs] {} failed: {}", url, e);
6009                        if cap_session.is_live()
6010                            && negentropy::classify_neg_sync_error(&e.to_string(), connected && !negentropy::neg_ever_confirmed(url.as_str())) == Some(false)
6011                        {
6012                            log_info!("[SyncDMs] {} marked no-NIP-77 for 24h", url);
6013                            negentropy::record_neg_support(url.as_str(), false);
6014                        }
6015                    }
6016                    Err(_) => log_warn!("[SyncDMs] {} timed out ({:?})", url, neg_outer),
6017                }
6018            }
6019
6020            let mut total_events = 0u32;
6021            let mut new_messages = 0u32;
6022
6023            // No-NIP-77 relays still contribute: one bounded REQ over the same
6024            // filter. The 500-event cap keeps a `since_days: None` call from
6025            // pulling a whole mailbox — deep history is negentropy's job on the
6026            // relays that speak it.
6027            if !skipped_no_neg.is_empty() {
6028                let req_filter = filter.clone().limit(500);
6029                match client
6030                    .stream_events(nostr_sdk::prelude::ReqTarget::manual(
6031                        skipped_no_neg.iter().cloned().map(|u| (u, vec![req_filter.clone()])),
6032                    ))
6033                    .timeout(relay_request_timeout(std::time::Duration::from_secs(20)))
6034                    .await
6035                {
6036                    Ok(stream) => {
6037                        let mut seen: std::collections::HashSet<[u8; 32]> = std::collections::HashSet::new();
6038                        let stream = stream.ready_chunks(event_handler::UNWRAP_BATCH);
6039                        tokio::pin!(stream);
6040                        while let Some(chunk) = stream.next().await {
6041                            // Straddles the stream: a swap mid-drain must not push
6042                            // the old account's wrappers through the new account's
6043                            // pipeline (ErrorSkip would ledger them there).
6044                            let events: Vec<Event> = chunk
6045                                .into_iter()
6046                                .filter_map(|(_relay, res)| res.ok())
6047                                .filter(|event| seen.insert(event.id.to_bytes()))
6048                                .collect();
6049                            total_events += events.len() as u32;
6050                            for prepared in event_handler::prepare_events(&events, my_pk).await {
6051                                if event_handler::commit_prepared_event(prepared, false, handler).await {
6052                                    new_messages += 1;
6053                                }
6054                            }
6055                        }
6056                    }
6057                    Err(e) => log_warn!("[SyncDMs] REQ pass failed: {}", e),
6058                }
6059            }
6060
6061            if all_missing.is_empty() {
6062                log_info!("[SyncDMs] No missing events");
6063                return Ok((total_events, new_messages));
6064            }
6065
6066            // Fetch missing events in batches
6067            log_info!("[SyncDMs] Fetching {} missing events", all_missing.len());
6068            let ids: Vec<EventId> = all_missing.into_iter().collect();
6069            let relay_strs: Vec<String> = client.relays().await.keys()
6070                .map(|u| u.to_string()).collect();
6071
6072            const BATCH_SIZE: usize = 500;
6073
6074            for batch in ids.chunks(BATCH_SIZE) {
6075                // The #p is not redundant: Ditto refuses gift-wrap REQs that carry
6076                // neither authors nor #p, even authed — ids-only returns nothing.
6077                let f = Filter::new().ids(batch.to_vec()).kind(Kind::GiftWrap).pubkey(my_pk);
6078                match client
6079                    .stream_events(nostr_sdk::prelude::ReqTarget::manual(
6080                        relay_strs.iter().cloned().map(|u| (u, vec![f.clone()])),
6081                    ))
6082                    .timeout(std::time::Duration::from_secs(30))
6083                    .await
6084                {
6085                    Ok(stream) => {
6086                        let prepared_stream = stream
6087                            .filter_map(|(_relay, res)| async move { res.ok() })
6088                            .ready_chunks(event_handler::UNWRAP_BATCH)
6089                            .map(move |events| {
6090                                db::spawn_bound(async move {
6091                                    event_handler::prepare_events(&events, my_pk).await
6092                                })
6093                            })
6094                            .buffer_unordered(8);
6095                        tokio::pin!(prepared_stream);
6096
6097                        while let Some(result) = prepared_stream.next().await {
6098                            let Ok(batch) = result else { continue };
6099                            total_events += batch.len() as u32;
6100                            for prepared in batch {
6101                                if event_handler::commit_prepared_event(prepared, false, handler).await {
6102                                    new_messages += 1;
6103                                }
6104                            }
6105                        }
6106                    }
6107                    Err(e) => log_warn!("[SyncDMs] Batch fetch error: {}", e),
6108                }
6109            }
6110
6111            log_info!("[SyncDMs] Complete: {} events processed, {} new messages", total_events, new_messages);
6112            Ok((total_events, new_messages))
6113        })
6114        .await
6115    }
6116
6117    // ========================================================================
6118    // Event Subscription
6119    // ========================================================================
6120
6121    /// Subscribe to incoming DM events (NIP-17 GiftWraps).
6122    ///
6123    /// Returns the subscription ID for use in a custom notification loop.
6124    /// For a complete listen-and-process loop, use [`listen()`](Self::listen) instead.
6125    pub async fn subscribe_dms(&self) -> Result<nostr_sdk::prelude::SubscriptionId> {
6126        use nostr_sdk::prelude::*;
6127        let client = state::nostr_client()
6128            .ok_or(VectorError::Other("Not connected".into()))?;
6129        let my_pk = state::my_public_key()
6130            .ok_or(VectorError::Other("Not logged in".into()))?;
6131
6132        let filter = Filter::new()
6133            .pubkey(my_pk)
6134            .kind(Kind::GiftWrap)
6135            .limit(0);
6136
6137        let output = client.subscribe(filter.clone()).await
6138            .map_err(|e| VectorError::Nostr(e.to_string()))?;
6139        live_subs::keep_output(&output, vec![filter]);
6140        Ok(output.value)
6141    }
6142
6143    /// Catch up every locally-held Community: fold control / re-foundings / rekeys / banlist and
6144    /// fetch recent messages into local state for each channel. History stays local; a listener is
6145    /// told what it fetched that was sent since it began listening ([`news`]). Called at `listen()`
6146    /// start and on reconnect; also safe to call manually after a known disconnect.
6147    ///
6148    /// Catch up every locally-held Community. Each is ENQUEUED for the follow worker (control/rekey re-fold + adopt),
6149    /// non-blocking. History is never replayed to a handler. Called at `listen()`
6150    /// start and on reconnect; safe to call manually — the v2 enqueue is a no-op if
6151    /// no `listen()` worker is running.
6152    /// Returns each community's non-fatal follow warnings (rekey/control catch-up
6153    /// failures), prefixed with the id. A caller that discards them is blind to
6154    /// "the sync ran, but this account never adopted the rotation" — which reads
6155    /// exactly like a healthy quiet sync while the account sits on a dead epoch.
6156    pub async fn sync_communities(&self) -> Result<Vec<String>> {
6157        let mut all_warnings: Vec<String> = Vec::new();
6158        // Discover + rehydrate memberships from the Community List across devices (CORD-02 §8),
6159        // bootstrapping from the client's connected relays so even a fresh device that
6160        // holds no community yet can find them. Best-effort.
6161        {
6162            use crate::community::{transport::LiveTransport, v2::service as v2};
6163            let bootstrap: Vec<String> = match crate::state::nostr_client() {
6164                Some(client) => client.relays().await.keys().map(|r| r.to_string()).collect(),
6165                None => Vec::new(),
6166            };
6167            let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
6168            if let Ok(outcome) = v2::sync_community_list(&transport, &bootstrap).await {
6169                // Headless: core already dropped the rows; a GUI shell additionally clears the
6170                // chat rows + STATE via `removed` (see `ListSyncOutcome`).
6171                let joined = outcome.joined;
6172                for c in &joined {
6173                    if community::v2::realtime::follow_worker_running() {
6174                        community::v2::realtime::enqueue_follow(c.id());
6175                    } else {
6176                        let cid_hex = crate::simd::hex::bytes_to_hex_32(&c.id().0);
6177                        all_warnings.extend(
6178                            Self::v2_inline_follow(c.id()).await.into_iter().map(|w| format!("{}: {w}", &cid_hex[..8])),
6179                        );
6180                    }
6181                }
6182                if !joined.is_empty() {
6183                    if let Some(client) = crate::state::nostr_client() {
6184                        community::v2::realtime::refresh_subscription(&client).await;
6185                    }
6186                }
6187            }
6188        }
6189
6190        let ids = db::community::list_community_ids().map_err(VectorError::from)?;
6191        for id in ids {
6192            // With a live listen() the coalescing worker owns the follow; headless
6193            // (no worker) it would be dropped, so walk it inline instead.
6194            if community::v2::realtime::follow_worker_running() {
6195                community::v2::realtime::enqueue_follow(&id);
6196            } else {
6197                let cid_hex = crate::simd::hex::bytes_to_hex_32(&id.0);
6198                all_warnings.extend(
6199                    Self::v2_inline_follow(&id).await.into_iter().map(|w| format!("{}: {w}", &cid_hex[..8])),
6200                );
6201            }
6202            // Back-fill each channel's chat. Without this a headless client only ever sees messages that arrive
6203            // LIVE: anything sent while it was down — or while it held no key for
6204            // a private channel — is never fetched, so a bot granted access reads
6205            // an empty room. Cheap when there is nothing new (id-deduped), and a
6206            // channel we cannot read simply yields nothing.
6207            if let Ok(Some(c)) = db::community::load_community_v2(&id) {
6208                for ch in &c.channels {
6209                    let hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
6210                    let _ = Self::v2_backfill_channel(
6211                        &id, &hex, 50, 2, None, None,
6212                        crate::community::transport::Evidence::Fast, 12,
6213                    ).await;
6214                }
6215            }
6216        }
6217        Ok(all_warnings)
6218    }
6219
6220
6221    /// Start listening for incoming DMs.
6222    ///
6223    /// Blocks until the client disconnects. Processes GiftWraps
6224    /// (DMs, files) → prepare_event → commit_prepared_event.
6225    ///
6226    /// ```no_run
6227    /// use vector_core::*;
6228    /// use std::sync::Arc;
6229    ///
6230    /// struct MyBot;
6231    /// impl InboundEventHandler for MyBot {
6232    ///     fn on_dm_received(&self, chat_id: &str, msg: &Message, _is_new: bool) {
6233    ///         if msg.mine { return; }
6234    ///         let to = chat_id.to_string();
6235    ///         let reply = format!("Echo: {}", msg.content);
6236    ///         tokio::spawn(async move {
6237    ///             let _ = VectorCore.send_dm(&to, &reply).await;
6238    ///         });
6239    ///     }
6240    /// }
6241    ///
6242    /// # async fn example() -> vector_core::Result<()> {
6243    /// let core = VectorCore::init(CoreConfig {
6244    ///     data_dir: "/tmp/bot-data".into(),
6245    ///     event_emitter: None,
6246    /// })?;
6247    /// core.login("nsec1...", None).await?;
6248    /// core.listen(Arc::new(MyBot)).await?;
6249    /// # Ok(())
6250    /// # }
6251    /// ```
6252    pub async fn listen(&self, handler: Arc<dyn InboundEventHandler>) -> Result<()> {
6253        self.listen_with(handler, CatchUp::Inline).await
6254    }
6255
6256    /// `listen`, choosing who fetches what was published while offline.
6257    pub async fn listen_with(&self, handler: Arc<dyn InboundEventHandler>, catch_up: CatchUp) -> Result<()> {
6258        use nostr_sdk::prelude::*;
6259
6260        let client = state::nostr_client()
6261            .ok_or(VectorError::Other("Not connected".into()))?;
6262        let my_pk = state::my_public_key()
6263            .ok_or(VectorError::Other("Not logged in".into()))?;
6264
6265        // Start the stream-AUTH responder BEFORE any relay interaction: a gating
6266        // relay issues its NIP-42 challenge ONCE per connection, and the DM
6267        // subscribe below consumes it via nostr-sdk's user auto-auth — if the
6268        // responder isn't already watching, that challenge is never remembered
6269        // and the stream keys registered later can NEVER authenticate (the relay
6270        // won't re-challenge an authed connection; the v2 sub dies silently).
6271        community::v2::streamauth::ensure_responder(&client);
6272
6273        // From here on, whatever is sent is news to this listener however it arrives: live, a
6274        // catch-up or a replay, once each. A UI pages history itself and keeps freshness.
6275        let listening_since = crate::clock::now_ms();
6276        let inline = catch_up == CatchUp::Inline;
6277        if inline {
6278            news::begin(handler.clone(), listening_since);
6279        } else {
6280            news::end();
6281        }
6282        let live_from = news::cutoff().unwrap_or(listening_since);
6283
6284        // The change baseline is what this device holds before anything folds, so a change
6285        // the catch-up brings in is compared rather than absorbed; one made before listening
6286        // began is history.
6287        if handler.wants_community_changes() {
6288            community::v2::changes::prime_all(&*handler);
6289        }
6290
6291        // Spawn the single per-community follow worker for this session; the v2
6292        // follow queue (fed by dispatch, catch-up, and sync) drains through it.
6293        community::v2::realtime::spawn_follow_worker(handler.clone());
6294        early::start(handler.clone());
6295
6296        // DMs go live BEFORE the catch-up: the subscription only carries what is
6297        // published after it starts, so a wrap sent mid-catch-up reaches us by one
6298        // or the other. Wrapper dedup absorbs any it gets from both. The stream is
6299        // read from here on, catch-up included, keeping only live subscriptions'
6300        // events: the catch-up's own traffic shares the notification ring and
6301        // would otherwise push them out of it.
6302        let notifications = client.notifications();
6303        let dm_sub_id = self.subscribe_dms().await?;
6304        live_subs::watch(&client);
6305        let (live_tx, mut live_rx) = tokio::sync::mpsc::channel::<(LiveRoute, Box<nostr_sdk::prelude::Event>)>(4096);
6306        let dm_sid = dm_sub_id.clone();
6307        db::spawn_bound(async move {
6308            let mut notifications = notifications;
6309            while let Some(notification) = notifications.next().await {
6310                // Relay OKs feed the send pipeline: an OK that outlives the
6311                // per-attempt wait still confirms delivery, and can rescue a
6312                // message already marked Failed.
6313                if let nostr_sdk::prelude::ClientNotification::Message { message, .. } = &notification {
6314                    if let nostr_sdk::prelude::RelayMessage::Ok { event_id, status, .. } = &**message {
6315                        sending::note_relay_ok(event_id, *status);
6316                    }
6317                }
6318                let nostr_sdk::prelude::ClientNotification::Event { event, subscription_id, .. } = notification else { continue };
6319                let route = if subscription_id == dm_sid {
6320                    LiveRoute::Dm
6321                } else if community::v2::realtime::routes_live(&subscription_id) {
6322                    LiveRoute::CommunityV2
6323                } else {
6324                    continue;
6325                };
6326                if live_tx.send((route, event)).await.is_err() {
6327                    break;
6328                }
6329            }
6330        });
6331
6332        // Outage resilience — catch up on connect, then re-sync periodically.
6333        //
6334        // Communities catch up BEFORE their subscriptions so a bot that was offline folds any
6335        // missed re-foundings / metadata / banlist changes (and recent messages) into local state,
6336        // and subscribes at the CURRENT epoch pseudonyms. History stays local (query it via
6337        // `get_messages`); what it brings in that was sent since listening began is news, and
6338        // reaches the handler once (see `news`, `LiveOnly`).
6339        if inline {
6340            let _ = self.sync_communities().await;
6341            let _ = self.sync_dms(None, &event_handler::LiveOnly::from(&*handler, live_from)).await;
6342        }
6343
6344        // Community channel events share the DM loop below, so `on_dm_received` /
6345        // `on_community_message` share a sink.
6346        community::v2::realtime::refresh_subscription(&client).await;
6347
6348        // The Community subscriptions start after the catch-up: what was published between the
6349        // two reaches the listener through a replay of the planes since listening began.
6350        if inline {
6351            Self::owe_catch_up(false, false, [(EVERY_RELAY.to_string(), live_from)]);
6352            // A relay closing a subscription, or the machine sleeping, leaves a gap the same
6353            // runner fills. The app sets its own.
6354            live_subs::set_catch_up(|what| {
6355                let now = crate::clock::now_ms();
6356                match what {
6357                    live_subs::CatchUp::All { away_ms } => Self::owe_catch_up(true, true, [(EVERY_RELAY.to_string(), now.saturating_sub(away_ms))]),
6358                    live_subs::CatchUp::Relay(url) => Self::owe_catch_up(false, false, [(url, now.saturating_sub(live_subs::MAX_BACKOFF.as_millis() as u64))]),
6359                }
6360            });
6361            #[cfg(not(target_arch = "wasm32"))]
6362            live_subs::start_wake_watch();
6363        }
6364
6365        // The subscriptions above are COMMITTED: live events flow from here. Say
6366        // so — the startup gauntlet (relay-connect wait + stream-auth priming)
6367        // can take a minute against a slow relay set, and without this signal a
6368        // bot cannot tell "still connecting" from "subscribed to nothing".
6369        // Fires even with 0 communities: that too is a completed, ready state.
6370        handler.on_subscription_ready(db::community::list_community_ids().map(|v| v.len()).unwrap_or(0));
6371
6372        // Outage resilience via the relay Monitor — event-driven, not polling.
6373        //
6374        // (1) Reconnect-driven catch-up: a `limit(0)` realtime sub never replays what was published
6375        // while we were down, so a relay (re)connecting is exactly when we must catch up: the
6376        // Communities refold, DMs reconcile (NIP-77 negentropy → only the diff), and the relay's
6377        // share of the planes is replayed from when it dropped. Idle when healthy. Stops on swap.
6378        if let Some(monitor) = client.monitor().filter(|_| catch_up == CatchUp::Inline) {
6379            let mut rx = monitor.subscribe();
6380            let pool = client.clone();
6381            db::spawn_bound(async move {
6382                // When each relay went down: on its return, it's replayed from there. One not up
6383                // by now has been down since listening began, as far as this listener knows.
6384                let mut down: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
6385                for (url, relay) in pool.relays().await {
6386                    if relay.status() != RelayStatus::Connected {
6387                        down.insert(url.to_string(), live_from);
6388                    }
6389                }
6390                loop {
6391                    match rx.recv().await {
6392                        Ok(MonitorNotification::StatusChanged { relay_url, status }) => {
6393                            let url = relay_url.to_string();
6394                            match status {
6395                                RelayStatus::Disconnected | RelayStatus::Terminated => {
6396                                    down.entry(url).or_insert_with(crate::clock::now_ms);
6397                                }
6398                                // Everything since listening began is news, so what the outage held back is too.
6399                                RelayStatus::Connected => {
6400                                    if let Some(since) = down.remove(&url) {
6401                                        VectorCore::owe_catch_up(true, true, [(url, since)]);
6402                                    }
6403                                }
6404                                _ => {}
6405                            }
6406                        }
6407                        // Status changes went by unread: catch up on everything recent.
6408                        Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
6409                            VectorCore::owe_catch_up(true, true, [(EVERY_RELAY.to_string(), crate::clock::now_ms().saturating_sub(30 * 60_000))]);
6410                        }
6411                        Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
6412                    }
6413                }
6414            });
6415        }
6416
6417        // (2) Health probe: a relay can report Connected while silently dead. Every 60s probe each
6418        // with a tiny query + timeout; a zombie is force-reconnected (which fires the monitor above
6419        // → catch-up), and Disconnected/Terminated relays are reconnected directly.
6420        {
6421            let client_health = client.clone();
6422            db::spawn_bound(async move {
6423                crate::rt::time::sleep(std::time::Duration::from_secs(30)).await; // warm-up
6424                // Bytes each relay had delivered when last checked: a relay that sent anything
6425                // since is serving, so it skips the probe.
6426                let heard = std::sync::Mutex::new(std::collections::HashMap::<RelayUrl, usize>::new());
6427                loop {
6428                    // A false "unhealthy" costs a full reconnect, so the probe follows the
6429                    // transport; probed concurrently so one slow relay can't stall the rest.
6430                    let budget = relay_request_timeout(std::time::Duration::from_secs(8));
6431                    let client_health = &client_health;
6432                    let heard = &heard;
6433                    futures_util::future::join_all(client_health.relays().await.into_iter().map(|(url, relay)| async move {
6434                        match relay.status() {
6435                            RelayStatus::Connected => {
6436                                let received = relay.stats().bytes_received();
6437                                let before = heard.lock().unwrap().insert(url.clone(), received);
6438                                if before.is_some_and(|b| received > b) {
6439                                    return;
6440                                }
6441                                // An id no event can have: the relay answers with a bare EOSE.
6442                                let probe = crate::rt::time::timeout(
6443                                    budget + std::time::Duration::from_secs(2),
6444                                    client_health
6445                                        .fetch_events(nostr_sdk::prelude::ReqTarget::single(
6446                                            url.to_string(),
6447                                            [Filter::new().id(EventId::from_byte_array([0; 32]))],
6448                                        ))
6449                                        .timeout(budget),
6450                                )
6451                                .await;
6452                                heard.lock().unwrap().insert(url.clone(), relay.stats().bytes_received());
6453                                if !matches!(probe, Ok(Ok(_))) {
6454                                    relay.disconnect();
6455                                    crate::rt::time::sleep(std::time::Duration::from_millis(500)).await;
6456                                    let _ = relay.try_connect().timeout(crate::relay_connect_timeout(std::time::Duration::from_secs(10))).await;
6457                                }
6458                            }
6459                            RelayStatus::Terminated | RelayStatus::Disconnected => {
6460                                let _ = relay.try_connect().timeout(crate::relay_connect_timeout(std::time::Duration::from_secs(10))).await;
6461                            }
6462                            _ => {}
6463                        }
6464                    })).await;
6465                    crate::rt::time::sleep(std::time::Duration::from_secs(60)).await;
6466                }
6467            });
6468        }
6469
6470        let client_for_closure = client.clone();
6471
6472        // The intake above ends when the client shuts down, which is what stops
6473        // this loop on `swap_session`.
6474        while let Some((route, event)) = live_rx.recv().await {
6475            match route {
6476                // DMs, files, reactions
6477                LiveRoute::Dm => {
6478                    let prepared = event_handler::prepare_event(*event, &client_for_closure, my_pk).await;
6479                    event_handler::commit_prepared_event(prepared, true, &*handler).await;
6480                }
6481                // Concord v2 plane events (authors-addressed kind-1059/21059).
6482                LiveRoute::CommunityV2 => community::v2::realtime::dispatch_event(*event, handler.clone()).await,
6483            }
6484        }
6485
6486        news::end();
6487        Ok(())
6488    }
6489
6490    /// Owe this session's listener a replay of every live plane from `since_ms` on.
6491    pub(crate) fn owe_live_replay(since_ms: u64) {
6492        Self::owe_catch_up(false, false, [(EVERY_RELAY.to_string(), since_ms)]);
6493    }
6494
6495    /// Owe this session's listener a catch-up: `communities` re-reads every Community, `dms`
6496    /// reconciles DMs, and each relay (or [`EVERY_RELAY`]) is replayed from its own time. One
6497    /// runs at a time; what's owed meanwhile runs next, merged.
6498    pub(crate) fn owe_catch_up(communities: bool, dms: bool, relays: impl IntoIterator<Item = (String, u64)>) {
6499        if news::listening_since().is_none() {
6500            return;
6501        }
6502        let session = db::current_session_id();
6503        let start = {
6504            let mut owed = CATCH_UPS.lock().unwrap_or_else(|e| e.into_inner());
6505            if owed.session != session {
6506                *owed = Owed { session, ..Owed::default() };
6507            }
6508            owed.communities |= communities;
6509            owed.dms |= dms;
6510            for (relay, since) in relays {
6511                let at = owed.relays.entry(relay).or_insert(since);
6512                *at = (*at).min(since);
6513            }
6514            !std::mem::replace(&mut owed.running, true)
6515        };
6516        if start {
6517            db::spawn_bound(Self::run_catch_ups(session));
6518        }
6519    }
6520
6521    async fn run_catch_ups(session: u64) {
6522        loop {
6523            // A burst of reconnects settles into one pass.
6524            crate::rt::time::sleep(std::time::Duration::from_secs(1)).await;
6525            let listener = news::listener().zip(news::cutoff());
6526            let owed = {
6527                let mut owed = CATCH_UPS.lock().unwrap_or_else(|e| e.into_inner());
6528                let nothing = !owed.communities && !owed.dms && owed.relays.is_empty();
6529                if owed.session != session || nothing || listener.is_none() {
6530                    owed.running = false;
6531                    return;
6532                }
6533                std::mem::replace(&mut *owed, Owed { session, running: true, ..Owed::default() })
6534            };
6535            let Some((handler, from)) = listener else { return };
6536            if owed.communities {
6537                let _ = VectorCore.sync_communities().await;
6538            }
6539            if owed.dms {
6540                let _ = VectorCore.sync_dms(None, &event_handler::LiveOnly::from(&*handler, from)).await;
6541            }
6542            if let Some(client) = state::nostr_client() {
6543                if owed.communities {
6544                    community::v2::realtime::refresh_subscription(&client).await;
6545                }
6546                for (relay, since) in owed.relays {
6547                    let since = since.saturating_sub(news::ALLOWANCE_MS).max(from);
6548                    let only = (relay != EVERY_RELAY).then_some(relay.as_str());
6549                    community::v2::realtime::replay(&client, nostr_sdk::prelude::Timestamp::from_secs(since / 1000), only, handler.clone()).await;
6550                }
6551            }
6552        }
6553    }
6554
6555    /// Disconnect and clean up.
6556    pub async fn logout(&self) {
6557        news::end();
6558        if let Some(client) = state::nostr_client() {
6559            let _ = client.disconnect().await;
6560        }
6561        db::close_database();
6562    }
6563
6564    /// Tear down the current session for an in-process account swap — the account-agnostic core of
6565    /// the app's `reset_session()`. Advances the session generation FIRST so any background task
6566    /// holding a `std::sync::Arc<crate::db::Session>` short-circuits before it can touch the next account's storage; shuts
6567    /// the client down (which ends any `listen()` notification loop bound to it, so the old account's
6568    /// events can't land in the new account's DB); closes the DB pool; and clears the key vaults plus
6569    /// all in-memory per-account state. Follow with `login()` to bind the next account, then re-attach
6570    /// `listen()`. (The app's `reset_session()` additionally clears Tauri-only caches it owns.)
6571    pub async fn swap_session(&self) {
6572        // FIRST — invalidate every captured guard before any teardown begins.
6573        state::clear_message_tombstones();
6574        news::end();
6575
6576        // Mini App sessions end as the account that joined them, while its client
6577        // and key still exist to announce the departure.
6578        #[cfg(feature = "xdc")]
6579        crate::xdc::session::leave_all(std::time::Duration::from_secs(4)).await;
6580        // Voice calls too: each announces its departure while it still can.
6581        #[cfg(feature = "calls")]
6582        crate::calls::voice::leave().await;
6583
6584        // Shut the client down before anything else: this detaches relay subscriptions and ends the
6585        // prior `listen()` loop, so it stops firing the old account's events into the new session.
6586        if let Some(client) = state::take_nostr_client() {
6587            let _ = client.shutdown().await;
6588        }
6589        db::close_database();
6590
6591        // Key vaults + transient secrets.
6592        state::ENCRYPTION_KEY.clear(&[&state::MY_SECRET_KEY]);
6593        state::MY_SECRET_KEY.clear(&[&state::ENCRYPTION_KEY]);
6594        {
6595            use zeroize::Zeroize;
6596            if let Ok(mut g) = state::MNEMONIC_SEED.lock() {
6597                if let Some(s) = g.as_mut() { s.zeroize(); }
6598                *g = None;
6599            }
6600            if let Ok(mut g) = state::PENDING_NSEC.lock() {
6601                if let Some(s) = g.as_mut() { s.zeroize(); }
6602                *g = None;
6603            }
6604        }
6605
6606        // Everything else the account owned — chats, profiles, wrapper ids,
6607        // parked events, row-id caches, the sync queue, the relay caches, the
6608        // theme tags, the active chat — went with the session `close_database`
6609        // released. Only teardown that DOES something beyond forgetting is left.
6610
6611        // Unsubscribing is an action: these hold live relay subscriptions keyed
6612        // to the prior account's plane pseudonyms.
6613        crate::community::v2::realtime::clear().await;
6614        // So is disconnecting: the pooled clients are AUTHENTICATED as the prior
6615        // account's plane secret keys, and must not be left holding sockets.
6616        crate::community::transport::clear_plane_pool();
6617    }
6618}
6619
6620#[cfg(test)]
6621mod catch_up_tests {
6622    use super::*;
6623
6624    #[tokio::test]
6625    async fn what_a_listener_is_owed_merges_and_runs_once() {
6626        let _g = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
6627        *CATCH_UPS.lock().unwrap() = Owed::default();
6628        VectorCore::owe_catch_up(true, false, [("wss://a".to_string(), 100)]);
6629        assert!(!CATCH_UPS.lock().unwrap().running, "nobody listening: nothing owed");
6630
6631        let _listening = news::listen_for_test(Arc::new(event_handler::NoOpEventHandler), crate::clock::now_ms());
6632        VectorCore::owe_catch_up(false, false, [("wss://a".to_string(), 100)]);
6633        VectorCore::owe_catch_up(false, true, [("wss://a".to_string(), 50), ("wss://b".to_string(), 70)]);
6634        let owed = CATCH_UPS.lock().unwrap();
6635        assert!(owed.running && owed.dms && !owed.communities);
6636        assert_eq!((owed.relays.get("wss://a"), owed.relays.get("wss://b")), (Some(&50), Some(&70)), "each relay from its earliest gap");
6637    }
6638}
6639
6640/// Up to `limit` messages strictly before the `(at_ms, id)` cursor, chronological, from a
6641/// chat's held messages (sorted by `at` alone). Only the page is converted, never the chat:
6642/// the cursor's own same-`at` run filtered by id, then older rows back to `limit`, widened to
6643/// a whole same-`at` run at that edge since the id tiebreak decides inside it.
6644fn page_before(
6645    held: &[compact::CompactMessage],
6646    interner: &compact::NpubInterner,
6647    before: Option<(u64, &str)>,
6648    limit: usize,
6649) -> Vec<Message> {
6650    let (lo, mut msgs) = match before {
6651        None => (held.len(), Vec::new()),
6652        Some((at, id)) => {
6653            let lo = held.partition_point(|m| m.at < at);
6654            let hi = held.partition_point(|m| m.at <= at);
6655            let tie = held[lo..hi].iter().map(|m| m.to_message(interner)).filter(|m| m.id.as_str() < id).collect();
6656            (lo, tie)
6657        }
6658    };
6659    let mut start = lo.saturating_sub(limit.saturating_sub(msgs.len()));
6660    while start > 0 && start < lo && held[start - 1].at == held[start].at {
6661        start -= 1;
6662    }
6663    msgs.extend(held[start..lo].iter().map(|m| m.to_message(interner)));
6664    msgs.sort_by(|a, b| (a.at, a.id.as_str()).cmp(&(b.at, b.id.as_str())));
6665    if msgs.len() > limit {
6666        msgs.drain(..msgs.len() - limit);
6667    }
6668    msgs
6669}
6670
6671#[cfg(test)]
6672mod page_before_tests {
6673    use super::*;
6674
6675    #[test]
6676    fn it_matches_converting_the_whole_chat() {
6677        let mut interner = compact::NpubInterner::new();
6678        let mut held = compact::CompactMessageVec::new();
6679        let mut seed: u64 = 7;
6680        for n in 0..400u64 {
6681            seed ^= seed << 13; seed ^= seed >> 7; seed ^= seed << 17;
6682            // Few distinct timestamps, so same-`at` runs are long and everywhere.
6683            let msg = Message { id: format!("{:064x}", seed), at: (n / 9) * 1000 + (seed % 3), ..Default::default() };
6684            held.insert(compact::CompactMessage::from_message(&msg, &mut interner));
6685        }
6686        let mut all: Vec<Message> = held.iter().map(|m| m.to_message(&interner)).collect();
6687        all.sort_by(|a, b| (a.at, a.id.as_str()).cmp(&(b.at, b.id.as_str())));
6688        let reference = |before: Option<(u64, &str)>, limit: usize| {
6689            let mut v: Vec<String> = all.iter()
6690                .filter(|m| before.is_none_or(|(at, id)| (m.at, m.id.as_str()) < (at, id)))
6691                .map(|m| m.id.clone())
6692                .collect();
6693            if v.len() > limit { v.drain(..v.len() - limit); }
6694            v
6695        };
6696        let ids = |v: Vec<Message>| v.into_iter().map(|m| m.id).collect::<Vec<_>>();
6697        for limit in [1, 3, 10, 50, 1000] {
6698            assert_eq!(ids(page_before(held.messages(), &interner, None, limit)), reference(None, limit));
6699            for c in all.iter().step_by(13) {
6700                for cursor in [(c.at, c.id.as_str()), (c.at, "0"), (c.at, "g"), (c.at + 1, "0")] {
6701                    assert_eq!(ids(page_before(held.messages(), &interner, Some(cursor), limit)), reference(Some(cursor), limit), "cursor {cursor:?} limit {limit}");
6702                }
6703            }
6704        }
6705    }
6706}
6707
6708#[cfg(all(test, feature = "tor", not(target_arch = "wasm32")))]
6709mod transport_policy_tests {
6710    use std::time::Duration;
6711
6712    use crate::transport::{egress, Egress, Kind, Lane};
6713
6714    fn live() -> u64 {
6715        crate::db::live_session_id()
6716    }
6717
6718    /// ONE test covering proxy + budgets: the preference lives on the live session, shared by
6719    /// every test, so it holds the database guard and restores Clearnet.
6720    #[test]
6721    fn tor_transport_policy() {
6722        let _serial = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
6723        let short = Duration::from_secs(5);
6724        let long = Duration::from_secs(300);
6725
6726        // Tor off: connections may go direct, and every caller's clearnet budget
6727        // passes through untouched so the common path is never slowed down.
6728        crate::transport::set_preference(Some(Kind::Clearnet));
6729        crate::tor::set_tor_enabled_pref(false);
6730        assert_eq!(egress(live(), Lane::Account, "relay.example.com", 443), Egress::Direct);
6731        assert_eq!(super::relay_connect_timeout(short), short);
6732        assert_eq!(super::relay_request_timeout(short), short);
6733
6734        // `RequiredButInactive` (Tor chosen, not up yet) must raise the floor just like
6735        // `Active`: that window is when connects are slowest.
6736        crate::tor::set_tor_enabled_pref(true);
6737        assert!(matches!(
6738            crate::tor::transport_state(),
6739            crate::tor::TorTransportState::RequiredButInactive
6740        ));
6741        // THE leak invariant: while Tor is the chosen transport nothing is direct, least of
6742        // all during bootstrap, which is exactly when a naive implementation falls through.
6743        assert!(
6744            matches!(egress(live(), Lane::Account, "relay.example.com", 443), Egress::Refuse(_)),
6745            "Tor enabled but inactive must never connect direct"
6746        );
6747        assert_eq!(super::relay_connect_timeout(short), Duration::from_secs(60));
6748        assert_eq!(super::relay_request_timeout(short), Duration::from_secs(30));
6749
6750        // Tor chosen on the welcome screen: an account whose own preference is off still opens
6751        // on Tor until it commits, so a staged sign-in can never connect direct.
6752        crate::tor::set_tor_enabled_pref(false);
6753        crate::tor::arm_prelogin_carry(true);
6754        assert!(crate::tor::effective_tor_pref(false), "an armed carry raises an off preference");
6755        crate::tor::set_tor_enabled_pref(crate::tor::effective_tor_pref(false));
6756        assert!(
6757            matches!(egress(live(), Lane::Account, "relay.example.com", 443), Egress::Refuse(_)),
6758            "an armed carry must refuse until Tor is up, never connect direct"
6759        );
6760        crate::tor::arm_prelogin_carry(false);
6761        assert!(!crate::tor::effective_tor_pref(false), "a disarmed carry leaves the preference alone");
6762        assert!(crate::tor::effective_tor_pref(true));
6763
6764        // The NIP-46 client the SDK builds for a remote signer gets the same policy.
6765        let opts = super::transport_relay_options();
6766        assert!(format!("{opts:?}").contains("proxy: Some"), "remote-signer relays must carry the transport");
6767
6768        // The floor only ever raises. A caller asking for longer than the floor has
6769        // a reason to, and shortening it would abort operations that used to finish.
6770        for tor in [true, false] {
6771            crate::tor::set_tor_enabled_pref(tor);
6772            assert_eq!(super::relay_connect_timeout(long), long, "connect, tor={tor}");
6773            assert_eq!(super::relay_request_timeout(long), long, "request, tor={tor}");
6774        }
6775        crate::transport::set_preference(Some(Kind::Clearnet));
6776    }
6777}
6778
6779#[cfg(test)]
6780mod facade_tests {
6781    use super::*;
6782
6783    /// SSRF regression: `download_attachment` must reject a private/link-local URL via
6784    /// `validate_url_not_private` BEFORE any network fetch (the URL is attacker-controlled).
6785    #[tokio::test]
6786    async fn download_attachment_rejects_private_url() {
6787        let att = crate::types::Attachment {
6788            url: "http://169.254.169.254/latest/meta-data/".to_string(),
6789            ..Default::default()
6790        };
6791        match VectorCore.download_attachment(&att).await {
6792            Err(VectorError::Other(msg)) => {
6793                assert!(msg.contains("Private/internal"), "expected SSRF rejection, got: {msg}")
6794            }
6795            other => panic!("expected SSRF rejection, got {other:?}"),
6796        }
6797    }
6798
6799    #[tokio::test]
6800    async fn download_attachment_rejects_empty_url() {
6801        let att = crate::types::Attachment::default();
6802        assert!(VectorCore.download_attachment(&att).await.is_err());
6803    }
6804
6805    /// A community surfaces in `list_communities` with `version: 2`, and
6806    /// `v2_community_for_channel` routes its channels to the send path.
6807    #[tokio::test]
6808    async fn list_communities_and_channel_routing_are_protocol_aware() {
6809        use crate::community::transport::memory::MemoryRelay;
6810        use nostr_sdk::prelude::Keys;
6811
6812        let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
6813        crate::db::close_database();
6814        crate::db::clear_id_caches();
6815        let tmp = tempfile::tempdir().unwrap();
6816        // A valid bech32-charset, npub-length account dir name.
6817        let acct = {
6818            const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
6819            let mut s = String::from("npub1");
6820            for i in 0..58 {
6821                s.push(B[(i * 7 + 3) % 32] as char);
6822            }
6823            s
6824        };
6825        std::fs::create_dir_all(tmp.path().join(&acct)).unwrap();
6826        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
6827        crate::db::set_current_account(acct.clone()).unwrap();
6828        crate::db::init_database(&acct).unwrap();
6829        let _ = crate::state::take_nostr_client();
6830        let me = Keys::generate();
6831        crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
6832        crate::state::set_my_public_key(me.public_key());
6833
6834        // Create a v2 community directly through the v2 service (offline).
6835        let relay = MemoryRelay::new();
6836        let community = crate::community::v2::service::create_community(&relay, "V2 Guild", vec!["wss://r".into()], None)
6837            .await
6838            .unwrap();
6839        let channel_hex = crate::simd::hex::bytes_to_hex_32(&community.channels[0].id.0);
6840
6841        // The facade lists it as version 2, owned by me.
6842        let listed = VectorCore.list_communities().await;
6843        let v2 = listed.iter().find(|c| c["version"] == 2).expect("the v2 community is listed");
6844        assert_eq!(v2["name"], "V2 Guild");
6845        assert_eq!(v2["is_owner"], true);
6846        assert_eq!(v2["channels"][0]["channel_id"], channel_hex);
6847
6848        // The channel routes to the v2 send path.
6849        assert_eq!(
6850            VectorCore.v2_community_for_channel(&channel_hex).unwrap(),
6851            Some(community.identity.community_id),
6852            "a v2 channel is routed to v2"
6853        );
6854        // An unknown channel routes nowhere.
6855        assert_eq!(VectorCore.v2_community_for_channel(&"00".repeat(32)).unwrap(), None);
6856    }
6857
6858    /// The facade builds an invite URL by trimming `/invite` off the base constant
6859    /// (`build_invite_url` re-appends its own `/invite/<naddr>`).
6860    /// Lock that the derived URL is v2-shaped and round-trips through the v2
6861    /// parser — a stale constant or a double-`/invite` would silently break joins.
6862    #[test]
6863    fn v2_invite_url_base_derivation_round_trips() {
6864        use crate::community::v2::derive::TOKEN_LEN;
6865        use crate::community::v2::invite::{build_invite_url, parse_invite_link};
6866        use nostr_sdk::prelude::Keys;
6867        let base = crate::community::v2::invite::INVITE_URL_BASE.trim_end_matches("/invite");
6868        assert!(!base.ends_with("/invite"), "the bare domain must not carry /invite");
6869        let signer = Keys::generate();
6870        let token = [0x07u8; TOKEN_LEN];
6871        let url = build_invite_url(base, &signer.public_key(), &token, &[]).unwrap();
6872        assert!(url.contains("/invite/"), "a v2 URL carries the naddr path");
6873        assert!(!url.contains("/invite/invite/"), "no doubled /invite from the base");
6874        let parsed = parse_invite_link(&url).unwrap();
6875        assert_eq!(parsed.link_signer, signer.public_key());
6876        assert_eq!(parsed.token, token);
6877    }
6878}
6879
6880#[cfg(test)]
6881mod history_paging_tests {
6882    use super::*;
6883
6884    fn msg(at: u64, id_byte: u8, content: &str) -> Message {
6885        Message {
6886            id: format!("{:02x}", id_byte).repeat(32),
6887            content: content.to_string(),
6888            at,
6889            ..Default::default()
6890        }
6891    }
6892
6893    /// The cursor is compared by VALUE: paging must step strictly through a
6894    /// same-millisecond wall (the id tiebreak) and must survive the cursored
6895    /// message being deleted — a persisted cursor must never wedge the walk.
6896    #[tokio::test]
6897    async fn history_pages_through_a_same_ms_wall_and_a_deleted_cursor() {
6898        let chat_id = "test-history-paging-wall";
6899        {
6900            let mut st = state::STATE.lock().await;
6901            st.ensure_community_chat(chat_id);
6902            // A wall of three messages in the SAME millisecond, plus one older.
6903            for m in [msg(500, 0x01, "old"), msg(900, 0xaa, "wall-a"), msg(900, 0xbb, "wall-b"), msg(900, 0xcc, "wall-c")] {
6904                st.add_message_to_chat(chat_id, &m);
6905            }
6906        }
6907        let core = VectorCore;
6908
6909        // Newest 2 — the tail of the wall, chronological.
6910        let newest = core.get_messages_before(chat_id, None, 2).await;
6911        assert_eq!(newest.iter().map(|m| m.content.as_str()).collect::<Vec<_>>(), ["wall-b", "wall-c"]);
6912
6913        // Page strictly before wall-b: its same-ms predecessor, then the older one.
6914        let cursor = (newest[0].at, newest[0].id.as_str().to_string());
6915        let page = core.get_messages_before(chat_id, Some((cursor.0, &cursor.1)), 10).await;
6916        assert_eq!(page.iter().map(|m| m.content.as_str()).collect::<Vec<_>>(), ["old", "wall-a"]);
6917
6918        // The cursored message vanishes (delete / self-destruct): the SAME cursor
6919        // still resolves to the same page, because nothing resolves it to a row.
6920        {
6921            let mut st = state::STATE.lock().await;
6922            let chat = st.get_chat_mut(chat_id).unwrap();
6923            chat.messages.remove_by_hex_id(&cursor.1);
6924        }
6925        let page = core.get_messages_before(chat_id, Some((cursor.0, &cursor.1)), 10).await;
6926        assert_eq!(
6927            page.iter().map(|m| m.content.as_str()).collect::<Vec<_>>(),
6928            ["old", "wall-a"],
6929            "a deleted cursor pages identically"
6930        );
6931
6932        // Unknown chat: empty, not an error.
6933        assert!(core.get_messages_before("test-history-paging-nochat", None, 5).await.is_empty());
6934    }
6935}
6936
6937#[cfg(test)]
6938mod moderation_cache_audit {
6939    /// Every moderation action changes who is a member, and the console's verdict is
6940    /// memoised for 90s. An action that does not drop the memo leaves the console
6941    /// listing people it just removed and flagging a raid that is already over —
6942    /// which is exactly what shipped: `invalidate_raid_report` existed with no
6943    /// caller at all. Parsed from source, so a new action cannot quietly skip it.
6944    #[test]
6945    fn every_moderation_action_drops_the_memoised_verdict() {
6946        let src = include_str!("lib.rs");
6947        for name in [
6948            "pub async fn refound_community",
6949            "pub async fn kick_community_members",
6950            "pub async fn set_members_banned",
6951            "pub async fn contain_raid",
6952        ] {
6953            let start = src.find(name).unwrap_or_else(|| panic!("{name} not found — rename?"));
6954            // The body ends where the next item at method indentation begins.
6955            let rest = &src[start + name.len()..];
6956            let end = rest.find("\n    pub ").unwrap_or(rest.len());
6957            assert!(
6958                rest[..end].contains("invalidate_raid_report"),
6959                "{name} mutates membership but never drops the memoised console verdict"
6960            );
6961        }
6962    }
6963
6964    /// A ban by ANOTHER admin reaches this device as an adopted fold, not a local
6965    /// call — and with a moderation bot doing the work, that is the ONLY way it ever
6966    /// arrives. The three stores the console reports from must drop the memo on
6967    /// write, or the human admin watches a raid that was handled 90 seconds ago.
6968    #[test]
6969    fn an_adopted_change_drops_the_verdict_too() {
6970        let src = include_str!("db/community.rs");
6971        for name in ["pub fn set_community_banlist", "pub fn set_community_roles", "pub fn set_guestbook"] {
6972            let start = src.find(name).unwrap_or_else(|| panic!("{name} not found — rename?"));
6973            let rest = &src[start + name.len()..];
6974            let end = rest.find("\npub fn ").unwrap_or(rest.len());
6975            assert!(
6976                rest[..end].contains("forget_console_verdict"),
6977                "{name} changes who the console reports on but leaves the memo standing"
6978            );
6979        }
6980    }
6981}