From 589f85cca00623899621609195ad23eec54bd8d6 Mon Sep 17 00:00:00 2001 From: Justin Williams Date: Wed, 25 Nov 2026 07:32:45 -0800 Subject: [PATCH 1/7] Move the log entry types into entry.rs Entry, Kind, Ref and FileInfo get a module of their own, the first step towards one home for what each kind of entry is. Co-Authored-By: Claude Opus 5.5 --- src-tauri/examples/seed.rs | 2 +- src-tauri/src/chat.rs | 5 ++- src-tauri/src/db.rs | 68 +------------------------------- src-tauri/src/entry.rs | 75 ++++++++++++++++++++++++++++++++++++ src-tauri/src/lib.rs | 4 +- src-tauri/tests/paging.rs | 5 ++- src-tauri/tests/two_peers.rs | 3 +- 7 files changed, 90 insertions(+), 72 deletions(-) create mode 100644 src-tauri/src/entry.rs diff --git a/src-tauri/examples/seed.rs b/src-tauri/examples/seed.rs index b4ee389..041d022 100644 --- a/src-tauri/examples/seed.rs +++ b/src-tauri/examples/seed.rs @@ -10,7 +10,7 @@ use std::path::Path; use anyhow::{Context, Result, ensure}; use iroh::SecretKey; -use tightbeam_lib::db::{Db, Entry}; +use tightbeam_lib::{db::Db, entry::Entry}; const LINES: &[&str] = &[ "hey", diff --git a/src-tauri/src/chat.rs b/src-tauri/src/chat.rs index a62dd3f..aa3e231 100644 --- a/src-tauri/src/chat.rs +++ b/src-tauri/src/chat.rs @@ -38,7 +38,10 @@ use tokio::{ time::timeout, }; -use crate::db::{Cursor, Db, Entry, FileInfo, FileState, Hit, Kind, Message, Page, Ref}; +use crate::{ + db::{Cursor, Db, FileState, Hit, Message, Page}, + entry::{Entry, FileInfo, Kind, Ref}, +}; pub const ALPN: &[u8] = b"tightbeam/1"; /// mDNS service name, so we only see other Tightbeam apps (`_tightbeam._udp.local`). diff --git a/src-tauri/src/db.rs b/src-tauri/src/db.rs index 9707319..1bbcd87 100644 --- a/src-tauri/src/db.rs +++ b/src-tauri/src/db.rs @@ -31,49 +31,7 @@ use anyhow::{Result, bail}; use rusqlite::{Connection, OptionalExtension, params}; use serde::{Deserialize, Serialize}; -/// An entry, by author and sequence number. -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct Ref { - pub author: String, - pub seq: u64, -} - -/// One entry in an author's log, as stored and synced. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Entry { - /// Endpoint id (public key) of whoever wrote it. - pub author: String, - /// Per-author sequence number, starting at 1 with no gaps. - pub seq: u64, - /// Milliseconds since the Unix epoch, from the author's clock. The time shown. - pub ts: i64, - /// Display order: `ts`, or one past the highest `hlc` the author had stored, if - /// that's later. Entries from peers before 0.5 have `hlc = ts`. - pub hlc: i64, - /// The message, the reaction's emoji ("" takes a reaction back), the edit's new text, - /// or "" for a delete. - pub text: String, - pub kind: Kind, -} - -/// A file attached to a message, as its sender describes it. Synced with the message; -/// the bytes follow separately. -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct FileInfo { - /// BLAKE3 of the contents: 64 lowercase hex digits. - pub hash: String, - pub name: String, - pub size: u64, - pub mime: String, - /// Set for an image the sender's app could display. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub width: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub height: Option, - /// A tiny copy of the image as a `data:` URL, shown until the file arrives. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub preview: Option, -} +use crate::entry::{Entry, FileInfo, Kind, Ref}; /// Where a message's file has got to on this computer. #[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)] @@ -103,30 +61,6 @@ pub struct StoredFile { pub size: u64, } -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Kind { - Message { - reply_to: Option, - /// Seconds it lasts once seen, for a vanishing message. - vanish: Option, - file: Option, - }, - /// Replaces the author's earlier reaction to `to`, if any. - Reaction { to: Ref }, - /// New text for one of the author's own messages. The latest edit wins. - Edit { of: Ref }, - /// Deletes one of the author's own messages. - Delete { of: Ref }, -} - -impl Entry { - pub fn message(author: impl Into, seq: u64, ts: i64, text: impl Into) -> Self { - let (author, text) = (author.into(), text.into()); - let kind = Kind::Message { reply_to: None, vanish: None, file: None }; - Self { author, seq, ts, hlc: ts, text, kind } - } -} - /// A message as the transcript shows it. #[derive(Debug, Clone, Serialize, PartialEq, Eq)] pub struct Message { diff --git a/src-tauri/src/entry.rs b/src-tauri/src/entry.rs new file mode 100644 index 0000000..8ba7778 --- /dev/null +++ b/src-tauri/src/entry.rs @@ -0,0 +1,75 @@ +//! Log entries: what each kind is. +//! +//! Every author keeps a log of numbered entries: messages, and reactions, edits and +//! deletes that refer to an earlier message by `(author, seq)`. A reply also refers to +//! the message it answers. + +use serde::{Deserialize, Serialize}; + +/// An entry, by author and sequence number. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct Ref { + pub author: String, + pub seq: u64, +} + +/// One entry in an author's log, as stored and synced. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Entry { + /// Endpoint id (public key) of whoever wrote it. + pub author: String, + /// Per-author sequence number, starting at 1 with no gaps. + pub seq: u64, + /// Milliseconds since the Unix epoch, from the author's clock. The time shown. + pub ts: i64, + /// Display order: `ts`, or one past the highest `hlc` the author had stored, if + /// that's later. Entries from peers before 0.5 have `hlc = ts`. + pub hlc: i64, + /// The message, the reaction's emoji ("" takes a reaction back), the edit's new text, + /// or "" for a delete. + pub text: String, + pub kind: Kind, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Kind { + Message { + reply_to: Option, + /// Seconds it lasts once seen, for a vanishing message. + vanish: Option, + file: Option, + }, + /// Replaces the author's earlier reaction to `to`, if any. + Reaction { to: Ref }, + /// New text for one of the author's own messages. The latest edit wins. + Edit { of: Ref }, + /// Deletes one of the author's own messages. + Delete { of: Ref }, +} + +impl Entry { + pub fn message(author: impl Into, seq: u64, ts: i64, text: impl Into) -> Self { + let (author, text) = (author.into(), text.into()); + let kind = Kind::Message { reply_to: None, vanish: None, file: None }; + Self { author, seq, ts, hlc: ts, text, kind } + } +} + +/// A file attached to a message, as its sender describes it. Synced with the message; +/// the bytes follow separately. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct FileInfo { + /// BLAKE3 of the contents: 64 lowercase hex digits. + pub hash: String, + pub name: String, + pub size: u64, + pub mime: String, + /// Set for an image the sender's app could display. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub width: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub height: Option, + /// A tiny copy of the image as a `data:` URL, shown until the file arrives. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub preview: Option, +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 2faab46..26c5324 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,14 +1,16 @@ pub mod chat; pub mod db; mod desktop; +pub mod entry; mod idle; mod updates; use std::{path::PathBuf, sync::Arc}; use chat::{ConnectionInfo, Core, Emit, Event, NewFile, Status}; -use db::{Cursor, Hit, Message, Page, Ref}; +use db::{Cursor, Hit, Message, Page}; use desktop::{Desktop, MAIN_WINDOW, MINIMIZED_ARG}; +use entry::Ref; use serde::Serialize; use tauri::{ Emitter, Manager, RunEvent, State, WindowEvent, diff --git a/src-tauri/tests/paging.rs b/src-tauri/tests/paging.rs index 31ff670..47a2d07 100644 --- a/src-tauri/tests/paging.rs +++ b/src-tauri/tests/paging.rs @@ -2,7 +2,10 @@ use std::time::Instant; -use tightbeam_lib::db::{Cursor, Db, Entry, Message}; +use tightbeam_lib::{ + db::{Cursor, Db, Message}, + entry::Entry, +}; const COUNT: u64 = 50_000; diff --git a/src-tauri/tests/two_peers.rs b/src-tauri/tests/two_peers.rs index a3a421a..8eba480 100644 --- a/src-tauri/tests/two_peers.rs +++ b/src-tauri/tests/two_peers.rs @@ -14,7 +14,8 @@ use std::{ use tightbeam_lib::{ chat::{Away, Core, Emit, Event, NewFile}, - db::{FileState, Ref}, + db::FileState, + entry::Ref, }; fn quiet() -> Emit { From 64a6a234b69edcd91c015c0ea4109ef11d355d1c Mon Sep 17 00:00:00 2001 From: Justin Williams Date: Wed, 25 Nov 2026 07:34:51 -0800 Subject: [PATCH 2/7] Give a msg frame's body to the entry module Frame::Msg wraps entry::Wire, and Entry::into_wire replaces to_frame. The JSON is unchanged: the wire-format tests pass as they were. Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/chat.rs | 75 +++++++++--------------------------------- src-tauri/src/entry.rs | 54 ++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 60 deletions(-) diff --git a/src-tauri/src/chat.rs b/src-tauri/src/chat.rs index aa3e231..45ebc6b 100644 --- a/src-tauri/src/chat.rs +++ b/src-tauri/src/chat.rs @@ -40,7 +40,7 @@ use tokio::{ use crate::{ db::{Cursor, Db, FileState, Hit, Message, Page}, - entry::{Entry, FileInfo, Kind, Ref}, + entry::{Entry, FileInfo, Kind, Ref, Wire}, }; pub const ALPN: &[u8] = b"tightbeam/1"; @@ -104,40 +104,8 @@ enum Frame { #[serde(default, skip_serializing_if = "Vec::is_empty")] features: Vec, }, - /// An entry in the sender's log. Plain, it's a message. - Msg { - seq: u64, - ts: i64, - /// Display order (see `Entry::hlc`). Added in 0.5; without it, `ts` is used. - #[serde(default, skip_serializing_if = "Option::is_none")] - hlc: Option, - text: String, - /// The message this one answers. Added in 0.4; older peers show a plain message. - #[serde(default, skip_serializing_if = "Option::is_none")] - reply_to: Option, - /// Makes this a reaction to that message: `text` is the emoji, or "" to take - /// the sender's reaction back. Added in 0.4; older peers show the emoji as a - /// message. - #[serde(default, skip_serializing_if = "Option::is_none")] - react_to: Option, - /// Makes this new text for one of the sender's own messages. Added in 0.4; older - /// peers show the new text as a message. - #[serde(default, skip_serializing_if = "Option::is_none")] - edit_of: Option, - /// Deletes one of the sender's own messages; `text` is "". Added in 0.4; older - /// peers show an empty message. - #[serde(default, skip_serializing_if = "Option::is_none")] - delete_of: Option, - /// A vanishing message: each side erases it this many seconds after the - /// recipient has seen it. Added in 0.6, and only sent to peers that say their - /// version in `Hello`: older ones would keep it. - #[serde(default, skip_serializing_if = "Option::is_none")] - vanish: Option, - /// A file, with `text` as its caption. Added in 0.7, and only sent to peers whose - /// `Hello` lists the `files` feature. - #[serde(default, skip_serializing_if = "Option::is_none")] - file: Option>, - }, + /// An entry in the sender's log (see `entry::Wire`). + Msg(Wire), Ack { have: u64, }, @@ -1134,7 +1102,7 @@ impl Core { generation }; for entry in self.db().since(&self.id(), their_have)? { - let _ = out.send(to_frame(entry)); + let _ = out.send(Frame::Msg(entry.into_wire())); } // Covers anything seen while we were apart. let _ = out.send(Frame::Seen { up_to: self.state().seen }); @@ -1181,7 +1149,7 @@ impl Core { ) -> Result<()> { loop { match read_frame(recv).await? { - Frame::Msg { + Frame::Msg(Wire { seq, ts, hlc, @@ -1192,7 +1160,7 @@ impl Core { delete_of, vanish, file, - } => { + }) => { // A reply to anyone but the two of us becomes a plain message. A // reaction to a stranger's message, or an edit or delete of anyone's // but the sender's own, is stored but never shown. A file that's too @@ -1624,7 +1592,7 @@ impl Core { /// Sends one of my entries now, if connected. Otherwise it goes with the catch-up. fn send_live(&self, entry: Entry) { if let Some(s) = &self.state().session { - let _ = s.out.send(to_frame(entry)); + let _ = s.out.send(Frame::Msg(entry.into_wire())); } } @@ -1733,21 +1701,6 @@ fn is_lan(addr: &TransportAddr, allow_loopback: bool) -> bool { } } -fn to_frame(entry: Entry) -> Frame { - let (mut reply_to, mut react_to, mut edit_of, mut delete_of) = (None, None, None, None); - let (mut vanish, mut file) = (None, None); - match entry.kind { - Kind::Message { reply_to: to, vanish: v, file: f } => { - (reply_to, vanish, file) = (to, v, f.map(Box::new)) - } - Kind::Reaction { to } => react_to = Some(to), - Kind::Edit { of } => edit_of = Some(of), - Kind::Delete { of } => delete_of = Some(of), - } - let (seq, ts, hlc, text) = (entry.seq, entry.ts, Some(entry.hlc), entry.text); - Frame::Msg { seq, ts, hlc, text, reply_to, react_to, edit_of, delete_of, vanish, file } -} - /// My `Hello`: who I am, the last of their entries I have, and what this build does. fn hello(name: String, have: u64) -> Frame { let features = FEATURES.iter().map(|f| f.to_string()).collect(); @@ -1944,10 +1897,12 @@ mod tests { fn extra_fields_on_known_frames_are_ignored() { let frame = parse(r#"{"t":"msg","seq":7,"ts":1,"text":"hi","pinned_by":{"author":"x","seq":2}}"#); - assert!(matches!(frame, Frame::Msg { seq: 7, hlc: None, ref text, .. } if text == "hi")); + assert!( + matches!(frame, Frame::Msg(Wire { seq: 7, hlc: None, ref text, .. }) if text == "hi") + ); let frame = parse(r#"{"t":"msg","seq":7,"ts":1,"text":"hi","reply_to":{"author":"x","seq":2}}"#); - assert!(matches!(frame, Frame::Msg { reply_to: Some(Ref { seq: 2, .. }), .. })); + assert!(matches!(frame, Frame::Msg(Wire { reply_to: Some(Ref { seq: 2, .. }), .. }))); } #[test] @@ -1986,7 +1941,7 @@ mod tests { kind: Kind::Message { reply_to: None, vanish: Some(60), file: None }, ..Entry::message("me", 9, 1, "psst") }; - let json = serde_json::to_string(&to_frame(vanishing)).unwrap(); + let json = serde_json::to_string(&Frame::Msg(vanishing.into_wire())).unwrap(); assert_eq!(json, r#"{"t":"msg","seq":9,"ts":1,"hlc":1,"text":"psst","vanish":60}"#); let file = FileInfo { hash: "ab".repeat(32), @@ -2001,7 +1956,7 @@ mod tests { kind: Kind::Message { reply_to: None, vanish: None, file: Some(file) }, ..Entry::message("me", 10, 1, "") }; - let json = serde_json::to_string(&to_frame(photo)).unwrap(); + let json = serde_json::to_string(&Frame::Msg(photo.into_wire())).unwrap(); let hash = "ab".repeat(32); assert_eq!( json, @@ -2010,7 +1965,7 @@ mod tests { ) ); // A plain message has the fields from before 0.4, plus `hlc` from 0.5. - let plain = to_frame(Entry::message("me", 7, 1, "hi")); + let plain = Frame::Msg(Entry::message("me", 7, 1, "hi").into_wire()); let json = serde_json::to_string(&plain).unwrap(); assert_eq!(json, r#"{"t":"msg","seq":7,"ts":1,"hlc":1,"text":"hi"}"#); let to = Ref { author: "x".into(), seq: 2 }; @@ -2019,7 +1974,7 @@ mod tests { kind: Kind::Reaction { to }, ..Entry::message("me", 8, 1, "") }; - let json = serde_json::to_string(&to_frame(reaction)).unwrap(); + let json = serde_json::to_string(&Frame::Msg(reaction.into_wire())).unwrap(); assert_eq!( json, r#"{"t":"msg","seq":8,"ts":1,"hlc":1,"text":"👍","react_to":{"author":"x","seq":2}}"# diff --git a/src-tauri/src/entry.rs b/src-tauri/src/entry.rs index 8ba7778..a2a2127 100644 --- a/src-tauri/src/entry.rs +++ b/src-tauri/src/entry.rs @@ -53,6 +53,60 @@ impl Entry { let kind = Kind::Message { reply_to: None, vanish: None, file: None }; Self { author, seq, ts, hlc: ts, text, kind } } + + /// How this entry goes over the wire, in a `msg` frame. + pub(crate) fn into_wire(self) -> Wire { + let (mut reply_to, mut react_to, mut edit_of, mut delete_of) = (None, None, None, None); + let (mut vanish, mut file) = (None, None); + match self.kind { + Kind::Message { reply_to: to, vanish: v, file: f } => { + (reply_to, vanish, file) = (to, v, f.map(Box::new)) + } + Kind::Reaction { to } => react_to = Some(to), + Kind::Edit { of } => edit_of = Some(of), + Kind::Delete { of } => delete_of = Some(of), + } + let (seq, ts, hlc, text) = (self.seq, self.ts, Some(self.hlc), self.text); + Wire { seq, ts, hlc, text, reply_to, react_to, edit_of, delete_of, vanish, file } + } +} + +/// An entry in the sender's log, as the body of a `msg` frame. Plain, it's a message. +/// +/// The same rules as for frames: new fields must be `#[serde(default)]`, so older peers +/// ignore them, and an existing field never changes its meaning or type. +#[derive(Debug, Serialize, Deserialize)] +pub(crate) struct Wire { + pub seq: u64, + pub ts: i64, + /// Display order (see `Entry::hlc`). Added in 0.5; without it, `ts` is used. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub hlc: Option, + pub text: String, + /// The message this one answers. Added in 0.4; older peers show a plain message. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reply_to: Option, + /// Makes this a reaction to that message: `text` is the emoji, or "" to take the + /// sender's reaction back. Added in 0.4; older peers show the emoji as a message. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub react_to: Option, + /// Makes this new text for one of the sender's own messages. Added in 0.4; older peers + /// show the new text as a message. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub edit_of: Option, + /// Deletes one of the sender's own messages; `text` is "". Added in 0.4; older peers + /// show an empty message. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub delete_of: Option, + /// A vanishing message: each side erases it this many seconds after the recipient + /// has seen it. Added in 0.6, and only sent to peers that say their version in + /// `Hello`: older ones would keep it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub vanish: Option, + /// A file, with `text` as its caption. Added in 0.7, and only sent to peers whose + /// `Hello` lists the `files` feature. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub file: Option>, } /// A file attached to a message, as its sender describes it. Synced with the message; From 8362c2f755ccbab17ba5871ddbcafabdea095c5b Mon Sep 17 00:00:00 2001 From: Justin Williams Date: Wed, 25 Nov 2026 07:37:22 -0800 Subject: [PATCH 3/7] Admission: one place for what a peer's entry must pass Wire::admit turns a msg frame into the entry that's stored, replacing the inline rules in read_loop. The per-kind limits (text, emoji, lifetime, files) live in entry.rs, used strictly for my entries and leniently for a peer's. New tests cover a round trip for every kind, which target counts when a frame names several, and each repair. Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/chat.rs | 142 +---------------------- src-tauri/src/entry.rs | 254 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 259 insertions(+), 137 deletions(-) diff --git a/src-tauri/src/chat.rs b/src-tauri/src/chat.rs index 45ebc6b..e8b51de 100644 --- a/src-tauri/src/chat.rs +++ b/src-tauri/src/chat.rs @@ -40,17 +40,17 @@ use tokio::{ use crate::{ db::{Cursor, Db, FileState, Hit, Message, Page}, - entry::{Entry, FileInfo, Kind, Ref, Wire}, + entry::{ + Entry, FileInfo, Kind, MAX_EMOJI_CHARS, MAX_FILE_BYTES, MAX_TEXT_CHARS, Ref, VANISH_SECS, + Wire, checked_file, clean, is_hash, + }, }; pub const ALPN: &[u8] = b"tightbeam/1"; /// mDNS service name, so we only see other Tightbeam apps (`_tightbeam._udp.local`). const SERVICE: &str = "tightbeam"; const MAX_FRAME: usize = 64 * 1024; -const MAX_TEXT_CHARS: usize = 4000; const MAX_NAME_CHARS: usize = 40; -/// Room for an emoji made of several code points, like a family or a flag. -const MAX_EMOJI_CHARS: usize = 16; const PAIR_PROMPT_TIMEOUT: Duration = Duration::from_secs(120); const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); const REDIAL_EVERY: Duration = Duration::from_secs(3); @@ -58,17 +58,10 @@ const REDIAL_EVERY: Duration = Duration::from_secs(3); const NUDGE_EVERY: Duration = Duration::from_secs(3); /// This build's version, sent in `Hello`. pub const VERSION: &str = env!("CARGO_PKG_VERSION"); -/// How long a vanishing message can last once seen: 5 seconds to 7 days. -const VANISH_SECS: std::ops::RangeInclusive = 5..=7 * 24 * 60 * 60; /// Search shows at most this many matches, the newest. pub const SEARCH_LIMIT: usize = 100; /// An away note is a few words, like "lunch" or "back at 3". const MAX_NOTE_CHARS: usize = 100; -/// The largest file that can be sent: 1 GB. -pub const MAX_FILE_BYTES: u64 = 1 << 30; -const MAX_FILE_NAME_CHARS: usize = 200; -/// Room for a tiny JPEG preview as a `data:` URL. -const MAX_PREVIEW_CHARS: usize = 8 * 1024; /// What this build can do beyond 0.6, said in `Hello`. const FEATURES: &[&str] = &[FILES]; /// Feature: sends and receives files. @@ -1149,47 +1142,8 @@ impl Core { ) -> Result<()> { loop { match read_frame(recv).await? { - Frame::Msg(Wire { - seq, - ts, - hlc, - text, - reply_to, - react_to, - edit_of, - delete_of, - vanish, - file, - }) => { - // A reply to anyone but the two of us becomes a plain message. A - // reaction to a stranger's message, or an edit or delete of anyone's - // but the sender's own, is stored but never shown. A file that's too - // big or badly described is left off. - let kind = match (delete_of, edit_of, react_to) { - (Some(of), ..) => Kind::Delete { of }, - (None, Some(of), _) => Kind::Edit { of }, - (None, None, Some(to)) => Kind::Reaction { to }, - (None, None, None) => { - let reply_to = reply_to.filter(|to| self.is_ours(to, peer)); - let vanish = - vanish.map(|v| v.clamp(*VANISH_SECS.start(), *VANISH_SECS.end())); - let file = file.and_then(|f| checked_file(*f)); - Kind::Message { reply_to, vanish, file } - } - }; - let limit = if matches!(kind, Kind::Reaction { .. }) { - MAX_EMOJI_CHARS - } else { - MAX_TEXT_CHARS - }; - let entry = Entry { - author: peer.to_string(), - seq, - ts, - hlc: hlc.unwrap_or(ts), - text: clean(&text, limit), - kind, - }; + Frame::Msg(wire) => { + let entry = wire.admit(peer, &self.id()); let (is_new, have) = { let db = self.db(); (db.insert(&entry)?, db.max_seq(peer)?) @@ -1721,52 +1675,6 @@ fn features_from(stored: Option<&str>) -> Vec { stored.split(',').filter(|f| !f.is_empty()).map(String::from).collect() } -/// A file's description, tidied, or `None` if it can't be accepted: no valid hash, empty, -/// or over the size limit. Image details that don't make sense are dropped. -fn checked_file(file: FileInfo) -> Option { - if !is_hash(&file.hash) || file.size == 0 || file.size > MAX_FILE_BYTES { - return None; - } - let mut name = clean(&file.name, MAX_FILE_NAME_CHARS); - if name.is_empty() { - name = "file".into(); - } - let mime = file.mime.trim().to_ascii_lowercase(); - let mime_ok = mime.len() <= 100 - && mime.contains('/') - && mime.chars().all(|c| c.is_ascii_alphanumeric() || "/.+-".contains(c)); - let mime = if mime_ok { mime } else { "application/octet-stream".into() }; - let dims = match (file.width, file.height) { - (Some(w), Some(h)) if (1..=100_000).contains(&w) && (1..=100_000).contains(&h) => { - Some((w, h)) - } - _ => None, - }; - let preview = file.preview.filter(|p| { - p.len() <= MAX_PREVIEW_CHARS - && ["data:image/jpeg;base64,", "data:image/png;base64,", "data:image/webp;base64,"] - .iter() - .any(|prefix| p.starts_with(prefix)) - && p.split_once(',').is_some_and(|(_, data)| { - data.chars().all(|c| c.is_ascii_alphanumeric() || "+/=".contains(c)) - }) - }); - Some(FileInfo { - hash: file.hash, - name, - size: file.size, - mime, - width: dims.map(|d| d.0), - height: dims.map(|d| d.1), - preview: preview.filter(|_| dims.is_some()), - }) -} - -/// A BLAKE3 hash as files are named by: 64 lowercase hex digits. -fn is_hash(s: &str) -> bool { - s.len() == 64 && s.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) -} - fn hash_file(path: &Path) -> Result { let mut hasher = blake3::Hasher::new(); hasher.update_reader(std::fs::File::open(path)?)?; @@ -1842,10 +1750,6 @@ fn title_name(name: Option) -> String { name.filter(|n| !n.is_empty()).unwrap_or_else(|| "the other person".into()) } -fn clean(s: &str, max_chars: usize) -> String { - s.trim().chars().take(max_chars).collect() -} - fn now_ms() -> i64 { SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0) } @@ -1998,38 +1902,4 @@ mod tests { assert_eq!(safe.chars().count(), 100); assert!(safe.ends_with(".jpeg")); } - - #[test] - fn file_details_are_checked() { - let good = FileInfo { - hash: "0f".repeat(32), - name: " pic.png ".into(), - size: 10, - mime: "Image/PNG".into(), - width: Some(4), - height: Some(3), - preview: Some("data:image/jpeg;base64,AAAA".into()), - }; - let checked = checked_file(good.clone()).unwrap(); - assert_eq!((checked.name.as_str(), checked.mime.as_str()), ("pic.png", "image/png")); - assert_eq!(checked.preview, good.preview); - - let bad_hash = FileInfo { hash: "../x".into(), ..good.clone() }; - assert!(checked_file(bad_hash).is_none()); - assert!(checked_file(FileInfo { hash: "0F".repeat(32), ..good.clone() }).is_none()); - assert!(checked_file(FileInfo { size: MAX_FILE_BYTES + 1, ..good.clone() }).is_none()); - assert!(checked_file(FileInfo { size: 0, ..good.clone() }).is_none()); - - let odd = checked_file(FileInfo { - mime: "text/html; charset=utf-8".into(), - width: Some(0), - preview: Some("data:image/svg+xml;base64,AAAA".into()), - ..good.clone() - }) - .unwrap(); - assert_eq!(odd.mime, "application/octet-stream"); - assert_eq!((odd.width, odd.height, odd.preview), (None, None, None)); - let script = Some("data:image/jpeg;base64,