Skip to content

Commit 9c69278

Browse files
authored
feat(desktop): adding rich link previews to messages (#3818)
## Overview **Category:** improvement **User impact:** Link previews appear in the composer and travel as privacy-safe sender-authored snapshots, so recipients never contact the linked site merely by opening a conversation. **Problem:** Cold-cache link paste could freeze the composer before the URL painted; recipient-side unfurling leaked visits; invalid or unresolved preview work could interfere with sending or leave dead cards behind. **Solution:** Paint pasted links before starting cold resolver work, resolve only in the sender's composer, attach only complete validated snapshots at Send, and render authored snapshots without recipient fallback fetching. ## Behavior - **Cold paste stays responsive:** bare and angle-bracket URL paste paths commit the visible link before resolver work begins. - **Sender-only fetching:** metadata is resolved while composing; recipients render only the sender-authored snapshot. - **Send never waits:** pending, failed, invalid, and unsendable previews are omitted. They do not block or cancel the message. - **Terminal misses disappear:** failed, timed-out, or 404 resolver results remove the composer card while preserving visible link text. - **Display-text links work:** Markdown links such as `[review the pull request](…)` produce and send the same snapshots as bare URLs. - **Compact and Rich presentation:** Compact remains the default; Rich preserves source description line breaks and paragraphs. - **Immediate draft-wide dismissal:** clicking × immediately hides all previews for the draft, suppresses links pasted later, and emits only `["link-preview", "none"]`. No confirmation detour. Suppression resets after send or clearing the draft. - **Zero recipient fallback:** missing, stale, malformed, off-relay, unsupported, or suppressed snapshots remain ordinary visible links; recipients never regenerate them. ## Implementation - Resolve previews from deferred composer URL state so paste can paint first. - Upload finished preview media to the active community relay and snapshot only valid, sendable media references. - Atomically capture ready snapshots at submit time; never append a late preview after send. - Validate snapshot and suppression tags in desktop/native and relay ingestion, rejecting duplicate or mixed forms. - Render composer previews as stable 55px attachment cards at desktop and narrow widths. - Add deterministic E2E coverage for cold paste, ready/pending/failed/invalid previews, display-text links, multiline Rich descriptions, immediate dismissal, later-pasted links, and suppression reset. ## Validation Validated head: `64f2e2937a2c70e388c132ae14b6be6d11716db8` - Push hooks passed: `check-push-org`, branch skew, desktop check, mobile tests, desktop tests, Rust tests, and desktop Tauri checks. - Focused screenshot E2E at the validated head: 5/5 passed across Compact/Rich composer and recipient states, 800px/420px geometry, display-text links, multiline descriptions, and immediate dismissal. - PR CI was triggered for this exact head and is currently running; completed checks are green at the time of this update. - Worktree is clean and both PR head and validated branch resolve to `64f2e2937…`. ## Screenshots ### Compact composer | Loading | Ready | |---|---| | ![Compact composer loading](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/3818/compact-composer-loading.png) | ![Compact composer ready](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/3818/compact-composer-ready.png) | ### Rich composer | Loading | Ready | |---|---| | ![Rich composer loading](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/3818/rich-composer-loading.png) | ![Rich composer ready](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/3818/rich-composer-ready.png) | ### Responsive composer | 800px loading | 800px ready | |---|---| | ![800px composer loading](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/3818/composer-800-loading.png) | ![800px composer ready](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/3818/composer-800-ready.png) | | 420px loading | 420px ready | |---|---| | ![420px composer loading](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/3818/composer-420-loading.png) | ![420px composer ready](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/3818/composer-420-ready.png) | ### Recipient presentation | Compact | Rich | |---|---| | ![Recipient compact](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/3818/recipient-compact.png) | ![Recipient rich](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/3818/recipient-rich.png) | ### Display-text Markdown link | Composer | Recipient | |---|---| | ![Display-text link in composer](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/3818/display-text-composer.png) | ![Display-text link with recipient preview](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/3818/display-text-recipient.png) | ### Rich multiline description ![Rich preview preserving description paragraphs](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/3818/rich-multiline-recipient.png) ### Immediate dismissal | Before × | Immediately after × | |---|---| | ![Preview before immediate dismissal](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/3818/dismissal-before.png) | ![Composer immediately after preview dismissal](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/3818/dismissal-after.png) | --------- Signed-off-by: Taylor Ho <[email protected]>
1 parent 04cc59e commit 9c69278

55 files changed

Lines changed: 5135 additions & 852 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎crates/buzz-relay/src/handlers/imeta.rs‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,55 @@ fn extract_ext_from_media_url(url: &str) -> Option<&str> {
369369
}
370370
}
371371

