#[macro_use]
mod macros;
pub mod rt;
pub mod files;
#[cfg(target_arch = "wasm32")]
pub mod webfiles;
pub mod logging;
pub mod error;
pub mod traits;
use crate::event_ext::FinalizeUnsignedWithId;
use nostr_sdk::prelude::{FinalizeEventAsync, ToBech32};
pub mod event_ext;
pub mod event_json;
pub mod tags;
pub mod types;
pub mod profile;
pub mod chat;
pub mod clock;
pub mod boot_payload;
pub mod compact;
pub mod state;
#[cfg(any(debug_assertions, feature = "bench"))]
pub mod stats;
pub mod crypto;
pub mod signer;
pub mod nip55;
pub mod nip07;
pub mod db;
pub mod spawn_audit;
#[cfg(test)]
mod vault_audit;
pub mod net;
pub mod fasthash;
pub mod event_size;
#[cfg(not(target_arch = "wasm32"))]
pub mod tls;
pub mod events_tracker;
pub mod proxy;
pub mod negentropy;
pub mod dm_catchup;
pub mod live_subs;
pub mod news;
pub mod blossom;
pub mod media;
pub mod blossom_servers;
pub mod blossom_capabilities;
pub mod blossom_error;
pub mod blossom_info;
pub mod blossom_stats;
pub mod inbox_relays;
pub mod relay_info;
pub mod emoji_packs;
pub mod text_color;
pub mod text_time;
pub mod text_spans;
pub mod secrets;
pub mod emoji_usage;
pub mod nostr_embed;
pub mod video_poster;
pub mod image_crop;
pub mod image_prep;
pub mod deep_link;
pub mod golink;
pub mod badges;
pub mod history_gaps;
pub mod bot_interface;
pub mod webxdc;
pub mod webxdc_permissions;
#[cfg(feature = "xdc")]
pub mod xdc;
#[cfg(feature = "tor")]
pub mod tor;
#[cfg(all(feature = "i2p", not(target_arch = "wasm32")))]
pub mod i2p;
pub mod transport;
pub mod svg;
#[cfg(not(target_arch = "wasm32"))]
pub mod vcache;
#[derive(Debug)]
pub struct VectorAuthenticator;
impl nostr_sdk::prelude::Authenticator for VectorAuthenticator {
fn make_auth_event<'a>(
&'a self,
relay_url: &'a nostr_sdk::prelude::RelayUrl,
challenge: &'a str,
) -> signer::BoxedFuture<'a, std::result::Result<nostr_sdk::prelude::Event, nostr_sdk::prelude::Error>>
{
Box::pin(async move {
let signer =
signer::active_signer().map_err(nostr_sdk::prelude::Error::other)?;
Ok(
nostr_sdk::prelude::ClientAuthentication::new(challenge, relay_url.clone())
.finalize_async(&signer)
.await?,
)
})
}
}
pub fn nostr_client_builder() -> nostr_sdk::prelude::ClientBuilder {
transport::ws::apply_transport(
nostr_sdk::prelude::ClientBuilder::new().authenticator(VectorAuthenticator),
transport::Lane::Account,
)
}
pub use transport::ws::{apply_transport, transport_relay_options};
pub trait ClientRelayExt {
fn add_managed_relay<'client, 'url, U>(
&'client self,
url: U,
) -> nostr_sdk::prelude::AddRelay<'client, 'url>
where
U: Into<nostr_sdk::prelude::RelayUrlArg<'url>>;
}
impl ClientRelayExt for nostr_sdk::prelude::Client {
fn add_managed_relay<'client, 'url, U>(
&'client self,
url: U,
) -> nostr_sdk::prelude::AddRelay<'client, 'url>
where
U: Into<nostr_sdk::prelude::RelayUrlArg<'url>>,
{
self.add_relay(url).reconnect(false)
}
}
pub async fn resubscribe_relay_after_reconnect(
client: &nostr_sdk::prelude::Client,
relay: &nostr_sdk::prelude::RelayUrl,
) {
use std::borrow::Cow;
crate::community::v2::realtime::note_resubscribe();
let Ok(Some(handle)) = client.relay(relay).await else { return };
let (mut sent, mut failed) = (0usize, 0usize);
for (id, per_relay) in client.subscriptions().await {
let Some(filters) = per_relay.get(relay) else { continue };
if filters.is_empty() {
continue;
}
let req = nostr_sdk::prelude::ClientMessage::Req {
subscription_id: Cow::Borrowed(&id),
filters: filters.iter().map(Cow::Borrowed).collect(),
};
match handle.send_msg(req).await {
Ok(()) => sent += 1,
Err(_) => failed += 1,
}
}
println!("[subs] {relay}: re-sent {sent} live sub(s), {failed} refused");
live_subs::heal(client).await;
}
pub fn relay_connect_timeout(clearnet: std::time::Duration) -> std::time::Duration {
transport::budget(transport::Op::RelayConnect, clearnet)
}
pub fn relay_request_timeout(clearnet: std::time::Duration) -> std::time::Duration {
transport::budget(transport::Op::RelayRequest, clearnet)
}
#[deprecated(note = "use vector_core::apply_transport(builder, lane)")]
pub fn apply_tor_proxy(
builder: nostr_sdk::prelude::ClientBuilder,
) -> nostr_sdk::prelude::ClientBuilder {
apply_transport(builder, transport::Lane::Account)
}
pub fn transport_aware<'c, 'e, 'u>(
send: nostr_sdk::client::SendEvent<'c, 'e, 'u>,
) -> nostr_sdk::client::SendEvent<'c, 'e, 'u> {
let wait = relay_request_timeout(std::time::Duration::from_secs(10));
send.ok_timeout(wait).authentication_timeout(wait)
}
#[deprecated(note = "use vector_core::transport_relay_options()")]
pub fn tor_relay_options() -> nostr_sdk::prelude::RelayOptions {
transport_relay_options()
}
pub async fn sign_builder(
builder: nostr_sdk::prelude::EventBuilder,
) -> std::result::Result<nostr_sdk::prelude::Event, String> {
let signer = signer::active_signer()?;
let event = builder
.finalize_async(&signer)
.await
.map_err(|e| e.to_string())?;
event_size::check(&event)?;
Ok(event)
}
pub async fn sign_and_send(
client: &nostr_sdk::prelude::Client,
builder: nostr_sdk::prelude::EventBuilder,
) -> std::result::Result<nostr_sdk::prelude::SendEventOutput, String> {
let event = sign_builder(builder).await?;
transport_aware(client.send_event(&event))
.await
.map_err(|e| e.to_string())
}
pub async fn fetch_answered(
client: &nostr_sdk::prelude::Client,
filter: nostr_sdk::prelude::Filter,
timeout: std::time::Duration,
) -> std::result::Result<Vec<nostr_sdk::prelude::Event>, String> {
use community::transport::{fetch_relay_eose_filters, EoseFail};
use nostr_sdk::prelude::RelayStatus;
let relays = client.relays().with_capabilities(nostr_sdk::prelude::RelayCapabilities::READ).await;
let live: Vec<_> = relays
.iter()
.filter(|(_, r)| !matches!(r.status(), RelayStatus::Terminated | RelayStatus::Shutdown | RelayStatus::Banned))
.map(|(url, _)| url)
.collect();
if live.is_empty() {
return Err("no relays to read from".to_string());
}
let reads = live.into_iter().map(|url| {
let url = url.to_string();
let filter = filter.clone();
async move {
match fetch_relay_eose_filters(client, &url, vec![filter.clone()], timeout).await {
Err(EoseFail::Closed) => {
crate::rt::time::sleep(std::time::Duration::from_millis(800)).await;
fetch_relay_eose_filters(client, &url, vec![filter], timeout).await
}
other => other,
}
}
});
let mut answered = false;
let mut seen = std::collections::HashSet::new();
let mut events = Vec::new();
for read in futures_util::future::join_all(reads).await.into_iter().flatten() {
answered = true;
events.extend(read.into_iter().filter(|e| seen.insert(e.id)));
}
if !answered {
return Err("none of your relays answered".to_string());
}
Ok(events)
}
pub fn newest_replaceable(events: Vec<nostr_sdk::prelude::Event>) -> Option<nostr_sdk::prelude::Event> {
events.into_iter().min_by(|a, b| b.created_at.cmp(&a.created_at).then_with(|| a.id.cmp(&b.id)))
}
pub async fn send_gift_wrap<'u, I, U, T>(
client: &nostr_sdk::prelude::Client,
relays: I,
receiver: &nostr_sdk::prelude::PublicKey,
rumor: nostr_sdk::prelude::UnsignedEvent,
extra_tags: T,
) -> std::result::Result<nostr_sdk::prelude::SendEventOutput, String>
where
I: IntoIterator<Item = U>,
U: Into<nostr_sdk::prelude::RelayUrlArg<'u>>,
T: IntoIterator<Item = nostr_sdk::prelude::Tag>,
{
let wrap = signer::gift_wrap(receiver, rumor, extra_tags).await?;
let targets: Vec<nostr_sdk::prelude::RelayUrlArg<'u>> =
relays.into_iter().map(Into::into).collect();
if targets.is_empty() {
crate::transport_aware(client.send_event(&wrap)).await.map_err(|e| e.to_string())
} else {
transport_aware(client.send_event(&wrap))
.to(targets)
.await
.map_err(|e| e.to_string())
}
}
pub fn community_relay_capabilities() -> nostr_sdk::prelude::RelayCapabilities {
nostr_sdk::prelude::RelayCapabilities::GOSSIP
}
pub fn discovery_relay_capabilities() -> nostr_sdk::prelude::RelayCapabilities {
community_relay_capabilities()
}
pub mod stored_event;
pub mod rumor;
pub mod sending;
pub mod pinned_chats;
pub mod rail_layout;
pub mod start_menu;
pub mod synced_prefs;
pub mod notify;
pub mod push;
pub mod wallpaper;
pub mod requests;
pub mod deletion;
pub mod early;
pub mod self_destruct;
pub mod transfer;
pub mod simd;
pub mod calls;
pub mod community;
pub mod event_handler;
pub use types::{Message, Attachment, Reaction, EditEntry, ImageMetadata, SiteMetadata, LoginResult, AttachmentFile, mention, extract_mentions};
pub use profile::{Profile, ProfileFlags, SlimProfile, Status};
pub use chat::{Chat, ChatType, ChatMetadata, SerializableChat};
pub use compact::{CompactMessage, CompactMessageVec, NpubInterner};
pub use state::{
ChatState, MY_SECRET_KEY, STATE, ENCRYPTION_KEY,
nostr_client, my_public_key, has_active_session,
set_nostr_client, set_my_public_key,
take_nostr_client, clear_my_public_key,
set_pending_bunker_setup, pending_bunker_setup, clear_pending_bunker_setup,
set_pending_nip55_setup, pending_nip55_setup, clear_pending_nip55_setup,
};
pub use crypto::{GuardedKey, GuardedSigner};
pub use signer::{
SignerKind, signer_kind, set_signer_kind, is_bunker, is_keyless,
BUNKER_SIGNER, bunker_signer, set_bunker_signer, take_bunker_signer,
build_bunker_signer, prewarm_bunker, drain_bunker_state,
parse_bunker_remote_pubkey, parse_bunker_relays,
BunkerConnectionState, bunker_state, set_bunker_state,
VectorAuthUrlHandler, attempt_bunker_login, WatchedBunkerSigner,
vector_metadata, build_nostrconnect_uri, build_nostrconnect_session,
VECTOR_APP_NAME, VECTOR_APP_URL, VECTOR_APP_ICON,
};
pub use nip55::{
Nip55Backend, Nip55Error, Nip55ResolverOutcome, Nip55Signer, Nip55State,
set_nip55_backend, nip55_backend, nip55_state, set_nip55_state, drain_nip55_state,
nip55_is_installed, nip55_pair, nip55_perms_json,
VECTOR_NIP55_SIGN_KINDS, VECTOR_NIP55_ENCRYPT_TYPES,
};
pub use nip07::{Nip07Backend, Nip07Signer, set_nip07_backend, nip07_backend, nip07_get_public_key};
pub use error::{DownloadError, VectorError, Result};
#[derive(Debug, Clone, Copy)]
pub enum DownloadStep {
Received { bytes: u64, total: Option<u64> },
Opening,
}
pub use traits::{EventEmitter, NoOpEmitter, set_event_emitter, emit_event};
pub use db::{set_app_data_dir, get_app_data_dir};
pub use sending::{SendCallback, NoOpSendCallback, SendConfig, SendResult};
pub use deletion::{delete_own_dm, delete_received_dm, DeleteOutcome};
pub use stored_event::{StoredEvent, StoredEventBuilder, SystemEventType};
pub use rumor::{RumorEvent, RumorContext, ConversationType, RumorProcessingResult, process_rumor};
pub use profile::{SyncPriority, ProfileSyncHandler, NoOpProfileSyncHandler};
pub use event_handler::{InboundEventHandler, LiveOnly, NoOpEventHandler, PreparedEvent, process_event};
use std::path::PathBuf;
use std::sync::Arc;
pub struct CoreConfig {
pub data_dir: PathBuf,
pub event_emitter: Option<Box<dyn EventEmitter>>,
}
#[derive(Clone, Copy)]
pub struct VectorCore;
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct PostOptions {
pub reply_to: Option<String>,
pub expires_in_secs: Option<u64>,
pub bot: Option<String>,
pub caption: Option<String>,
pub compress: bool,
}
impl Default for PostOptions {
fn default() -> Self {
PostOptions { reply_to: None, expires_in_secs: None, bot: None, caption: None, compress: true }
}
}
impl PostOptions {
pub fn compress(mut self, on: bool) -> Self {
self.compress = on;
self
}
pub fn reply_to(mut self, message_id: impl Into<String>) -> Self {
self.reply_to = Some(message_id.into());
self
}
pub fn expires_in(mut self, secs: u64) -> Self {
self.expires_in_secs = Some(secs);
self
}
pub fn to_bot(mut self, bot: impl Into<String>) -> Self {
self.bot = Some(bot.into());
self
}
pub fn caption(mut self, text: impl Into<String>) -> Self {
self.caption = Some(text.into());
self
}
}
pub(crate) async fn ready_to_send(bytes: Vec<u8>, filename: &str, compress: bool) -> Result<(Vec<u8>, String)> {
if !compress || image::guess_format(&bytes).is_err() || crate::svg::looks_like_svg(&bytes) {
return Ok((bytes, filename.to_string()));
}
let prepared = crate::rt::spawn_blocking(move || {
crate::image_prep::prepare(&bytes, crate::image_prep::ImageUse::Photo).or_else(|e| crate::image_prep::strip(&bytes).ok_or(e))
})
.await
.map_err(|e| VectorError::Other(format!("image: {e}")))?
.map_err(|e| VectorError::Other(format!("{e}; send it uncompressed to share it as it is")))?;
let path = std::path::Path::new(filename);
let same = path.extension().and_then(|e| e.to_str()).is_some_and(|e| {
let e = e.to_ascii_lowercase();
e == prepared.extension || (prepared.extension == "jpg" && e == "jpeg")
});
let name = if same { filename.to_string() } else { path.with_extension(prepared.extension).to_string_lossy().into_owned() };
Ok((prepared.bytes, name))
}
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct NewCommunity {
pub description: Option<String>,
pub first_channel: Option<String>,
pub relays: Vec<String>,
}
impl NewCommunity {
pub fn description(mut self, text: impl Into<String>) -> Self {
self.description = Some(text.into());
self
}
pub fn first_channel(mut self, name: impl Into<String>) -> Self {
self.first_channel = Some(name.into());
self
}
pub fn relays(mut self, relays: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.relays = relays.into_iter().map(Into::into).collect();
self
}
}
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct NewChannel {
pub private: bool,
pub category_id: Option<String>,
pub view: Option<String>,
pub topic: Option<String>,
}
impl NewChannel {
pub fn private(mut self) -> Self {
self.private = true;
self
}
pub fn in_category(mut self, category_id: impl Into<String>) -> Self {
self.category_id = Some(category_id.into());
self
}
pub fn view(mut self, view: impl Into<String>) -> Self {
self.view = Some(view.into());
self
}
pub fn topic(mut self, topic: impl Into<String>) -> Self {
self.topic = Some(topic.into());
self
}
}
#[derive(Debug, Clone, serde::Serialize)]
#[non_exhaustive]
pub struct LinkPreview {
pub community_id: String,
pub name: String,
pub description: Option<String>,
pub icon: Option<crate::community::CommunityImage>,
pub joined: bool,
pub verified: bool,
}
enum LiveRoute {
Dm,
CommunityV2,
}
const EVERY_RELAY: &str = "*";
#[derive(Default)]
struct Owed {
session: u64,
communities: bool,
dms: bool,
relays: std::collections::HashMap<String, u64>,
running: bool,
}
static CATCH_UPS: std::sync::LazyLock<std::sync::Mutex<Owed>> = std::sync::LazyLock::new(Default::default);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CatchUp {
Inline,
External,
}
fn drop_community_image(url: Option<String>, kept: Option<&str>) {
let Some(url) = url.filter(|u| Some(u.as_str()) != kept) else { return };
if let Ok(signer) = crate::signer::active_signer() {
crate::blossom::delete_blobs_best_effort(signer, vec![url]);
}
}
const BACKFILL_CONTINUATIONS: usize = 3;
const UNPROVEN_EPOCHS: u64 = 2;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct BackfillCount {
pub fetched: usize,
pub new_messages: usize,
pub next_before: Option<u64>,
pub unreachable: bool,
}
impl VectorCore {
pub fn init(config: CoreConfig) -> Result<Self> {
db::set_app_data_dir(config.data_dir);
if let Some(emitter) = config.event_emitter {
traits::set_event_emitter(emitter);
}
#[cfg(not(target_arch = "wasm32"))]
let _ = rustls::crypto::ring::default_provider().install_default();
net::raise_fd_limit();
Ok(VectorCore)
}
pub fn accounts(&self) -> Result<Vec<String>> {
db::get_accounts().map_err(VectorError::from)
}
pub async fn login(&self, key: &str, password: Option<&str>) -> Result<LoginResult> {
use nostr_sdk::prelude::*;
let keys = if key.starts_with("nsec1") {
let secret = SecretKey::from_bech32(key)
.map_err(|e| VectorError::Nostr(format!("Invalid nsec: {}", e)))?;
Keys::new(secret)
} else {
Keys::from_mnemonic(key, None)
.map_err(|e| VectorError::Nostr(format!("Key derivation failed: {}", e)))?
};
let public_key = keys.public_key();
let npub = public_key.to_bech32()
.map_err(|e| VectorError::Nostr(format!("Failed to encode npub: {}", e)))?;
let secret_bytes = keys.secret_key().to_secret_bytes();
state::MY_SECRET_KEY.set(secret_bytes, &[&state::ENCRYPTION_KEY]);
state::set_my_public_key(public_key);
db::set_current_account(npub.clone())?;
db::init_database(&npub)?;
{
let nsec = keys.secret_key().to_bech32()
.map_err(|e| VectorError::Nostr(format!("Failed to encode nsec: {}", e)))?;
*state::PENDING_NSEC.lock().unwrap() = Some(nsec.clone());
let existing_encrypted = db::get_pkey().ok().flatten().is_some_and(|v| !v.starts_with("nsec1"));
if !(state::resolve_encryption_enabled_from_db() && existing_encrypted) {
db::set_pkey(&nsec)?;
}
}
let has_encryption = state::resolve_encryption_enabled_from_db();
if has_encryption {
if let Some(pwd) = password {
let kdf = crate::crypto::Kdf::of_account().map_err(VectorError::Crypto)?;
let key = zeroize::Zeroizing::new(crate::crypto::derive_key(pwd, &kdf).await);
crate::crypto::install_unlocked_key(&key, &kdf).map_err(VectorError::Crypto)?;
}
}
state::init_encryption_enabled();
let client = crate::nostr_client_builder()
.monitor(Monitor::new(1024))
.build();
for relay in state::TRUSTED_RELAYS {
client.add_managed_relay(*relay).await.ok();
}
client.connect().await;
let _ = { state::set_nostr_client(client); Ok::<(), ()>(()) };
Ok(LoginResult { npub, has_encryption })
}
pub fn generate_nsec(&self) -> Result<String> {
use nostr_sdk::prelude::*;
Keys::generate().secret_key().to_bech32()
.map_err(|e| VectorError::Nostr(format!("Failed to encode nsec: {}", e)))
}
pub async fn send_dm(&self, to_npub: &str, content: &str) -> Result<sending::SendResult> {
let config = SendConfig { self_send: false, ..SendConfig::headless() };
sending::send_dm(to_npub, content, None, &config, Arc::new(NoOpSendCallback)).await
.map_err(VectorError::Other)
}
pub async fn send_dm_reply(&self, to_npub: &str, replied_to: &str, content: &str) -> Result<sending::SendResult> {
let config = SendConfig { self_send: false, ..SendConfig::headless() };
sending::send_dm(to_npub, content, Some(replied_to), &config, Arc::new(NoOpSendCallback)).await
.map_err(VectorError::Other)
}
pub async fn download_attachment(&self, attachment: &Attachment) -> Result<Vec<u8>> {
self.download_attachment_from(attachment, None).await
}
pub async fn download_attachment_from(
&self,
attachment: &Attachment,
author_npub: Option<&str>,
) -> Result<Vec<u8>> {
self.download_attachment_within(attachment, author_npub, 256 * 1024 * 1024)
.await
.map_err(|e| VectorError::Other(e.to_string()))
}
pub async fn download_attachment_within(
&self,
attachment: &Attachment,
author_npub: Option<&str>,
max_bytes: usize,
) -> std::result::Result<Vec<u8>, DownloadError> {
self.download_attachment_reporting(attachment, author_npub, max_bytes, |_| true).await
}
pub async fn download_attachment_reporting<F: FnMut(DownloadStep) -> bool>(
&self,
attachment: &Attachment,
author_npub: Option<&str>,
max_bytes: usize,
mut step: F,
) -> std::result::Result<Vec<u8>, DownloadError> {
use futures_util::StreamExt;
let max_download = max_bytes;
if attachment.url.is_empty() {
return Err(DownloadError::Unusable("attachment has no URL".into()));
}
let client = crate::net::build_http_client_with_options(
None,
Some(crate::net::transfer_stall()),
true,
)
.map_err(DownloadError::Unreachable)?;
let mut last_err = String::from("download failed");
let mut network_waits = 0u8;
let mut all_answered = true;
let mut candidates: Vec<String> = vec![attachment.url.clone()];
candidates.extend(attachment.fallback_urls.iter().cloned());
let mut hash_swap_tried = false;
let mut i = 0;
'sources: while i < candidates.len() {
let url = candidates[i].clone();
i += 1;
let extend_with_swap = |candidates: &mut Vec<String>, servers: &[String]| {
let extra = crate::blossom::hash_swap_candidates(&attachment.url, servers);
for c in extra {
if !candidates.contains(&c) {
candidates.push(c);
}
}
};
macro_rules! next_source {
() => {{
log_net_fail!("[Download] source failed ({}): {}", url, last_err);
if i == candidates.len() && !hash_swap_tried {
hash_swap_tried = true;
let servers = crate::blossom_servers::author_swap_servers(author_npub, false).await;
extend_with_swap(&mut candidates, &servers);
}
continue 'sources;
}};
}
if let Err(e) = crate::net::validate_url_not_private(&url) {
last_err = e.to_string();
next_source!();
}
macro_rules! network_changed {
($e:expr) => {{
if $e.is_transient() && network_waits < 8 {
network_waits += 1;
match crate::net::wait_after(&$e).await {
Ok(()) => {
i -= 1;
continue 'sources;
}
Err(text) => return Err(DownloadError::Unreachable(text)),
}
}
}};
}
let resp = match crate::net::proxied_request(&client, reqwest::Method::GET, &url).await.send().await {
Ok(r) => r,
Err(e) => {
network_changed!(e);
last_err = format!("download: {e}");
all_answered = false;
next_source!();
}
};
if !resp.status().is_success() {
last_err = format!("download failed: HTTP {}", resp.status());
all_answered = false;
next_source!();
}
let mut encrypted: Vec<u8> = Vec::with_capacity(
resp.content_length().map(|l| usize::try_from(l).unwrap_or(usize::MAX).min(max_download).min(4 * 1024 * 1024)).unwrap_or(64 * 1024),
);
let total = resp.content_length();
if !step(DownloadStep::Received { bytes: 0, total }) {
return Err(DownloadError::Cancelled);
}
let mut stream = resp.bytes_stream();
loop {
if total.is_some_and(|t| encrypted.len() as u64 >= t) {
break;
}
#[cfg(target_arch = "wasm32")]
let next = match crate::rt::time::timeout(crate::transport::budget(crate::transport::Op::HttpRead, crate::net::transfer_stall()), stream.next()).await {
Ok(next) => next,
Err(_) => {
last_err = "read body: stalled".to_string();
all_answered = false;
next_source!();
}
};
#[cfg(not(target_arch = "wasm32"))]
let next = stream.next().await;
let Some(chunk) = next else { break };
let chunk = match chunk {
Ok(c) => c,
Err(e) => {
network_changed!(e);
last_err = format!("read body: {e}");
all_answered = false;
next_source!();
}
};
if encrypted.len() + chunk.len() > max_download {
return Err(DownloadError::TooLarge(max_download));
}
encrypted.extend_from_slice(&chunk);
if !step(DownloadStep::Received { bytes: encrypted.len() as u64, total }) {
return Err(DownloadError::Cancelled);
}
}
if !step(DownloadStep::Opening) {
return Err(DownloadError::Cancelled);
}
if attachment.key.is_empty() || attachment.nonce.is_empty() {
let hash = crate::crypto::sha256_hex(&encrypted);
if crate::blossom::plaintext_matches(&url, attachment.original_hash.as_deref(), &hash) {
return Ok(encrypted);
}
last_err = "plaintext blob fails its hash claim".to_string();
next_source!();
}
match crate::crypto::decrypt_data_owned(encrypted, &attachment.key, &attachment.nonce) {
Ok(plain) => {
if i > 1 {
log_net_info!("[Download] fallback source {}/{} served {}", i, candidates.len(), url);
}
return Ok(plain);
}
Err(e) => {
last_err = format!("decrypt: {e}");
next_source!();
}
}
}
log_net_fail!("[Download] all {} source(s) failed for {}: {}", candidates.len(), attachment.url, last_err);
Err(if all_answered { DownloadError::Unusable(last_err) } else { DownloadError::Unreachable(last_err) })
}
pub async fn probe_attachment_size(&self, message_id: &str, attachment_id: &str) -> Option<u64> {
crate::db::scoped(async move {
let (chat_id, message) = self.get_message(message_id).await?;
let att = message.attachments.iter().find(|a| a.id == attachment_id)?;
if att.size > 0 {
return Some(att.size);
}
if !(att.url.starts_with("https://") || att.url.starts_with("http://")) {
return None;
}
if !message.mine && crate::requests::shielded() && state::STATE.lock().await.dm_unanswered(&chat_id) {
return None;
}
let probe = crate::net::get_remote_file_size(&att.url);
let size = crate::rt::time::timeout(crate::net::tor_http_timeout(std::time::Duration::from_secs(5)), probe).await.ok().flatten()?;
if let Err(e) = db::attachments::set_attachment_size(message_id, attachment_id, size) {
crate::log_warn!("[Attachments] could not record a probed size: {e}");
}
state::STATE.lock().await.update_attachment(&chat_id, message_id, attachment_id, |a| a.size = size);
Some(size)
})
.await
}
pub async fn send_file(&self, to_npub: &str, file_path: &str) -> Result<sending::SendResult> {
let path = std::path::Path::new(file_path);
let bytes = std::fs::read(path)
.map_err(VectorError::Io)?;
let filename = path.file_name()
.and_then(|n| n.to_str())
.unwrap_or("file");
let extension = path.extension()
.and_then(|e| e.to_str())
.unwrap_or("bin");
sending::send_file_dm(
to_npub,
std::sync::Arc::new(bytes),
filename,
extension,
None,
None,
&SendConfig::default(),
Arc::new(NoOpSendCallback),
).await.map_err(VectorError::Other)
}
pub async fn send_file_bytes(&self, to_npub: &str, bytes: Vec<u8>, filename: &str, opts: &PostOptions) -> Result<sending::SendResult> {
if opts.expires_in_secs.is_some() {
return Err(VectorError::Other("DMs have no per-message expiry".into()));
}
let (bytes, filename) = ready_to_send(bytes, filename, opts.compress).await?;
let extension = std::path::Path::new(&filename).extension().and_then(|e| e.to_str()).unwrap_or("bin").to_lowercase();
let config = SendConfig { self_send: false, ..SendConfig::headless() };
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))
.await
.map_err(VectorError::Other)?;
if let Some(caption) = opts.caption.as_deref().filter(|c| !c.trim().is_empty()) {
let file_id = sent.event_id.clone().unwrap_or_else(|| sent.pending_id.clone());
self.send_dm_reply(to_npub, &file_id, caption).await?;
}
Ok(sent)
}
pub async fn remove_reaction(&self, reaction_id: &str) -> Result<()> {
crate::db::scoped(async move {
use nostr_sdk::prelude::{EventId, PublicKey, ToBech32};
let session = crate::db::current_session();
let (chat_id, message_id, author_npub, is_community) =
Self::locate_reaction(reaction_id).await.ok_or_else(|| VectorError::NotFound(format!("reaction {reaction_id}")))?;
let me = state::my_public_key().ok_or_else(|| VectorError::NotInitialized("not logged in".into()))?;
if me.to_bech32().ok().as_deref() != Some(author_npub.as_str()) {
return Err(VectorError::Other("only its own author can withdraw a reaction".into()));
}
let updated = state::STATE.lock().await.remove_reaction_from_message(&message_id, reaction_id);
let _ = crate::db::events::delete_event(reaction_id).await;
if let Some((_, mut message)) = updated {
traits::emit_message_update(&chat_id, &message_id, &mut message).await;
}
if !session.is_live() {
return Err(VectorError::Other("account changed while withdrawing the reaction".into()));
}
if is_community {
use crate::community::transport::LiveTransport;
let id = self.v2_community_for_channel(&chat_id)?.ok_or_else(|| VectorError::NotFound("community channel".into()))?;
let community = crate::db::community::load_community_v2(&id)
.map_err(VectorError::Db)?
.ok_or_else(|| VectorError::NotFound("community".into()))?;
let ch = crate::community::ChannelId(Self::id32(&chat_id, "channel_id")?);
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
crate::community::v2::service::delete_own(&transport, &community, &ch, reaction_id, crate::community::v2::kind::REACTION)
.await
.map_err(VectorError::Other)?;
} else {
let rid = EventId::from_hex(reaction_id).map_err(|e| VectorError::Nostr(e.to_string()))?;
let recipient = PublicKey::parse(&chat_id).map_err(|e| VectorError::Nostr(e.to_string()))?;
crate::deletion::delete_own_reaction(&rid, recipient).await.map_err(VectorError::Other)?;
}
Ok(())
})
.await
}
async fn locate_reaction(reaction_id: &str) -> Option<(String, String, String, bool)> {
if let Some(found) = state::STATE.lock().await.find_reaction(reaction_id) {
return Some(found);
}
let parent = crate::db::events::reaction_target(reaction_id).ok().flatten()?;
let (chat_id, message) = crate::db::events::get_message_by_id(&parent).await.ok().flatten()?;
let author = message.reactions.iter().find(|r| r.id == reaction_id)?.author_id.clone();
let community = crate::db::community::community_id_for_channel(&chat_id).ok().flatten().is_some();
Some((chat_id, parent, author, community))
}
pub async fn remove_my_reaction(&self, message_id: &str, emoji: &str) -> Result<bool> {
match Self::own_reaction_id(message_id, emoji).await {
Some(id) => self.remove_reaction(&id).await.map(|_| true),
None => Ok(false),
}
}
async fn own_reaction_id(message_id: &str, emoji: &str) -> Option<String> {
use nostr_sdk::prelude::ToBech32;
let me = state::my_public_key()?.to_bech32().ok()?;
let resident = state::STATE.lock().await.find_message(message_id).map(|(_, m)| m);
let message = match resident {
Some(m) => m,
None => crate::db::events::get_message_by_id(message_id).await.ok().flatten()?.1,
};
message.reactions.iter().find(|r| r.author_id == me && r.emoji == emoji).map(|r| r.id.clone())
}
pub async fn send_reaction(
&self,
to_npub: &str,
reference_id: &str,
emoji: &str,
emoji_url: Option<&str>,
) -> Result<String> {
use nostr_sdk::prelude::*;
let client = state::nostr_client().ok_or(VectorError::Other("Not connected".into()))?;
let my_public_key = state::my_public_key().ok_or(VectorError::Other("Not logged in".into()))?;
if let Some(existing) = Self::own_reaction_id(reference_id, emoji).await {
return Ok(existing);
}
badges::check_new_reaction_allowance(reference_id, emoji)
.await
.map_err(VectorError::Other)?;
let reference_event = EventId::from_hex(reference_id)
.map_err(|e| VectorError::Nostr(e.to_string()))?;
let receiver_pubkey = PublicKey::from_bech32(to_npub)
.map_err(|e| VectorError::Nostr(e.to_string()))?;
let custom_emoji_tag = emoji_url.and_then(|url| {
if !emoji.starts_with(':') || !emoji.ends_with(':') || emoji.len() < 3 || url.is_empty() {
return None;
}
let shortcode = &emoji[1..emoji.len() - 1];
if shortcode.is_empty() { return None; }
Some(Tag::custom("emoji", [shortcode.to_string(), url.to_string()]))
});
let reaction_target = nostr_sdk::prelude::nip25::ReactionTarget {
event_id: reference_event,
public_key: receiver_pubkey,
coordinate: None,
kind: Some(Kind::PrivateDirectMessage),
relay_hint: None,
};
let mut builder =
nostr_sdk::prelude::nip25::ReactionBuilder::new(reaction_target, emoji)
.into_event_builder();
if let Some(tag) = custom_emoji_tag {
builder = builder.tag(tag);
}
let rumor = builder.finalize_unsigned_with_id(my_public_key);
let inner_rumor_id = rumor.id;
let rumor_id = inner_rumor_id.ok_or(VectorError::Other("Failed to get rumor ID".into()))?.to_hex();
let outcome = inbox_relays::send_gift_wrap_retained(&client, &receiver_pubkey, rumor.clone(), [])
.await.map_err(VectorError::Other)?;
if !outcome.output.success.is_empty() {
if let Some(rid) = inner_rumor_id {
if let Err(e) = db::nip17_keys::store_wrap_key(
&outcome.wrap_event_id, &rid, &receiver_pubkey,
db::nip17_keys::WrapRole::Recipient,
&outcome.wrap_secret, &outcome.targeted_relays,
) {
crate::log_warn!("[Reaction] failed to persist wrap key: {}", e);
}
}
}
let self_wrap_client = client.clone();
db::spawn_bound(async move {
if let Ok(self_outcome) = inbox_relays::send_gift_wrap_retained(
&self_wrap_client, &my_public_key, rumor, [],
).await {
if !self_outcome.output.success.is_empty() {
if let Some(rid) = inner_rumor_id {
let _ = db::nip17_keys::store_wrap_key(
&self_outcome.wrap_event_id, &rid, &my_public_key,
db::nip17_keys::WrapRole::SelfSend,
&self_outcome.wrap_secret, &self_outcome.targeted_relays,
);
}
}
}
});
let reaction = Reaction {
id: rumor_id.clone(),
reference_id: reference_id.to_string(),
author_id: my_public_key.to_bech32().unwrap_or_else(|_| my_public_key.to_hex()),
emoji: emoji.to_string(),
emoji_url: emoji_url.map(|s| s.to_string()),
};
let msg_for_save = {
let mut st = state::STATE.lock().await;
match st.add_reaction_to_message(reference_id, reaction) {
Some((cid, true)) => st.find_message(reference_id).map(|(_, m)| (cid, m)),
_ => None,
}
};
if let Some((cid, mut msg)) = msg_for_save {
let _ = db::events::save_message(&cid, &msg).await;
traits::emit_message_update(&cid, reference_id, &mut msg).await;
}
Ok(rumor_id)
}
pub async fn send_typing(&self, to_npub: &str) -> Result<()> {
use nostr_sdk::prelude::*;
let client = state::nostr_client().ok_or(VectorError::Other("Not connected".into()))?;
let my_public_key = state::my_public_key().ok_or(VectorError::Other("Not logged in".into()))?;
let pubkey = PublicKey::from_bech32(to_npub).map_err(|e| VectorError::Nostr(e.to_string()))?;
if pubkey == my_public_key {
return Ok(());
}
let expiry = Timestamp::from_secs(crate::clock::timestamp().as_secs() + 30);
let rumor = EventBuilder::new(Kind::ApplicationSpecificData, "typing")
.tag(Tag::public_key(pubkey))
.tag(Tag::custom("d", vec!["vector"]))
.tag(Tag::expiration(expiry))
.finalize_unsigned_with_id(my_public_key);
signer::active_signer().map_err(VectorError::Other)?;
let wrap = signer::gift_wrap(&pubkey, rumor, [Tag::expiration(expiry)])
.await
.map_err(VectorError::Nostr)?;
transport_aware(client.send_event(&wrap))
.to(state::active_trusted_relays().await)
.await
.map_err(|e| VectorError::Nostr(e.to_string()))?;
Ok(())
}
pub async fn edit_dm(&self, to_npub: &str, message_id: &str, new_content: &str) -> Result<String> {
crate::db::scoped(async move {
use nostr_sdk::prelude::*;
let client = state::nostr_client().ok_or(VectorError::Other("Not connected".into()))?;
let my_public_key = state::my_public_key().ok_or(VectorError::Other("Not logged in".into()))?;
let my_npub = my_public_key.to_bech32().map_err(|e| VectorError::Nostr(e.to_string()))?;
let receiver_pubkey = PublicKey::from_bech32(to_npub).map_err(|e| VectorError::Nostr(e.to_string()))?;
let reference_event = EventId::from_hex(message_id).map_err(|e| VectorError::Nostr(e.to_string()))?;
let (plain, text_spans) = crate::text_spans::extract_own(new_content);
let new_content = plain.as_str();
let emoji_tags = emoji_packs::resolve_outbound_emoji_tags(new_content);
let expiry_tags: Vec<Tag> = crate::self_destruct::edit_expiry(message_id)
.await
.map_err(VectorError::Other)?
.map(|exp| Tag::expiration(Timestamp::from_secs(exp)))
.into_iter()
.collect();
let mut builder = EventBuilder::new(
Kind::from_u16(stored_event::event_kind::MESSAGE_EDIT),
new_content,
).tag(Tag::event(reference_event));
for et in &emoji_tags {
builder = builder.tag(Tag::custom(
"emoji",
[et.shortcode.clone(), et.url.clone()],
));
}
builder = builder.tags(crate::text_spans::to_nostr_tags(&text_spans));
let rumor = builder.tags(expiry_tags.clone()).finalize_unsigned_with_id(my_public_key);
let edit_id = rumor.id.ok_or(VectorError::Other("Failed to get edit rumor ID".into()))?.to_hex();
let edit_ts_ms = rumor.created_at.as_secs() * 1000;
let msg_for_emit = {
let mut st = state::STATE.lock().await;
st.update_message_in_chat_with(to_npub, message_id, |msg, i| {
msg.apply_edit(new_content.to_string(), edit_ts_ms, emoji_tags.clone(), text_spans.clone(), i);
msg.set_preview_metadata(None);
})
};
if let Some(mut msg) = msg_for_emit {
traits::emit_message_update(to_npub, message_id, &mut msg).await;
if let Ok(db_chat_id) = db::id_cache::get_chat_id_by_identifier(to_npub) {
let _ = db::events::save_edit_event(
&edit_id, message_id, new_content, &emoji_tags, &text_spans, db_chat_id, None, &my_npub,
).await;
}
}
inbox_relays::send_gift_wrap(&client, &receiver_pubkey, rumor.clone(), expiry_tags.clone())
.await.map_err(VectorError::Other)?;
let self_wrap_client = client.clone();
let self_wrap_session = crate::db::current_session();
db::spawn_bound(async move {
if !self_wrap_session.is_live() { return; }
if let Ok(wrap) = signer::gift_wrap(&my_public_key, rumor, expiry_tags).await {
let _ = crate::transport_aware(self_wrap_client.send_event(&wrap)).await;
}
});
Ok(edit_id)
})
.await
}
pub async fn delete_dm(&self, message_id: &str) -> Result<deletion::DeleteOutcome> {
use nostr_sdk::prelude::*;
let rumor_id = EventId::from_hex(message_id).map_err(|e| VectorError::Nostr(e.to_string()))?;
let (chat_id, msg) = self.get_message(message_id).await.ok_or_else(|| VectorError::Other("message not found".into()))?;
if !chat_id.starts_with("npub1") {
return Err(VectorError::Other("not a DM".into()));
}
let outcome = if msg.mine { deletion::delete_own_dm(&rumor_id).await } else { deletion::delete_received_dm(&rumor_id).await }
.map_err(VectorError::Other)?;
state::STATE.lock().await.remove_message(message_id);
let _ = crate::db::events::delete_event(message_id).await;
traits::emit_event_json("message_removed", serde_json::json!({ "id": message_id, "chat_id": chat_id, "reason": "deleted" }));
Ok(outcome)
}
pub async fn get_chats(&self) -> Vec<SerializableChat> {
let state = state::STATE.lock().await;
state.chats.iter()
.map(|c| c.to_serializable_with_last_n(1, &state.interner))
.collect()
}
pub async fn get_messages(&self, chat_id: &str, limit: usize, offset: usize) -> Vec<Message> {
let state = state::STATE.lock().await;
let Some(chat) = state.get_chat(chat_id) else { return Vec::new() };
let msgs = chat.messages.messages();
let start = offset.min(msgs.len());
let end = offset.saturating_add(limit).min(msgs.len());
msgs[start..end].iter().map(|m| m.to_message(&state.interner)).collect()
}
pub async fn get_message(&self, message_id: &str) -> Option<(String, Message)> {
{
let state = state::STATE.lock().await;
if let Some((chat, msg)) = state.find_message(message_id) {
return Some((chat.id.clone(), msg));
}
}
db::events::get_message_by_id(message_id).await.ok().flatten()
}
pub async fn get_messages_with_attachment(&self, content_hash: &str) -> Vec<(String, Message)> {
let Ok(ids) = db::attachments::events_with_attachment_hash(content_hash) else { return Vec::new() };
let mut out = Vec::with_capacity(ids.len());
for id in ids {
if let Some(found) = self.get_message(&id).await {
out.push(found);
}
}
out
}
pub async fn get_messages_before(
&self,
chat_id: &str,
before: Option<(u64, &str)>,
limit: usize,
) -> Vec<Message> {
let state = state::STATE.lock().await;
let Some(chat) = state.get_chat(chat_id) else {
return Vec::new();
};
page_before(chat.messages.messages(), &state.interner, before, limit)
}
pub async fn get_profile(&self, npub: &str) -> Option<SlimProfile> {
let state = state::STATE.lock().await;
state.get_profile(npub)
.map(|p| SlimProfile::from_profile(p, &state.interner))
}
pub async fn load_profile(&self, npub: &str) -> bool {
profile::sync::load_profile(npub.to_string(), &NoOpProfileSyncHandler).await
}
pub async fn update_profile(&self, name: &str, avatar: &str, banner: &str, about: &str) -> bool {
profile::sync::update_profile(
name.to_string(), avatar.to_string(), banner.to_string(), about.to_string(),
&NoOpProfileSyncHandler,
).await
}
pub async fn update_bot_profile(&self, name: &str, avatar: &str, banner: &str, about: &str) -> bool {
profile::sync::update_bot_profile(
name.to_string(), avatar.to_string(), banner.to_string(), about.to_string(),
&NoOpProfileSyncHandler,
).await
}
pub async fn set_stream_consent(&self, on: bool) -> Result<bool> {
db::scoped_result(profile::sync::set_stream_consent(on, &NoOpProfileSyncHandler))
.await
.map_err(VectorError::Other)
}
pub async fn update_status(&self, status: &str) -> bool {
profile::sync::update_status(status.to_string()).await
}
pub async fn upload_public_image(&self, file_path: &str) -> Result<String> {
let path = std::path::Path::new(file_path);
let bytes = std::fs::read(path).map_err(VectorError::Io)?;
if bytes.is_empty() {
return Err(VectorError::Other("Empty image file".into()));
}
let extension = path.extension().and_then(|e| e.to_str()).unwrap_or("bin").to_lowercase();
let mime = crate::crypto::mime_from_extension(&extension);
let _client = state::nostr_client().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
let signer = crate::signer::active_signer()
.map_err(|e| VectorError::Other(format!("Signer unavailable: {e}")))?;
let servers = crate::blossom_servers::compute_enabled_servers();
if servers.is_empty() {
return Err(VectorError::Other("No Blossom servers configured".into()));
}
crate::blossom::upload_blob_with_failover(
signer,
servers,
std::sync::Arc::new(bytes),
Some(mime),
Some(crate::net::tor_http_timeout(std::time::Duration::from_secs(20))),
)
.await
.map_err(VectorError::Other)
}
pub async fn block_user(&self, npub: &str) -> bool {
profile::sync::block_user(npub.to_string(), &NoOpProfileSyncHandler).await
}
pub async fn unblock_user(&self, npub: &str) -> bool {
profile::sync::unblock_user(npub.to_string(), &NoOpProfileSyncHandler).await
}
pub async fn set_nickname(&self, npub: &str, nickname: &str) -> bool {
profile::sync::set_nickname(npub.to_string(), nickname.to_string(), &NoOpProfileSyncHandler).await
}
pub async fn get_blocked_users(&self) -> Vec<SlimProfile> {
profile::sync::get_blocked_users().await
}
pub fn queue_profile_sync(&self, npub: &str, priority: SyncPriority) {
profile::sync::queue_profile_sync(npub.to_string(), priority, false);
}
pub fn my_npub(&self) -> Option<String> {
state::my_public_key()
.and_then(|pk| ToBech32::to_bech32(&pk).ok())
}
pub async fn list_communities(&self) -> Vec<serde_json::Value> {
let ids = crate::db::community::list_community_ids().unwrap_or_default();
let me = state::my_public_key();
let mut out = Vec::new();
for id in ids {
let Ok(Some(c)) = crate::db::community::load_community_v2(&id) else { continue };
let is_owner = me.is_some_and(|m| c.owner().is_ok_and(|o| o == m));
out.push(serde_json::json!({
"community_id": crate::simd::hex::bytes_to_hex_32(&c.identity.community_id.0),
"version": 2,
"name": c.name,
"description": c.description,
"is_owner": is_owner,
"dissolved": c.dissolved,
"channels": c.layout().1.into_iter()
.map(|(ch, cat)| serde_json::json!({
"channel_id": crate::simd::hex::bytes_to_hex_32(&ch.id.0),
"name": ch.name,
"private": ch.private,
"readable": !(ch.private && ch.key.is_none()),
"epoch": ch.epoch.0,
"category_id": cat.map(|k| crate::simd::hex::bytes_to_hex_32(&k.id)),
"topic": ch.topic(),
"view": ch.view().as_str(),
}))
.collect::<Vec<_>>(),
"categories": Self::categories_json(&c),
}));
}
out
}
pub async fn create_community_v2(&self, name: &str) -> Result<serde_json::Value> {
self.create_community_with(name, &NewCommunity::default()).await
}
pub async fn create_community_with(&self, name: &str, opts: &NewCommunity) -> Result<serde_json::Value> {
use crate::community::{v2::service as v2, transport::LiveTransport};
let relays: Vec<String> = if opts.relays.is_empty() {
crate::state::active_trusted_relays().await.iter().map(|s| s.to_string()).collect()
} else {
crate::community::v2::service::clean_relays(&[], &opts.relays).map_err(VectorError::Other)?
};
if relays.is_empty() {
return Err(VectorError::Other("no relays available to host the Community".into()));
}
let session = crate::db::current_session();
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
let mut community = v2::create_community_on_roles_v2(&transport, name, relays, opts.description.clone())
.await
.map_err(VectorError::Other)?;
if !session.is_live() {
return Err(VectorError::Other("account changed while creating the community".into()));
}
self.register_v2_chats(&community, &session).await;
if let Some(first) = opts.first_channel.as_deref().map(str::trim).filter(|n| !n.is_empty() && *n != "general") {
if let Some(ch) = community.channels.first().cloned() {
let mut meta = ch.metadata();
meta.name = first.to_string();
match v2::edit_channel_metadata(&transport, &community, &ch.id, &meta).await {
Ok(()) => {
if let Ok(Some(fresh)) = crate::db::community::load_community_v2(community.id()) {
community = fresh;
if session.is_live() {
self.register_v2_chats(&community, &session).await;
}
}
}
Err(e) => crate::log_warn!("[v2:create] the first channel keeps the name general: {e}"),
}
}
}
if let Some(client) = state::nostr_client() {
crate::community::v2::realtime::refresh_subscription(&client).await;
}
Ok(Self::v2_summary(&community))
}
fn v2_community_for_channel(&self, channel_id: &str) -> Result<Option<crate::community::CommunityId>> {
let Some(cid_hex) = crate::db::community::community_id_for_channel(channel_id).map_err(VectorError::Other)? else {
return Ok(None);
};
let cid = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&cid_hex));
Ok(crate::db::community::community_held(&cid).map_err(VectorError::Other)?.then_some(cid))
}
fn v2_summary(community: &crate::community::v2::community::CommunityV2) -> serde_json::Value {
let me = state::my_public_key();
let is_owner = me.is_some_and(|m| community.owner().is_ok_and(|o| o == m));
serde_json::json!({
"community_id": crate::simd::hex::bytes_to_hex_32(&community.identity.community_id.0),
"version": 2,
"name": community.name,
"description": community.description,
"is_owner": is_owner,
"primary_channel": community.primary_channel().map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0)),
"channels": community.layout().1.into_iter()
.map(|(c, cat)| serde_json::json!({
"channel_id": crate::simd::hex::bytes_to_hex_32(&c.id.0),
"name": c.name,
"private": c.private,
"category_id": cat.map(|k| crate::simd::hex::bytes_to_hex_32(&k.id)),
"topic": c.topic(),
"view": c.view().as_str(),
}))
.collect::<Vec<_>>(),
"categories": Self::categories_json(community),
})
}
pub fn my_channel_permissions(community: &crate::community::v2::community::CommunityV2) -> std::collections::HashMap<[u8; 32], u64> {
let Some(me) = state::my_public_key() else { return Default::default() };
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
if roster.everyone.is_none() {
return Default::default();
}
let owner = community.owner().ok().map(|o| o.to_hex());
community
.channels
.iter()
.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))
.collect()
}
pub fn categories_json(community: &crate::community::v2::community::CommunityV2) -> serde_json::Value {
community
.layout()
.0
.into_iter()
.map(|k| serde_json::json!({ "category_id": crate::simd::hex::bytes_to_hex_32(&k.id), "name": k.name }))
.collect()
}
pub async fn register_v2_chats(&self, community: &crate::community::v2::community::CommunityV2, __session: &std::sync::Arc<crate::db::Session>) {
register_v2_chats_inner(community).await
}
}
pub(crate) async fn register_v2_chats_inner(community: &crate::community::v2::community::CommunityV2) {
crate::community::v2::changes::prime(community);
crate::db::scoped(async move {
let owner_npub = community.owner().ok().and_then(|p| ToBech32::to_bech32(&p).ok());
let me = state::my_public_key();
let is_owner = me.is_some_and(|m| community.owner().is_ok_and(|o| o == m));
let id_hex = crate::simd::hex::bytes_to_hex_32(&community.identity.community_id.0);
let Some(primary) = community.primary_channel() else { return };
let primary_hex = crate::simd::hex::bytes_to_hex_32(&primary.id.0);
let slims = {
let mut st = state::STATE.lock().await;
let mut slims = Vec::new();
for ch in &community.channels {
let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
st.upsert_community_chat(
&ch_hex,
&community.name,
community.description.as_deref().unwrap_or(""),
&id_hex,
is_owner,
community.icon.is_some(),
owner_npub.as_deref(),
Some(community.created_at_ms),
community.dissolved,
&ch.name,
&primary_hex,
);
if let Some(chat) = st.chats.iter().find(|c| c.id == ch_hex) {
slims.push(crate::db::chats::SlimChatDB::from_chat(chat, &st.interner));
}
}
slims
};
for slim in &slims {
let _ = crate::db::chats::save_slim_chat(slim);
}
})
.await
}
const RAID_REPORT_TTL_SECS: u64 = 90;
struct RaidReportCache;
struct PolicyReportCache;
struct PolicyReportGate;
type ReportCache<T> = std::sync::Arc<std::sync::Mutex<std::collections::HashMap<String, (u64, std::sync::Arc<T>)>>>;
fn policy_report_cache() -> ReportCache<serde_json::Value> {
crate::db::current_session().scoped::<PolicyReportCache, _>()
}
fn policy_report_gate() -> std::sync::Arc<std::sync::Mutex<()>> {
crate::db::current_session().scoped::<PolicyReportGate, _>()
}
fn raid_report_cache() -> ReportCache<crate::community::raid::RaidReport> {
crate::db::current_session().scoped::<RaidReportCache, _>()
}
fn report_get<T>(cache: &ReportCache<T>, cid_hex: &str, now_secs: u64) -> Option<std::sync::Arc<T>> {
let mut map = cache.lock().unwrap_or_else(|e| e.into_inner());
map.retain(|_, (at, _)| now_secs.saturating_sub(*at) < RAID_REPORT_TTL_SECS);
map.get(cid_hex).map(|(_, report)| report.clone())
}
fn report_put<T>(cache: &ReportCache<T>, cid_hex: &str, now_secs: u64, report: std::sync::Arc<T>) {
let mut map = cache.lock().unwrap_or_else(|e| e.into_inner());
map.retain(|_, (at, _)| now_secs.saturating_sub(*at) < RAID_REPORT_TTL_SECS);
map.insert(cid_hex.to_string(), (now_secs, report));
}
fn report_once<T>(
cache: &ReportCache<T>,
gate: &std::sync::Mutex<()>,
cid_hex: &str,
now_secs: u64,
compute: impl FnOnce() -> Result<std::sync::Arc<T>>,
) -> Result<std::sync::Arc<T>> {
if let Some(hit) = report_get(cache, cid_hex, now_secs) {
return Ok(hit);
}
let _turn = gate.lock().unwrap_or_else(|e| e.into_inner());
if let Some(hit) = report_get(cache, cid_hex, now_secs) {
return Ok(hit);
}
let report = compute()?;
report_put(cache, cid_hex, now_secs, report.clone());
Ok(report)
}
#[cfg(test)]
mod report_cache_tests {
use super::*;
#[test]
fn an_expired_report_goes_on_the_next_touch() {
let cache: ReportCache<u32> = Default::default();
report_put(&cache, "a", 1_000, std::sync::Arc::new(1));
report_put(&cache, "b", 1_050, std::sync::Arc::new(2));
assert_eq!(report_get(&cache, "a", 1_000 + RAID_REPORT_TTL_SECS - 1).as_deref(), Some(&1));
assert_eq!(report_get(&cache, "a", 1_000 + RAID_REPORT_TTL_SECS), None, "a report is fresh for the TTL, no longer");
assert_eq!(cache.lock().unwrap().len(), 1, "the lookup dropped it");
report_put(&cache, "c", 1_050 + RAID_REPORT_TTL_SECS, std::sync::Arc::new(3));
let map = cache.lock().unwrap();
assert!(!map.contains_key("b") && map.contains_key("c"), "and so does an insert");
}
#[test]
fn callers_that_miss_together_share_one_evaluation() {
let cache: ReportCache<u32> = Default::default();
let gate = std::sync::Mutex::new(());
let runs = std::sync::atomic::AtomicU32::new(0);
std::thread::scope(|s| {
for _ in 0..4 {
s.spawn(|| {
let got = report_once(&cache, &gate, "a", 1_000, || {
runs.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
std::thread::sleep(std::time::Duration::from_millis(50));
Ok(std::sync::Arc::new(7))
});
assert_eq!(got.unwrap().as_ref(), &7);
});
}
});
assert_eq!(runs.load(std::sync::atomic::Ordering::SeqCst), 1);
let again = report_once(&cache, &gate, "a", 1_000 + RAID_REPORT_TTL_SECS, || Ok(std::sync::Arc::new(8)));
assert_eq!(again.unwrap().as_ref(), &8, "an expired report is evaluated afresh");
}
}
impl VectorCore {
pub async fn join_community(&self, invite_url: &str) -> Result<serde_json::Value> {
use crate::community::transport::LiveTransport;
crate::community::v2::invite::parse_invite_link(invite_url)
.map_err(|_| VectorError::Other("not a Vector invite link".into()))?;
let session = crate::db::current_session();
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
let community = crate::community::v2::service::accept_public_link(&transport, invite_url)
.await
.map_err(VectorError::Other)?;
self.register_v2_chats(&community, &session).await;
if let Some(client) = state::nostr_client() {
crate::community::v2::realtime::refresh_subscription(&client).await;
}
if crate::community::v2::realtime::follow_worker_running() {
crate::community::v2::realtime::enqueue_follow(community.id());
} else {
let seed_community = community.clone();
db::spawn_bound(async move {
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(20));
if matches!(
crate::community::v2::service::sync_guestbook(&transport, &seed_community).await,
Ok(fresh) if !fresh.is_empty()
) {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&seed_community.id().0);
emit_event("community_refreshed", &serde_json::json!({ "community_id": cid_hex }));
}
});
}
Ok(Self::v2_summary(&community))
}
pub fn list_pending_invites(&self) -> Result<Vec<serde_json::Value>> {
let rows = crate::db::community::list_pending_invites().map_err(VectorError::Other)?;
Ok(rows
.iter()
.filter_map(|p| {
let v2 = crate::community::v2::invite::CommunityInvite::from_bundle_json(&p.bundle_json).ok()?;
Some(serde_json::json!({
"community_id": p.community_id,
"name": v2.name,
"inviter_npub": p.inviter_npub,
"version": 2,
}))
})
.collect())
}
pub async fn accept_pending_invite(&self, community_id: &str) -> Result<serde_json::Value> {
crate::db::scoped(async move {
use crate::community::transport::LiveTransport;
let bundle_json = crate::db::community::get_pending_invite(community_id)
.map_err(VectorError::Other)?
.ok_or_else(|| VectorError::Other(format!("no pending invite for {community_id}")))?;
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
let session = crate::db::current_session();
let inviter = crate::db::community::list_pending_invites()
.ok()
.and_then(|rows| rows.into_iter().find(|p| p.community_id == community_id).map(|p| p.inviter_npub));
let community = match crate::community::v2::service::accept_parked_invite(&transport, &bundle_json, inviter.as_deref()).await {
Ok(c) => c,
Err(e) if e == crate::community::v2::service::ERR_DISSOLVED => {
let relays = crate::community::v2::invite::CommunityInvite::from_bundle_json(&bundle_json)
.map(|i| i.relays)
.unwrap_or_default();
crate::community::v2::service::retire_dead_invite(&transport, community_id, &relays).await;
return Err(VectorError::Other("this community has been dissolved — the invite was removed".into()));
}
Err(e) => return Err(VectorError::Other(e)),
};
self.register_v2_chats(&community, &session).await;
if let Some(client) = state::nostr_client() {
crate::community::v2::realtime::refresh_subscription(&client).await;
}
crate::community::v2::realtime::enqueue_follow(community.id());
let _ = crate::db::community::delete_pending_invite(community_id);
Ok(Self::v2_summary(&community))
})
.await
}
fn v2_community(community_id: &str) -> Result<crate::community::v2::community::CommunityV2> {
use crate::community::CommunityId;
if community_id.len() != 64 {
return Err(VectorError::Other("malformed community id".into()));
}
let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
crate::db::community::load_community_v2(&cid)
.map_err(VectorError::Other)?
.ok_or_else(|| VectorError::Other("community not found".into()))
}
fn channel_id_of(channel_id: &str) -> Result<crate::community::ChannelId> {
crate::simd::hex::hex_to_bytes_32_checked(channel_id)
.map(crate::community::ChannelId)
.ok_or_else(|| VectorError::Other("malformed channel id".into()))
}
pub async fn create_channel(&self, community_id: &str, name: &str, private: bool) -> Result<String> {
use crate::community::{v2::service, transport::LiveTransport};
let community = Self::v2_community(community_id)?;
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
let id = if private {
service::create_private_channel(&transport, &community, name).await
} else {
service::create_public_channel(&transport, &community, name).await
}
.map_err(VectorError::Other)?;
if let Some(client) = state::nostr_client() {
crate::community::v2::realtime::refresh_subscription(&client).await;
}
Ok(crate::simd::hex::bytes_to_hex_32(&id.0))
}
pub async fn create_channel_with(&self, community_id: &str, name: &str, opts: &NewChannel) -> Result<String> {
use crate::community::{v2::service, transport::LiveTransport};
let name = name.trim();
if name.is_empty() {
return Err(VectorError::Other("a channel needs a name".into()));
}
let view = opts.view.as_deref().map(Self::view_named).transpose()?;
let session = crate::db::current_session();
let community = Self::v2_community(community_id)?;
let category = opts.category_id.as_deref().map(|c| Self::id32(c, "category_id")).transpose()?;
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(20));
let id = service::create_channel_in(&transport, &community, name, opts.private, category).await.map_err(VectorError::Other)?;
let channel_id = crate::simd::hex::bytes_to_hex_32(&id.0);
if let Ok(Some(fresh)) = crate::db::community::load_community_v2(community.id()) {
if session.is_live() {
self.register_v2_chats(&fresh, &session).await;
}
}
if view.is_some() || opts.topic.is_some() {
let view = view.unwrap_or(crate::community::v2::community::ChannelView::Chat).as_str();
if let Err(e) = self.edit_channel_details(community_id, &channel_id, name, opts.topic.as_deref(), view).await {
crate::log_warn!("[v2:create] channel {} stands without its view or topic: {e}", &channel_id[..12]);
}
}
if let Some(client) = state::nostr_client() {
crate::community::v2::realtime::refresh_subscription(&client).await;
}
Ok(channel_id)
}
pub async fn preview_public_link(&self, url: &str) -> Result<LinkPreview> {
use crate::community::{transport::LiveTransport, CommunityId};
crate::community::v2::invite::parse_invite_link(url).map_err(|_| VectorError::Other("not a Vector invite link".into()))?;
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
let bundle = crate::community::v2::service::fetch_public_bundle(&transport, url).await.map_err(VectorError::Other)?;
let community_id = bundle.community_id.clone();
if let Ok(id) = Self::id32(&community_id, "community_id") {
if let Ok(Some(local)) = crate::db::community::load_community_v2(&CommunityId(id)) {
return Ok(LinkPreview {
community_id,
name: local.name.clone(),
description: local.description.clone(),
icon: local.icon.as_ref().map(|i| i.to_community_image()),
joined: true,
verified: true,
});
}
}
let (folded, verified) = crate::community::v2::service::preview_bundle_checked(&transport, &bundle).await.map_err(VectorError::Other)?;
Ok(LinkPreview {
community_id,
name: folded.name.clone(),
description: folded.description.clone(),
icon: folded.icon.as_ref().map(|i| i.to_community_image()),
joined: false,
verified,
})
}
pub async fn rename_channel(&self, community_id: &str, channel_id: &str, name: &str) -> Result<()> {
use crate::community::{v2::service, transport::LiveTransport};
let community = Self::v2_community(community_id)?;
let id = Self::channel_id_of(channel_id)?;
let mut meta = community
.channel(&id)
.ok_or_else(|| VectorError::Other("unknown channel".into()))?
.metadata();
meta.name = name.to_string();
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
service::edit_channel_metadata(&transport, &community, &id, &meta)
.await
.map_err(VectorError::Other)
}
pub async fn delete_channel(&self, community_id: &str, channel_id: &str) -> Result<()> {
use crate::community::{v2::service, transport::LiveTransport};
let community = Self::v2_community(community_id)?;
let id = Self::channel_id_of(channel_id)?;
let name = community.channel(&id).map(|c| c.name.clone()).unwrap_or_default();
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
service::delete_channel(&transport, &community, &id, &name)
.await
.map_err(VectorError::Other)
}
pub async fn grant_channel_access(&self, community_id: &str, channel_id: &str, npub: &str) -> Result<()> {
use crate::community::{v2::service, transport::LiveTransport};
let community = Self::v2_community(community_id)?;
let id = Self::channel_id_of(channel_id)?;
let member = nostr_sdk::prelude::PublicKey::parse(npub)
.map_err(|e| VectorError::Other(format!("bad npub: {e}")))?;
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
service::grant_channel_access(&transport, &community, &id, &member)
.await
.map_err(VectorError::Other)
}
pub async fn revoke_channel_access(&self, community_id: &str, channel_id: &str, npub: &str) -> Result<()> {
use crate::community::{v2::service, transport::LiveTransport};
let community = Self::v2_community(community_id)?;
let id = Self::channel_id_of(channel_id)?;
let member = nostr_sdk::prelude::PublicKey::parse(npub)
.map_err(|e| VectorError::Other(format!("bad npub: {e}")))?;
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
service::revoke_channel_access(&transport, &community, &id, &member)
.await
.map_err(VectorError::Other)
}
pub fn member_can_read_channel(&self, community_id: &str, channel_id: &str, npub: &str) -> Result<bool> {
use nostr_sdk::prelude::PublicKey;
let community = Self::v2_community(community_id)?;
let id = Self::channel_id_of(channel_id)?;
let ch = community.channel(&id).ok_or_else(|| VectorError::Other("unknown channel".into()))?;
let who = PublicKey::parse(npub).map_err(|_| VectorError::Other(format!("invalid npub: {npub}")))?.to_hex();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
if crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default().contains(&who) {
return Ok(false);
}
if !ch.private {
return Ok(true);
}
if community.owner().map(|o| o.to_hex()) == Ok(who.clone()) {
return Ok(true);
}
let roster = crate::db::community::get_community_roles(&cid_hex).map_err(VectorError::Other)?;
let access_ids = roster.channel_role_ids(&crate::simd::hex::bytes_to_hex_32(&id.0));
Ok(roster
.grants
.iter()
.filter(|g| g.member == who)
.any(|g| g.role_ids.iter().any(|rid| access_ids.contains(rid))))
}
pub fn channel_access(&self, community_id: &str, channel_id: &str) -> Result<serde_json::Value> {
use nostr_sdk::prelude::{PublicKey, ToBech32};
let community = Self::v2_community(community_id)?;
let id = Self::channel_id_of(channel_id)?;
let ch = community
.channel(&id)
.ok_or_else(|| VectorError::Other("unknown channel".into()))?;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let roster = crate::db::community::get_community_roles(&cid_hex).map_err(VectorError::Other)?;
let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
let chan_hex = crate::simd::hex::bytes_to_hex_32(&id.0);
let owner_hex = community.owner().ok().map(|o| o.to_hex());
let (roles, members): (Vec<serde_json::Value>, Vec<String>) = if roster.everyone.is_some() {
use crate::community::roles::{OverwriteTarget, Permissions};
let scope = roster.syncs.get(&chan_hex).cloned().unwrap_or_else(|| chan_hex.clone());
let roles = roster
.overwrites
.iter()
.filter(|o| o.scope == scope && o.allow.contains(Permissions::VIEW_CHANNEL))
.filter_map(|o| match &o.target {
OverwriteTarget::Role(id) => roster.role(id).map(|r| serde_json::json!({ "role_id": r.role_id, "name": r.name })),
_ => None,
})
.collect();
let mut named: Vec<String> = roster.grants.iter().map(|g| g.member.clone()).collect();
named.extend(roster.overwrites.iter().filter_map(|o| match &o.target {
OverwriteTarget::Member(m) => Some(m.clone()),
_ => None,
}));
named.sort();
named.dedup();
let members = named
.into_iter()
.filter(|m| !banned.contains(m) && Some(m) != owner_hex.as_ref() && roster.is_entitled(owner_hex.as_deref(), m, &chan_hex, &[], &[]))
.filter_map(|m| PublicKey::from_hex(&m).ok().and_then(|pk| pk.to_bech32().ok()))
.collect();
(roles, members)
} else {
let access_ids = roster.channel_role_ids(&chan_hex);
let roles = roster
.channel_roles(&chan_hex)
.into_iter()
.map(|r| serde_json::json!({ "role_id": r.role_id, "name": r.name }))
.collect();
let members = roster
.grants
.iter()
.filter(|g| !banned.contains(&g.member))
.filter(|g| g.role_ids.iter().any(|rid| access_ids.contains(rid)))
.filter_map(|g| PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok()))
.collect();
(roles, members)
};
Ok(serde_json::json!({
"channel_id": chan_hex,
"private": ch.private,
"readable": !(ch.private && ch.key.is_none()),
"owner": community.owner().ok().and_then(|o| o.to_bech32().ok()),
"roles": roles,
"members": members,
}))
}
pub async fn create_public_invite(
&self,
community_id: &str,
expires_at_ms: Option<u64>,
label: Option<String>,
) -> Result<String> {
use crate::community::CommunityId;
if community_id.len() != 64 {
return Err(VectorError::Other("malformed community id".into()));
}
let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
let community = crate::db::community::load_community_v2(&cid)
.map_err(VectorError::Other)?
.ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
let base = crate::community::v2::invite::INVITE_URL_BASE.trim_end_matches("/invite");
let label = Some(crate::community::v2::invite::resolve_invite_label(community_id, label).map_err(VectorError::Other)?);
let minted = crate::community::v2::service::mint_public_link_sync_later(&community, base, expires_at_ms, label)
.await
.map_err(VectorError::Other)?;
Ok(minted.url)
}
pub async fn invite_to_community(&self, community_id: &str, invitee_npub: &str) -> Result<serde_json::Value> {
crate::db::scoped(async move {
use crate::community::CommunityId;
let my_pk = crate::state::my_public_key()
.ok_or_else(|| VectorError::Other("Public key not set".into()))?;
if community_id.len() != 64 {
return Err(VectorError::Other("malformed community id".into()));
}
let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
let recipient = nostr_sdk::prelude::PublicKey::parse(invitee_npub)
.map_err(|e| VectorError::Other(format!("bad invitee npub: {e}")))?;
let client = crate::state::nostr_client().ok_or_else(|| VectorError::Other("Not connected".into()))?;
let bundle = {
let lock = crate::community::v2::realtime::follow_lock(&cid);
let _rotation = lock.lock().await;
let community = crate::db::community::load_community_v2(&cid)
.map_err(VectorError::Other)?
.ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
crate::community::v2::service::bundle_of(
&community,
crate::community::v2::service::BundleAudience::Member(recipient),
Some(my_pk),
None,
None,
)
};
let bundle_json = serde_json::to_string(&bundle).map_err(|e| VectorError::Other(e.to_string()))?;
let expires_at = crate::clock::timestamp().as_secs()
+ crate::community::v2::invite::DIRECT_INVITE_EXPIRY_SECS;
let expiry_tag = nostr_sdk::prelude::Tag::expiration(nostr_sdk::prelude::Timestamp::from_secs(expires_at));
let rumor = nostr_sdk::prelude::EventBuilder::new(
nostr_sdk::prelude::Kind::Custom(crate::community::v2::kind::DIRECT_INVITE),
bundle_json,
)
.tag(expiry_tag.clone())
.finalize_unsigned_with_id(my_pk);
let k_tag = nostr_sdk::prelude::Tag::custom(
"k",
[crate::community::v2::kind::DIRECT_INVITE.to_string()],
);
crate::inbox_relays::send_gift_wrap(&client, &recipient, rumor, [k_tag, expiry_tag])
.await
.map_err(VectorError::Other)?;
Ok(serde_json::json!({ "invited": invitee_npub, "version": 2 }))
})
.await
}
pub fn list_public_invites(&self, community_id: &str) -> Result<Vec<crate::db::community::PublicInviteRecord>> {
crate::db::community::list_public_invites(community_id).map_err(VectorError::Other)
}
pub async fn sync_public_invites(&self, community_id: &str) -> Result<bool> {
let held = Self::held_v2(community_id)?;
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
crate::community::v2::service::adopt_invite_list(&transport, &held).await.map_err(VectorError::Other)
}
pub async fn revoke_public_invite(&self, community_id: &str, token: &str) -> Result<()> {
use crate::community::{transport::LiveTransport, CommunityId};
if community_id.len() != 64 {
return Err(VectorError::Other("malformed community id".into()));
}
let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(20));
let community = crate::db::community::load_community_v2(&cid)
.map_err(VectorError::Other)?
.ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
crate::community::v2::service::revoke_public_link(&transport, &community, token)
.await
.map_err(VectorError::Other)
}
pub async fn send_community_message(
&self,
channel_id: &str,
content: &str,
replied_to: Option<&str>,
) -> Result<String> {
self.send_community_message_expiring(channel_id, content, replied_to, None).await
}
pub async fn send_community_message_expiring(
&self,
channel_id: &str,
content: &str,
replied_to: Option<&str>,
expires_in_secs: Option<u64>,
) -> Result<String> {
let opts = PostOptions { reply_to: replied_to.map(str::to_string), expires_in_secs, ..Default::default() };
self.post_community_message(channel_id, content, &opts).await
}
pub async fn post_community_message(&self, channel_id: &str, content: &str, opts: &PostOptions) -> Result<String> {
self.post_community(channel_id, content, Vec::new(), opts, std::time::Duration::from_secs(12)).await
}
async fn post_community(
&self,
channel_id: &str,
content: &str,
mut extra_tags: Vec<nostr_sdk::prelude::Tag>,
opts: &PostOptions,
timeout: std::time::Duration,
) -> Result<String> {
use crate::community::transport::LiveTransport;
let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
let community = crate::db::community::load_community_v2(&id)
.map_err(VectorError::Other)?
.ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
let transport = LiveTransport::with_timeout(timeout);
let reply = match opts.reply_to.as_deref().filter(|r| !r.is_empty()) {
Some(parent_id) => {
let author_hex = {
let st = state::STATE.lock().await;
st.find_message(parent_id)
.and_then(|(_, m)| m.npub.as_deref().and_then(|n| nostr_sdk::prelude::PublicKey::parse(n).ok()))
.map(|pk| pk.to_hex())
.unwrap_or_default()
};
Some((parent_id.to_string(), author_hex))
}
None => None,
};
let reply_ref = reply.as_ref().map(|(id, author)| (id.as_str(), author.as_str()));
let (named, role_mentions) = crate::community::mentions::resolve_in(&crate::simd::hex::bytes_to_hex_32(&id.0), content);
let (plain, text_spans) = crate::text_spans::extract_own(&named);
let content = plain.as_str();
let emoji_owned = crate::emoji_packs::resolve_outbound_emoji_tags(content);
let emoji_pairs: Vec<(&str, &str)> = emoji_owned.iter().map(|t| (t.shortcode.as_str(), t.url.as_str())).collect();
extra_tags.extend(crate::text_spans::to_nostr_tags(&text_spans).chain(crate::community::mentions::to_tags(&role_mentions)));
if let Some(bot) = opts.bot.as_deref().filter(|b| !b.is_empty()) {
let pk = nostr_sdk::prelude::PublicKey::parse(bot).map_err(|_| VectorError::Other(format!("{bot} isn't an npub or hex pubkey")))?;
extra_tags.push(crate::bot_interface::bot_tag(&pk));
}
if let Some(secs) = opts.expires_in_secs.filter(|s| *s > 0) {
let at = crate::clock::now_secs().saturating_add(secs);
extra_tags.push(nostr_sdk::prelude::Tag::expiration(nostr_sdk::prelude::Timestamp::from_secs(at)));
}
crate::community::v2::service::send_chat_message(&transport, &community, &ch, content, reply_ref, &emoji_pairs, extra_tags)
.await
.map_err(VectorError::Other)
}
pub async fn send_community_file(&self, channel_id: &str, file_path: &str) -> Result<String> {
self.post_community_file(channel_id, file_path, &PostOptions::default().compress(false)).await
}
pub async fn post_community_file(&self, channel_id: &str, file_path: &str, opts: &PostOptions) -> Result<String> {
let path = std::path::Path::new(file_path);
let bytes = std::fs::read(path).map_err(VectorError::Io)?;
let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("file").to_string();
self.post_community_bytes(channel_id, bytes, &filename, opts).await
}
pub async fn post_community_bytes(&self, channel_id: &str, bytes: Vec<u8>, filename: &str, opts: &PostOptions) -> Result<String> {
crate::db::scoped(async move {
use crate::community::attachments;
if bytes.is_empty() {
return Err(VectorError::Other("Empty file".into()));
}
let (bytes, filename) = ready_to_send(bytes, filename, opts.compress).await?;
let filename = filename.as_str();
let extension = std::path::Path::new(filename).extension().and_then(|e| e.to_str()).unwrap_or("bin").to_lowercase();
let id = self
.v2_community_for_channel(channel_id)?
.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
let community = crate::db::community::load_community_v2(&id)
.map_err(VectorError::Other)?
.ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
if community.dissolved {
return Err(VectorError::Other("this community has been dissolved".into()));
}
let author_pk = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
let file_hash = crate::crypto::sha256_hex(&bytes);
let mime = crate::crypto::mime_from_extension(&extension);
let img_meta = crate::crypto::generate_image_metadata(&bytes);
let params = crate::crypto::generate_encryption_params();
let encrypted = crate::crypto::encrypt_data(&bytes, ¶ms)?;
let encrypted_size = encrypted.len() as u64;
let _client = state::nostr_client().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
let signer = crate::signer::active_signer().map_err(|e| VectorError::Other(format!("Signer unavailable: {e}")))?;
let servers = crate::blossom_servers::compute_enabled_servers();
if servers.is_empty() {
return Err(VectorError::Other("No Blossom servers configured".into()));
}
let noop_progress: crate::blossom::ProgressCallback = std::sync::Arc::new(|_, _| Ok(()));
let accepted = crate::blossom::upload_blob_with_progress_and_failover(
signer.clone(),
servers,
std::sync::Arc::new(encrypted),
Some(mime),
true,
noop_progress,
Some(3),
Some(std::time::Duration::from_secs(2)),
None,
).await.map_err(VectorError::Other)?;
let url = accepted.url;
let attachment = crate::types::Attachment {
id: file_hash.clone(),
key: params.key.clone(),
nonce: params.nonce.clone(),
extension: extension.clone(),
name: filename.to_string(),
url,
path: String::new(),
size: encrypted_size,
img_meta,
downloading: false,
downloaded: false,
verified: true,
webxdc_topic: extension
.eq_ignore_ascii_case("xdc")
.then(|| crate::webxdc::mint_topic_id(&file_hash, &author_pk.to_hex())),
..Default::default()
};
let imeta = vec![attachments::attachment_to_imeta(&attachment)];
let caption = opts.caption.clone().unwrap_or_default();
self.post_community(channel_id, &caption, imeta, opts, std::time::Duration::from_secs(30)).await
})
.await
}
pub async fn send_community_typing(&self, channel_id: &str) -> Result<()> {
use crate::community::transport::LiveTransport;
let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
let community = crate::db::community::load_community_v2(&id)
.map_err(VectorError::Other)?
.ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(8));
crate::community::v2::service::send_typing(&transport, &community, &ch)
.await
.map_err(VectorError::Other)
}
pub async fn send_community_reaction(
&self,
channel_id: &str,
message_id: &str,
emoji: &str,
emoji_url: Option<&str>,
) -> Result<()> {
crate::db::scoped(async move {
if Self::own_reaction_id(message_id, emoji).await.is_some() {
return Ok(());
}
let emoji_tags: Vec<crate::types::EmojiTag> = match emoji_url {
Some(url) if emoji.starts_with(':') && emoji.ends_with(':') && emoji.len() >= 3 && !url.is_empty() => {
vec![crate::types::EmojiTag { shortcode: emoji[1..emoji.len() - 1].to_string(), url: url.to_string() }]
}
_ => Vec::new(),
};
let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
let community = crate::db::community::load_community_v2(&id)
.map_err(VectorError::Other)?
.ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
let held = {
let st = state::STATE.lock().await;
st.find_message(message_id)
.and_then(|(_, m)| m.npub.as_deref().and_then(|n| nostr_sdk::prelude::PublicKey::parse(n).ok()))
};
let held = held.or_else(|| {
crate::db::events::event_author(message_id)
.ok()
.flatten()
.and_then(|n| nostr_sdk::prelude::PublicKey::parse(&n).ok())
});
let target_author = match held {
Some(pk) => pk,
None => crate::community::v2::service::fetch_channel(&transport, &community, &ch, 500)
.await
.map_err(VectorError::Other)?
.iter()
.find(|f| f.event.opened().rumor_id.to_hex() == message_id)
.map(|f| f.event.opened().author)
.ok_or_else(|| VectorError::Other("reacted-to message not found".into()))?,
};
let pair = emoji_tags.first().map(|t| (t.shortcode.as_str(), t.url.as_str()));
crate::community::v2::service::send_reaction(
&transport, &community, &ch, message_id, &target_author.to_hex(), crate::community::v2::kind::MESSAGE, emoji, pair,
)
.await
.map(|_| ())
.map_err(VectorError::Other)
})
.await
}
pub async fn edit_community_message(&self, channel_id: &str, message_id: &str, new_content: &str) -> Result<()> {
let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
let (named, _) = crate::community::mentions::resolve_in(&crate::simd::hex::bytes_to_hex_32(&id.0), new_content);
let (plain, text_spans) = crate::text_spans::extract_own(&named);
let new_content = plain.as_str();
let span_tags: Vec<nostr_sdk::prelude::Tag> = crate::text_spans::to_nostr_tags(&text_spans).collect();
let emoji_tags = emoji_packs::resolve_outbound_emoji_tags(new_content);
let community = crate::db::community::load_community_v2(&id)
.map_err(VectorError::Other)?
.ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
let emoji_pairs: Vec<(&str, &str)> = emoji_tags.iter().map(|t| (t.shortcode.as_str(), t.url.as_str())).collect();
crate::community::v2::service::send_edit_tagged(&transport, &community, &ch, message_id, new_content, &emoji_pairs, span_tags)
.await
.map(|_| ())
.map_err(VectorError::Other)
}
pub async fn delete_community_message(&self, message_id: &str) -> Result<()> {
let channel_id = self.message_chat(message_id).await?;
self.delete_community_message_in(&channel_id, message_id).await
}
pub async fn message_chat(&self, message_id: &str) -> Result<String> {
if let Some((_, chat)) = state::STATE.lock().await.find_chat_for_message(message_id) {
return Ok(chat);
}
crate::db::events::locate_message(message_id)
.map_err(VectorError::Other)?
.chat
.ok_or_else(|| VectorError::Other("message not found (already deleted?)".into()))
}
pub async fn delete_community_message_in(&self, channel_id: &str, message_id: &str) -> Result<()> {
use crate::community::transport::LiveTransport;
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
let attachment_urls: Vec<String> = self
.get_message(message_id)
.await
.map(|(_, msg)| msg.attachments.iter().flat_map(|a| a.all_urls().map(str::to_string)).collect())
.unwrap_or_default();
let attachment_urls =
crate::db::attachments::urls_unreferenced_elsewhere(&attachment_urls, message_id).unwrap_or_default();
let id = self
.v2_community_for_channel(channel_id)?
.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
let community = crate::db::community::load_community_v2(&id)
.map_err(VectorError::Other)?
.ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
crate::community::v2::service::delete_own(&transport, &community, &ch, message_id, crate::community::v2::kind::MESSAGE)
.await
.map_err(VectorError::Other)?;
if !attachment_urls.is_empty() {
if let Some(_client) = state::nostr_client() {
if let Ok(signer) = crate::signer::active_signer() {
crate::blossom::delete_blobs_best_effort(signer, attachment_urls);
}
}
}
let removed_chat = {
let mut st = state::STATE.lock().await;
st.remove_message(message_id).map(|(cid, _)| cid)
};
let _ = crate::db::events::delete_event(message_id).await;
traits::emit_event_json("message_removed", serde_json::json!({
"id": message_id, "chat_id": removed_chat.as_deref().unwrap_or(channel_id), "reason": "deleted",
}));
Ok(())
}
pub async fn hide_community_message(&self, channel_id: &str, message_id: &str) -> Result<()> {
use crate::community::transport::LiveTransport;
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
let author_npub = {
let st = state::STATE.lock().await;
st.find_message(message_id).and_then(|(_, m)| m.npub)
};
let author_npub = match author_npub {
Some(n) => n,
None => crate::db::events::event_author(message_id)
.ok()
.flatten()
.ok_or_else(|| VectorError::Other("can't resolve the target message's author".into()))?,
};
let author = nostr_sdk::prelude::PublicKey::parse(&author_npub)
.map_err(|_| VectorError::Other("target message has an unreadable author".into()))?;
let id = self
.v2_community_for_channel(channel_id)?
.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
let community = crate::db::community::load_community_v2(&id)
.map_err(VectorError::Other)?
.ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
crate::community::v2::service::moderation_delete(
&transport, &community, &ch, message_id, crate::community::v2::kind::MESSAGE, &author,
)
.await
.map_err(VectorError::Other)?;
let removed_chat = {
let mut st = state::STATE.lock().await;
st.remove_message(message_id).map(|(cid, _)| cid)
};
let _ = crate::db::events::delete_event(message_id).await;
traits::emit_event_json("message_removed", serde_json::json!({
"id": message_id, "chat_id": removed_chat.as_deref().unwrap_or(channel_id), "reason": "hidden",
}));
Ok(())
}
pub async fn sync_community_channel(&self, channel_id: &str, limit: usize) -> Result<(usize, Vec<String>)> {
self.sync_community_channel_before(channel_id, limit, None).await
}
pub async fn sync_community_channel_page(
&self,
channel_id: &str,
limit: usize,
before_secs: Option<u64>,
since_secs: Option<u64>,
) -> Result<(BackfillCount, Vec<String>)> {
let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
let warnings = if community::v2::realtime::follow_worker_running() {
community::v2::realtime::enqueue_follow(&id);
Vec::new()
} else {
Self::v2_inline_follow(&id).await
};
let count = Self::v2_backfill_channel_counted(
&id, channel_id, limit, 8, since_secs, before_secs,
crate::community::transport::Evidence::Fast, 12,
).await;
Ok((count, warnings))
}
pub async fn fill_community_gap(&self, channel_id: &str, before_ms: u64) -> Result<usize> {
let Some(gap) = history_gaps::gap_at(channel_id, before_ms / 1000) else {
return Ok(0);
};
let before = gap.hi + 1;
let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
let count = Self::v2_backfill_channel_counted(
&id, channel_id, 50, 2, None, Some(before),
crate::community::transport::Evidence::Fast, 12,
).await;
if count.next_before.is_some_and(|n| n >= before) {
history_gaps::abandon(channel_id, before);
}
Ok(count.new_messages)
}
pub async fn sync_community_channel_before(
&self,
channel_id: &str,
limit: usize,
before_secs: Option<u64>,
) -> Result<(usize, Vec<String>)> {
let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
let warnings = if community::v2::realtime::follow_worker_running() {
community::v2::realtime::enqueue_follow(&id);
Vec::new()
} else {
Self::v2_inline_follow(&id).await
};
let new = Self::v2_backfill_channel(
&id, channel_id, limit, 8, None, before_secs,
crate::community::transport::Evidence::Fast, 12,
).await;
Ok((new, warnings))
}
pub async fn sync_channel_events(
&self,
channel_id: &str,
max_events: usize,
until_s: Option<u64>,
since_s: Option<u64>,
) -> Result<usize> {
let max = max_events.clamp(1, 500);
let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
let community = crate::db::community::load_community_v2(&id)
.map_err(VectorError::Other)?
.ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
if community.dissolved {
return Err(VectorError::Other("this community has been dissolved".into()));
}
let ch_id = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
let ch = community
.channel(&ch_id)
.ok_or_else(|| VectorError::Other("no such channel in this community".into()))?;
if ch.private && ch.key.is_none() {
return Err(VectorError::Other(
"this private channel has no key yet (awaiting rekey delivery)".into(),
));
}
let new = Self::v2_backfill_channel(
&id, channel_id, max, 1, since_s, until_s,
crate::community::transport::Evidence::Fast, 12,
)
.await;
Ok(new)
}
pub async fn get_chat_commands(&self, chat_id: &str) -> crate::bot_interface::ChatCommandsSnapshot {
use crate::bot_interface::{self, ChatCommandsSnapshot};
use nostr_sdk::prelude::ToBech32;
let mut bots: Vec<nostr_sdk::prelude::PublicKey> = Vec::new();
let mut relays: Vec<String> = Vec::new();
let community_hex = crate::db::community::community_id_for_channel(chat_id).ok().flatten();
if let Some(cid_hex) = community_hex {
let Ok(Some(community)) = Self::load_held(&cid_hex) else {
return ChatCommandsSnapshot { bots: 0, commands: Vec::new(), fresh: true };
};
let members = community::v2::service::stored_memberlist(&community).unwrap_or_default();
relays = community.relays.clone();
let state = crate::state::STATE.lock().await;
for pk in members {
let Ok(npub) = pk.to_bech32();
if state.get_profile(&npub).map(|p| p.flags.is_bot()).unwrap_or(false) {
bots.push(pk);
}
}
} else if chat_id.starts_with("npub1") {
if let Ok(pk) = nostr_sdk::prelude::PublicKey::parse(chat_id) {
let is_bot = {
let state = crate::state::STATE.lock().await;
state.get_profile(chat_id).map(|p| p.flags.is_bot()).unwrap_or(false)
};
if is_bot {
bots.push(pk);
if let Some(client) = crate::state::nostr_client() {
relays = client.relays().await.keys().map(|u| u.to_string()).collect();
}
}
}
}
if bots.is_empty() {
return ChatCommandsSnapshot { bots: 0, commands: Vec::new(), fresh: true };
}
relays.extend(bot_interface::DISCOVERY_RELAYS.iter().map(|s| s.to_string()));
relays.sort();
relays.dedup();
bots.sort_by_key(|p| p.to_hex());
let bot_hexes: Vec<String> = bots.iter().map(|p| p.to_hex()).collect();
let commands = bot_interface::assemble_from_store(&bot_hexes);
let fresh = bot_interface::commands_fresh(chat_id, &bot_hexes);
if !fresh {
bot_interface::spawn_commands_refresh(chat_id.to_string(), bots.clone(), relays);
}
ChatCommandsSnapshot { bots: bots.len(), commands, fresh }
}
pub async fn get_community_members(&self, community_id: &str) -> Vec<serde_json::Value> {
use nostr_sdk::prelude::ToBech32;
let Ok(Some(community)) = Self::load_held(community_id) else { return Vec::new() };
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let (events, cursor) = crate::db::community::get_guestbook_shared(&cid_hex).unwrap_or_default();
if cursor == 0 {
if crate::community::v2::realtime::follow_worker_running() {
crate::community::v2::realtime::enqueue_follow(community.id());
} else {
let c2 = community.clone();
db::spawn_bound(async move {
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(20));
if matches!(crate::community::v2::service::sync_guestbook(&transport, &c2).await, Ok(fresh) if !fresh.is_empty()) {
emit_event("community_refreshed", &serde_json::json!({ "community_id": cid_hex }));
}
});
}
}
let parts = crate::community::v2::service::stored_member_parts(&community, &events).unwrap_or_default();
let counted = parts.counted.into_iter().filter_map(|pk| pk.to_bech32().ok()).map(|npub| serde_json::json!({ "npub": npub }));
let unlisted = parts
.unlisted
.into_iter()
.filter_map(|(pk, why)| pk.to_bech32().ok().map(|npub| serde_json::json!({ "npub": npub, "unlisted": why })));
counted.chain(unlisted).collect()
}
pub fn get_community_banned(&self, community_id: &str) -> Vec<String> {
use nostr_sdk::prelude::{PublicKey, ToBech32};
let cid_hex = match Self::load_held(community_id) {
Ok(Some(c)) => crate::simd::hex::bytes_to_hex_32(&c.id().0),
_ => community_id.to_string(),
};
crate::db::community::get_community_banlist(&cid_hex)
.unwrap_or_default()
.iter()
.filter_map(|hex| PublicKey::parse(hex).ok())
.filter_map(|pk| pk.to_bech32().ok())
.collect()
}
pub fn community_moderation_intel(&self, community_id: &str) -> Result<serde_json::Value> {
let community = Self::load_held(community_id)?
.ok_or_else(|| VectorError::Other("moderation tools require a Concord v2 community".into()))?;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let report = Self::policy_console_report(&cid_hex, &community)?;
let invites = crate::db::community::list_public_invites(&cid_hex).unwrap_or_default();
let banlist = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
let caps = self.community_capabilities(community_id).unwrap_or_else(|_| serde_json::json!({}));
let owner_b32 = community.owner().map_err(VectorError::Other)?.to_bech32().unwrap_or_default();
let unlisted: Vec<String> = crate::db::community::get_guestbook_shared(&cid_hex)
.ok()
.and_then(|(events, _)| crate::community::v2::service::stored_member_parts(&community, &events).ok())
.map(|p| p.unlisted.into_keys().filter_map(|pk| pk.to_bech32().ok()).collect())
.unwrap_or_default();
Ok(serde_json::json!({
"community_id": cid_hex,
"name": community.name,
"owner_npub": owner_b32,
"epoch": community.root_epoch.0,
"report": &*report,
"unlisted": unlisted,
"invites": invites.iter().map(|i| serde_json::json!({
"token": i.token,
"label": i.label,
"created_at": i.created_at,
"expires_at": i.expires_at,
"join_count": i.join_count,
})).collect::<Vec<_>>(),
"banlist_count": banlist.len(),
"banlist_max": crate::community::v2::roles::MAX_BANLIST,
"capabilities": caps,
"channels": community.channels.iter().map(|c| serde_json::json!({
"id": crate::simd::hex::bytes_to_hex_32(&c.id.0),
"name": c.name,
})).collect::<Vec<_>>(),
}))
}
pub fn screen_community_message(
&self,
channel_id: &str,
author_npub: &str,
text: &str,
) -> Result<serde_json::Value> {
use nostr_sdk::prelude::PublicKey;
let Some(id) = self.v2_community_for_channel(channel_id)? else {
return Ok(serde_json::json!({ "findings": [] }));
};
let community = crate::db::community::load_community_v2(&id)
.map_err(VectorError::Other)?
.ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let owner = community.owner().map_err(VectorError::Other)?;
let author = PublicKey::parse(author_npub).map_err(|_| VectorError::Other("unreadable author".into()))?;
use crate::community::roles::Permissions;
const MOD_MASK: u64 = Permissions::MANAGE_ROLES
| Permissions::MANAGE_CHANNELS
| Permissions::MANAGE_METADATA
| Permissions::KICK
| Permissions::BAN
| Permissions::MANAGE_MESSAGES;
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
let hex = author.to_hex();
let roles: Vec<String> =
roster.grants.iter().find(|g| g.member == hex).map(|g| g.role_ids.clone()).unwrap_or_default();
let is_staff = roles
.iter()
.any(|rid| roster.roles.iter().any(|r| &r.role_id == rid && (r.permissions.0 & MOD_MASK) != 0));
let now_ms = crate::clock::now_ms();
let findings = crate::community::policy::harness::screen_message(
&cid_hex, &owner, &author, &roles, is_staff, channel_id, text, now_ms,
);
Ok(serde_json::json!({ "findings": findings }))
}
pub fn check_community_raid(&self, community_id: &str) -> Result<serde_json::Value> {
let Some(community) = Self::load_held(community_id)? else {
return Ok(serde_json::json!({ "detected": false }));
};
let caps = self.community_capabilities(community_id)?;
if caps["ban"].as_bool() != Some(true) {
return Ok(serde_json::json!({ "detected": false }));
}
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let report = Self::policy_console_report(&cid_hex, &community)?;
let biggest = report["cohorts"].get(0);
Ok(serde_json::json!({
"detected": report["raid_detected"].as_bool().unwrap_or(false),
"suspects": report["suspects"].as_u64().unwrap_or(0),
"cohort": biggest.and_then(|c| c["size"].as_u64()).unwrap_or(0),
"sample": biggest
.and_then(|c| c["sample"].as_str())
.map(|s| s.chars().take(60).collect::<String>())
.unwrap_or_default(),
}))
}
fn raid_report(cid_hex: &str) -> Result<std::sync::Arc<crate::community::raid::RaidReport>> {
use crate::community::raid;
use crate::community::v2::guestbook::GuestbookEntry;
use nostr_sdk::prelude::PublicKey;
use std::collections::{HashMap, HashSet};
let now_secs = crate::clock::now_secs();
if let Some(report) = report_get(&raid_report_cache(), cid_hex, now_secs) {
return Ok(report);
}
let community = crate::db::community::load_community_v2(&crate::community::CommunityId(
crate::simd::hex::hex_to_bytes_32(cid_hex),
))
.map_err(VectorError::Other)?
.ok_or_else(|| VectorError::Other("moderation tools require a Concord v2 community".into()))?;
let owner_b32 = community.owner().map_err(VectorError::Other)?.to_bech32().unwrap_or_default();
let me_b32 = state::my_public_key().and_then(|p| p.to_bech32().ok()).unwrap_or_default();
let roster = crate::db::community::get_community_roles(cid_hex).unwrap_or_default();
let staff: HashSet<String> = roster
.grants
.iter()
.filter(|g| !g.role_ids.is_empty())
.filter_map(|g| PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok()))
.collect();
let members: Vec<String> = crate::community::v2::service::stored_memberlist(&community)
.unwrap_or_default()
.into_iter()
.filter_map(|pk| pk.to_bech32().ok())
.collect();
let (events, _cursor) = crate::db::community::get_guestbook(cid_hex).unwrap_or_default();
let mut joined_at: HashMap<String, u64> = HashMap::new();
let mut invite_label: HashMap<String, String> = HashMap::new();
for e in &events {
let GuestbookEntry::Join { member, invited_by, at_ms } = &e.entry else { continue };
let Ok(b32) = member.to_bech32();
let slot = joined_at.entry(b32.clone()).or_insert(*at_ms);
*slot = (*slot).min(*at_ms);
if let Some((_creator, label)) = invited_by {
invite_label.entry(b32).or_insert_with(|| label.clone());
}
}
let footprints: HashMap<String, crate::db::community::AuthorFootprint> =
crate::db::community::community_author_footprints(cid_hex)
.unwrap_or_default()
.into_iter()
.map(|f| (f.npub.clone(), f))
.collect();
const TEXT_WINDOW: usize = 4_000;
let mut texts: HashMap<String, (Vec<String>, Vec<u64>)> = HashMap::new();
for (npub, at, text) in crate::db::community::community_recent_texts(cid_hex, TEXT_WINDOW).unwrap_or_default() {
let slot = texts.entry(npub).or_default();
slot.0.push(text);
slot.1.push(at);
}
let signals: Vec<raid::MemberSignals> = members
.iter()
.map(|npub| {
let f = footprints.get(npub);
raid::MemberSignals {
npub: npub.clone(),
joined_at_ms: joined_at.get(npub).copied().unwrap_or(0),
invite_label: invite_label.get(npub).cloned(),
messages: f.map(|f| f.messages).unwrap_or(0),
first_secs: f.map(|f| f.first_secs).unwrap_or(0),
last_secs: f.map(|f| f.last_secs).unwrap_or(0),
texts: texts.get(npub).map(|t| t.0.clone()).unwrap_or_default(),
text_secs: texts.get(npub).map(|t| t.1.clone()).unwrap_or_default(),
is_owner: *npub == owner_b32,
is_admin: staff.contains(npub),
is_me: *npub == me_b32,
}
})
.collect();
let params = raid::RaidParams {
known_shortcodes: crate::emoji_packs::known_shortcodes(),
..Default::default()
};
let report = std::sync::Arc::new(raid::assess(&signals, now_secs, ¶ms));
report_put(&raid_report_cache(), cid_hex, now_secs, report.clone());
Ok(report)
}
pub fn policy_presets(&self) -> Result<serde_json::Value> {
let presets: Vec<serde_json::Value> = crate::community::policy::presets::all()
.into_iter()
.map(|p| {
serde_json::json!({
"id": p.id,
"name": p.name,
"description": p.description,
"example": p.example,
"caveat": p.caveat,
"dials": p.dials,
"rules": crate::community::policy::presets::describe(&p.policy),
"bytes": serde_json::to_string(&p.policy).unwrap_or_default(),
})
})
.collect();
let rule_kinds: Vec<serde_json::Value> = crate::community::policy::presets::rule_kinds()
.into_iter()
.map(|k| {
serde_json::json!({
"id": k.id,
"label": k.label,
"description": k.description,
"input": k.input,
"input_label": k.input_label,
"input_hint": k.input_hint,
"rule": k.rule,
})
})
.collect();
Ok(serde_json::json!({ "presets": presets, "rule_kinds": rule_kinds }))
}
pub fn preview_community_policy(&self, community_id: &str, bytes: &str) -> Result<serde_json::Value> {
use crate::community::v2::guestbook::GuestbookEntry;
let community = Self::load_held(community_id)?
.ok_or_else(|| VectorError::Other("policies require a Concord v2 community".into()))?;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let owner = community.owner().map_err(VectorError::Other)?;
let me = state::my_public_key();
use crate::community::roles::Permissions;
const MOD_MASK: u64 = Permissions::MANAGE_ROLES
| Permissions::MANAGE_CHANNELS
| Permissions::MANAGE_METADATA
| Permissions::KICK
| Permissions::BAN
| Permissions::MANAGE_MESSAGES;
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
let staff: std::collections::HashSet<String> = roster
.grants
.iter()
.filter(|g| {
g.role_ids
.iter()
.any(|rid| roster.roles.iter().any(|r| &r.role_id == rid && (r.permissions.0 & MOD_MASK) != 0))
})
.map(|g| g.member.clone())
.collect();
let roles_of: std::collections::HashMap<String, Vec<String>> =
roster.grants.iter().map(|g| (g.member.clone(), g.role_ids.clone())).collect();
let (events, _cursor) = crate::db::community::get_guestbook_shared(&cid_hex).unwrap_or_default();
let mut joined_at: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
let mut invite_label: std::collections::HashMap<String, String> = std::collections::HashMap::new();
for e in events.iter() {
let GuestbookEntry::Join { member, invited_by, at_ms } = &e.entry else { continue };
let hex = member.to_hex();
let slot = joined_at.entry(hex.clone()).or_insert(*at_ms);
*slot = (*slot).min(*at_ms);
if let Some((_c, label)) = invited_by {
invite_label.entry(hex).or_insert_with(|| label.clone());
}
}
let members: Vec<crate::community::policy::harness::MemberRow> =
crate::community::v2::service::stored_memberlist(&community)
.unwrap_or_default()
.into_iter()
.map(|pk| {
let hex = pk.to_hex();
(
pk,
joined_at.get(&hex).copied(),
staff.contains(&hex),
roles_of.get(&hex).cloned().unwrap_or_default(),
invite_label.get(&hex).cloned(),
)
})
.collect();
let now_ms = crate::clock::now_ms();
let assembled =
crate::community::policy::harness::assemble(&cid_hex, &owner, me.as_ref(), &members, now_ms)
.map_err(VectorError::Other)?;
let preview = crate::community::policy::harness::preview_policy(&assembled, bytes, now_ms);
serde_json::to_value(preview).map_err(|e| VectorError::Other(e.to_string()))
}
pub fn list_community_policies(&self, community_id: &str) -> Result<serde_json::Value> {
let community = Self::load_held(community_id)?
.ok_or_else(|| VectorError::Other("policies require a Concord v2 community".into()))?;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let stored = crate::db::community::get_community_policies(&cid_hex).map_err(VectorError::Other)?;
let rows: Vec<serde_json::Value> = stored
.iter()
.map(|p| {
let verdict = serde_json::from_str::<crate::community::policy::document::Policy>(&p.bytes)
.map_err(|e| e.to_string())
.and_then(|doc| doc.validate().map_err(|r| format!("{r:?}")));
serde_json::json!({
"policy_id": p.policy_id,
"hash": p.hash,
"enabled": p.enabled,
"updated_at": p.updated_at,
"bytes": p.bytes,
"valid": verdict.is_ok(),
"error": verdict.err(),
})
})
.collect();
Ok(serde_json::json!({
"community_id": cid_hex,
"policies": rows,
"using_builtin": !stored
.iter()
.any(|p| p.policy_id == crate::community::policy::harness::DEFAULTS_POLICY_ID),
}))
}
pub fn set_community_policy(&self, community_id: &str, policy_id: &str, bytes: &str, enabled: bool) -> Result<serde_json::Value> {
let community = Self::load_held(community_id)?
.ok_or_else(|| VectorError::Other("policies require a Concord v2 community".into()))?;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
if bytes.len() > crate::community::policy::types::caps::MAX_POLICY_BYTES {
return Err(VectorError::Other("policy exceeds the maximum document size".into()));
}
let doc: crate::community::policy::document::Policy =
serde_json::from_str(bytes).map_err(|e| VectorError::Other(format!("policy is not valid JSON: {e}")))?;
doc.validate().map_err(|r| VectorError::Other(format!("policy rejected: {r:?}")))?;
let hash = crate::community::policy::harness::hash_policy_bytes(bytes.as_bytes());
let hash_hex = crate::simd::hex::bytes_to_hex_32(&hash.0);
let now_secs = crate::clock::now_secs();
crate::db::community::set_community_policy(&cid_hex, policy_id, bytes, &hash_hex, enabled, now_secs)
.map_err(VectorError::Other)?;
Self::invalidate_raid_report(&cid_hex);
Ok(serde_json::json!({ "policy_id": policy_id, "hash": hash_hex, "enabled": enabled }))
}
pub fn delete_community_policy(&self, community_id: &str, policy_id: &str) -> Result<()> {
let community = Self::load_held(community_id)?
.ok_or_else(|| VectorError::Other("policies require a Concord v2 community".into()))?;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
crate::db::community::delete_community_policy(&cid_hex, policy_id).map_err(VectorError::Other)?;
Self::invalidate_raid_report(&cid_hex);
Ok(())
}
pub fn builtin_policy_json(&self) -> Result<String> {
serde_json::to_string_pretty(&crate::community::policy::harness::default_policy())
.map_err(|e| VectorError::Other(e.to_string()))
}
fn policy_console_report(cid_hex: &str, community: &crate::community::v2::community::CommunityV2) -> Result<std::sync::Arc<serde_json::Value>> {
let now_secs = crate::clock::now_secs();
report_once(&policy_report_cache(), &policy_report_gate(), cid_hex, now_secs, || {
Self::evaluate_policy_console(cid_hex, community, now_secs)
})
}
fn evaluate_policy_console(
cid_hex: &str,
community: &crate::community::v2::community::CommunityV2,
now_secs: u64,
) -> Result<std::sync::Arc<serde_json::Value>> {
use crate::community::v2::guestbook::GuestbookEntry;
let owner = community.owner().map_err(VectorError::Other)?;
let me = state::my_public_key();
use crate::community::roles::Permissions;
const MOD_MASK: u64 = Permissions::MANAGE_ROLES
| Permissions::MANAGE_CHANNELS
| Permissions::MANAGE_METADATA
| Permissions::KICK
| Permissions::BAN
| Permissions::MANAGE_MESSAGES;
let roster = crate::db::community::get_community_roles(cid_hex).unwrap_or_default();
let staff: std::collections::HashSet<String> = roster
.grants
.iter()
.filter(|g| {
g.role_ids
.iter()
.any(|rid| roster.roles.iter().any(|r| &r.role_id == rid && (r.permissions.0 & MOD_MASK) != 0))
})
.map(|g| g.member.clone())
.collect();
let roles_of: std::collections::HashMap<String, Vec<String>> =
roster.grants.iter().map(|g| (g.member.clone(), g.role_ids.clone())).collect();
let (events, _cursor) = crate::db::community::get_guestbook(cid_hex).unwrap_or_default();
let mut joined_at: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
let mut invite_label: std::collections::HashMap<String, String> = std::collections::HashMap::new();
for e in &events {
let GuestbookEntry::Join { member, invited_by, at_ms } = &e.entry else { continue };
let hex = member.to_hex();
let slot = joined_at.entry(hex.clone()).or_insert(*at_ms);
*slot = (*slot).min(*at_ms);
if let Some((_creator, label)) = invited_by {
invite_label.entry(hex).or_insert_with(|| label.clone());
}
}
let members: Vec<crate::community::policy::harness::MemberRow> =
crate::community::v2::service::stored_memberlist(community)
.unwrap_or_default()
.into_iter()
.map(|pk| {
let hex = pk.to_hex();
(
pk,
joined_at.get(&hex).copied(),
staff.contains(&hex),
roles_of.get(&hex).cloned().unwrap_or_default(),
invite_label.get(&hex).cloned(),
)
})
.collect();
let now_ms = now_secs.saturating_mul(1000);
let assembled =
crate::community::policy::harness::assemble(cid_hex, &owner, me.as_ref(), &members, now_ms)
.map_err(VectorError::Other)?;
Ok(std::sync::Arc::new(
crate::community::policy::harness::evaluate_for_console(cid_hex, &assembled, now_ms)
.map_err(VectorError::Other)?,
))
}
pub fn policy_side_by_side(&self, community_id: &str) -> Result<serde_json::Value> {
use crate::community::v2::guestbook::GuestbookEntry;
use nostr_sdk::prelude::PublicKey;
let community = Self::load_held(community_id)?
.ok_or_else(|| VectorError::Other("moderation tools require a Concord v2 community".into()))?;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let owner = community.owner().map_err(VectorError::Other)?;
use crate::community::roles::Permissions;
const MOD_MASK: u64 = Permissions::MANAGE_ROLES
| Permissions::MANAGE_CHANNELS
| Permissions::MANAGE_METADATA
| Permissions::KICK
| Permissions::BAN
| Permissions::MANAGE_MESSAGES;
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
let staff: std::collections::HashSet<String> = roster
.grants
.iter()
.filter(|g| {
g.role_ids.iter().any(|rid| {
roster.roles.iter().any(|r| &r.role_id == rid && (r.permissions.0 & MOD_MASK) != 0)
})
})
.map(|g| g.member.clone())
.collect();
let roles_of: std::collections::HashMap<String, Vec<String>> =
roster.grants.iter().map(|g| (g.member.clone(), g.role_ids.clone())).collect();
let (events, _cursor) = crate::db::community::get_guestbook_shared(&cid_hex).unwrap_or_default();
let mut joined_at: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
for e in events.iter() {
let GuestbookEntry::Join { member, at_ms, .. } = &e.entry else { continue };
let hex = member.to_hex();
let slot = joined_at.entry(hex).or_insert(*at_ms);
*slot = (*slot).min(*at_ms);
}
let members: Vec<(PublicKey, Option<u64>, bool, Vec<String>)> =
crate::community::v2::service::stored_memberlist(&community)
.unwrap_or_default()
.into_iter()
.map(|pk| {
let hex = pk.to_hex();
(pk, joined_at.get(&hex).copied(), staff.contains(&hex), roles_of.get(&hex).cloned().unwrap_or_default())
})
.collect();
let assessments: Vec<(String, String)> = Self::raid_report(&cid_hex)
.map(|r| {
r.members
.iter()
.map(|m| (m.npub.clone(), format!("{:?}", m.verdict).to_lowercase()))
.collect()
})
.unwrap_or_default();
let now_ms = crate::clock::now_ms();
let diff = crate::community::policy::harness::run_side_by_side(
&cid_hex, &owner, &members, &assessments, now_ms,
)
.map_err(VectorError::Other)?;
serde_json::to_value(diff).map_err(|e| VectorError::Other(e.to_string()))
}
pub fn invalidate_raid_report(community_id: &str) {
policy_report_cache().lock().unwrap_or_else(|e| e.into_inner()).remove(community_id);
raid_report_cache().lock().unwrap_or_else(|e| e.into_inner()).remove(community_id);
}
pub async fn refound_community(&self, community_id: &str, retain: &[&str]) -> Result<()> {
let community = Self::load_held(community_id)?
.ok_or_else(|| VectorError::Other("re-founding requires a Concord v2 community".into()))?;
let removed = Self::members_to_remove(&community, retain)?;
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(30));
crate::community::v2::service::refound_community(&transport, &community, &removed)
.await
.map_err(VectorError::Other)?;
Self::invalidate_raid_report(community_id);
Ok(())
}
fn members_to_remove(
community: &crate::community::v2::community::CommunityV2,
retain: &[&str],
) -> Result<Vec<nostr_sdk::prelude::PublicKey>> {
use nostr_sdk::prelude::PublicKey;
let keep: std::collections::HashSet<PublicKey> =
retain.iter().filter_map(|n| PublicKey::parse(n).ok()).collect();
if keep.is_empty() {
return Ok(Vec::new());
}
let me = state::my_public_key();
let owner = community.owner().ok();
Ok(crate::community::v2::service::stored_memberlist(community)
.map_err(VectorError::Other)?
.into_iter()
.filter(|pk| !keep.contains(pk))
.filter(|pk| Some(*pk) != me && Some(*pk) != owner)
.collect())
}
pub async fn purge_and_refound(
&self,
community_id: &str,
retain: &[&str],
on_progress: &(dyn Fn(usize, usize) + Sync),
) -> Result<serde_json::Value> {
let community = Self::load_held(community_id)?
.ok_or_else(|| VectorError::Other("re-founding requires a Concord v2 community".into()))?;
let removed = Self::members_to_remove(&community, retain)?;
let keep: Vec<nostr_sdk::prelude::PublicKey> = retain
.iter()
.filter_map(|n| nostr_sdk::prelude::PublicKey::parse(n).ok())
.collect();
log_info!("[Moderation] purge: {} to remove, {} retained", removed.len(), keep.len());
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(30));
if keep.is_empty() {
crate::community::v2::service::refound_community(&transport, &community, &removed)
.await
.map_err(VectorError::Other)?;
} else {
crate::community::v2::service::refound_community_retaining(&transport, &community, &removed, &keep)
.await
.map_err(VectorError::Other)?;
}
let fresh = Self::load_held(community_id)?
.ok_or_else(|| VectorError::Other("community gone during the purge".into()))?;
let sweep = crate::community::v2::service::kick_members(&transport, &fresh, &removed, on_progress)
.await
.map_err(VectorError::Other)?;
let _ = crate::community::v2::service::sync_guestbook(&transport, &fresh).await;
log_info!(
"[Moderation] purge: rotated to epoch {}, kicked {}/{} ({} refused, {} failed)",
fresh.root_epoch.0,
sweep.kicked.len(),
removed.len(),
sweep.refused.len(),
sweep.failed.len()
);
Ok(serde_json::json!({
"kicked": sweep.kicked.len(),
"refused": sweep.refused.len(),
"failed": sweep.failed.len(),
"rotated": true,
}))
}
pub async fn kick_community_members(
&self,
community_id: &str,
npubs: &[&str],
on_progress: &(dyn Fn(usize, usize) + Sync),
) -> Result<serde_json::Value> {
let community = Self::load_held(community_id)?
.ok_or_else(|| VectorError::Other("kicking requires a Concord v2 community".into()))?;
use nostr_sdk::prelude::PublicKey;
let targets: Vec<PublicKey> = npubs.iter().filter_map(|n| PublicKey::parse(n).ok()).collect();
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(30));
let sweep = crate::community::v2::service::kick_members(&transport, &community, &targets, on_progress)
.await
.map_err(VectorError::Other)?;
let _ = crate::community::v2::service::sync_guestbook(&transport, &community).await;
log_info!(
"[Moderation] kick sweep: {}/{} kicked ({} refused, {} failed)",
sweep.kicked.len(),
targets.len(),
sweep.refused.len(),
sweep.failed.len()
);
Self::invalidate_raid_report(community_id);
Ok(serde_json::json!({
"kicked": sweep.kicked.len(),
"refused": sweep.refused.iter().map(|(_, why)| why.clone()).collect::<Vec<_>>(),
"failed": sweep.failed.len(),
}))
}
pub async fn revoke_all_public_invites(&self, community_id: &str) -> Result<(usize, usize)> {
let tokens: Vec<String> = crate::db::community::list_public_invites(community_id)
.map_err(VectorError::Other)?
.into_iter()
.map(|i| i.token)
.collect();
let mut revoked = 0usize;
let mut failed = 0usize;
for token in &tokens {
match self.revoke_public_invite(community_id, token).await {
Ok(()) => revoked += 1,
Err(_) => failed += 1,
}
}
Ok((revoked, failed))
}
pub async fn v2_inline_follow(id: &crate::community::CommunityId) -> Vec<String> {
crate::db::scoped(async move {
use crate::community::transport::LiveTransport;
let session = crate::db::current_session();
let lock = crate::community::v2::realtime::follow_lock(id);
let _guard = lock.lock().await;
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
let mut warnings: Vec<String> = Vec::new();
let Ok(Some(community)) = crate::db::community::load_community_v2(id) else {
warnings.push("v2 community not found".to_string());
return warnings;
};
let cid_hex = crate::simd::hex::bytes_to_hex_32(&id.0);
match crate::community::v2::service::follow_rekeys(&transport, &community, &session).await {
Ok(f) if f.dissolved => return warnings,
Ok(f) if f.self_removed => {
let _ = crate::db::community::delete_community_retain_keys(&cid_hex);
return warnings;
}
Ok(_) => {}
Err(e) => warnings.push(format!("v2 rekey follow failed: {e}")),
}
if let Ok(Some(fresh)) = crate::db::community::load_community_v2(id) {
match crate::community::v2::service::follow_control(&transport, &fresh).await {
Ok(control) if control.moved() => {
if let Ok(Some(latest)) = crate::db::community::load_community_v2(id) {
if let Err(e) = crate::community::v2::service::follow_rekeys(&transport, &latest, &session).await {
warnings.push(format!("v2 rekey follow failed: {e}"));
}
}
}
Ok(_) => {}
Err(e) => warnings.push(format!("v2 control follow failed: {e}")),
}
}
if let Some(me) = crate::my_public_key() {
if crate::db::community::is_author_banned(&cid_hex, &me) {
let _ = crate::db::community::delete_community_retain_keys(&cid_hex);
return warnings;
}
}
let quiet = crate::event_handler::NoOpEventHandler;
if let Ok(Some(folded)) = crate::db::community::load_community_v2(id) {
crate::community::v2::service::owe_new_departures(&folded);
}
crate::community::v2::realtime::settle_owed_retractions(id, &transport, &quiet).await;
if let Ok(Some(folded)) = crate::db::community::load_community_v2(id) {
crate::community::v2::service::rejudge_held(&folded, &quiet).await;
}
warnings
})
.await
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn v2_backfill_channel(
id: &crate::community::CommunityId,
channel_id: &str,
limit: usize,
max_pages: usize,
since: Option<u64>,
until: Option<u64>,
evidence: crate::community::transport::Evidence,
transport_secs: u64,
) -> usize {
let (mut new, mut until) = (0, until);
let mut waiting = Vec::new();
for _ in 0..BACKFILL_CONTINUATIONS {
let (count, still) = Self::v2_backfill_window(id, channel_id, limit, max_pages, since, until, evidence, transport_secs).await;
new += count.new_messages;
waiting.extend(still);
match count.next_before {
Some(next) if until.is_none_or(|u| next < u) => until = Some(next),
_ => break,
}
}
if !waiting.is_empty() {
if let Some(me) = state::my_public_key() {
Self::v2_ingest_chat_page_waiting(channel_id, me, crate::db::current_session(), waiting).await;
}
}
new
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn v2_backfill_channel_counted(
id: &crate::community::CommunityId,
channel_id: &str,
limit: usize,
max_pages: usize,
since: Option<u64>,
until: Option<u64>,
evidence: crate::community::transport::Evidence,
transport_secs: u64,
) -> BackfillCount {
Self::v2_backfill_window(id, channel_id, limit, max_pages, since, until, evidence, transport_secs).await.0
}
#[allow(clippy::too_many_arguments)]
async fn v2_backfill_window(
id: &crate::community::CommunityId,
channel_id: &str,
limit: usize,
max_pages: usize,
since: Option<u64>,
until: Option<u64>,
evidence: crate::community::transport::Evidence,
transport_secs: u64,
) -> (BackfillCount, Vec<crate::community::v2::service::FetchedEvent>) {
let session = crate::db::current_session();
let Some(my_pk) = state::my_public_key() else { return (BackfillCount::default(), Vec::new()) };
if crate::db::community::get_community_dissolved(&crate::simd::hex::bytes_to_hex_32(&id.0)).unwrap_or(false) {
return (BackfillCount::default(), Vec::new());
}
let Ok(Some(community)) = crate::db::community::load_community_v2(id) else { return (BackfillCount::default(), Vec::new()) };
let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(transport_secs));
let held = std::sync::atomic::AtomicUsize::new(0);
let began = crate::clock::now_secs();
let floor = crate::history_gaps::floor(channel_id, until, began);
let reach = crate::history_gaps::reach(since, floor);
let live = community.channel(&ch).map_or(community.root_epoch, |c| community.channel_secret(c).1);
let past = until.is_none().then(|| match crate::history_gaps::proven_epoch(channel_id) {
Some(e) => (crate::community::Epoch(e), since),
None => (crate::community::Epoch(live.0.saturating_sub(UNPROVEN_EPOCHS)), reach),
});
let unread: Vec<nostr_sdk::prelude::PublicKey> = match community.channel(&ch).filter(|_| until.is_none()) {
Some(c) => {
let read = crate::history_gaps::history_read(channel_id);
let cid_hex = crate::simd::hex::bytes_to_hex_32(&id.0);
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());
c.published_history().into_iter().map(|(_, g)| g.pk()).chain(views).filter(|pk| !read.contains(&pk.to_hex())).collect()
}
None => Vec::new(),
};
let Ok((page, next_before, complete)) = crate::community::v2::service::fetch_channel_history_since_epoch(
&transport,
&community,
&ch,
limit.max(50),
max_pages,
reach,
until,
evidence,
|page, settled, next| {
crate::community::v2::service::catch_up_pages_on(page, settled, next, floor, |id| crate::db::events::event_exists(id).unwrap_or(false))
},
|wraps| {
if until.is_some() {
return Default::default();
}
let hex: Vec<String> = wraps.iter().map(|w| w.to_hex()).collect();
let settled = crate::db::events::community_wraps_settled(&hex);
let skip: std::collections::HashSet<_> = wraps.iter().zip(&hex).filter(|(_, h)| settled.contains(*h)).map(|(w, _)| *w).collect();
held.fetch_add(skip.len(), std::sync::atomic::Ordering::Relaxed);
skip
},
past,
&unread,
)
.await
else {
return (BackfillCount { unreachable: true, ..Default::default() }, Vec::new());
};
let fetched = page.len() + held.into_inner();
let (new_messages, waiting) = Self::v2_ingest_chat_page_keeping(channel_id, my_pk, session, page).await;
crate::history_gaps::note_walk(channel_id, until, next_before, floor, |t| crate::db::events::newest_message_before(channel_id, t));
if until.is_none() && since.is_none() && complete {
crate::history_gaps::prove(channel_id, began, live.0);
}
if complete && !unread.is_empty() {
crate::history_gaps::mark_history_read(channel_id, unread.iter().map(|pk| pk.to_hex()));
}
(BackfillCount { fetched, new_messages, next_before, unreachable: false }, waiting)
}
pub(crate) async fn v2_ingest_chat_page(
channel_id: &str,
my_pk: nostr_sdk::prelude::PublicKey,
session: std::sync::Arc<crate::db::Session>,
page: Vec<crate::community::v2::service::FetchedEvent>,
) -> usize {
Self::v2_ingest_chat_page_keeping(channel_id, my_pk, session, page).await.0
}
async fn v2_ingest_chat_page_waiting(
channel_id: &str,
my_pk: nostr_sdk::prelude::PublicKey,
session: std::sync::Arc<crate::db::Session>,
page: Vec<crate::community::v2::service::FetchedEvent>,
) {
Self::v2_ingest_chat_page_keeping(channel_id, my_pk, session, page).await;
}
async fn v2_ingest_chat_page_keeping(
channel_id: &str,
my_pk: nostr_sdk::prelude::PublicKey,
session: std::sync::Arc<crate::db::Session>,
page: Vec<crate::community::v2::service::FetchedEvent>,
) -> (usize, Vec<crate::community::v2::service::FetchedEvent>) {
crate::db::scoped(async move {
use crate::community::v2::inbound::ChatPersist;
let judged_on = crate::community::v2::service::writers_head(channel_id);
let page = crate::community::v2::service::rejudge_page(channel_id, page);
let since = page.iter().map(|f| f.event.opened().at_ms).min();
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();
let mut new = 0usize;
let mut unapplied: Vec<usize> = Vec::new();
let mut outcomes: Vec<ChatPersist> = Vec::with_capacity(page.len());
let mut sources: Vec<usize> = Vec::with_capacity(page.len());
let stored = crate::db::events::existing_event_ids(&crate::community::v2::inbound::page_event_ids(page.iter().map(|f| &f.event))).unwrap_or_default();
for (i, f) in page.iter().enumerate() {
if let crate::community::v2::chat::ChatEvent::Webxdc { opened } = &f.event {
if opened.author != my_pk {
if let Some((topic, addr)) = crate::webxdc::parse_peer_signal(&opened.rumor.content) {
let Ok(npub) = ToBech32::to_bech32(&opened.author);
crate::community::v2::inbound::persist_webxdc_signal(
channel_id,
&npub,
&topic,
addr.as_deref(),
&opened.rumor_id.to_hex(),
opened.at_ms / 1000,
)
.await;
}
}
continue;
}
crate::community::v2::inbound::hydrate_target(&f.event, channel_id).await;
let outcome = {
let mut st = state::STATE.lock().await;
crate::community::v2::inbound::apply_page_event_to_state(&mut st, &f.event, channel_id, &my_pk, &stored)
};
match outcome {
Some(outcome) => {
if matches!(outcome, ChatPersist::New(_)) {
new += 1;
}
outcomes.push(outcome);
sources.push(i);
}
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),
None => {}
}
}
for o in &mut outcomes {
if let ChatPersist::New(m) | ChatPersist::Updated { message: m, .. } = o {
crate::db::attachments::verify_message_attachments(m, Some(channel_id)).await;
}
}
crate::community::v2::inbound::persist_chat_page(channel_id, &outcomes, &session).await;
if let Some(since) = since {
crate::community::v2::service::owe_if_moved(channel_id, judged_on, since);
}
crate::community::v2::service::owe_if_departed(channel_id, &posted);
{
let quoted: Vec<&mut crate::types::Message> = outcomes
.iter_mut()
.filter_map(|o| match o {
ChatPersist::New(m)
| ChatPersist::Updated { message: m, .. }
| ChatPersist::ReactionRemoved { message: m, .. } => Some(m),
ChatPersist::Removed { .. } => None,
})
.collect();
let _ = crate::db::events::populate_reply_contexts(quoted).await;
}
for outcome in &outcomes {
match outcome {
ChatPersist::New(msg) => crate::traits::emit_message_new(channel_id, msg),
ChatPersist::Updated { message, .. }
| ChatPersist::ReactionRemoved { message, .. } => {
let mut message = message.clone();
let target_id = message.id.clone();
crate::traits::emit_message_update(channel_id, &target_id, &mut message).await;
}
ChatPersist::Removed { id: target_id, .. } => crate::traits::emit_event(
"message_removed",
&serde_json::json!({ "id": target_id, "chat_id": channel_id, "reason": "deleted" }),
),
}
}
if let Some(listener) = crate::news::listener() {
for (outcome, i) in outcomes.into_iter().zip(sources) {
let event = &page[i].event;
let at = match &outcome {
ChatPersist::New(m) => m.at,
_ => event.opened().at_ms,
};
if crate::news::is_news(at) {
crate::community::v2::inbound::notify_chat_outcome(&*listener, channel_id, event, outcome, true).await;
}
}
}
let mut waiting = Vec::new();
for i in unapplied {
let f = &page[i];
if crate::community::v2::inbound::awaits_target(&f.event).await {
waiting.push(crate::community::v2::service::FetchedEvent { event: f.event.clone(), epoch: f.epoch, wrap: f.wrap.clone() });
}
}
(new, waiting)
})
.await
}
fn unheld_id(community_id: &str) -> Result<crate::community::CommunityId> {
crate::simd::hex::hex_to_bytes_32_checked(community_id)
.map(crate::community::CommunityId)
.ok_or_else(|| VectorError::Other("malformed community id".into()))
}
fn load_held(community_id: &str) -> Result<Option<crate::community::v2::community::CommunityV2>> {
if community_id.len() != 64 {
return Ok(None);
}
let cid = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
crate::db::community::load_community_v2(&cid).map_err(VectorError::Other)
}
pub fn community_capabilities(&self, community_id: &str) -> Result<serde_json::Value> {
let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
use crate::community::roles::Permissions;
let me = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?.to_hex();
let owner_hex = v2.owner().map_err(VectorError::Other)?.to_hex();
let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
if banned.contains(&me) && me != owner_hex {
return Ok(serde_json::json!({
"manage_metadata": false, "manage_channels": false, "create_invite": false, "kick": false,
"ban": false, "manage_messages": false, "manage_roles": false, "manage_admin_role": false,
"pin_messages": false, "control_write": false, "moderate_members": false, "view_audit_log": false,
"manage_nicknames": false, "change_nickname": false,
}));
}
let control_write = crate::community::v2::control::ControlPlane::of(&v2).can_write();
let has = |p: u64| roster.is_authorized(&me, Some(&owner_hex), p);
let has_ctl = |p: u64| control_write && has(p);
Ok(serde_json::json!({
"manage_metadata": has_ctl(Permissions::MANAGE_METADATA), "manage_channels": has_ctl(Permissions::MANAGE_CHANNELS),
"create_invite": has_ctl(Permissions::CREATE_INVITE), "kick": has(Permissions::KICK), "ban": has_ctl(Permissions::BAN),
"manage_messages": has(Permissions::MANAGE_MESSAGES), "manage_roles": has_ctl(Permissions::MANAGE_ROLES),
"manage_admin_role": me == owner_hex && control_write,
"pin_messages": has_ctl(Permissions::PIN_MESSAGES),
"control_write": control_write,
"moderate_members": has(Permissions::MODERATE_MEMBERS),
"view_audit_log": has(Permissions::VIEW_AUDIT_LOG),
"manage_nicknames": has(Permissions::MANAGE_NICKNAMES),
"change_nickname": roster.may_name(&me, Some(&owner_hex), &me),
}))
}
pub async fn check_community_relays(&self, community_id: &str, relays: &[String]) -> Result<Vec<crate::community::v2::service::RelayCheck>> {
let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(15));
crate::community::v2::service::check_relays(&transport, &v2, relays).await.map_err(VectorError::Other)
}
pub async fn move_community_relays(&self, community_id: &str, relays: &[String]) -> Result<crate::community::v2::service::RelayMove> {
let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(15));
crate::community::v2::service::move_relays(&transport, &v2, relays).await.map_err(VectorError::Other)
}
pub async fn community_audit_log(&self, community_id: &str) -> Result<crate::community::v2::service::AuditLog> {
let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(15));
crate::community::v2::service::audit_log(&transport, &v2).await.map_err(VectorError::Other)
}
pub async fn pin_community_message(&self, community_id: &str, channel_id: &str, message_id: &str) -> Result<()> {
use crate::community::{transport::LiveTransport, ChannelId};
let v2 = Self::load_held(community_id)?
.ok_or_else(|| VectorError::Other("pins are only available in Concord v2 communities".into()))?;
let ch = ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
crate::community::v2::service::pin_message(&transport, &v2, &ch, message_id)
.await
.map_err(VectorError::Other)
}
pub async fn unpin_community_message(&self, community_id: &str, channel_id: &str, message_id: &str) -> Result<()> {
use crate::community::{transport::LiveTransport, ChannelId};
let v2 = Self::load_held(community_id)?
.ok_or_else(|| VectorError::Other("pins are only available in Concord v2 communities".into()))?;
let ch = ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
crate::community::v2::service::unpin_message(&transport, &v2, &ch, message_id)
.await
.map_err(VectorError::Other)
}
pub async fn fetch_pinned_attachment(
&self,
community_id: &str,
channel_id: &str,
rumor_id: &str,
) -> Result<serde_json::Value> {
crate::db::scoped(async move {
use crate::community::ChannelId;
let v2 = Self::load_held(community_id)?
.ok_or_else(|| VectorError::Other("pins are only available in Concord v2 communities".into()))?;
let ch = ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
let pins = crate::community::v2::service::read_channel_pins(&v2, &ch).map_err(VectorError::Other)?;
let pin = pins
.pins
.iter()
.find(|p| p.rumor_id == rumor_id)
.ok_or_else(|| VectorError::Other("that message is not pinned".into()))?;
let dir = crate::db::get_download_dir();
let tag = pin
.tags
.iter()
.find(|t| t.first().map(String::as_str) == Some("imeta"))
.map(|t| nostr_sdk::prelude::Tag::custom("imeta", t[1..].to_vec()))
.ok_or_else(|| VectorError::Other("this pin carries no attachment".into()))?;
let attachment = crate::community::attachments::attachment_from_imeta(&tag, &dir)
.ok_or_else(|| VectorError::Other("this pin's attachment metadata is malformed".into()))?;
let respond = |path: &str| {
serde_json::json!({
"path": path,
"name": attachment.name.to_string(),
"extension": attachment.extension.to_string(),
})
};
let expected = attachment.original_hash.as_deref();
let in_memory = crate::media::ram::cache().admits(attachment.size);
let keep = !in_memory || crate::media::keep_media();
if let Some(hash) = expected.and_then(crate::simd::hex::hex_to_bytes_32_checked).filter(|h| crate::media::resident(h)) {
return Ok(respond(&crate::media::MediaRef::held(&hash)));
}
let path = std::path::PathBuf::from(&*attachment.path);
if let Ok(bytes) = std::fs::read(&path) {
match expected {
Some(want) if crate::crypto::sha256_hex(&bytes) == want => return Ok(respond(&path.to_string_lossy())),
None => return Ok(respond(&path.to_string_lossy())),
_ => {} }
}
let author_npub = nostr_sdk::prelude::PublicKey::from_hex(&pin.author)
.ok()
.and_then(|pk| nostr_sdk::prelude::ToBech32::to_bech32(&pk).ok());
let bytes = self.download_attachment_from(&attachment, author_npub.as_deref()).await?;
let hash = crate::crypto::sha256_hex(&bytes);
if expected.is_some_and(|want| hash != want) {
return Err(VectorError::Other("downloaded bytes do not match the pinned content hash".into()));
}
let held = crate::simd::hex::hex_to_bytes_32(&hash);
let mime = crate::crypto::mime_from_extension(&attachment.extension.to_ascii_lowercase());
if keep {
#[cfg(not(target_arch = "wasm32"))]
crate::media::store::keep_sealed(&bytes, held, mime, crate::db::media_store::Origin::Sealed)
.map_err(|e| VectorError::Other(format!("could not keep the attachment: {e}")))?;
#[cfg(target_arch = "wasm32")]
crate::media::store::keep_sealed(&bytes, held, mime, crate::db::media_store::Origin::Sealed)
.await
.map_err(|e| VectorError::Other(format!("could not keep the attachment: {e}")))?;
}
if in_memory {
match crate::media::ram::insert(held, bytes, mime) {
Ok(_) => {}
Err(_) if keep => {}
Err(_) => return Err(VectorError::Other("too much media is open to show this one".into())),
}
}
Ok(respond(&crate::media::MediaRef::held(&held)))
})
.await
}
pub fn get_channel_pins(&self, community_id: &str, channel_id: &str) -> Result<serde_json::Value> {
use crate::community::ChannelId;
let Some(v2) = Self::load_held(community_id)? else {
return Ok(serde_json::json!({ "pins": [], "sealed": false, "version": 0 }));
};
let ch = ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
let pins = crate::community::v2::service::read_channel_pins(&v2, &ch).map_err(VectorError::Other)?;
serde_json::to_value(&pins).map_err(|e| VectorError::Other(e.to_string()))
}
pub fn community_role_graph(&self, community_id: &str) -> Result<serde_json::Value> {
use nostr_sdk::prelude::{PublicKey, ToBech32};
let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
let roles: Vec<serde_json::Value> = roster
.roles
.iter()
.map(|r| {
let channel_id = match &r.scope {
crate::community::roles::RoleScope::Channel(c) => Some(c.to_ascii_lowercase()),
crate::community::roles::RoleScope::Server => None,
};
serde_json::json!({
"role_id": r.role_id,
"name": r.name,
"position": r.position,
"color": r.color,
"channel_id": channel_id,
"display": r.display,
})
})
.collect();
let grants: Vec<serde_json::Value> = roster
.grants
.iter()
.filter(|g| !banned.contains(&g.member))
.filter_map(|g| {
let npub = PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok())?;
Some(serde_json::json!({ "npub": npub, "role_ids": g.role_ids }))
})
.collect();
let activated = roster.everyone.is_some();
let mut readers = serde_json::Map::new();
if activated {
if let Some(v2) = Self::load_held(community_id)? {
let owner_hex = v2.owner().ok().map(|o| o.to_hex());
let mut candidates: std::collections::BTreeSet<PublicKey> =
crate::community::v2::service::stored_memberlist(&v2).unwrap_or_default().into_iter().collect();
candidates.extend(roster.grants.iter().filter_map(|g| PublicKey::from_hex(&g.member).ok()));
for ch in v2.channels.iter().filter(|c| c.private) {
let chan = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
let npubs: Vec<String> = candidates
.iter()
.filter(|pk| !banned.contains(&pk.to_hex()) && roster.is_entitled(owner_hex.as_deref(), &pk.to_hex(), &chan, &[], &[]))
.filter_map(|pk| pk.to_bech32().ok())
.collect();
readers.insert(chan, npubs.into());
}
}
}
Ok(serde_json::json!({ "roles": roles, "grants": grants, "activated": activated, "readers": readers }))
}
pub fn community_roles_view(&self, community_id: &str) -> Result<serde_json::Value> {
use crate::community::roles::{Permissions, RoleScope};
let v2 = Self::load_held(community_id)?
.ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
let me = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?.to_hex();
let owner_hex = v2.owner().map_err(VectorError::Other)?.to_hex();
let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
let is_owner = me == owner_hex;
let can_manage = is_owner
|| (!banned.contains(&me) && roster.is_authorized(&me, Some(&owner_hex), Permissions::MANAGE_ROLES));
let rank = if is_owner { Some(0) } else { roster.highest_position(&me) };
let grantable = if is_owner { u64::MAX } else { roster.effective_permissions(&me).0 };
let mut roles: Vec<&crate::community::roles::Role> = roster.roles.iter().collect();
roles.sort_by(|a, b| a.position.cmp(&b.position).then_with(|| a.role_id.cmp(&b.role_id)));
let activated = Self::roles_v2_active(community_id, &roster);
let roles: Vec<serde_json::Value> = roles
.into_iter()
.map(|r| {
let holders: Vec<String> = roster
.grants
.iter()
.filter(|g| !banned.contains(&g.member) && g.role_ids.iter().any(|id| id == &r.role_id))
.filter_map(|g| nostr_sdk::prelude::PublicKey::from_hex(&g.member).ok())
.filter_map(|pk| nostr_sdk::prelude::ToBech32::to_bech32(&pk).ok())
.collect();
serde_json::json!({
"role_id": r.role_id,
"name": r.name,
"position": r.position,
"color": r.color,
"permissions": r.permissions.0.to_string(),
"channel_id": match &r.scope { RoleScope::Channel(c) => Some(c.to_ascii_lowercase()), RoleScope::Server => None },
"holders": holders,
"display": r.display,
"mentionable": r.mentionable,
"manageable": can_manage && (is_owner || {
let support = roster.permissions_above(&me, r.position);
support.contains(Permissions::MANAGE_ROLES) && r.permissions.0 & !support.0 == 0
}),
})
})
.collect();
let channels: Vec<serde_json::Value> = v2
.channels
.iter()
.map(|c| serde_json::json!({
"channel_id": crate::simd::hex::bytes_to_hex_32(&c.id.0),
"name": c.name,
"private": c.private,
}))
.collect();
Ok(serde_json::json!({
"is_owner": is_owner,
"can_manage": can_manage,
"rank": rank,
"grantable": grantable.to_string(),
"activated": activated,
"everyone": roster.everyone.map(|p| p.0.to_string()),
"everyone_editable": activated && (is_owner || roster.permissions_above(&me, u32::MAX).contains(Permissions::MANAGE_ROLES)),
"everyone_default": crate::community::v2::roles::EVERYONE_DEFAULT.to_string(),
"roles": roles,
"channels": channels,
"max_roles": crate::community::v2::roles::MAX_ROLES_PER_COMMUNITY,
"max_per_member": crate::community::v2::roles::MAX_ROLES_PER_MEMBER,
}))
}
fn parse_permissions(s: &str) -> Result<u64> {
if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {
return Err(VectorError::Other(format!("permissions must be a decimal string, got {s:?}")));
}
s.parse::<u64>().map_err(|_| VectorError::Other("permissions out of range".into()))
}
fn role_scope(channel_id: Option<&str>) -> Result<crate::community::roles::RoleScope> {
use crate::community::roles::RoleScope;
match channel_id {
None => Ok(RoleScope::Server),
Some(c) if c.len() == 64 && c.bytes().all(|b| b.is_ascii_hexdigit()) => Ok(RoleScope::Channel(c.to_ascii_lowercase())),
Some(_) => Err(VectorError::Other("channel_id must be 32-byte hex".into())),
}
}
pub async fn create_role(&self, community_id: &str, name: &str, color: u32, permissions: &str, channel_id: Option<&str>) -> Result<String> {
let v2 = Self::load_held(community_id)?
.ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
let perms = Self::parse_permissions(permissions)?;
let scope = Self::role_scope(channel_id)?;
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
let id = if Self::roles_v2_active(community_id, &roster) {
if channel_id.is_some() {
return Err(VectorError::Other("on the new roles, channel access is set on the channel".into()));
}
crate::community::v2::service::create_role_v2(&transport, &v2, name, color, perms).await
} else {
crate::community::v2::service::create_role(&transport, &v2, name, color, perms, scope).await
}
.map_err(VectorError::Other)?;
Self::converge_v2_authority(&transport, community_id).await;
Ok(id)
}
pub async fn edit_role(&self, community_id: &str, role_id: &str, name: &str, color: u32, permissions: &str, channel_id: Option<&str>) -> Result<()> {
self.edit_role_shown(community_id, role_id, name, color, permissions, channel_id, None, None).await
}
#[allow(clippy::too_many_arguments)]
pub async fn edit_role_shown(
&self,
community_id: &str,
role_id: &str,
name: &str,
color: u32,
permissions: &str,
channel_id: Option<&str>,
display: Option<bool>,
mentionable: Option<bool>,
) -> Result<()> {
let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
if Self::roles_v2_active(community_id, &roster) {
let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
let perms = Self::parse_permissions(permissions)?;
let current = roster.role(role_id).ok_or_else(|| VectorError::Other("no such role".into()))?;
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
crate::community::v2::service::edit_role_v2(
&transport,
&v2,
role_id,
name,
color,
perms,
display.unwrap_or(current.display),
mentionable.unwrap_or(current.mentionable),
)
.await
.map_err(VectorError::Other)?;
Self::converge_v2_authority(&transport, community_id).await;
return Ok(());
}
let v2 = Self::load_held(community_id)?
.ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
let perms = Self::parse_permissions(permissions)?;
let scope = Self::role_scope(channel_id)?;
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
crate::community::v2::service::edit_role(&transport, &v2, role_id, name, color, perms, scope)
.await
.map_err(VectorError::Other)?;
Self::converge_v2_authority(&transport, community_id).await;
Ok(())
}
pub async fn reorder_roles(&self, community_id: &str, ordered: &[String]) -> Result<usize> {
let v2 = Self::load_held(community_id)?
.ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
if Self::roles_v2_active(community_id, &roster) {
let moved = crate::community::v2::service::reorder_roles_v2(&transport, &v2, ordered).await.map_err(VectorError::Other)?;
if moved > 0 {
Self::converge_v2_authority(&transport, community_id).await;
}
return Ok(moved);
}
let moved = crate::community::v2::service::reorder_roles(&transport, &v2, ordered)
.await
.map_err(VectorError::Other)?;
if moved > 0 {
Self::converge_v2_authority(&transport, community_id).await;
}
Ok(moved)
}
fn roles_v2_active(community_id: &str, roster: &crate::community::roles::CommunityRoles) -> bool {
if roster.everyone.is_some() {
return true;
}
let Some(cid) = crate::simd::hex::hex_to_bytes_32_checked(community_id) else { return false };
let everyone = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::everyone_locator(&crate::community::CommunityId(cid)));
crate::db::community::get_edition_head(community_id, &everyone).ok().flatten().is_some()
}
fn held_v2(community_id: &str) -> Result<crate::community::v2::community::CommunityV2> {
Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("this needs a Concord v2 community".into()))
}
fn short_transport() -> crate::community::transport::LiveTransport {
crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12))
}
fn view_named(view: &str) -> Result<crate::community::v2::community::ChannelView> {
crate::community::v2::community::ChannelView::try_parse(view)
.ok_or_else(|| VectorError::Other(format!("no channel view named {view:?}: chat, forum or voice")))
}
fn id32(hex: &str, what: &str) -> Result<[u8; 32]> {
crate::simd::hex::hex_to_bytes_32_checked(hex).ok_or_else(|| VectorError::Other(format!("{what} must be 32-byte hex")))
}
pub fn channel_permissions_view(&self, community_id: &str, channel_id: &str) -> Result<serde_json::Value> {
use crate::community::roles::{OverwriteTarget, Permissions};
let v2 = Self::held_v2(community_id)?;
let me = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?.to_hex();
let owner_hex = v2.owner().map_err(VectorError::Other)?.to_hex();
let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
let is_owner = me == owner_hex;
let chan = channel_id.to_ascii_lowercase();
let mut roles: Vec<&crate::community::roles::Role> = roster.roles.iter().collect();
roles.sort_by(|a, b| a.position.cmp(&b.position).then_with(|| a.role_id.cmp(&b.role_id)));
let overwrites: Vec<serde_json::Value> = roster
.overwrites
.iter()
.filter(|o| o.scope == chan)
.map(|o| {
let (kind, id) = match &o.target {
OverwriteTarget::Everyone => ("everyone", None),
OverwriteTarget::Role(id) => ("role", Some(id.clone())),
OverwriteTarget::Member(m) => ("member", Some(m.clone())),
};
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();
serde_json::json!({ "kind": kind, "id": id, "npub": npub, "allow": o.allow.0.to_string(), "deny": o.deny.0.to_string() })
})
.collect();
let category = crate::simd::hex::hex_to_bytes_32_checked(&chan)
.and_then(|b| v2.channel(&crate::community::ChannelId(b)))
.and_then(|c| c.category())
.filter(|k| v2.categories.iter().any(|x| x.id == *k))
.map(|k| crate::simd::hex::bytes_to_hex_32(&k));
Ok(serde_json::json!({
"activated": Self::roles_v2_active(community_id, &roster),
"category": category,
"synced": roster.syncs.get(&chan),
"can_manage": is_owner || roster.is_authorized(&me, Some(&owner_hex), Permissions::MANAGE_ROLES),
"grantable": if is_owner { u64::MAX.to_string() } else { roster.effective_permissions(&me).0.to_string() },
"roles": roles.iter().map(|r| serde_json::json!({ "role_id": r.role_id, "name": r.name, "color": r.color, "position": r.position })).collect::<Vec<_>>(),
"overwrites": overwrites,
"members": crate::community::v2::service::stored_memberlist(&v2)
.unwrap_or_default()
.into_iter()
.filter(|pk| pk.to_hex() != owner_hex)
.map(|pk| serde_json::json!({ "id": pk.to_hex(), "npub": ToBech32::to_bech32(&pk).ok() }))
.collect::<Vec<_>>(),
}))
}
pub async fn set_channel_overwrite(&self, community_id: &str, scope_id: &str, kind: &str, target_id: Option<&str>, allow: &str, deny: &str) -> Result<()> {
use crate::community::roles::OverwriteTarget;
let v2 = Self::held_v2(community_id)?;
let target = match (kind, target_id) {
("everyone", _) => OverwriteTarget::Everyone,
("role", Some(id)) => OverwriteTarget::Role(crate::simd::hex::bytes_to_hex_32(&Self::id32(id, "role_id")?)),
("member", Some(m)) => OverwriteTarget::Member(
nostr_sdk::prelude::PublicKey::parse(m).map_err(|_| VectorError::Other("invalid member key".into()))?.to_hex(),
),
_ => return Err(VectorError::Other("an overwrite targets everyone, a role or a member".into())),
};
let (allow, deny) = (Self::parse_permissions(allow)?, Self::parse_permissions(deny)?);
let transport = Self::short_transport();
crate::community::v2::service::set_overwrite(&transport, &v2, Self::id32(scope_id, "scope_id")?, target, allow, deny)
.await
.map_err(VectorError::Other)?;
Self::converge_v2_authority(&transport, community_id).await;
Ok(())
}
pub async fn set_channel_sync(&self, community_id: &str, channel_id: &str, category_id: Option<&str>) -> Result<()> {
let v2 = Self::held_v2(community_id)?;
let channel = crate::community::ChannelId(Self::id32(channel_id, "channel_id")?);
let category = category_id.map(|c| Self::id32(c, "category_id")).transpose()?;
let transport = Self::short_transport();
crate::community::v2::service::set_channel_sync(&transport, &v2, &channel, category).await.map_err(VectorError::Other)?;
Self::converge_v2_authority(&transport, community_id).await;
Ok(())
}
pub fn channel_send_denied(&self, community_id: &str, channel_id: &str, npubs: &[String]) -> Result<Vec<String>> {
Self::channel_denied(community_id, channel_id, npubs, crate::community::roles::Permissions::SEND_MESSAGES)
}
pub fn channel_react_denied(&self, community_id: &str, channel_id: &str, npubs: &[String]) -> Result<Vec<String>> {
Self::channel_denied(community_id, channel_id, npubs, crate::community::roles::Permissions::ADD_REACTIONS)
}
fn channel_denied(community_id: &str, channel_id: &str, npubs: &[String], perm: u64) -> Result<Vec<String>> {
let v2 = Self::held_v2(community_id)?;
let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
if roster.everyone.is_none() {
return Ok(Vec::new());
}
let owner = v2.owner().ok().map(|o| o.to_hex());
let chan = channel_id.to_ascii_lowercase();
let ch = Self::id32(channel_id, "channel_id").ok().and_then(|b| v2.channel(&crate::community::ChannelId(b)));
let private = ch.is_some_and(|c| c.private);
Ok(npubs
.iter()
.filter(|n| {
nostr_sdk::prelude::PublicKey::parse(n.as_str())
.is_ok_and(|pk| !roster.channel_permissions(owner.as_deref(), &pk.to_hex(), &chan, private).contains(perm))
})
.cloned()
.collect())
}
pub fn community_mentions(&self, community_id: &str) -> Result<serde_json::Value> {
use crate::community::roles::Permissions;
use nostr_sdk::prelude::PublicKey;
let v2 = Self::held_v2(community_id)?;
let owner = v2.owner().map_err(VectorError::Other)?.to_hex();
let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
let me = crate::state::my_public_key().map(|pk| pk.to_hex()).unwrap_or_default();
let members: std::collections::BTreeSet<&str> = std::iter::once(owner.as_str()).chain(roster.grants.iter().map(|g| g.member.as_str())).collect();
let pingers: Vec<String> = members
.into_iter()
.filter(|m| !banned.iter().any(|b| b == m) && roster.is_authorized(m, Some(&owner), Permissions::MENTION_EVERYONE))
.filter_map(|m| PublicKey::from_hex(m).ok()?.to_bech32().ok())
.collect();
let held: std::collections::HashSet<&str> = roster.roles_of(&me).map(|r| r.role_id.as_str()).collect();
let mut roles: Vec<&crate::community::roles::Role> = roster.roles.iter().filter(|r| crate::community::mentions::is_role_id(&r.role_id)).collect();
roles.sort_by_key(|r| r.position);
let roles: Vec<serde_json::Value> = roles
.into_iter()
.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()) }))
.collect();
Ok(serde_json::json!({
"anyone": roster.everyone.is_some_and(|e| e.contains(Permissions::MENTION_EVERYONE)),
"pingers": pingers,
"roles": roles,
}))
}
pub fn role_mentions_ping_me(&self, community_id: &str, author_npub: &str, content: &str, role_ids: &[String]) -> bool {
if role_ids.is_empty() {
return false;
}
let (Some(me), Ok(author), Ok(Some(held))) = (
crate::state::my_public_key(),
nostr_sdk::prelude::PublicKey::parse(author_npub),
Self::load_held(community_id),
) else {
return false;
};
let (Ok(owner), Ok(roster)) = (held.owner(), crate::db::community::get_community_roles(community_id)) else { return false };
let author = author.to_hex();
if crate::db::community::get_community_banlist(community_id).unwrap_or_default().contains(&author) {
return false;
}
crate::community::mentions::pings(&roster, Some(&owner.to_hex()), &author, &me.to_hex(), content, role_ids)
}
pub fn post_silenced(&self, community_id: &str, channel_id: &str, author_npub: &str) -> bool {
if self.channel_send_denied(community_id, channel_id, &[author_npub.to_string()]).is_ok_and(|d| !d.is_empty()) {
return true;
}
let (Ok(v2), Ok(author)) = (Self::held_v2(community_id), nostr_sdk::prelude::PublicKey::parse(author_npub)) else { return false };
crate::community::v2::service::community_timeouts(&v2).is_ok_and(|t| t.contains_key(&author))
}
pub fn community_timeouts(&self, community_id: &str) -> Result<serde_json::Value> {
let v2 = Self::held_v2(community_id)?;
let running = crate::community::v2::service::community_timeouts(&v2).map_err(VectorError::Other)?;
Ok(running
.into_iter()
.filter_map(|(pk, (from, until))| Some((pk.to_bech32().ok()?, serde_json::json!({ "from": from, "until": until }))))
.collect::<serde_json::Map<_, _>>()
.into())
}
pub async fn timeout_member(&self, community_id: &str, npub: &str, seconds: u64) -> Result<()> {
let v2 = Self::held_v2(community_id)?;
let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
crate::community::v2::service::timeout_member(&Self::short_transport(), &v2, &member, seconds).await.map_err(VectorError::Other)
}
pub fn community_nicknames(&self, community_id: &str) -> Result<serde_json::Value> {
let v2 = Self::held_v2(community_id)?;
let named = crate::community::v2::service::community_nicknames(&v2).map_err(VectorError::Other)?;
Ok(named
.into_iter()
.filter_map(|(pk, nick)| Some((pk.to_bech32().ok()?, serde_json::Value::String(nick))))
.collect::<serde_json::Map<_, _>>()
.into())
}
pub fn member_nickname(&self, community_id: &str, npub: &str) -> Option<String> {
let v2 = Self::held_v2(community_id).ok()?;
let member = nostr_sdk::prelude::PublicKey::parse(npub).ok()?;
crate::community::v2::service::community_nicknames(&v2).ok()?.remove(&member)
}
pub async fn set_community_nickname(&self, community_id: &str, npub: &str, nickname: &str) -> Result<()> {
let v2 = Self::held_v2(community_id)?;
let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
crate::community::v2::service::set_nickname(&Self::short_transport(), &v2, &member, nickname).await.map_err(VectorError::Other)
}
pub async fn delete_role(&self, community_id: &str, role_id: &str) -> Result<()> {
let v2 = Self::held_v2(community_id)?;
let transport = Self::short_transport();
crate::community::v2::service::delete_role_v2(&transport, &v2, role_id).await.map_err(VectorError::Other)?;
Self::converge_v2_authority(&transport, community_id).await;
Ok(())
}
pub async fn set_everyone_permissions(&self, community_id: &str, permissions: &str) -> Result<()> {
let v2 = Self::held_v2(community_id)?;
let perms = Self::parse_permissions(permissions)?;
let transport = Self::short_transport();
crate::community::v2::service::set_everyone(&transport, &v2, perms).await.map_err(VectorError::Other)?;
Self::converge_v2_authority(&transport, community_id).await;
Ok(())
}
pub async fn activate_roles_v2(&self, community_id: &str, everyone: &str) -> Result<usize> {
let v2 = Self::held_v2(community_id)?;
let perms = Self::parse_permissions(everyone)?;
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(30));
let carried = crate::community::v2::service::activate_roles_v2(&transport, &v2, perms).await.map_err(VectorError::Other)?;
Self::converge_v2_authority(&transport, community_id).await;
Ok(carried)
}
pub async fn create_category(&self, community_id: &str, name: &str) -> Result<String> {
let v2 = Self::held_v2(community_id)?;
let id = crate::community::v2::service::create_category(&Self::short_transport(), &v2, name).await.map_err(VectorError::Other)?;
Ok(crate::simd::hex::bytes_to_hex_32(&id))
}
pub async fn rename_category(&self, community_id: &str, category_id: &str, name: &str) -> Result<()> {
let v2 = Self::held_v2(community_id)?;
crate::community::v2::service::rename_category(&Self::short_transport(), &v2, Self::id32(category_id, "category_id")?, name).await.map_err(VectorError::Other)
}
pub async fn delete_category(&self, community_id: &str, category_id: &str) -> Result<()> {
let v2 = Self::held_v2(community_id)?;
crate::community::v2::service::delete_category(&Self::short_transport(), &v2, Self::id32(category_id, "category_id")?).await.map_err(VectorError::Other)
}
pub async fn move_category(&self, community_id: &str, category_id: &str, index: usize) -> Result<()> {
let v2 = Self::held_v2(community_id)?;
crate::community::v2::service::move_category(&Self::short_transport(), &v2, Self::id32(category_id, "category_id")?, index).await.map_err(VectorError::Other)
}
pub async fn move_channel(&self, community_id: &str, channel_id: &str, category_id: Option<&str>, index: usize) -> Result<()> {
let v2 = Self::held_v2(community_id)?;
let channel = crate::community::ChannelId(Self::id32(channel_id, "channel_id")?);
let category = category_id.map(|c| Self::id32(c, "category_id")).transpose()?;
crate::community::v2::service::move_channel(&Self::short_transport(), &v2, &channel, category, index).await.map_err(VectorError::Other)
}
pub async fn edit_channel_details(&self, community_id: &str, channel_id: &str, name: &str, topic: Option<&str>, view: &str) -> Result<()> {
let view = Self::view_named(view)?;
let v2 = Self::held_v2(community_id)?;
let channel = crate::community::ChannelId(Self::id32(channel_id, "channel_id")?);
crate::community::v2::service::edit_channel_details(&Self::short_transport(), &v2, &channel, name, topic, view).await.map_err(VectorError::Other)
}
pub async fn set_channel_private(&self, community_id: &str, channel_id: &str, private: bool) -> Result<()> {
let v2 = Self::held_v2(community_id)?;
let channel = crate::community::ChannelId(Self::id32(channel_id, "channel_id")?);
let transport = Self::short_transport();
if private {
return crate::community::v2::service::privatize_channel(&transport, &v2, &channel).await.map_err(VectorError::Other);
}
crate::community::v2::service::publicize_channel(&transport, &v2, &channel).await.map_err(VectorError::Other)
}
pub async fn set_member_roles(&self, community_id: &str, npub: &str, role_ids: Vec<String>) -> Result<()> {
let v2 = Self::load_held(community_id)?
.ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
crate::community::v2::service::set_member_roles(&transport, &v2, &member, role_ids)
.await
.map_err(VectorError::Other)?;
Self::converge_v2_authority_soon(community_id);
Ok(())
}
pub async fn modify_member_roles(&self, community_id: &str, npub: &str, add: &[String], remove: &[String]) -> Result<()> {
let v2 = Self::load_held(community_id)?
.ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
let (add, remove): (Vec<String>, Vec<String>) =
(add.iter().map(|r| r.to_ascii_lowercase()).collect(), remove.iter().map(|r| r.to_ascii_lowercase()).collect());
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
crate::community::v2::service::change_member_roles(&transport, &v2, &member, move |current| {
let mut next: Vec<String> = current.iter().map(|r| r.to_ascii_lowercase()).filter(|r| !remove.contains(r)).collect();
next.extend(add.into_iter().filter(|r| !remove.contains(r)));
next
})
.await
.map_err(VectorError::Other)?;
Self::converge_v2_authority_soon(community_id);
Ok(())
}
pub fn member_has_permission(&self, community_id: &str, npub: &str, permission: u64) -> Result<bool> {
use nostr_sdk::prelude::PublicKey;
let who = PublicKey::parse(npub).map_err(|_| VectorError::Other(format!("invalid npub: {npub}")))?.to_hex();
let owner_hex = Self::load_held(community_id)?
.ok_or_else(|| VectorError::Other("community not found".into()))?
.owner()
.map_err(VectorError::Other)?
.to_hex();
if who != owner_hex && crate::db::community::get_community_banlist(community_id).unwrap_or_default().contains(&who) {
return Ok(false);
}
let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
Ok(roster.is_authorized(&who, Some(&owner_hex), permission))
}
pub fn community_roles(&self, community_id: &str) -> Result<serde_json::Value> {
use nostr_sdk::prelude::{PublicKey, ToBech32};
let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
let owner = v2.owner().map_err(VectorError::Other)?;
let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
let admins: Vec<String> = roster.grants.iter()
.filter(|g| roster.is_admin(&g.member) && !banned.contains(&g.member))
.filter_map(|g| PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok()))
.collect();
Ok(serde_json::json!({ "owner": owner.to_bech32().ok(), "admins": admins }))
}
fn converge_v2_authority_soon(community_id: &str) {
let Some(id) = crate::simd::hex::hex_to_bytes_32_checked(community_id).map(crate::community::CommunityId) else { return };
if crate::community::v2::realtime::follow_worker_running() {
crate::community::v2::realtime::enqueue_follow(&id);
return;
}
let community_id = community_id.to_string();
crate::db::spawn_bound(async move {
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
Self::converge_v2_authority(&transport, &community_id).await;
});
}
async fn converge_v2_authority(
transport: &crate::community::transport::LiveTransport,
community_id: &str,
) {
crate::db::scoped(async move {
if let Ok(Some(fresh)) = Self::load_held(community_id) {
let _ = crate::community::v2::service::follow_control(transport, &fresh).await;
if let Ok(added) = crate::community::v2::service::sync_guestbook(transport, &fresh).await {
if !added.is_empty() {
traits::emit_event_json(
"community_refreshed",
serde_json::json!({ "community_id": community_id }),
);
}
}
}
})
.await
}
pub async fn grant_admin(&self, community_id: &str, npub: &str) -> Result<()> {
use crate::community::transport::LiveTransport;
let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
crate::community::v2::service::grant_admin(&transport, &v2, &member)
.await
.map_err(VectorError::Other)?;
Self::converge_v2_authority(&transport, community_id).await;
Ok(())
}
pub async fn revoke_admin(&self, community_id: &str, npub: &str) -> Result<()> {
use crate::community::transport::LiveTransport;
let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
crate::community::v2::service::revoke_admin(&transport, &v2, &member)
.await
.map_err(VectorError::Other)?;
Self::converge_v2_authority(&transport, community_id).await;
Ok(())
}
pub async fn kick_member(&self, community_id: &str, npub: &str) -> Result<()> {
crate::db::scoped(async move {
use crate::community::transport::LiveTransport;
let pk = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
crate::community::v2::service::kick_member(&transport, &v2, &pk)
.await
.map_err(VectorError::Other)?;
if let Ok(fresh) = crate::community::v2::service::sync_guestbook(&transport, &v2).await {
if !fresh.is_empty() {
emit_event("community_refreshed", &serde_json::json!({ "community_id": community_id }));
}
}
Self::converge_v2_authority(&transport, community_id).await;
Ok(())
})
.await
}
pub async fn set_member_banned(&self, community_id: &str, npub: &str, banned: bool) -> Result<()> {
self.set_members_banned(community_id, &[npub], banned).await
}
pub async fn set_members_banned(&self, community_id: &str, npubs: &[&str], banned: bool) -> Result<()> {
use crate::community::{transport::LiveTransport, CommunityId};
if npubs.is_empty() {
return Ok(());
}
let mut pks: Vec<nostr_sdk::prelude::PublicKey> = Vec::with_capacity(npubs.len());
for n in npubs {
let pk = nostr_sdk::prelude::PublicKey::parse(n).map_err(|_| VectorError::Other(format!("invalid npub: {n}")))?;
if !pks.contains(&pk) {
pks.push(pk);
}
}
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
if community_id.len() != 64 {
return Err(VectorError::Other("malformed community id".into()));
}
let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
crate::community::v2::service::set_members_banned(&transport, &cid, &pks, banned)
.await
.map_err(VectorError::Other)?;
Self::invalidate_raid_report(community_id);
Self::announce_ban_change(community_id);
Ok(())
}
fn announce_ban_change(community_id: &str) {
emit_event("community_refreshed", &serde_json::json!({ "community_id": community_id }));
}
pub async fn rescue_stranded_members(&self, community_id: &str, npubs: &[&str]) -> Result<serde_json::Value> {
use nostr_sdk::prelude::PublicKey;
let community = Self::load_held(community_id)?
.ok_or_else(|| VectorError::Other("rescuing requires a Concord v2 community".into()))?;
let mut targets: Vec<PublicKey> = Vec::with_capacity(npubs.len());
for n in npubs {
let pk = PublicKey::parse(n).map_err(|_| VectorError::Other(format!("invalid npub: {n}")))?;
if !targets.contains(&pk) {
targets.push(pk);
}
}
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(30));
let report = crate::community::v2::service::rescue_stranded_members(&transport, &community, &targets)
.await
.map_err(VectorError::Other)?;
serde_json::to_value(report).map_err(|e| VectorError::Other(e.to_string()))
}
pub async fn repair_community_roster(&self, community_id: &str) -> Result<serde_json::Value> {
use crate::community::CommunityId;
if community_id.len() != 64 {
return Err(VectorError::Other("malformed community id".into()));
}
let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
if crate::db::community::load_community_v2(&cid).map_err(VectorError::Other)?.is_none() {
return Err(VectorError::Other("not a held Concord v2 community".into()));
}
let before = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
let before_at = crate::db::community::get_community_roles_at(community_id).map_err(VectorError::Other)?;
crate::db::community::set_community_roles(community_id, &before, 0).map_err(VectorError::Other)?;
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(20));
let community = crate::db::community::load_community_v2(&cid)
.map_err(VectorError::Other)?
.ok_or_else(|| VectorError::Other("community vanished mid-repair".into()))?;
let follow = crate::community::v2::service::follow_control(&transport, &community).await;
let after = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
Ok(serde_json::json!({
"provenance_before": before_at,
"provenance_after": crate::db::community::get_community_roles_at(community_id).unwrap_or(0),
"roles_before": before.roles.len(),
"grants_before": before.grants.len(),
"roles_after": after.roles.len(),
"grants_after": after.grants.len(),
"fold_error": follow.as_ref().err().cloned(),
"repaired": after.grants.len() > before.grants.len(),
}))
}
pub async fn explain_epoch_state(&self, community_id: &str) -> Result<serde_json::Value> {
use crate::community::{transport::LiveTransport, CommunityId};
if community_id.len() != 64 {
return Err(VectorError::Other("malformed community id".into()));
}
let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
let community = crate::db::community::load_community_v2(&cid)
.map_err(VectorError::Other)?
.ok_or_else(|| VectorError::Other("not a held Concord v2 community".into()))?;
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(15));
crate::community::v2::service::explain_epoch_state(&transport, &community)
.await
.map_err(VectorError::Other)
}
pub async fn contain_raid(
&self,
community_id: &str,
npubs: &[&str],
window_start_secs: u64,
cut_also: &[&str],
) -> Result<crate::community::v2::service::ContainmentReport> {
use crate::community::{transport::LiveTransport, CommunityId};
if community_id.len() != 64 {
return Err(VectorError::Other("malformed community id".into()));
}
let mut pks: Vec<nostr_sdk::prelude::PublicKey> = Vec::with_capacity(npubs.len());
for n in npubs {
let pk = nostr_sdk::prelude::PublicKey::parse(n).map_err(|_| VectorError::Other(format!("invalid npub: {n}")))?;
if !pks.contains(&pk) {
pks.push(pk);
}
}
let mut extra: Vec<nostr_sdk::prelude::PublicKey> = Vec::with_capacity(cut_also.len());
for n in cut_also {
let pk = nostr_sdk::prelude::PublicKey::parse(n).map_err(|_| VectorError::Other(format!("invalid npub: {n}")))?;
if !extra.contains(&pk) {
extra.push(pk);
}
}
let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
if !crate::db::community::community_held(&cid).map_err(VectorError::Other)? {
return Err(VectorError::Other("community not found".into()));
}
let session = crate::db::current_session();
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(20));
let report = crate::community::v2::service::contain_raid(&transport, &cid, &pks, window_start_secs, &extra)
.await
.map_err(VectorError::Other)?;
if !session.is_live() {
return Err(VectorError::Other("account changed during raid containment".into()));
}
Self::invalidate_raid_report(community_id);
Ok(report)
}
pub async fn dissolve_community(&self, community_id: &str) -> Result<()> {
use crate::community::{transport::LiveTransport, CommunityId};
if community_id.len() != 64 {
return Err(VectorError::Other("malformed community id".into()));
}
let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
let community = crate::db::community::load_community_v2(&cid)
.map_err(VectorError::Other)?
.ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
crate::community::v2::service::dissolve_community(&transport, &community)
.await
.map_err(VectorError::Other)?;
drop_community_image(community.icon.as_ref().map(|i| i.url.clone()), None);
drop_community_image(community.banner.as_ref().map(|i| i.url.clone()), community.icon.as_ref().map(|i| i.url.as_str()));
Ok(())
}
pub async fn edit_community_metadata(&self, community_id: &str, name: Option<&str>, description: Option<&str>) -> Result<()> {
use crate::community::{transport::LiveTransport, CommunityId};
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
if community_id.len() != 64 {
return Err(VectorError::Other("malformed community id".into()));
}
let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
let community = crate::db::community::load_community_v2(&cid)
.map_err(VectorError::Other)?
.ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
let mut meta = community.metadata();
if let Some(n) = name {
meta.name = n.to_string();
}
if let Some(d) = description {
meta.description = if d.is_empty() { None } else { Some(d.to_string()) };
}
crate::community::v2::service::edit_community_metadata(&transport, &community, &meta)
.await
.map_err(VectorError::Other)
}
pub async fn remove_community_image(&self, community_id: &str, is_banner: bool) -> Result<()> {
use crate::community::{transport::LiveTransport, CommunityId};
let session = crate::db::current_session();
let cid = CommunityId(Self::id32(community_id, "community_id")?);
let community = crate::db::community::load_community_v2(&cid)
.map_err(VectorError::Other)?
.ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
let mut meta = community.metadata();
let gone = if is_banner { meta.banner.take() } else { meta.icon.take() };
let kept = if is_banner { meta.icon.as_ref() } else { meta.banner.as_ref() }.map(|i| i.url.clone());
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
crate::community::v2::service::edit_community_metadata(&transport, &community, &meta)
.await
.map_err(VectorError::Other)?;
if !session.is_live() {
return Err(VectorError::Other("account changed while removing the image".into()));
}
drop_community_image(gone.map(|i| i.url), kept.as_deref());
if let Some(updated) = crate::community::v2::service::persist_community_image(&cid, None, is_banner).await {
self.register_v2_chats(&updated, &session).await;
}
Ok(())
}
pub async fn set_community_image(&self, community_id: &str, bytes: &[u8], is_banner: bool) -> Result<String> {
let usage = if is_banner { crate::image_prep::ImageUse::Banner } else { crate::image_prep::ImageUse::Icon };
let raw = bytes.to_vec();
let prepared = crate::rt::spawn_blocking(move || crate::image_prep::prepare(&raw, usage))
.await
.map_err(|e| VectorError::Other(format!("image preparation stopped: {e}")))?
.map_err(VectorError::Other)?;
self.publish_community_image(community_id, prepared.bytes, prepared.extension, is_banner, None).await
}
pub async fn publish_community_image(
&self,
community_id: &str,
bytes: Vec<u8>,
extension: &str,
is_banner: bool,
progress: Option<crate::blossom::ProgressCallback>,
) -> Result<String> {
use crate::community::{transport::LiveTransport, CommunityId};
let session = crate::db::current_session();
let cid = CommunityId(Self::id32(community_id, "community_id")?);
crate::db::community::load_community_v2(&cid)
.map_err(VectorError::Db)?
.ok_or_else(|| VectorError::NotFound("community".into()))?;
if crate::svg::looks_like_svg(&bytes) {
return Err(VectorError::Other(crate::community::SVG_REFUSED.to_string()));
}
let hash = crate::crypto::sha256_hex(&bytes);
let params = crate::crypto::generate_encryption_params();
let encrypted = crate::crypto::encrypt_data(&bytes, ¶ms).map_err(VectorError::Other)?;
let signer = crate::signer::active_signer().map_err(|e| VectorError::Other(format!("signer: {e}")))?;
let servers = state::get_blossom_servers();
if servers.is_empty() {
return Err(VectorError::Other("no Blossom servers configured".into()));
}
let progress = progress.unwrap_or_else(|| std::sync::Arc::new(|_, _| Ok(())));
let url = crate::blossom::upload_blob_with_progress_and_failover(
signer,
servers,
std::sync::Arc::new(encrypted),
Some("application/octet-stream"),
true,
progress,
None,
None,
None,
)
.await
.map_err(VectorError::Other)?
.url;
let mut extra = serde_json::Map::new();
extra.insert("ext".into(), serde_json::Value::String(extension.to_string()));
let image = crate::community::v2::control::ImageRef { url: url.clone(), key: params.key.clone(), nonce: params.nonce.clone(), hash, extra };
if !session.is_live() {
return Err(VectorError::Other("account changed while setting the image".into()));
}
let community = crate::db::community::load_community_v2(&cid)
.map_err(VectorError::Db)?
.ok_or_else(|| VectorError::NotFound("community".into()))?;
let mut meta = community.metadata();
let replaced = if is_banner { meta.banner.replace(image.clone()) } else { meta.icon.replace(image.clone()) };
let kept = if is_banner { meta.icon.as_ref() } else { meta.banner.as_ref() }.map(|i| i.url.clone());
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
crate::community::v2::service::edit_community_metadata(&transport, &community, &meta)
.await
.map_err(VectorError::Other)?;
if !session.is_live() {
return Err(VectorError::Other("account changed while setting the image".into()));
}
drop_community_image(replaced.map(|i| i.url).filter(|u| *u != url), kept.as_deref());
if let Some(updated) = crate::community::v2::service::persist_community_image(&cid, Some(image), is_banner).await {
self.register_v2_chats(&updated, &session).await;
}
Ok(url)
}
pub async fn community_image(&self, community_id: &str, is_banner: bool) -> Result<Option<Vec<u8>>> {
use crate::community::CommunityId;
let cid = CommunityId(Self::id32(community_id, "community_id")?);
let community = crate::db::community::load_community_v2(&cid)
.map_err(VectorError::Other)?
.ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
let Some(image) = (if is_banner { community.banner } else { community.icon }) else {
return Ok(None);
};
let cap: usize = if is_banner { 16 } else { 10 } * 1024 * 1024;
crate::net::validate_url_not_private(&image.url).map_err(|e| VectorError::Network(format!("community image URL refused: {e}")))?;
let client = crate::net::build_http_client(std::time::Duration::from_secs(30)).map_err(VectorError::Network)?;
let resp = crate::net::proxied_request(&client, reqwest::Method::GET, &image.url)
.await
.send()
.await
.map_err(|e| VectorError::Network(format!("download: {e}")))?;
if !resp.status().is_success() {
return Err(VectorError::Network(format!("download failed: HTTP {}", resp.status())));
}
let mut encrypted: Vec<u8> = Vec::with_capacity(resp.content_length().map_or(64 * 1024, |l| (l as usize).min(cap)));
let mut body = resp.bytes_stream();
while let Some(chunk) = futures_util::StreamExt::next(&mut body).await {
let chunk = chunk.map_err(|e| VectorError::Network(format!("read body: {e}")))?;
if encrypted.len() + chunk.len() > cap {
return Err(VectorError::Other("community image too large".into()));
}
encrypted.extend_from_slice(&chunk);
}
let plain = crate::crypto::decrypt_data_owned(encrypted, &image.key, &image.nonce).map_err(VectorError::Crypto)?;
if crate::crypto::sha256_hex(&plain) != image.hash {
return Err(VectorError::Crypto("community image failed its integrity check".into()));
}
if crate::svg::looks_like_svg(&plain) {
return Err(VectorError::Other(crate::community::SVG_REFUSED.to_string()));
}
Ok(Some(plain))
}
pub async fn set_voice_relays(&self, community_id: &str, relays: &[String]) -> Result<Vec<String>> {
use crate::community::{transport::LiveTransport, CommunityId};
let cid = CommunityId(Self::id32(community_id, "community_id")?);
let community = crate::db::community::load_community_v2(&cid)
.map_err(VectorError::Other)?
.ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
let mut clean: Vec<String> = Vec::new();
for r in relays.iter().map(|r| r.trim().trim_end_matches('/').to_string()).filter(|r| !r.is_empty()) {
let parsed = url::Url::parse(&r).map_err(|_| VectorError::Other(format!("{r} isn't a relay address")))?;
if parsed.scheme() != "https" || parsed.host_str().is_none() {
return Err(VectorError::Other(format!("{r}: a voice relay is an https:// address")));
}
let normal = format!("{}/", parsed.as_str().trim_end_matches('/'));
if !clean.contains(&normal) {
clean.push(normal);
}
}
if clean.len() > crate::community::v2::community::MAX_VOICE_RELAYS {
return Err(VectorError::Other(format!("at most {} voice relays", crate::community::v2::community::MAX_VOICE_RELAYS)));
}
let mut meta = community.metadata();
if clean.is_empty() {
meta.extra.remove("voice_relays");
} else {
meta.extra.insert("voice_relays".into(), serde_json::json!(clean));
}
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
crate::community::v2::service::edit_community_metadata(&transport, &community, &meta).await.map_err(VectorError::Other)?;
Ok(clean)
}
pub async fn leave_community(&self, community_id: &str) -> Result<()> {
crate::db::scoped(async move {
use crate::community::transport::LiveTransport;
if community_id.len() != 64 {
return Err(VectorError::Other("malformed community id".into()));
}
use crate::community::v2::service;
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
let Some(v2) = Self::load_held(community_id)? else {
let cid = Self::unheld_id(community_id)?;
let at_ms = service::leave_unheld_locally(&cid).await.ok_or_else(|| VectorError::Other("community not found".into()))?;
service::announce_unheld_leave(&transport, &cid, at_ms).await;
return Ok(());
};
let channel_ids: Vec<String> =
v2.channels.iter().map(|ch| crate::simd::hex::bytes_to_hex_32(&ch.id.0)).collect();
service::leave_community(&transport, &v2).await.map_err(VectorError::Other)?;
service::forget_community_chats(&crate::simd::hex::bytes_to_hex_32(&v2.id().0), &channel_ids).await;
Ok(())
})
.await
}
pub async fn leave_community_now(&self, community_id: &str) -> Result<()> {
crate::db::scoped(async move {
use crate::community::v2::service;
let Some(v2) = Self::load_held(community_id)? else {
let cid = Self::unheld_id(community_id)?;
let at_ms = service::leave_unheld_locally(&cid).await.ok_or_else(|| VectorError::Other("community not found".into()))?;
crate::db::spawn_bound(async move {
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
service::announce_unheld_leave(&transport, &cid, at_ms).await;
});
return Ok(());
};
let channel_ids: Vec<String> =
v2.channels.iter().map(|ch| crate::simd::hex::bytes_to_hex_32(&ch.id.0)).collect();
let at_ms = service::leave_locally(&v2).map_err(VectorError::Other)?;
service::forget_community_chats(&crate::simd::hex::bytes_to_hex_32(&v2.id().0), &channel_ids).await;
crate::db::spawn_bound(async move {
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
service::announce_leave(&transport, &v2, at_ms).await;
if let Some(client) = state::nostr_client() {
crate::community::v2::realtime::refresh_subscription(&client).await;
}
crate::community::transport::prune_unneeded_community_relays(&v2.relays).await;
});
Ok(())
})
.await
}
pub async fn decline_community_invite(&self, community_id: &str) -> Result<()> {
crate::db::scoped(async move {
use crate::db::community as db;
let bundle = db::get_pending_invite(community_id)
.ok()
.flatten()
.and_then(|j| crate::community::v2::invite::CommunityInvite::from_bundle_json(&j).ok());
let relays: Vec<String> = bundle.as_ref().map(|b| b.relays.clone()).unwrap_or_default();
let wraps = db::pending_invite_wraps(community_id).unwrap_or_default();
db::delete_pending_invite(community_id).map_err(VectorError::Other)?;
if let Some(cid) = bundle.and_then(|_| crate::simd::hex::hex_to_bytes_32_checked(community_id)) {
let removed_at = crate::clock::now_ms();
crate::community::v2::service::tombstone_community_list_durable(crate::community::CommunityId(cid), relays.clone(), removed_at);
}
for wrap in wraps.iter().filter_map(|w| nostr_sdk::prelude::EventId::from_hex(w).ok()) {
crate::deletion::delete_received_wrap(wrap);
}
if !relays.is_empty() {
crate::community::transport::prune_unneeded_community_relays(&relays).await;
}
Ok(())
})
.await
}
pub async fn sync_dms(
&self,
since_days: Option<u64>,
handler: &dyn InboundEventHandler,
) -> Result<(u32, u32)> {
crate::db::scoped(async move {
use futures_util::StreamExt;
use nostr_sdk::prelude::*;
let client = state::nostr_client()
.ok_or(VectorError::Other("Not connected".into()))?;
let my_pk = state::my_public_key()
.ok_or(VectorError::Other("Not logged in".into()))?;
let (items, filter) = if let Some(days) = since_days {
let since_ts = crate::clock::timestamp().as_secs().saturating_sub(days * 24 * 3600);
let items = db::wrappers::load_negentropy_items_since(since_ts)
.unwrap_or_default();
let filter = Filter::new()
.pubkey(my_pk)
.kind(Kind::GiftWrap)
.since(Timestamp::from_secs(since_ts));
(items, filter)
} else {
let items = db::wrappers::load_negentropy_items().unwrap_or_default();
let filter = Filter::new()
.pubkey(my_pk)
.kind(Kind::GiftWrap);
(items, filter)
};
log_info!("[SyncDMs] {} negentropy items, since_days={:?}", items.len(), since_days);
let items = std::sync::Arc::new(items);
let sync_opts = nostr_sdk::prelude::SyncOptions::new()
.direction(nostr_sdk::prelude::SyncDirection::Down)
.initial_timeout(relay_request_timeout(std::time::Duration::from_secs(10)))
.dry_run();
let relay_map = client.relays().await;
let (all_relays, no_neg_relays): (Vec<_>, Vec<_>) =
relay_map.iter()
.map(|(url, relay)| (url.clone(), relay.clone()))
.partition(|(url, _)| negentropy::neg_supported_cached(url.as_str()) != Some(false));
drop(relay_map);
let skipped_no_neg: Vec<String> = no_neg_relays.iter().map(|(u, _)| u.to_string()).collect();
if !skipped_no_neg.is_empty() {
log_info!("[SyncDMs] {} relay(s) on REQ path (no NIP-77)", skipped_no_neg.len());
}
let neg_budget = relay_request_timeout(std::time::Duration::from_secs(10));
let neg_outer = neg_budget + std::time::Duration::from_secs(5);
let connect_allowance = relay_request_timeout(std::time::Duration::from_secs(3))
.min(neg_outer);
let mut relay_futs = futures_util::stream::FuturesUnordered::new();
for (url, relay) in &all_relays {
let url = url.clone();
let relay = relay.clone();
let f = filter.clone();
let i = items.clone();
let o = sync_opts.clone();
relay_futs.push(async move {
if !negentropy::wait_connected(&relay, connect_allowance).await {
return (url, None, false);
}
let result = crate::rt::time::timeout(
neg_outer,
relay.sync(f).items(i.iter().copied()).opts(o),
).await;
let connected = relay.status() == RelayStatus::Connected;
(url, Some(result), connected)
});
}
let cap_session = crate::db::current_session();
let mut all_missing: std::collections::HashSet<EventId> = std::collections::HashSet::new();
while let Some((url, result, connected)) = relay_futs.next().await {
let Some(result) = result else {
log_warn!("[SyncDMs] {} skipped: not connected", url);
continue;
};
match result {
Ok(Ok(recon)) => {
let count = recon.remote.len();
all_missing.extend(recon.remote);
log_info!("[SyncDMs] {} reconciled: {} missing", url, count);
negentropy::record_neg_support(url.as_str(), true);
}
Ok(Err(e)) => {
log_warn!("[SyncDMs] {} failed: {}", url, e);
if cap_session.is_live()
&& negentropy::classify_neg_sync_error(&e.to_string(), connected && !negentropy::neg_ever_confirmed(url.as_str())) == Some(false)
{
log_info!("[SyncDMs] {} marked no-NIP-77 for 24h", url);
negentropy::record_neg_support(url.as_str(), false);
}
}
Err(_) => log_warn!("[SyncDMs] {} timed out ({:?})", url, neg_outer),
}
}
let mut total_events = 0u32;
let mut new_messages = 0u32;
if !skipped_no_neg.is_empty() {
let req_filter = filter.clone().limit(500);
match client
.stream_events(nostr_sdk::prelude::ReqTarget::manual(
skipped_no_neg.iter().cloned().map(|u| (u, vec![req_filter.clone()])),
))
.timeout(relay_request_timeout(std::time::Duration::from_secs(20)))
.await
{
Ok(stream) => {
let mut seen: std::collections::HashSet<[u8; 32]> = std::collections::HashSet::new();
let stream = stream.ready_chunks(event_handler::UNWRAP_BATCH);
tokio::pin!(stream);
while let Some(chunk) = stream.next().await {
let events: Vec<Event> = chunk
.into_iter()
.filter_map(|(_relay, res)| res.ok())
.filter(|event| seen.insert(event.id.to_bytes()))
.collect();
total_events += events.len() as u32;
for prepared in event_handler::prepare_events(&events, my_pk).await {
if event_handler::commit_prepared_event(prepared, false, handler).await {
new_messages += 1;
}
}
}
}
Err(e) => log_warn!("[SyncDMs] REQ pass failed: {}", e),
}
}
if all_missing.is_empty() {
log_info!("[SyncDMs] No missing events");
return Ok((total_events, new_messages));
}
log_info!("[SyncDMs] Fetching {} missing events", all_missing.len());
let ids: Vec<EventId> = all_missing.into_iter().collect();
let relay_strs: Vec<String> = client.relays().await.keys()
.map(|u| u.to_string()).collect();
const BATCH_SIZE: usize = 500;
for batch in ids.chunks(BATCH_SIZE) {
let f = Filter::new().ids(batch.to_vec()).kind(Kind::GiftWrap).pubkey(my_pk);
match client
.stream_events(nostr_sdk::prelude::ReqTarget::manual(
relay_strs.iter().cloned().map(|u| (u, vec![f.clone()])),
))
.timeout(std::time::Duration::from_secs(30))
.await
{
Ok(stream) => {
let prepared_stream = stream
.filter_map(|(_relay, res)| async move { res.ok() })
.ready_chunks(event_handler::UNWRAP_BATCH)
.map(move |events| {
db::spawn_bound(async move {
event_handler::prepare_events(&events, my_pk).await
})
})
.buffer_unordered(8);
tokio::pin!(prepared_stream);
while let Some(result) = prepared_stream.next().await {
let Ok(batch) = result else { continue };
total_events += batch.len() as u32;
for prepared in batch {
if event_handler::commit_prepared_event(prepared, false, handler).await {
new_messages += 1;
}
}
}
}
Err(e) => log_warn!("[SyncDMs] Batch fetch error: {}", e),
}
}
log_info!("[SyncDMs] Complete: {} events processed, {} new messages", total_events, new_messages);
Ok((total_events, new_messages))
})
.await
}
pub async fn subscribe_dms(&self) -> Result<nostr_sdk::prelude::SubscriptionId> {
use nostr_sdk::prelude::*;
let client = state::nostr_client()
.ok_or(VectorError::Other("Not connected".into()))?;
let my_pk = state::my_public_key()
.ok_or(VectorError::Other("Not logged in".into()))?;
let filter = Filter::new()
.pubkey(my_pk)
.kind(Kind::GiftWrap)
.limit(0);
let output = client.subscribe(filter.clone()).await
.map_err(|e| VectorError::Nostr(e.to_string()))?;
live_subs::keep_output(&output, vec![filter]);
Ok(output.value)
}
pub async fn sync_communities(&self) -> Result<Vec<String>> {
let mut all_warnings: Vec<String> = Vec::new();
{
use crate::community::{transport::LiveTransport, v2::service as v2};
let bootstrap: Vec<String> = match crate::state::nostr_client() {
Some(client) => client.relays().await.keys().map(|r| r.to_string()).collect(),
None => Vec::new(),
};
let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
if let Ok(outcome) = v2::sync_community_list(&transport, &bootstrap).await {
let joined = outcome.joined;
for c in &joined {
if community::v2::realtime::follow_worker_running() {
community::v2::realtime::enqueue_follow(c.id());
} else {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&c.id().0);
all_warnings.extend(
Self::v2_inline_follow(c.id()).await.into_iter().map(|w| format!("{}: {w}", &cid_hex[..8])),
);
}
}
if !joined.is_empty() {
if let Some(client) = crate::state::nostr_client() {
community::v2::realtime::refresh_subscription(&client).await;
}
}
}
}
let ids = db::community::list_community_ids().map_err(VectorError::from)?;
for id in ids {
if community::v2::realtime::follow_worker_running() {
community::v2::realtime::enqueue_follow(&id);
} else {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&id.0);
all_warnings.extend(
Self::v2_inline_follow(&id).await.into_iter().map(|w| format!("{}: {w}", &cid_hex[..8])),
);
}
if let Ok(Some(c)) = db::community::load_community_v2(&id) {
for ch in &c.channels {
let hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
let _ = Self::v2_backfill_channel(
&id, &hex, 50, 2, None, None,
crate::community::transport::Evidence::Fast, 12,
).await;
}
}
}
Ok(all_warnings)
}
pub async fn listen(&self, handler: Arc<dyn InboundEventHandler>) -> Result<()> {
self.listen_with(handler, CatchUp::Inline).await
}
pub async fn listen_with(&self, handler: Arc<dyn InboundEventHandler>, catch_up: CatchUp) -> Result<()> {
use nostr_sdk::prelude::*;
let client = state::nostr_client()
.ok_or(VectorError::Other("Not connected".into()))?;
let my_pk = state::my_public_key()
.ok_or(VectorError::Other("Not logged in".into()))?;
community::v2::streamauth::ensure_responder(&client);
let listening_since = crate::clock::now_ms();
let inline = catch_up == CatchUp::Inline;
if inline {
news::begin(handler.clone(), listening_since);
} else {
news::end();
}
let live_from = news::cutoff().unwrap_or(listening_since);
if handler.wants_community_changes() {
community::v2::changes::prime_all(&*handler);
}
community::v2::realtime::spawn_follow_worker(handler.clone());
early::start(handler.clone());
let notifications = client.notifications();
let dm_sub_id = self.subscribe_dms().await?;
live_subs::watch(&client);
let (live_tx, mut live_rx) = tokio::sync::mpsc::channel::<(LiveRoute, Box<nostr_sdk::prelude::Event>)>(4096);
let dm_sid = dm_sub_id.clone();
db::spawn_bound(async move {
let mut notifications = notifications;
while let Some(notification) = notifications.next().await {
if let nostr_sdk::prelude::ClientNotification::Message { message, .. } = ¬ification {
if let nostr_sdk::prelude::RelayMessage::Ok { event_id, status, .. } = &**message {
sending::note_relay_ok(event_id, *status);
}
}
let nostr_sdk::prelude::ClientNotification::Event { event, subscription_id, .. } = notification else { continue };
let route = if subscription_id == dm_sid {
LiveRoute::Dm
} else if community::v2::realtime::routes_live(&subscription_id) {
LiveRoute::CommunityV2
} else {
continue;
};
if live_tx.send((route, event)).await.is_err() {
break;
}
}
});
if inline {
let _ = self.sync_communities().await;
let _ = self.sync_dms(None, &event_handler::LiveOnly::from(&*handler, live_from)).await;
}
community::v2::realtime::refresh_subscription(&client).await;
if inline {
Self::owe_catch_up(false, false, [(EVERY_RELAY.to_string(), live_from)]);
live_subs::set_catch_up(|what| {
let now = crate::clock::now_ms();
match what {
live_subs::CatchUp::All { away_ms } => Self::owe_catch_up(true, true, [(EVERY_RELAY.to_string(), now.saturating_sub(away_ms))]),
live_subs::CatchUp::Relay(url) => Self::owe_catch_up(false, false, [(url, now.saturating_sub(live_subs::MAX_BACKOFF.as_millis() as u64))]),
}
});
#[cfg(not(target_arch = "wasm32"))]
live_subs::start_wake_watch();
}
handler.on_subscription_ready(db::community::list_community_ids().map(|v| v.len()).unwrap_or(0));
if let Some(monitor) = client.monitor().filter(|_| catch_up == CatchUp::Inline) {
let mut rx = monitor.subscribe();
let pool = client.clone();
db::spawn_bound(async move {
let mut down: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
for (url, relay) in pool.relays().await {
if relay.status() != RelayStatus::Connected {
down.insert(url.to_string(), live_from);
}
}
loop {
match rx.recv().await {
Ok(MonitorNotification::StatusChanged { relay_url, status }) => {
let url = relay_url.to_string();
match status {
RelayStatus::Disconnected | RelayStatus::Terminated => {
down.entry(url).or_insert_with(crate::clock::now_ms);
}
RelayStatus::Connected => {
if let Some(since) = down.remove(&url) {
VectorCore::owe_catch_up(true, true, [(url, since)]);
}
}
_ => {}
}
}
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
VectorCore::owe_catch_up(true, true, [(EVERY_RELAY.to_string(), crate::clock::now_ms().saturating_sub(30 * 60_000))]);
}
Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
}
}
});
}
{
let client_health = client.clone();
db::spawn_bound(async move {
crate::rt::time::sleep(std::time::Duration::from_secs(30)).await; let heard = std::sync::Mutex::new(std::collections::HashMap::<RelayUrl, usize>::new());
loop {
let budget = relay_request_timeout(std::time::Duration::from_secs(8));
let client_health = &client_health;
let heard = &heard;
futures_util::future::join_all(client_health.relays().await.into_iter().map(|(url, relay)| async move {
match relay.status() {
RelayStatus::Connected => {
let received = relay.stats().bytes_received();
let before = heard.lock().unwrap().insert(url.clone(), received);
if before.is_some_and(|b| received > b) {
return;
}
let probe = crate::rt::time::timeout(
budget + std::time::Duration::from_secs(2),
client_health
.fetch_events(nostr_sdk::prelude::ReqTarget::single(
url.to_string(),
[Filter::new().id(EventId::from_byte_array([0; 32]))],
))
.timeout(budget),
)
.await;
heard.lock().unwrap().insert(url.clone(), relay.stats().bytes_received());
if !matches!(probe, Ok(Ok(_))) {
relay.disconnect();
crate::rt::time::sleep(std::time::Duration::from_millis(500)).await;
let _ = relay.try_connect().timeout(crate::relay_connect_timeout(std::time::Duration::from_secs(10))).await;
}
}
RelayStatus::Terminated | RelayStatus::Disconnected => {
let _ = relay.try_connect().timeout(crate::relay_connect_timeout(std::time::Duration::from_secs(10))).await;
}
_ => {}
}
})).await;
crate::rt::time::sleep(std::time::Duration::from_secs(60)).await;
}
});
}
let client_for_closure = client.clone();
while let Some((route, event)) = live_rx.recv().await {
match route {
LiveRoute::Dm => {
let prepared = event_handler::prepare_event(*event, &client_for_closure, my_pk).await;
event_handler::commit_prepared_event(prepared, true, &*handler).await;
}
LiveRoute::CommunityV2 => community::v2::realtime::dispatch_event(*event, handler.clone()).await,
}
}
news::end();
Ok(())
}
pub(crate) fn owe_live_replay(since_ms: u64) {
Self::owe_catch_up(false, false, [(EVERY_RELAY.to_string(), since_ms)]);
}
pub(crate) fn owe_catch_up(communities: bool, dms: bool, relays: impl IntoIterator<Item = (String, u64)>) {
if news::listening_since().is_none() {
return;
}
let session = db::current_session_id();
let start = {
let mut owed = CATCH_UPS.lock().unwrap_or_else(|e| e.into_inner());
if owed.session != session {
*owed = Owed { session, ..Owed::default() };
}
owed.communities |= communities;
owed.dms |= dms;
for (relay, since) in relays {
let at = owed.relays.entry(relay).or_insert(since);
*at = (*at).min(since);
}
!std::mem::replace(&mut owed.running, true)
};
if start {
db::spawn_bound(Self::run_catch_ups(session));
}
}
async fn run_catch_ups(session: u64) {
loop {
crate::rt::time::sleep(std::time::Duration::from_secs(1)).await;
let listener = news::listener().zip(news::cutoff());
let owed = {
let mut owed = CATCH_UPS.lock().unwrap_or_else(|e| e.into_inner());
let nothing = !owed.communities && !owed.dms && owed.relays.is_empty();
if owed.session != session || nothing || listener.is_none() {
owed.running = false;
return;
}
std::mem::replace(&mut *owed, Owed { session, running: true, ..Owed::default() })
};
let Some((handler, from)) = listener else { return };
if owed.communities {
let _ = VectorCore.sync_communities().await;
}
if owed.dms {
let _ = VectorCore.sync_dms(None, &event_handler::LiveOnly::from(&*handler, from)).await;
}
if let Some(client) = state::nostr_client() {
if owed.communities {
community::v2::realtime::refresh_subscription(&client).await;
}
for (relay, since) in owed.relays {
let since = since.saturating_sub(news::ALLOWANCE_MS).max(from);
let only = (relay != EVERY_RELAY).then_some(relay.as_str());
community::v2::realtime::replay(&client, nostr_sdk::prelude::Timestamp::from_secs(since / 1000), only, handler.clone()).await;
}
}
}
}
pub async fn logout(&self) {
news::end();
if let Some(client) = state::nostr_client() {
let _ = client.disconnect().await;
}
db::close_database();
}
pub async fn swap_session(&self) {
state::clear_message_tombstones();
news::end();
#[cfg(feature = "xdc")]
crate::xdc::session::leave_all(std::time::Duration::from_secs(4)).await;
#[cfg(feature = "calls")]
crate::calls::voice::leave().await;
if let Some(client) = state::take_nostr_client() {
let _ = client.shutdown().await;
}
db::close_database();
state::ENCRYPTION_KEY.clear(&[&state::MY_SECRET_KEY]);
state::MY_SECRET_KEY.clear(&[&state::ENCRYPTION_KEY]);
{
use zeroize::Zeroize;
if let Ok(mut g) = state::MNEMONIC_SEED.lock() {
if let Some(s) = g.as_mut() { s.zeroize(); }
*g = None;
}
if let Ok(mut g) = state::PENDING_NSEC.lock() {
if let Some(s) = g.as_mut() { s.zeroize(); }
*g = None;
}
}
crate::community::v2::realtime::clear().await;
crate::community::transport::clear_plane_pool();
}
}
#[cfg(test)]
mod catch_up_tests {
use super::*;
#[tokio::test]
async fn what_a_listener_is_owed_merges_and_runs_once() {
let _g = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
*CATCH_UPS.lock().unwrap() = Owed::default();
VectorCore::owe_catch_up(true, false, [("wss://a".to_string(), 100)]);
assert!(!CATCH_UPS.lock().unwrap().running, "nobody listening: nothing owed");
let _listening = news::listen_for_test(Arc::new(event_handler::NoOpEventHandler), crate::clock::now_ms());
VectorCore::owe_catch_up(false, false, [("wss://a".to_string(), 100)]);
VectorCore::owe_catch_up(false, true, [("wss://a".to_string(), 50), ("wss://b".to_string(), 70)]);
let owed = CATCH_UPS.lock().unwrap();
assert!(owed.running && owed.dms && !owed.communities);
assert_eq!((owed.relays.get("wss://a"), owed.relays.get("wss://b")), (Some(&50), Some(&70)), "each relay from its earliest gap");
}
}
fn page_before(
held: &[compact::CompactMessage],
interner: &compact::NpubInterner,
before: Option<(u64, &str)>,
limit: usize,
) -> Vec<Message> {
let (lo, mut msgs) = match before {
None => (held.len(), Vec::new()),
Some((at, id)) => {
let lo = held.partition_point(|m| m.at < at);
let hi = held.partition_point(|m| m.at <= at);
let tie = held[lo..hi].iter().map(|m| m.to_message(interner)).filter(|m| m.id.as_str() < id).collect();
(lo, tie)
}
};
let mut start = lo.saturating_sub(limit.saturating_sub(msgs.len()));
while start > 0 && start < lo && held[start - 1].at == held[start].at {
start -= 1;
}
msgs.extend(held[start..lo].iter().map(|m| m.to_message(interner)));
msgs.sort_by(|a, b| (a.at, a.id.as_str()).cmp(&(b.at, b.id.as_str())));
if msgs.len() > limit {
msgs.drain(..msgs.len() - limit);
}
msgs
}
#[cfg(test)]
mod page_before_tests {
use super::*;
#[test]
fn it_matches_converting_the_whole_chat() {
let mut interner = compact::NpubInterner::new();
let mut held = compact::CompactMessageVec::new();
let mut seed: u64 = 7;
for n in 0..400u64 {
seed ^= seed << 13; seed ^= seed >> 7; seed ^= seed << 17;
let msg = Message { id: format!("{:064x}", seed), at: (n / 9) * 1000 + (seed % 3), ..Default::default() };
held.insert(compact::CompactMessage::from_message(&msg, &mut interner));
}
let mut all: Vec<Message> = held.iter().map(|m| m.to_message(&interner)).collect();
all.sort_by(|a, b| (a.at, a.id.as_str()).cmp(&(b.at, b.id.as_str())));
let reference = |before: Option<(u64, &str)>, limit: usize| {
let mut v: Vec<String> = all.iter()
.filter(|m| before.is_none_or(|(at, id)| (m.at, m.id.as_str()) < (at, id)))
.map(|m| m.id.clone())
.collect();
if v.len() > limit { v.drain(..v.len() - limit); }
v
};
let ids = |v: Vec<Message>| v.into_iter().map(|m| m.id).collect::<Vec<_>>();
for limit in [1, 3, 10, 50, 1000] {
assert_eq!(ids(page_before(held.messages(), &interner, None, limit)), reference(None, limit));
for c in all.iter().step_by(13) {
for cursor in [(c.at, c.id.as_str()), (c.at, "0"), (c.at, "g"), (c.at + 1, "0")] {
assert_eq!(ids(page_before(held.messages(), &interner, Some(cursor), limit)), reference(Some(cursor), limit), "cursor {cursor:?} limit {limit}");
}
}
}
}
}
#[cfg(all(test, feature = "tor", not(target_arch = "wasm32")))]
mod transport_policy_tests {
use std::time::Duration;
use crate::transport::{egress, Egress, Kind, Lane};
fn live() -> u64 {
crate::db::live_session_id()
}
#[test]
fn tor_transport_policy() {
let _serial = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
let short = Duration::from_secs(5);
let long = Duration::from_secs(300);
crate::transport::set_preference(Some(Kind::Clearnet));
crate::tor::set_tor_enabled_pref(false);
assert_eq!(egress(live(), Lane::Account, "relay.example.com", 443), Egress::Direct);
assert_eq!(super::relay_connect_timeout(short), short);
assert_eq!(super::relay_request_timeout(short), short);
crate::tor::set_tor_enabled_pref(true);
assert!(matches!(
crate::tor::transport_state(),
crate::tor::TorTransportState::RequiredButInactive
));
assert!(
matches!(egress(live(), Lane::Account, "relay.example.com", 443), Egress::Refuse(_)),
"Tor enabled but inactive must never connect direct"
);
assert_eq!(super::relay_connect_timeout(short), Duration::from_secs(60));
assert_eq!(super::relay_request_timeout(short), Duration::from_secs(30));
crate::tor::set_tor_enabled_pref(false);
crate::tor::arm_prelogin_carry(true);
assert!(crate::tor::effective_tor_pref(false), "an armed carry raises an off preference");
crate::tor::set_tor_enabled_pref(crate::tor::effective_tor_pref(false));
assert!(
matches!(egress(live(), Lane::Account, "relay.example.com", 443), Egress::Refuse(_)),
"an armed carry must refuse until Tor is up, never connect direct"
);
crate::tor::arm_prelogin_carry(false);
assert!(!crate::tor::effective_tor_pref(false), "a disarmed carry leaves the preference alone");
assert!(crate::tor::effective_tor_pref(true));
let opts = super::transport_relay_options();
assert!(format!("{opts:?}").contains("proxy: Some"), "remote-signer relays must carry the transport");
for tor in [true, false] {
crate::tor::set_tor_enabled_pref(tor);
assert_eq!(super::relay_connect_timeout(long), long, "connect, tor={tor}");
assert_eq!(super::relay_request_timeout(long), long, "request, tor={tor}");
}
crate::transport::set_preference(Some(Kind::Clearnet));
}
}
#[cfg(test)]
mod facade_tests {
use super::*;
#[tokio::test]
async fn download_attachment_rejects_private_url() {
let att = crate::types::Attachment {
url: "http://169.254.169.254/latest/meta-data/".to_string(),
..Default::default()
};
match VectorCore.download_attachment(&att).await {
Err(VectorError::Other(msg)) => {
assert!(msg.contains("Private/internal"), "expected SSRF rejection, got: {msg}")
}
other => panic!("expected SSRF rejection, got {other:?}"),
}
}
#[tokio::test]
async fn download_attachment_rejects_empty_url() {
let att = crate::types::Attachment::default();
assert!(VectorCore.download_attachment(&att).await.is_err());
}
#[tokio::test]
async fn list_communities_and_channel_routing_are_protocol_aware() {
use crate::community::transport::memory::MemoryRelay;
use nostr_sdk::prelude::Keys;
let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
crate::db::close_database();
crate::db::clear_id_caches();
let tmp = tempfile::tempdir().unwrap();
let acct = {
const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
let mut s = String::from("npub1");
for i in 0..58 {
s.push(B[(i * 7 + 3) % 32] as char);
}
s
};
std::fs::create_dir_all(tmp.path().join(&acct)).unwrap();
crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
crate::db::set_current_account(acct.clone()).unwrap();
crate::db::init_database(&acct).unwrap();
let _ = crate::state::take_nostr_client();
let me = Keys::generate();
crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
crate::state::set_my_public_key(me.public_key());
let relay = MemoryRelay::new();
let community = crate::community::v2::service::create_community(&relay, "V2 Guild", vec!["wss://r".into()], None)
.await
.unwrap();
let channel_hex = crate::simd::hex::bytes_to_hex_32(&community.channels[0].id.0);
let listed = VectorCore.list_communities().await;
let v2 = listed.iter().find(|c| c["version"] == 2).expect("the v2 community is listed");
assert_eq!(v2["name"], "V2 Guild");
assert_eq!(v2["is_owner"], true);
assert_eq!(v2["channels"][0]["channel_id"], channel_hex);
assert_eq!(
VectorCore.v2_community_for_channel(&channel_hex).unwrap(),
Some(community.identity.community_id),
"a v2 channel is routed to v2"
);
assert_eq!(VectorCore.v2_community_for_channel(&"00".repeat(32)).unwrap(), None);
}
#[test]
fn v2_invite_url_base_derivation_round_trips() {
use crate::community::v2::derive::TOKEN_LEN;
use crate::community::v2::invite::{build_invite_url, parse_invite_link};
use nostr_sdk::prelude::Keys;
let base = crate::community::v2::invite::INVITE_URL_BASE.trim_end_matches("/invite");
assert!(!base.ends_with("/invite"), "the bare domain must not carry /invite");
let signer = Keys::generate();
let token = [0x07u8; TOKEN_LEN];
let url = build_invite_url(base, &signer.public_key(), &token, &[]).unwrap();
assert!(url.contains("/invite/"), "a v2 URL carries the naddr path");
assert!(!url.contains("/invite/invite/"), "no doubled /invite from the base");
let parsed = parse_invite_link(&url).unwrap();
assert_eq!(parsed.link_signer, signer.public_key());
assert_eq!(parsed.token, token);
}
}
#[cfg(test)]
mod history_paging_tests {
use super::*;
fn msg(at: u64, id_byte: u8, content: &str) -> Message {
Message {
id: format!("{:02x}", id_byte).repeat(32),
content: content.to_string(),
at,
..Default::default()
}
}
#[tokio::test]
async fn history_pages_through_a_same_ms_wall_and_a_deleted_cursor() {
let chat_id = "test-history-paging-wall";
{
let mut st = state::STATE.lock().await;
st.ensure_community_chat(chat_id);
for m in [msg(500, 0x01, "old"), msg(900, 0xaa, "wall-a"), msg(900, 0xbb, "wall-b"), msg(900, 0xcc, "wall-c")] {
st.add_message_to_chat(chat_id, &m);
}
}
let core = VectorCore;
let newest = core.get_messages_before(chat_id, None, 2).await;
assert_eq!(newest.iter().map(|m| m.content.as_str()).collect::<Vec<_>>(), ["wall-b", "wall-c"]);
let cursor = (newest[0].at, newest[0].id.as_str().to_string());
let page = core.get_messages_before(chat_id, Some((cursor.0, &cursor.1)), 10).await;
assert_eq!(page.iter().map(|m| m.content.as_str()).collect::<Vec<_>>(), ["old", "wall-a"]);
{
let mut st = state::STATE.lock().await;
let chat = st.get_chat_mut(chat_id).unwrap();
chat.messages.remove_by_hex_id(&cursor.1);
}
let page = core.get_messages_before(chat_id, Some((cursor.0, &cursor.1)), 10).await;
assert_eq!(
page.iter().map(|m| m.content.as_str()).collect::<Vec<_>>(),
["old", "wall-a"],
"a deleted cursor pages identically"
);
assert!(core.get_messages_before("test-history-paging-nochat", None, 5).await.is_empty());
}
}
#[cfg(test)]
mod moderation_cache_audit {
#[test]
fn every_moderation_action_drops_the_memoised_verdict() {
let src = include_str!("lib.rs");
for name in [
"pub async fn refound_community",
"pub async fn kick_community_members",
"pub async fn set_members_banned",
"pub async fn contain_raid",
] {
let start = src.find(name).unwrap_or_else(|| panic!("{name} not found — rename?"));
let rest = &src[start + name.len()..];
let end = rest.find("\n pub ").unwrap_or(rest.len());
assert!(
rest[..end].contains("invalidate_raid_report"),
"{name} mutates membership but never drops the memoised console verdict"
);
}
}
#[test]
fn an_adopted_change_drops_the_verdict_too() {
let src = include_str!("db/community.rs");
for name in ["pub fn set_community_banlist", "pub fn set_community_roles", "pub fn set_guestbook"] {
let start = src.find(name).unwrap_or_else(|| panic!("{name} not found — rename?"));
let rest = &src[start + name.len()..];
let end = rest.find("\npub fn ").unwrap_or(rest.len());
assert!(
rest[..end].contains("forget_console_verdict"),
"{name} changes who the console reports on but leaves the memo standing"
);
}
}
}