Skip to main content

vector_core/
deep_link.rs

1//! Deep links: the places a link opens in Vector, in the one grammar every client parses.
2//!
3//! A place is a path: `profile/<npub>`, `emojis/pack/<naddr>`, `dm/<npub>`,
4//! `settings[/<category>[/<section>[/<group>]]]`, `nexus[/<app>]` or `requests`. It rides `vector://<path>`,
5//! Vector Web's own address `https://web.vectorapp.io/#<path>`, and a Vector link's fragment
6//! (`https://vectorapp.io/go#<path>`). The website's own paths carry only the places it has a
7//! page for (profiles, emoji packs, DMs), so the rest of its namespace stays the website's.
8//! Vector links (golink.rs) and community invites keep their own shapes. A link only opens a
9//! place: joining, launching or changing anything there still takes the user's tap.
10
11use serde::Serialize;
12
13use crate::golink::GoLink;
14
15/// Vector Web's own address: a place rides its fragment, which never reaches the server.
16pub const WEB_BASE: &str = "https://web.vectorapp.io/#";
17
18/// What a link opens, as the frontend's `executeDeepLinkAction` takes it.
19#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
20pub struct DeepLinkAction {
21    /// profile | emoji_pack | chat | settings | nexus | requests | go | community_invite
22    pub action_type: String,
23    /// An npub, an naddr, a chat id, `category[/section]`, an app id, a Vector link's payload,
24    /// or an invite's whole URL; empty for a place with nothing to name.
25    pub target: String,
26    /// For "chat": the message to land on.
27    #[serde(skip_serializing_if = "Option::is_none")]
28    pub message: Option<String>,
29    /// For "chat": a call answered from a notification, taken up once it rings here.
30    #[serde(skip_serializing_if = "Option::is_none")]
31    pub call: Option<String>,
32    /// The npub the action belongs to; dropped if a different account is live when it's taken.
33    #[serde(skip_serializing_if = "Option::is_none")]
34    pub account: Option<String>,
35}
36
37fn action(action_type: &str, target: impl Into<String>) -> DeepLinkAction {
38    DeepLinkAction { action_type: action_type.to_string(), target: target.into(), ..Default::default() }
39}
40
41/// The action a URL opens, or `None` when it isn't a Vector deep link.
42pub fn parse_deep_link(url: &str) -> Option<DeepLinkAction> {
43    let url = url.trim();
44
45    if let Some(link) = GoLink::parse_url(url) {
46        return Some(action("go", link.payload()));
47    }
48    if let Some(payload) = crate::golink::go_payload(url) {
49        return parse_path(payload).filter(|a| in_app_only(&a.action_type));
50    }
51
52    // Invites carry their secret in the fragment, which the path parser strips: the join flow
53    // re-parses the whole URL.
54    if let Some((before, frag)) = url.split_once('#') {
55        if !frag.is_empty() && is_invite_locator(before) {
56            return Some(action("community_invite", url));
57        }
58    }
59
60    if let Some(path) = url.strip_prefix(WEB_BASE).or_else(|| url.strip_prefix("vector://")) {
61        return parse_path(path);
62    }
63    let path = url.strip_prefix("https://vectorapp.io/").or_else(|| url.strip_prefix("http://vectorapp.io/"))?;
64    parse_path(path).filter(|a| !in_app_only(&a.action_type))
65}
66
67/// A place with no page on the website, so its web link is a Vector link (`go#…`).
68fn in_app_only(action_type: &str) -> bool {
69    matches!(action_type, "settings" | "nexus" | "requests")
70}
71
72fn parse_path(path: &str) -> Option<DeepLinkAction> {
73    let path = path.split(['?', '#']).next().unwrap_or_default();
74    let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
75    match segments.as_slice() {
76        ["profile", npub, ..] => valid_npub(npub).then(|| action("profile", *npub)),
77        ["dm", npub] => valid_npub(npub).then(|| action("chat", *npub)),
78        // `emojis/pack/<naddr>` matches the website's route and the app's share links.
79        ["emojis", "pack", naddr, ..] => {
80            let naddr = strip_html_suffix(naddr);
81            valid_naddr(naddr).then(|| action("emoji_pack", naddr))
82        }
83        ["settings", rest @ ..] => (rest.len() <= 3 && rest.iter().all(|s| settings_id(s))).then(|| action("settings", rest.join("/"))),
84        ["nexus"] => Some(action("nexus", "")),
85        ["nexus", app] => crate::webxdc::is_safe_app_id(app).then(|| action("nexus", *app)),
86        ["requests"] => Some(action("requests", "")),
87        _ => None,
88    }
89}
90
91/// npub1 and 58 bech32 characters.
92fn valid_npub(npub: &str) -> bool {
93    npub.starts_with("npub1") && npub.len() == 63
94}
95
96/// A plausible naddr: the pack modal decodes it and says so when it can't.
97fn valid_naddr(naddr: &str) -> bool {
98    naddr.starts_with("naddr1") && naddr.len() >= 30
99}
100
101/// A Settings category, section or group id; an unknown one opens Settings where it would anyway.
102fn settings_id(s: &str) -> bool {
103    s.len() <= 32 && s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
104}
105
106/// The locator half of an invite link (everything before the `#`).
107///
108/// The bundle coordinate rides as an naddr path segment (`/invite/<naddr>`) and is honoured
109/// from ANY host: the naddr+fragment self-authenticates and the domain is never contacted, so
110/// an Armada-minted link joins natively. Mirrors the frontend's `isCommunityInviteUrl`.
111fn is_invite_locator(before: &str) -> bool {
112    match before.rsplit_once("/invite/") {
113        Some((_, naddr)) => valid_naddr(strip_html_suffix(naddr.trim_end_matches('/'))),
114        None => false,
115    }
116}
117
118/// Some link expanders and mobile launchers append `.html` to a URL that looks like a file path.
119fn strip_html_suffix(s: &str) -> &str {
120    s.strip_suffix(".html").unwrap_or(s)
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126
127    const NADDR: &str = "naddr1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq";
128
129    fn npub() -> String {
130        format!("npub1{}", "q".repeat(58))
131    }
132
133    fn opens(url: &str) -> Option<(String, String)> {
134        parse_deep_link(url).map(|a| (a.action_type, a.target))
135    }
136
137    #[test]
138    fn every_place_opens_from_the_app_scheme_the_website_and_vector_web() {
139        let npub = npub();
140        let places = [
141            (format!("profile/{npub}"), "profile", npub.clone()),
142            (format!("dm/{npub}"), "chat", npub.clone()),
143            (format!("emojis/pack/{NADDR}"), "emoji_pack", NADDR.to_string()),
144            ("settings".to_string(), "settings", String::new()),
145            ("settings/network".to_string(), "settings", "network".to_string()),
146            ("settings/network/relays".to_string(), "settings", "network/relays".to_string()),
147            ("settings/appearance/display/composer".to_string(), "settings", "appearance/display/composer".to_string()),
148            ("nexus".to_string(), "nexus", String::new()),
149            ("nexus/chess.v2_beta".to_string(), "nexus", "chess.v2_beta".to_string()),
150            ("requests".to_string(), "requests", String::new()),
151        ];
152        for (path, kind, target) in places {
153            let web_link = if in_app_only(kind) { format!("https://vectorapp.io/go#{path}") } else { format!("https://vectorapp.io/{path}") };
154            for url in [format!("vector://{path}"), web_link, format!("{WEB_BASE}{path}")] {
155                assert_eq!(opens(&url), Some((kind.to_string(), target.clone())), "{url}");
156            }
157        }
158    }
159
160    #[test]
161    fn the_website_keeps_its_paths_for_places_it_has_no_page_for() {
162        for path in ["settings/privacy", "nexus/chess", "requests"] {
163            assert_eq!(parse_deep_link(&format!("https://vectorapp.io/{path}")), None, "{path}");
164            assert!(parse_deep_link(&format!("vector://go#{path}")).is_some(), "{path}");
165            assert!(parse_deep_link(&format!("{WEB_BASE}go/{path}")).is_some(), "{path}");
166        }
167        assert_eq!(parse_deep_link(&format!("https://vectorapp.io/go#profile/{}", npub())), None, "a go link carries only in-app places");
168        assert!(crate::golink::is_go_url("https://vectorapp.io/go#settings/privacy"), "and is never fetched for a preview");
169    }
170
171    #[test]
172    fn a_place_that_names_something_malformed_opens_nothing() {
173        for url in [
174            "vector://profile/notanpub".to_string(),
175            format!("vector://dm/{}/extra", npub()),
176            "vector://emojis/pack/naddr1short".to_string(),
177            "vector://settings/network/relays/more/deeper".to_string(),
178            "vector://settings/Network".to_string(),
179            "vector://settings/../danger".to_string(),
180            "vector://nexus/../../etc".to_string(),
181            "vector://nexus/a/b".to_string(),
182            "vector://requests/x".to_string(),
183            "vector://unknown".to_string(),
184            format!("https://evil.example/profile/{}", npub()),
185            format!("https://web.vectorapp.io/profile/{}", npub()),
186        ] {
187            assert_eq!(parse_deep_link(&url), None, "{url}");
188        }
189    }
190
191    #[test]
192    fn a_query_or_fragment_after_a_place_is_ignored() {
193        assert_eq!(opens("vector://settings/network?from=docs#top"), Some(("settings".into(), "network".into())));
194        assert_eq!(opens(&format!("https://vectorapp.io/emojis/pack/{NADDR}.html")), Some(("emoji_pack".into(), NADDR.into())));
195    }
196
197    // A retired fragment-only link is not an invite.
198    #[test]
199    fn a_fragment_only_invite_link_is_not_an_invite() {
200        for url in ["vector://invite#AgEs3q1MZz0", "https://vectorapp.io/invite#AgEs3q1MZz0"] {
201            assert!(parse_deep_link(url).map(|a| a.action_type) != Some("community_invite".into()), "{url}");
202        }
203    }
204
205    // The bundle coordinate rides in the PATH (`/invite/<naddr>#<frag>`), and the community-invite
206    // catch runs BEFORE the path parser strips the fragment. Any host counts: the naddr+fragment
207    // self-authenticates.
208    #[test]
209    fn v2_naddr_invite_parses_from_every_host() {
210        for url in [
211            format!("vector://invite/{NADDR}#BAHs3q1MZz0aBcDeF"),
212            format!("https://vectorapp.io/invite/{NADDR}#BAHs3q1MZz0aBcDeF"),
213            format!("https://armada.buzz/invite/{NADDR}#BAHs3q1MZz0aBcDeF"),
214        ] {
215            let action = parse_deep_link(&url).unwrap_or_else(|| panic!("{url}"));
216            assert_eq!(action.action_type, "community_invite");
217            assert_eq!(action.target, url, "join flow re-parses the full URL");
218        }
219    }
220
221    #[test]
222    fn invite_without_fragment_is_not_an_invite() {
223        assert!(parse_deep_link("vector://invite").is_none());
224    }
225
226    #[test]
227    fn invite_path_that_is_not_an_naddr_is_not_an_invite() {
228        assert!(parse_deep_link("https://vectorapp.io/invite/npub1abc#frag").is_none());
229        assert!(parse_deep_link("https://evil.example/invite/naddr1#frag").is_none());
230    }
231
232    #[test]
233    fn fragment_on_non_invite_paths_does_not_hijack() {
234        assert!(parse_deep_link("vector://profile/notanpub#x").is_none());
235        let npub = npub();
236        assert_eq!(opens(&format!("vector://profile/{npub}")), Some(("profile".into(), npub)));
237    }
238
239    #[test]
240    fn a_vector_link_opens_from_every_carrier() {
241        let payload = format!("c/{}/{}", "a".repeat(64), "b".repeat(64));
242        for url in [format!("https://vectorapp.io/go#{payload}"), format!("vector://go#{payload}"), format!("{WEB_BASE}go/{payload}")] {
243            assert_eq!(opens(&url), Some(("go".into(), payload.clone())), "{url}");
244        }
245        assert!(parse_deep_link("https://vectorapp.io/go#c/not-an-id").is_none());
246        assert!(parse_deep_link("https://vectorapp.io/go").is_none());
247    }
248}