From 1cd45af7fb8cddf4824bd46095eb0680c04c3c66 Mon Sep 17 00:00:00 2001 From: selikhov Date: Sat, 3 Oct 2026 07:25:35 +0300 Subject: [PATCH] Engine pieces for the home, messages and settings screens The home page lists the latest chats across servers and the profiles page raises an identity's security level, so the engine gains: - Store::recent_chats / History::recent_chats: the newest message of every chat, the most recently active first (one pass over the time index). - identity::improve_level: the hash cash search on every core, in chunks of counters, cancellable, reporting each better level reached; the key and so the unique id stay the same. - privacy.private_messages and privacy.pokes (everyone, friends, nobody): private messages and pokes of everyone else are dropped, next to what privacy.block_mode does for blocked contacts. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/voelin-core/Cargo.toml | 2 + crates/voelin-core/src/history.rs | 14 +++++++ crates/voelin-core/src/identity.rs | 65 ++++++++++++++++++++++++++++++ crates/voelin-core/src/session.rs | 40 +++++++++++++++++- crates/voelin-core/src/settings.rs | 29 +++++++++++++ crates/voelin-store/src/chat.rs | 42 +++++++++++++++++++ docs/architecture.md | 4 +- 8 files changed, 195 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fee7ebc..568c86d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9108,6 +9108,7 @@ dependencies = [ "toml", "tracing", "tsclientlib", + "tsproto", "tsproto-packets", "tsproto-types", "voelin-audio", diff --git a/crates/voelin-core/Cargo.toml b/crates/voelin-core/Cargo.toml index 1888da0..acb58c4 100644 --- a/crates/voelin-core/Cargo.toml +++ b/crates/voelin-core/Cargo.toml @@ -47,6 +47,8 @@ voelin-query = { path = "../voelin-query" } voelin-store = { path = "../voelin-store" } voelin-stream = { path = "../voelin-stream" } tsclientlib = { path = "../proto/tsclientlib" } +# The hash cash level, for raising an identity's security level. +tsproto = { path = "../proto/tsproto" } tsproto-packets = { path = "../proto/tsproto-packets" } tsproto-types = { path = "../proto/tsproto-types" } diff --git a/crates/voelin-core/src/history.rs b/crates/voelin-core/src/history.rs index 0543467..7ba035e 100644 --- a/crates/voelin-core/src/history.rs +++ b/crates/voelin-core/src/history.rs @@ -365,6 +365,17 @@ impl History { Ok(rows.into_iter().map(HistoryMessage::from).collect()) } + /// The newest stored message of every chat with the server's unique id, + /// the most recently active chat first, at most `limit` chats (a list + /// of recent chats across servers). + pub async fn recent_chats( + &self, + limit: usize, + ) -> Result, String> { + let rows = self.run(false, move |s| s.recent_chats(Some(limit))).await?; + Ok(rows.into_iter().map(|m| (m.server_uid.clone(), HistoryMessage::from(m))).collect()) + } + /// Delete messages older than `before_ms` (pinned ones stay). pub(crate) fn prune(&self, before_ms: i64) { self.send(Job::Run { @@ -812,6 +823,9 @@ mod tests { ["m49", "n49"] ); assert!(page[0].id > 0); + let recent = history.recent_chats(5).await.unwrap(); + assert_eq!(recent.len(), 1, "one chat"); + assert_eq!((recent[0].0.as_str(), recent[0].1.message.ts_ms), ("srv", 49)); // Kept in memory only: negative ids, not in the file. let kept = history.write_async(true, vec![live("secret", 99)], 5000).await.unwrap(); assert!(kept[0].message.id < 0); diff --git a/crates/voelin-core/src/identity.rs b/crates/voelin-core/src/identity.rs index eea4bbf..97a6e97 100644 --- a/crates/voelin-core/src/identity.rs +++ b/crates/voelin-core/src/identity.rs @@ -26,6 +26,7 @@ use std::collections::{BTreeMap, HashSet}; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}; use std::{fs, str}; use rusqlite::{Connection, OpenFlags, OptionalExtension}; @@ -195,6 +196,51 @@ pub fn write_export(path: &Path, nickname: &str, identity: &Identity) -> Result< file.write_all(export(nickname, identity).as_bytes()).map_err(|e| IdentityError::read(path, e)) } +/// Raise `identity`'s hash cash security level to at least `target` on +/// every core: the counters after its current one are searched in parallel +/// chunks, and the identity with the first counter found that reaches +/// `target` is returned (the same key, so the same unique id). `progress` +/// hears each better level reached, from the worker threads; setting +/// `cancel` stops the search with `None`. Each level takes about twice as +/// long as the one before; there is no upper limit. +pub fn improve_level( + identity: &Identity, + target: u8, + cancel: &AtomicBool, + progress: impl Fn(u8) + Sync, +) -> Option { + const CHUNK: u64 = 1 << 14; + if identity.level() >= target { + return Some(identity.clone()); + } + let omega = identity.key().to_pub().to_ts(); + let threads = std::thread::available_parallelism().map_or(1, |n| n.get()); + let next = AtomicU64::new(identity.max_counter().max(identity.counter())); + let found = AtomicU64::new(u64::MAX); + let best = AtomicU8::new(identity.level()); + std::thread::scope(|scope| { + for _ in 0..threads { + scope.spawn(|| { + while !cancel.load(Ordering::Relaxed) && found.load(Ordering::Relaxed) == u64::MAX { + let start = next.fetch_add(CHUNK, Ordering::Relaxed); + for counter in start..start.saturating_add(CHUNK) { + let level = tsproto::algorithms::get_hash_cash_level(&omega, counter); + if level > best.fetch_max(level, Ordering::Relaxed) { + progress(level); + } + if level >= target { + found.fetch_min(counter, Ordering::Relaxed); + break; + } + } + } + }); + } + }); + let counter = found.into_inner(); + (counter != u64::MAX).then(|| Identity::new(identity.key().clone(), counter)) +} + /// Does `path` start with the SQLite file header? fn is_sqlite(path: &Path) -> Result { let mut head = [0u8; 16]; @@ -439,6 +485,25 @@ mod tests { Identity::create() } + #[test] + fn improve_level_keeps_the_key() { + let identity = synthetic(); + let levels = std::sync::Mutex::new(Vec::new()); + let better = improve_level(&identity, 13, &AtomicBool::new(false), |l| { + levels.lock().unwrap().push(l); + }) + .unwrap(); + assert!(better.level() >= 13); + assert_eq!(better.key().to_pub().get_uid(), identity.key().to_pub().get_uid()); + assert!(better.counter() > identity.counter()); + assert!(levels.into_inner().unwrap().iter().any(|l| *l >= 13)); + // Cancelled: nothing. + assert!(improve_level(&identity, 60, &AtomicBool::new(true), |_| {}).is_none()); + // Already there: the same identity. + let same = improve_level(&better, 8, &AtomicBool::new(false), |_| {}).unwrap(); + assert_eq!(same.counter(), better.counter()); + } + fn temp_dir(name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("voelin-identity-{name}-{}", std::process::id())); diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index 87d0d52..68911b9 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -30,7 +30,8 @@ use crate::history::{self, ChatCtx, HistoryMessage, MessageSource, SharedHistory use crate::query::{self, QueryCmd, QueryEvent}; use crate::route::{ChatRoute, Dedup, route_chat}; use crate::settings::{ - BlockMode, CACHE_FETCH_IMAGES, CACHE_MAX_MB, PRIVACY_BLOCK_MODE, SharedSettings, + Allowed, BlockMode, CACHE_FETCH_IMAGES, CACHE_MAX_MB, Key, PRIVACY_BLOCK_MODE, PRIVACY_POKES, + PRIVACY_PRIVATE_MESSAGES, SharedSettings, }; use crate::stream::{ LayerSpec, OwnStreamEvent, PeerConfig, SrtpProfile, StreamFrame, StreamHandle, StreamInfo, @@ -49,6 +50,26 @@ fn max_cache_bytes(settings: &SharedSettings) -> u64 { settings.current().get(&CACHE_MAX_MB).saturating_mul(1024 * 1024) } +/// Whether a privacy setting lets someone with this relation (`None`: no +/// unique id known) reach us. +fn allows(setting: Allowed, relation: Option) -> bool { + match setting { + Allowed::Everyone => true, + Allowed::Friends => relation == Some(Relation::Friend), + Allowed::Nobody => false, + } +} + +#[cfg(test)] +#[test] +fn privacy_settings() { + assert!(allows(Allowed::Everyone, None)); + assert!(allows(Allowed::Friends, Some(Relation::Friend))); + assert!(!allows(Allowed::Friends, Some(Relation::Neutral))); + assert!(!allows(Allowed::Friends, None)); + assert!(!allows(Allowed::Nobody, Some(Relation::Friend))); +} + pub(crate) struct SessionHandle { tx: mpsc::UnboundedSender, } @@ -869,6 +890,12 @@ impl Session { self.settings.current().get(&PRIVACY_BLOCK_MODE) } + /// Whether `privacy.private_messages` or `privacy.pokes` (`key`) lets + /// the person with this unique id reach us. + fn allowed(&self, key: &'static Key, uid: Option<&str>) -> bool { + allows(self.settings.current().get(key), uid.map(|u| self.contacts.relation(u))) + } + fn stream_input(&self, input: StreamInput) { match &self.streams { Some(s) => s.send(input), @@ -1339,6 +1366,10 @@ impl Session { debug!(?from_uid, "poke of a blocked contact hidden"); return; } + if !self.allowed(&PRIVACY_POKES, from_uid.as_deref()) { + debug!(?from_uid, "poke dropped (privacy.pokes)"); + return; + } let session = self.id; self.emit(Event::Poke { session, from, from_uid, from_name, message, blocked }); } @@ -1540,6 +1571,13 @@ impl Session { debug!(author = ?msg.author_uid, "private message of a blocked contact hidden"); return; } + if matches!(msg.target, ChatTarget::Private(_)) + && msg.author_id != self.state.own_client + && !self.allowed(&PRIVACY_PRIVATE_MESSAGES, msg.author_uid.as_deref()) + { + debug!(author = ?msg.author_uid, "private message dropped (privacy.private_messages)"); + return; + } if let Some(ctx) = self.chat_ctx() { let stored = match &entry { Some(entry) => history::gateway_message(&ctx.server_uid, entry), diff --git a/crates/voelin-core/src/settings.rs b/crates/voelin-core/src/settings.rs index e59177a..7accc11 100644 --- a/crates/voelin-core/src/settings.rs +++ b/crates/voelin-core/src/settings.rs @@ -1141,6 +1141,33 @@ pub static PRIVACY_BLOCK_MODE: Key = Key::new( BlockMode::default, ); +/// Who may reach us with private messages or pokes; the others' are +/// dropped (neither reported nor stored). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Allowed { + /// Anyone (blocked contacts still follow `privacy.block_mode`). + #[default] + Everyone, + /// Contacts marked friend. + Friends, + Nobody, +} + +pub static PRIVACY_PRIVATE_MESSAGES: Key = Key::new( + "privacy.private_messages", + Kind::Choice(&["everyone", "friends", "nobody"]), + "Who may send us private messages: everyone, friends or nobody.", + Allowed::default, +); + +pub static PRIVACY_POKES: Key = Key::new( + "privacy.pokes", + Kind::Choice(&["everyone", "friends", "nobody"]), + "Who may poke us: everyone, friends or nobody.", + Allowed::default, +); + /// What an audio source of our stream captures, as stored; see /// [`AudioSourceSetting`]. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -1290,6 +1317,8 @@ pub fn builtin_keys() -> Vec<&'static dyn Setting> { &CACHE_FETCH_IMAGES, &FILES_PROGRESS_MS, &PRIVACY_BLOCK_MODE, + &PRIVACY_PRIVATE_MESSAGES, + &PRIVACY_POKES, #[cfg(feature = "media")] &STUDIO_SCENES, #[cfg(feature = "media")] diff --git a/crates/voelin-store/src/chat.rs b/crates/voelin-store/src/chat.rs index c7e6b01..3b1353b 100644 --- a/crates/voelin-store/src/chat.rs +++ b/crates/voelin-store/src/chat.rs @@ -529,6 +529,24 @@ impl Store { Ok(rows) } + /// The newest message of every chat (of every server), the most + /// recently active chat first, at most `limit` chats (`None`: all). + pub fn recent_chats(&self, limit: Option) -> Result> { + // SQLite takes the bare columns from the row with the MAX. + // ponytail: one pass over the time index; keep a table of each + // chat's last message if histories grow into the millions. + let sql = format!( + "SELECT {COLUMNS}, MAX(ts_ms) FROM messages WHERE server_uid <> '' + GROUP BY server_uid, target ORDER BY ts_ms DESC, id DESC LIMIT ?1" + ); + let limit = limit.map_or(-1, |l| l as i64); + Ok(self + .db + .prepare_cached(&sql)? + .query_map([limit], message_from_row)? + .collect::>>()?) + } + /// One message by its local id. pub fn message(&self, id: i64) -> Result> { Ok(self @@ -767,6 +785,30 @@ mod tests { rows.iter().map(|m| m.text.as_str()).collect() } + #[test] + fn recent_chats_newest_first() { + let mut store = Store::open_in_memory().unwrap(); + let mut dm = msg(MessageSource::Voice, "b", "hi", 3000); + dm.target = ChatTarget::Private("uid-b".into()); + let mut other = msg(MessageSource::Voice, "c", "elsewhere", 2500); + other.server_uid = "srv2".into(); + store + .write_messages( + &[ + msg(MessageSource::Voice, "a", "old", 1000), + msg(MessageSource::Voice, "a", "newer", 2000), + dm, + other, + ], + 0, + ) + .unwrap(); + let recent = store.recent_chats(None).unwrap(); + assert_eq!(texts(&recent), ["hi", "elsewhere", "newer"]); + assert_eq!(recent[0].target, ChatTarget::Private("uid-b".into())); + assert_eq!(texts(&store.recent_chats(Some(1)).unwrap()), ["hi"]); + } + #[test] fn batch_insert_and_pages() { let mut store = Store::open_in_memory().unwrap(); diff --git a/docs/architecture.md b/docs/architecture.md index 76c8947..983387e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -222,7 +222,9 @@ for Home's friends list, and records sightings in one write per change. A contact's mute and volume apply to their voice in every session. Messages of blocked contacts are flagged (`ChatMessage::blocked`, live and in history); their private messages and pokes are dropped or flagged per -`privacy.block_mode`. `stream.permissions = friends` lets friends watch our +`privacy.block_mode`. `privacy.private_messages` and `privacy.pokes` +(everyone, friends, nobody) drop those of everyone else. +`stream.permissions = friends` lets friends watch our stream without asking and asks for everyone else. ## Streams