1pub fn mint_topic_id(file_hash: &str, sender_hex: &str) -> String {
21 use sha2::{Digest, Sha256};
22 use std::sync::atomic::{AtomicU64, Ordering};
23 static MINTED: AtomicU64 = AtomicU64::new(0);
24 let nanos = web_time::SystemTime::now()
26 .duration_since(web_time::UNIX_EPOCH)
27 .map(|d| d.as_nanos())
28 .unwrap_or(0);
29 let seq = MINTED.fetch_add(1, Ordering::Relaxed);
30 let mut hasher = Sha256::new();
31 hasher.update(b"webxdc-realtime-v1:");
32 hasher.update(file_hash.as_bytes());
33 hasher.update(b":");
34 hasher.update(sender_hex.as_bytes());
35 hasher.update(b":");
36 hasher.update(nanos.to_le_bytes());
37 hasher.update(b":");
38 hasher.update(seq.to_le_bytes());
39 base32_nopad_encode(&hasher.finalize())
40}
41
42pub fn derive_url_topic_id(url: &str, msg_id: &str) -> String {
52 use sha2::{Digest, Sha256};
53 let mut hasher = Sha256::new();
54 hasher.update(b"webxdc-url-realtime-v1:");
55 hasher.update(url.as_bytes());
56 hasher.update(b":");
57 hasher.update(msg_id.as_bytes());
58 base32_nopad_encode(&hasher.finalize())
59}
60
61pub fn base32_nopad_decode(encoded: &[u8]) -> Result<Vec<u8>, String> {
63 let mut out = Vec::with_capacity(encoded.len() * 5 / 8);
64 let (mut buf, mut bits) = (0u64, 0u32);
65 for &c in encoded {
66 let v = match c {
67 b'A'..=b'Z' => c - b'A',
68 b'a'..=b'z' => c - b'a',
69 b'2'..=b'7' => c - b'2' + 26,
70 _ => return Err(format!("invalid base32 character {:?}", c as char)),
71 };
72 buf = (buf << 5) | v as u64;
73 bits += 5;
74 if bits >= 8 {
75 bits -= 8;
76 out.push((buf >> bits) as u8);
77 }
78 }
79 Ok(out)
80}
81
82pub fn base32_nopad_encode(bytes: &[u8]) -> String {
85 const ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
86 let mut out = String::with_capacity((bytes.len() * 8).div_ceil(5));
87 let mut buf: u64 = 0;
88 let mut bits: u32 = 0;
89 for &b in bytes {
90 buf = (buf << 8) | b as u64;
91 bits += 8;
92 while bits >= 5 {
93 bits -= 5;
94 out.push(ALPHABET[((buf >> bits) & 0x1F) as usize] as char);
95 }
96 }
97 if bits > 0 {
98 out.push(ALPHABET[((buf << (5 - bits)) & 0x1F) as usize] as char);
99 }
100 out
101}
102
103#[cfg(test)]
104mod tests {
105 use super::*;
106
107 #[test]
108 fn minted_topic_is_32_bytes_base32() {
109 let t = mint_topic_id("abc123", "deadbeef");
110 assert_eq!(t.len(), 52);
112 assert!(t.chars().all(|c| c.is_ascii_uppercase() || ('2'..='7').contains(&c)));
113 }
114
115 #[test]
116 fn resends_mint_distinct_topics() {
117 let a = mint_topic_id("abc123", "deadbeef");
118 let b = mint_topic_id("abc123", "deadbeef");
119 assert_ne!(a, b, "same file re-sent must start a fresh session topic");
120 }
121
122 #[test]
123 fn base32_matches_rfc4648_vectors() {
124 assert_eq!(base32_nopad_encode(b""), "");
126 assert_eq!(base32_nopad_encode(b"f"), "MY");
127 assert_eq!(base32_nopad_encode(b"fo"), "MZXQ");
128 assert_eq!(base32_nopad_encode(b"foo"), "MZXW6");
129 assert_eq!(base32_nopad_encode(b"foob"), "MZXW6YQ");
130 assert_eq!(base32_nopad_encode(b"fooba"), "MZXW6YTB");
131 assert_eq!(base32_nopad_encode(b"foobar"), "MZXW6YTBOI");
132 }
133}
134
135pub fn peer_signal_content(topic_id: &str, node_addr: Option<&str>) -> String {
139 match node_addr {
140 Some(addr) => serde_json::json!({ "op": "ad", "topic": topic_id, "addr": addr }).to_string(),
141 None => serde_json::json!({ "op": "left", "topic": topic_id }).to_string(),
142 }
143}
144
145pub fn parse_peer_signal(content: &str) -> Option<(String, Option<String>)> {
150 let v: serde_json::Value = serde_json::from_str(content).ok()?;
151 let topic_id = v
152 .get("topic")
153 .and_then(|t| t.as_str())
154 .filter(|t| t.len() == 52 && t.bytes().all(|b| b.is_ascii_uppercase() || (b'2'..=b'7').contains(&b)))?
155 .to_string();
156 let node_addr = match v.get("op").and_then(|o| o.as_str())? {
157 "ad" => Some(v.get("addr").and_then(|a| a.as_str()).filter(|a| !a.is_empty() && a.len() <= 2048)?.to_string()),
158 "left" => None,
159 _ => return None,
160 };
161 Some((topic_id, node_addr))
162}
163
164#[cfg(test)]
165mod url_topic_tests {
166 use super::*;
167
168 #[test]
169 fn a_url_topic_is_deterministic_per_message_and_survives_server_rebuilds() {
170 let a = derive_url_topic_id("https://x.org/app.xdc", "msg1");
171 assert_eq!(a, derive_url_topic_id("https://x.org/app.xdc", "msg1"));
172 assert_eq!(a.len(), 52, "must be a valid 52-char base32 TopicId");
173 assert!(parse_peer_signal(&peer_signal_content(&a, Some("iroh:x"))).is_some());
174 assert_ne!(a, derive_url_topic_id("https://x.org/other.xdc", "msg1"), "different URL = disjoint topics");
175 assert_ne!(a, derive_url_topic_id("https://x.org/app.xdc", "msg2"), "re-share = fresh session");
176 }
177}
178
179#[cfg(test)]
180mod peer_signal_tests {
181 use super::*;
182
183 #[test]
184 fn peer_signal_round_trips_and_bounds() {
185 let topic = "A".repeat(52);
186 let ad = peer_signal_content(&topic, Some("iroh:node/abc"));
187 assert_eq!(parse_peer_signal(&ad), Some((topic.clone(), Some("iroh:node/abc".into()))));
188 let left = peer_signal_content(&topic, None);
189 assert_eq!(parse_peer_signal(&left), Some((topic.clone(), None)));
190
191 assert_eq!(parse_peer_signal(&peer_signal_content("short", Some("a"))), None);
193 let oversized = "a".repeat(2049);
194 assert_eq!(parse_peer_signal(&peer_signal_content(&topic, Some(&oversized))), None);
195 assert_eq!(parse_peer_signal(&format!("{{\"op\":\"warp\",\"topic\":\"{topic}\"}}")), None);
196 assert_eq!(parse_peer_signal("not json"), None);
197 }
198}
199
200#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
202#[serde(default)]
203pub struct MarketplaceApp {
204 pub id: String,
206 pub name: String,
208 pub description: String,
210 pub version: String,
212 pub blossom_hash: String,
214 pub download_url: String,
216 pub size: u64,
218 pub icon_url: Option<String>,
220 pub icon_mime: Option<String>,
222 pub icon_cached: Option<String>,
224 pub categories: Vec<String>,
226 pub changelog: Option<String>,
228 pub developer: Option<String>,
230 pub source_url: Option<String>,
232 pub publisher: String,
234 pub published_at: u64,
236 pub signed_at: u64,
238 pub installed: bool,
240 pub local_path: Option<String>,
242 pub installed_version: Option<String>,
244 pub update_available: bool,
246 pub requested_permissions: String,
249}
250
251use nostr_sdk::prelude::*;
254
255pub const MINIAPP_MARKETPLACE_KIND: u16 = 30078;
258
259pub const MINIAPP_APP_ID: &str = "vector/miniapp";
261
262pub const TRUSTED_PUBLISHER: &str = "npub16ye7evyevwnl0fc9hujsxf9zym72e063awn0pvde0huvpyec5nyq4dg4wn";
265
266pub fn is_safe_app_id(id: &str) -> bool {
271 !id.is_empty()
272 && id.len() <= 128
273 && !id.contains("..")
274 && id.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
275}
276
277pub fn parse_marketplace_event(event: &Event) -> Option<MarketplaceApp> {
278 if event.kind.as_u16() != MINIAPP_MARKETPLACE_KIND {
280 return None;
281 }
282
283 let mut id = None;
285 let mut name = None;
286 let mut description = None;
287 let mut version = None;
288 let mut blossom_hash = None;
289 let mut download_url = None;
290 let mut size: Option<u64> = None;
291 let mut icon_url = None;
292 let mut icon_mime = None;
293 let mut categories = Vec::new();
294 let mut developer = None;
295 let mut source_url = None;
296 let mut requested_permissions = String::new();
297 let mut released_at: Option<u64> = None;
298
299 for tag in event.tags.iter() {
300 let tag_vec: Vec<String> = tag.clone().to_vec();
301 if tag_vec.len() < 2 {
302 continue;
303 }
304
305 match tag_vec[0].as_str() {
306 "d" => id = Some(tag_vec[1].clone()),
307 "name" => name = Some(tag_vec[1].clone()),
308 "description" => description = Some(tag_vec[1].clone()),
309 "version" => version = Some(tag_vec[1].clone()),
310 "x" => blossom_hash = Some(tag_vec[1].clone()),
311 "url" => download_url = Some(tag_vec[1].clone()),
312 "size" => size = tag_vec[1].parse().ok(),
313 "icon" => {
314 icon_url = Some(tag_vec[1].clone());
316 if tag_vec.len() >= 3 {
317 icon_mime = Some(tag_vec[2].clone());
318 }
319 }
320 "dev" => developer = Some(tag_vec[1].clone()),
321 "src" => source_url = Some(tag_vec[1].clone()),
322 "permissions" => {
323 requested_permissions = tag_vec[1].clone();
325 }
326 "published_at" => released_at = tag_vec[1].parse().ok(),
327 "t" => {
328 let tag_value = &tag_vec[1];
330 if tag_value != "miniapp" && tag_value != "webxdc" {
331 categories.push(tag_value.clone());
332 }
333 }
334 _ => {}
335 }
336 }
337
338 let id = id?;
340 if !is_safe_app_id(&id) {
341 log_warn!("[Marketplace] Rejected app with unsafe d-tag id: {:?}", id);
342 return None;
343 }
344 let name = name?;
345 let blossom_hash = blossom_hash?;
346 let download_url = download_url?;
347
348 let publisher = event.pubkey.to_bech32().unwrap_or_else(|_| event.pubkey.to_hex());
349 let created = event.created_at.as_secs();
351 let published_at = released_at.filter(|t| *t <= created).unwrap_or(created);
352
353 Some(MarketplaceApp {
354 id,
355 name,
356 description: description.unwrap_or_default(),
357 version: version.unwrap_or_else(|| "1.0.0".to_string()),
358 blossom_hash,
359 download_url,
360 size: size.unwrap_or(0),
361 icon_url,
362 icon_mime,
363 icon_cached: None,
364 categories,
365 changelog: if event.content.is_empty() { None } else { Some(event.content.clone()) },
366 developer,
367 source_url,
368 publisher,
369 published_at,
370 signed_at: created,
371 installed: false,
372 local_path: None,
373 installed_version: None,
374 update_available: false,
375 requested_permissions,
376 })
377}
378
379pub struct MarketplaceListing<'a> {
381 pub app_id: &'a str,
382 pub name: &'a str,
383 pub description: &'a str,
384 pub version: &'a str,
385 pub categories: Vec<&'a str>,
386 pub changelog: Option<&'a str>,
387 pub developer: Option<&'a str>,
388 pub source_url: Option<&'a str>,
389 pub permissions: Option<&'a str>,
391 pub released_at: Option<u64>,
393}
394
395pub async fn build_marketplace_event<T: crate::signer::VectorSigner>(
397 signer: &T,
398 listing: &MarketplaceListing<'_>,
399 blossom_hash: &str,
400 download_url: &str,
401 size: u64,
402 icon_info: Option<(&str, &str)>, ) -> Result<Event, String> {
404 let tags = marketplace_tags(listing, blossom_hash, download_url, size, icon_info);
405 EventBuilder::new(Kind::from(MINIAPP_MARKETPLACE_KIND), listing.changelog.unwrap_or(""))
406 .tags(tags)
407 .finalize_async(signer)
408 .await
409 .map_err(|e| format!("Failed to sign marketplace event: {}", e))
410}
411
412fn marketplace_tags(
414 listing: &MarketplaceListing<'_>,
415 blossom_hash: &str,
416 download_url: &str,
417 size: u64,
418 icon_info: Option<(&str, &str)>,
419) -> Vec<Tag> {
420 let MarketplaceListing {
421 app_id,
422 name,
423 description,
424 version,
425 ref categories,
426 developer,
427 source_url,
428 permissions,
429 released_at,
430 changelog: _,
431 } = *listing;
432 let mut tags = vec![
433 Tag::custom("d", vec![app_id.to_string()]),
434 Tag::custom("name", vec![name.to_string()]),
435 Tag::custom("description", vec![description.to_string()]),
436 Tag::custom("version", vec![version.to_string()]),
437 Tag::custom("x", vec![blossom_hash.to_string()]),
438 Tag::custom("url", vec![download_url.to_string()]),
439 Tag::custom("size", vec![size.to_string()]),
440 Tag::custom("t", vec!["miniapp".to_string()]),
441 Tag::custom("t", vec!["webxdc".to_string()]),
442 ];
443
444 if let Some((icon_url, mime_type)) = icon_info {
446 let mut icon = vec![icon_url.to_string()];
447 if !mime_type.is_empty() {
448 icon.push(mime_type.to_string());
449 }
450 tags.push(Tag::custom("icon", icon));
451 }
452
453 if let Some(at) = released_at {
454 tags.push(Tag::custom("published_at", vec![at.to_string()]));
455 }
456
457 if let Some(dev) = developer {
459 if !dev.is_empty() {
460 tags.push(Tag::custom(
461 "dev",
462 vec![dev.to_string()]
463 ));
464 }
465 }
466
467 if let Some(src) = source_url {
469 if !src.is_empty() {
470 tags.push(Tag::custom(
471 "src",
472 vec![src.to_string()]
473 ));
474 }
475 }
476
477 for category in categories {
479 tags.push(Tag::custom("t", vec![category.to_string()]));
480 }
481
482 if let Some(perms) = permissions {
484 if !perms.is_empty() {
485 tags.push(Tag::custom(
486 "permissions",
487 vec![perms.to_string()]
488 ));
489 }
490 }
491
492 tags
493}
494
495pub async fn edit_marketplace_listing(
499 current: &MarketplaceApp,
500 listing: &MarketplaceListing<'_>,
501) -> Result<MarketplaceApp, String> {
502 if listing.app_id != current.id {
503 return Err("A listing keeps its App ID".into());
504 }
505 let me = crate::state::my_public_key().ok_or("Not signed in")?;
506 if PublicKey::parse(¤t.publisher).ok() != Some(me) {
507 return Err("Only its publisher can edit this listing".into());
508 }
509 let signer = crate::signer::active_signer()?;
510 let listing = MarketplaceListing {
511 version: ¤t.version,
512 categories: listing.categories.clone(),
513 released_at: Some(current.published_at),
514 ..*listing
515 };
516 let icon = current.icon_url.as_deref().map(|url| (url, current.icon_mime.as_deref().unwrap_or("")));
517 let event = build_marketplace_event(&signer, &listing, ¤t.blossom_hash, ¤t.download_url, current.size, icon).await?;
518 let client = crate::state::nostr_client().ok_or("Not connected")?;
519 crate::inbox_relays::send_event_pool_first_ok(&client, &event)
520 .await
521 .map_err(|e| format!("Failed to publish the listing: {e}"))?;
522 let mut app = parse_marketplace_event(&event).ok_or("The edited listing didn't parse")?;
523 app.icon_cached = current.icon_cached.clone();
524 app.installed = current.installed;
525 app.local_path = current.local_path.clone();
526 app.installed_version = current.installed_version.clone();
527 app.update_available = current.update_available;
528 Ok(app)
529}
530
531#[cfg(test)]
532mod listing_date_tests {
533 use super::*;
534
535 fn listing(created: u64, released: Option<&str>) -> Event {
536 let mut tags = vec![
537 Tag::custom("d", vec!["app".to_string()]),
538 Tag::custom("name", vec!["App".to_string()]),
539 Tag::custom("x", vec!["ab".repeat(32)]),
540 Tag::custom("url", vec!["https://example.com/x".to_string()]),
541 ];
542 if let Some(at) = released {
543 tags.push(Tag::custom("published_at", vec![at.to_string()]));
544 }
545 EventBuilder::new(Kind::from(MINIAPP_MARKETPLACE_KIND), "")
546 .tags(tags)
547 .custom_created_at(Timestamp::from(created))
548 .finalize(&Keys::generate())
549 .unwrap()
550 }
551
552 #[test]
553 fn an_edit_keeps_its_release_date() {
554 assert_eq!(parse_marketplace_event(&listing(2_000, Some("1000"))).unwrap().published_at, 1_000);
555 }
556
557 #[test]
558 fn an_edit_names_the_same_package_and_keeps_its_date() {
559 let listing = MarketplaceListing {
560 app_id: "app", name: "App", description: "New words", version: "1.2.0",
561 categories: vec!["game", "mobile"], changelog: Some("Fixes"), developer: None,
562 source_url: None, permissions: None, released_at: Some(1_000),
563 };
564 let hash = "cd".repeat(32);
565 let tags = marketplace_tags(&listing, &hash, "https://example.com/pkg", 42, Some(("https://example.com/i.png", "")));
566 let event = EventBuilder::new(Kind::from(MINIAPP_MARKETPLACE_KIND), "Fixes")
567 .tags(tags)
568 .custom_created_at(Timestamp::from(5_000))
569 .finalize(&Keys::generate())
570 .unwrap();
571 let app = parse_marketplace_event(&event).unwrap();
572 assert_eq!((app.blossom_hash.as_str(), app.download_url.as_str(), app.size), (hash.as_str(), "https://example.com/pkg", 42));
573 assert_eq!((app.published_at, app.signed_at), (1_000, 5_000));
574 assert_eq!(app.categories, vec!["game", "mobile"]);
575 assert_eq!(app.icon_url.as_deref(), Some("https://example.com/i.png"));
576 assert_eq!(app.icon_mime, None, "no MIME type is written as none, not as empty");
577 }
578
579 #[test]
580 fn a_release_is_dated_by_its_event() {
581 assert_eq!(parse_marketplace_event(&listing(2_000, None)).unwrap().published_at, 2_000);
582 assert_eq!(parse_marketplace_event(&listing(2_000, Some("3000"))).unwrap().published_at, 2_000);
584 assert_eq!(parse_marketplace_event(&listing(2_000, Some("soon"))).unwrap().published_at, 2_000);
585 }
586}
587
588#[cfg(test)]
589mod app_id_tests {
590 use super::is_safe_app_id;
591
592 #[test]
593 fn accepts_normal_ids() {
594 for id in ["com.example.app", "my-cool-app", "abc123", "app.v2", "a"] {
595 assert!(is_safe_app_id(id), "should accept {:?}", id);
596 }
597 assert!(is_safe_app_id(&"x".repeat(128)), "128 chars should be accepted");
598 }
599
600 #[test]
601 fn rejects_traversal_and_unsafe() {
602 for id in ["", "..", "....", "a..b", "../../etc/passwd", "..\\win",
603 "foo/bar", "foo\\bar", "/abs", "C:\\x", "app id", "café"] {
604 assert!(!is_safe_app_id(id), "should reject {:?}", id);
605 }
606 assert!(!is_safe_app_id(&"x".repeat(129)), "129 chars should be rejected");
607 }
608}