Skip to main content

vector_core/
webxdc.rs

1//! WebXDC Mini App helpers shared across transports (DM + Community).
2//!
3//! The realtime-channel topic for a Mini App is minted ONCE at send time and
4//! carried on the file event as a `webxdc-topic` tag, so every participant
5//! joins the SAME gossip topic. Locally-derived topics are asymmetric in DMs
6//! (each side's chat_id is the other party's npub), which silently splits the
7//! players onto disjoint topics — the tag is the single source of truth.
8
9/// Mint a fresh realtime-channel topic id for an outbound `.xdc` attachment.
10///
11/// 32 bytes of SHA-256 over a domain separator + file hash + sender + send-time
12/// nanos + a per-process counter, encoded base32 (RFC 4648, no padding) — the
13/// same codec the miniapp realtime layer's `decode_topic_id` expects, so the tag
14/// value round-trips into an iroh `TopicId`.
15///
16/// The counter is what actually guarantees re-sends are distinct sessions. The
17/// clock cannot: `SystemTime::now()` reports nanos but does not RESOLVE them, so
18/// two sends of the same file inside one tick hashed identical input and minted
19/// the same topic — the "fresh" session silently rejoined the previous one.
20pub 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    // device-clock: entropy for an id, not a time anyone reads.
25    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
42/// Derive the realtime topic for a URL-shared Mini App.
43///
44/// A pasted `.xdc` URL has no file event to carry a minted topic, so every
45/// recipient derives the same one from what the message already gives them:
46/// the URL string and the message id (which keeps re-shares distinct
47/// sessions, the role nanos+counter play in `mint_topic_id`). Deliberately
48/// NOT the content hash: servers rebuild identical apps into new bytes, and
49/// players who tapped the same card at different times must still share a
50/// session — the message is the session anchor, the URL only the source.
51pub 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
61/// BASE32 no-pad decoding (RFC 4648), the inverse of [`base32_nopad_encode`].
62pub 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
82/// BASE32 no-pad encoding (RFC 4648). Mirrors the miniapp realtime layer's
83/// codec exactly — the two must agree for topic tags to decode.
84pub 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        // 32 bytes → ceil(256/5) = 52 base32 chars
111        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        // RFC 4648 §10 test vectors (padding stripped)
125        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
135/// The kind-3310 peer-signal content on the Concord chat plane:
136/// `{"op":"ad","topic":..,"addr":..}` advertises an Iroh node, `{"op":"left",..}`
137/// departs.
138pub 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
145/// Parse + bound a kind-3310 peer signal: `Some((topic, Some(addr)))` for an
146/// advertisement, `Some((topic, None))` for a departure. Both fields are
147/// author-controlled: the topic must be a 52-char base32 TopicId and the addr is
148/// size-bounded — the realtime layer's decode is the final word.
149pub 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        // Author-controlled fields are bounded: bad topic, oversized addr, junk op.
192        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/// Represents a Mini App listing in the marketplace
201#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
202#[serde(default)]
203pub struct MarketplaceApp {
204    /// Unique identifier (from d-tag)
205    pub id: String,
206    /// Display name
207    pub name: String,
208    /// Description
209    pub description: String,
210    /// Version string
211    pub version: String,
212    /// Blossom SHA-256 hash of the .xdc file
213    pub blossom_hash: String,
214    /// Full Blossom download URL
215    pub download_url: String,
216    /// File size in bytes
217    pub size: u64,
218    /// Optional icon URL (Blossom)
219    pub icon_url: Option<String>,
220    /// Optional icon MIME type (e.g., "image/png", "image/svg+xml")
221    pub icon_mime: Option<String>,
222    /// Locally cached icon path (for offline support)
223    pub icon_cached: Option<String>,
224    /// Categories/tags
225    pub categories: Vec<String>,
226    /// Extended description or changelog (from content)
227    pub changelog: Option<String>,
228    /// Developer name (the actual creator of the game/app)
229    pub developer: Option<String>,
230    /// Source code or website URL
231    pub source_url: Option<String>,
232    /// Publisher's public key (npub)
233    pub publisher: String,
234    /// When it was released: the event's time, or the date an edit of it carries
235    pub published_at: u64,
236    /// When this copy was signed: of an app's copies, the newest is the app
237    pub signed_at: u64,
238    /// Whether this app is installed locally
239    pub installed: bool,
240    /// Local file path if installed
241    pub local_path: Option<String>,
242    /// Installed version (if different from marketplace version, update is available)
243    pub installed_version: Option<String>,
244    /// Whether an update is available (marketplace version != installed version)
245    pub update_available: bool,
246    /// Requested permissions (comma-separated string for easy serialization)
247    /// Format: "microphone,camera,fullscreen"
248    pub requested_permissions: String,
249}
250
251// ─── Marketplace listings (kind 30078, `t=miniapp`) ─────────────────────────
252
253use nostr_sdk::prelude::*;
254
255/// The event kind for Mini App marketplace listings
256/// Kind 30078 = Parameterized Replaceable Application-Specific Data
257pub const MINIAPP_MARKETPLACE_KIND: u16 = 30078;
258
259/// The application identifier for Vector Mini Apps marketplace
260pub const MINIAPP_APP_ID: &str = "vector/miniapp";
261
262/// Trusted publisher npub (only apps from this pubkey are shown initially)
263/// This is the Vector project's official npub for publishing verified apps
264pub const TRUSTED_PUBLISHER: &str = "npub16ye7evyevwnl0fc9hujsxf9zym72e063awn0pvde0huvpyec5nyq4dg4wn";
265
266/// Parse a Nostr event into a MarketplaceApp
267/// A marketplace `d`-tag id is attacker-controlled and becomes a filesystem path (`<id>.xdc`).
268/// Allow only a bounded, separator-free, traversal-free token so an id can never escape the
269/// miniapps dir. Permits reverse-DNS / slug / hash ids; bans `/`, `\`, `..`, absolute/UNC paths.
270pub 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    // Verify it's the correct kind
279    if event.kind.as_u16() != MINIAPP_MARKETPLACE_KIND {
280        return None;
281    }
282
283    // Extract required tags
284    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 tag format: ["icon", "<url>", "<mime-type>"]
315                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                // Permissions tag format: ["permissions", "microphone,camera,fullscreen"]
324                requested_permissions = tag_vec[1].clone();
325            }
326            "published_at" => released_at = tag_vec[1].parse().ok(),
327            "t" => {
328                // Skip the generic "miniapp" and "webxdc" tags for categories
329                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    // Validate required fields
339    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    // An edited listing keeps the release date it carries; one claimed after the event itself isn't believed.
350    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
379/// The publisher-supplied metadata of a marketplace listing.
380pub 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    /// Comma-separated permissions string
390    pub permissions: Option<&'a str>,
391    /// The release date an edit keeps (`published_at` tag); None for a new release, dated by the event.
392    pub released_at: Option<u64>,
393}
394
395/// Build a Nostr event for publishing a Mini App to the marketplace
396pub 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)>, // (url, mime_type)
403) -> 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
412/// A listing's tags; an icon without a known MIME type is written without one.
413fn 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    // Add optional icon with MIME type: ["icon", "<url>", "<mime-type>"]
445    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    // Add optional developer name
458    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    // Add optional source URL
468    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    // Add category tags
478    for category in categories {
479        tags.push(Tag::custom("t", vec![category.to_string()]));
480    }
481
482    // Add optional permissions tag
483    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
495/// Re-sign a listing's metadata over the package it already names: its text, tags and
496/// permissions change, its download and release date don't. Only its publisher can, as
497/// the replacement is keyed by their pubkey. The version stays the package's.
498pub 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(&current.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: &current.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, &current.blossom_hash, &current.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        // A release date after the event, or one that isn't a number, isn't believed.
583        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}