372+
/// Validate an authored link-preview media URL/hash pair.
373+
///
374+
/// Empty pairs are allowed. Non-empty media must be an exact, credential-free
375+
/// URL on this tenant's media origin with a content-addressed image path.
376+
pub fn validate_local_image_media_pair(
377+
media_url: &str,
378+
sha256: &str,
379+
media_base_url: &str,
380+
) -> bool {
381+
const IMAGE_EXTS: &[&str] = &["jpg", "png", "gif", "webp"];
382+
if media_url.is_empty() && sha256.is_empty() {
383+
return true;
384+
}
385+
if media_url.is_empty()
386+
|| sha256.len() != 64
387+
|| !sha256.chars().all(|c| matches!(c, '0'..='9' | 'a'..='f'))
388+
{
389+
return false;
390+
}
391+
392+
let Ok(parsed) = url::Url::parse(media_url) else {
393+
return false;
394+
};
395+
let Ok(base) = url::Url::parse(media_base_url) else {
396+
return false;
397+
};
398+
if parsed.scheme() != base.scheme()
399+
|| parsed.host_str() != base.host_str()
400+
|| parsed.port_or_known_default() != base.port_or_known_default()
401+
|| !parsed.username().is_empty()
402+
|| parsed.password().is_some()
403+
|| parsed.query().is_some()
404+
|| parsed.fragment().is_some()
405+
{
406+
return false;
407+
}
408+
409+
let Some(filename) = parsed.path().strip_prefix("/media/") else {
410+
return false;
411+
};
412+
let Some((path_hash, ext)) = filename.split_once('.') else {
413+
return false;
414+
};
415+
!filename.contains('/')
416+
&& !filename.contains('%')
417+
&& path_hash == sha256
418+
&& IMAGE_EXTS.contains(&ext)
419+
}
420+
372421
/// Validate that a URL references a valid local media blob path.
373422
fn is_local_media_url(url: &str, media_base_url: &str) -> bool {
374423
// A safe extension token: 1–8 lowercase alphanumeric chars. Covers media
@@ -423,6 +472,48 @@ mod tests {
423472
const HASH: &str = "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789";
424473
const BASE: &str = "https://relay.example.com/media";
425474

475+
#[test]
476+
fn link_preview_media_pair_requires_exact_local_image_url_and_hash() {
477+
let hash = HASH;
478+
let valid = format!("{BASE}/{hash}.png");
479+
assert!(validate_local_image_media_pair(&valid, hash, BASE));
480+
assert!(!validate_local_image_media_pair(
481+
&format!("https://evil.example/media/{hash}.png"),
482+
hash,
483+
BASE
484+
));
485+
assert!(!validate_local_image_media_pair(
486+
&format!("{BASE}/{hash}.png?token=leak"),
487+
hash,
488+
BASE
489+
));
490+
assert!(!validate_local_image_media_pair(
491+
&format!("{BASE}/{hash}.png#fragment"),
492+
hash,
493+
BASE
494+
));
495+
assert!(!validate_local_image_media_pair(
496+
&format!("https://[email protected]/media/{hash}.png"),
497+
hash,
498+
BASE
499+
));
500+
assert!(!validate_local_image_media_pair(
501+
&format!("{BASE}/{hash}.svg"),
502+
hash,
503+
BASE
504+
));
505+
assert!(!validate_local_image_media_pair(
506+
&format!("{BASE}/{hash}.png/extra"),
507+
hash,
508+
BASE
509+
));
510+
assert!(!validate_local_image_media_pair(
511+
&format!("{BASE}/{hash}.png"),
512+
&"0".repeat(64),
513+
BASE
514+
));
515+
}
516+
426517
#[test]
427518
fn test_local_media_url_relative() {
428519
assert!(is_local_media_url(&format!("/media/{HASH}.jpg"), BASE));

‎crates/buzz-relay/src/handlers/ingest.rs‎

Lines changed: 176 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,72 @@ pub fn reject_with_transport(transport: &'static str, reason: &'static str) {
212212
.increment(1);
213213
}
214214

215+
fn valid_link_preview_text(value: &str, max: usize, allow_newlines: bool) -> bool {
216+
value.len() <= max
217+
&& !value
218+
.chars()
219+
.any(|character| character.is_control() && !(allow_newlines && character == '\n'))
220+
}
221+
222+
fn validate_link_preview_tags(event: &Event, media_base_url: &str) -> Result<(), String> {
223+
const MAX_SNAPSHOTS: usize = 8;
224+
const MAX_TITLE: usize = 300;
225+
const MAX_SITE: usize = 100;
226+
const MAX_DESCRIPTION: usize = 1000;
227+
228+
let mut count = 0;
229+
let mut suppressed = false;
230+
let mut seen = std::collections::HashSet::new();
231+
for tag in event.tags.iter() {
232+
let parts = tag.as_slice();
233+
if parts.first().map(String::as_str) != Some("link-preview") {
234+
continue;
235+
}
236+
count += 1;
237+
if parts == ["link-preview", "none"] {
238+
if count > 1 {
239+
return Err("link-preview suppression cannot include snapshots".into());
240+
}
241+
suppressed = true;
242+
continue;
243+
}
244+
if suppressed
245+
|| count > MAX_SNAPSHOTS
246+
|| parts.len() != 11
247+
|| parts[1] != "snapshot"
248+
|| parts[2] != "1"
249+
{
250+
return Err("invalid link-preview snapshot tag".into());
251+
}
252+
let canonical =
253+
url::Url::parse(&parts[3]).map_err(|_| "invalid link-preview canonical URL")?;
254+
if canonical.scheme() != "https"
255+
|| !canonical.username().is_empty()
256+
|| canonical.password().is_some()
257+
|| canonical.fragment().is_some()
258+
|| !seen.insert(parts[3].clone())
259+
|| !event.content.contains(&parts[3])
260+
{
261+
return Err("invalid link-preview canonical URL".into());
262+
}
263+
for (value, max, allow_newlines) in [
264+
(&parts[4], MAX_TITLE, false),
265+
(&parts[5], MAX_SITE, false),
266+
(&parts[6], MAX_DESCRIPTION, true),
267+
] {
268+
if !valid_link_preview_text(value, max, allow_newlines) {
269+
return Err("invalid link-preview snapshot text".into());
270+
}
271+
}
272+
if !super::imeta::validate_local_image_media_pair(&parts[7], &parts[8], media_base_url)
273+
|| !super::imeta::validate_local_image_media_pair(&parts[9], &parts[10], media_base_url)
274+
{
275+
return Err("link-preview media must reference matching local image blobs".into());
276+
}
277+
}
278+
Ok(())
279+
}
280+
215281
/// Successful ingestion result.
216282
pub struct IngestResult {
217283
/// Hex-encoded event ID.
@@ -2647,15 +2713,20 @@ async fn ingest_event_inner(
26472713
});
26482714
}
26492715

2716+
let tenant_media_base =
2717+
crate::api::media::media_base_url_for_tenant(&state.config.relay_url, tenant.host());
2718+
if kind_u32 == KIND_STREAM_MESSAGE {
2719+
validate_link_preview_tags(&event, &tenant_media_base)
2720+
.map_err(|e| IngestError::Rejected(format!("invalid: {e}")))?;
2721+
}
2722+
26502723
let imeta_tags: Vec<Vec<String>> = event
26512724
.tags
26522725
.iter()
26532726
.filter(|t| t.kind().to_string() == "imeta")
26542727
.map(|t| t.as_slice().iter().map(|s| s.to_string()).collect())
26552728
.collect();
26562729
if !imeta_tags.is_empty() {
2657-
let tenant_media_base =
2658-
crate::api::media::media_base_url_for_tenant(&state.config.relay_url, tenant.host());
26592730
crate::api::validate_imeta_tags(&imeta_tags, &tenant_media_base)
26602731
.map_err(|e| IngestError::Rejected(format!("invalid: {e}")))?;
26612732
crate::api::verify_imeta_blobs(tenant, &imeta_tags, &state.media_storage)
@@ -3632,6 +3703,109 @@ mod tests {
36323703
assert!(validate_diff_event(&event).is_err());
36333704
}
36343705

3706+
#[test]
3707+
fn link_preview_suppression_accepts_blanket_marker() {
3708+
let event = make_event_with_tags(
3709+
KIND_STREAM_MESSAGE,
3710+
"https://example.com",
3711+
&[&["link-preview", "none"]],
3712+
);
3713+
3714+
assert!(validate_link_preview_tags(&event, "https://media.example.com").is_ok());
3715+
}
3716+
3717+
#[test]
3718+
fn link_preview_suppression_rejects_duplicate_marker() {
3719+
let event = make_event_with_tags(
3720+
KIND_STREAM_MESSAGE,
3721+
"https://example.com",
3722+
&[&["link-preview", "none"], &["link-preview", "none"]],
3723+
);
3724+
3725+
assert_eq!(
3726+
validate_link_preview_tags(&event, "https://media.example.com"),
3727+
Err("link-preview suppression cannot include snapshots".into())
3728+
);
3729+
}
3730+
3731+
#[test]
3732+
fn link_preview_suppression_rejects_mixed_snapshot_tags_in_either_order() {
3733+
let snapshot = [
3734+
"link-preview",
3735+
"snapshot",
3736+
"1",
3737+
"https://example.com",
3738+
"Example",
3739+
"Example",
3740+
"Description",
3741+
"",
3742+
"",
3743+
"",
3744+
"",
3745+
];
3746+
for tags in [
3747+
vec![&["link-preview", "none"][..], &snapshot[..]],
3748+
vec![&snapshot[..], &["link-preview", "none"][..]],
3749+
] {
3750+
let event = make_event_with_tags(KIND_STREAM_MESSAGE, "https://example.com", &tags);
3751+
assert!(validate_link_preview_tags(&event, "https://media.example.com").is_err());
3752+
}
3753+
}
3754+
3755+
fn make_link_preview_event(title: &str, site: &str, description: &str) -> Event {
3756+
make_event_with_tags(
3757+
KIND_STREAM_MESSAGE,
3758+
"https://example.com",
3759+
&[&[
3760+
"link-preview",
3761+
"snapshot",
3762+
"1",
3763+
"https://example.com",
3764+
title,
3765+
site,
3766+
description,
3767+
"",
3768+
"",
3769+
"",
3770+
"",
3771+
]],
3772+
)
3773+
}
3774+
3775+
#[test]
3776+
fn link_preview_snapshot_accepts_description_newlines() {
3777+
let event = make_link_preview_event(
3778+
"Example title",
3779+
"Example site",
3780+
"First paragraph\n\nSecond paragraph",
3781+
);
3782+
3783+
assert!(validate_link_preview_tags(&event, "https://media.example.com").is_ok());
3784+
}
3785+
3786+
#[test]
3787+
fn link_preview_snapshot_rejects_title_and_site_newlines() {
3788+
for (title, site) in [
3789+
("Example\ntitle", "Example site"),
3790+
("Example title", "Example\nsite"),
3791+
] {
3792+
let event = make_link_preview_event(title, site, "Description");
3793+
assert!(validate_link_preview_tags(&event, "https://media.example.com").is_err());
3794+
}
3795+
}
3796+
3797+
#[test]
3798+
fn link_preview_snapshot_rejects_non_newline_controls_in_all_text_fields() {
3799+
for (title, site, description) in [
3800+
("Example\ttitle", "Example site", "Description"),
3801+
("Example title", "Example\rsite", "Description"),
3802+
("Example title", "Example site", "Unsafe\tdescription"),
3803+
] {
3804+
let event = make_link_preview_event(title, site, description);
3805+
assert!(validate_link_preview_tags(&event, "https://media.example.com").is_err());
3806+
}
3807+
}
3808+
36353809
fn make_dummy_event() -> Event {
36363810
let keys = nostr::Keys::generate();
36373811
nostr::EventBuilder::new(nostr::Kind::Custom(9), "")

0 commit comments

Comments
 (0)