Skip to main content
← rust.krizaka.comkrizaka.com

krizaka_rust/
deep_link.rs

1//! Deep links: `verikora://app/bibliotheque/bail?tags=2026` or `https://www.verikora.com/app/bibliotheque/bail` opens the
2//! same screen as the web (the URL is the state). A link becomes a **route inside the app** (`/app/bibliotheque/bail?tags=2026`)
3//! or is refused; it is never a place the window navigates to.
4//!
5//! The custom scheme reads like Expo Router's: `verikora://app/x` is the route `/app/x` (the "host" is the first segment).
6//! A web link is accepted only on the product's own hosts. The route keeps its query, drops its fragment, and may only start
7//! with one of the product's prefixes when it gives some.
8
9use url::Url;
10
11/// The longest link the app accepts; anything longer is refused rather than cut.
12// @fixed: the length of a link a person can follow, not a setting
13pub const MAX_LINK: usize = 2048;
14
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct LinkRules {
17    /// The product's scheme, lowercase (`verikora`).
18    pub scheme: String,
19    /// The product's web hosts whose links open the app (`www.verikora.com`, `dev.verikora.com`).
20    pub hosts: Vec<String>,
21    /// The routes a link may open (`/app`, `/verify`); empty means every route.
22    pub prefixes: Vec<String>,
23}
24
25#[derive(Debug, PartialEq, Eq)]
26pub enum LinkError {
27    TooLong,
28    Invalid,
29    /// Another scheme, or a web link on a host that is not the product's.
30    NotOurs,
31    /// A route the product does not open from a link, or that could leave the app (`//host`, `..`, a backslash).
32    Refused(String),
33}
34
35impl std::fmt::Display for LinkError {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        match self {
38            LinkError::TooLong => write!(f, "the link is too long"),
39            LinkError::Invalid => write!(f, "not a valid link"),
40            LinkError::NotOurs => write!(f, "not a link to this app"),
41            LinkError::Refused(route) => write!(f, "this link does not open in the app: {route}"),
42        }
43    }
44}
45
46impl std::error::Error for LinkError {}
47
48/// The route a link opens, or why it does not.
49pub fn route(rules: &LinkRules, link: &str) -> Result<String, LinkError> {
50    let link = link.trim();
51    if link.len() > MAX_LINK {
52        return Err(LinkError::TooLong);
53    }
54    if link.chars().any(|c| c.is_control() || c == '\\') {
55        return Err(LinkError::Invalid);
56    }
57    let url = Url::parse(link).map_err(|_| LinkError::Invalid)?;
58    if !url.username().is_empty() || url.password().is_some() {
59        return Err(LinkError::Invalid);
60    }
61    let path = if url.scheme() == rules.scheme {
62        match url.host_str() {
63            Some(first) if !first.is_empty() => format!("/{first}{}", url.path()),
64            _ => url.path().to_string(),
65        }
66    } else if url.scheme() == "https"
67        && url.port().is_none()
68        && url
69            .host_str()
70            .is_some_and(|h| rules.hosts.iter().any(|ours| ours.eq_ignore_ascii_case(h)))
71    {
72        url.path().to_string()
73    } else {
74        return Err(LinkError::NotOurs);
75    };
76    let path = match path.trim_end_matches('/') {
77        "" => "/".to_string(),
78        trimmed => trimmed.to_string(),
79    };
80    if !path.starts_with('/')
81        || path.starts_with("//")
82        || path
83            .split('/')
84            .any(|s| s == ".." || s == "." || s.eq_ignore_ascii_case("%2e%2e"))
85    {
86        return Err(LinkError::Refused(path));
87    }
88    let allowed = rules.prefixes.is_empty()
89        || rules
90            .prefixes
91            .iter()
92            .any(|p| path == *p || path.starts_with(&format!("{}/", p.trim_end_matches('/'))));
93    if !allowed {
94        return Err(LinkError::Refused(path));
95    }
96    Ok(match url.query() {
97        Some(q) if !q.is_empty() => format!("{path}?{q}"),
98        _ => path,
99    })
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105
106    fn rules() -> LinkRules {
107        LinkRules {
108            scheme: "verikora".into(),
109            hosts: vec!["www.verikora.com".into(), "dev.verikora.com".into()],
110            prefixes: vec!["/app".into(), "/verify".into()],
111        }
112    }
113
114    #[test]
115    fn the_scheme_reads_like_expo_router_and_keeps_the_query() {
116        assert_eq!(
117            route(&rules(), "verikora://app/bibliotheque/bail?tags=2026").unwrap(),
118            "/app/bibliotheque/bail?tags=2026"
119        );
120        assert_eq!(
121            route(&rules(), "verikora:///app/rapports").unwrap(),
122            "/app/rapports"
123        );
124        assert_eq!(route(&rules(), "verikora://app/").unwrap(), "/app");
125        assert_eq!(
126            route(&rules(), "verikora://verify/abc#top").unwrap(),
127            "/verify/abc"
128        );
129    }
130
131    #[test]
132    fn a_web_link_opens_the_app_only_on_the_products_hosts() {
133        assert_eq!(
134            route(&rules(), "https://www.verikora.com/app/verifications/42").unwrap(),
135            "/app/verifications/42"
136        );
137        assert_eq!(
138            route(&rules(), "https://DEV.verikora.com/app").unwrap(),
139            "/app"
140        );
141        for other in [
142            "https://www.verikora.com.evil.example/app",
143            "https://evil.example/app",
144            "http://www.verikora.com/app",
145            "https://www.verikora.com:8443/app",
146            "sovkora://app/x",
147            "javascript:alert(1)",
148            "file:///etc/passwd",
149        ] {
150            assert_eq!(route(&rules(), other), Err(LinkError::NotOurs), "{other}");
151        }
152    }
153
154    #[test]
155    fn a_route_outside_the_prefixes_or_one_that_could_leave_the_app_is_refused() {
156        for bad in [
157            "verikora://admin/users",
158            "verikora://application",
159            "https://www.verikora.com/",
160            "verikora:////evil.example/app",
161        ] {
162            assert!(
163                matches!(route(&rules(), bad), Err(LinkError::Refused(_))),
164                "{bad}"
165            );
166        }
167        // Dot segments are resolved under the link's first segment: they can never climb out of it.
168        assert_eq!(
169            route(&rules(), "verikora://app/a/../../admin").unwrap(),
170            "/app/admin"
171        );
172        assert_eq!(
173            route(&rules(), "https://www.verikora.com/app/../admin"),
174            Err(LinkError::Refused("/admin".into()))
175        );
176        for invalid in [
177            "verikora://app/a\\b",
178            "verikora://app/\u{0}",
179            "https://u:p@www.verikora.com/app",
180            "not a link",
181        ] {
182            assert_eq!(
183                route(&rules(), invalid),
184                Err(LinkError::Invalid),
185                "{invalid}"
186            );
187        }
188    }
189
190    #[test]
191    fn no_prefixes_means_every_route_and_a_long_link_is_refused_not_cut() {
192        let open = LinkRules {
193            prefixes: vec![],
194            ..rules()
195        };
196        assert_eq!(route(&open, "verikora://tarifs").unwrap(), "/tarifs");
197        assert_eq!(route(&open, "verikora://").unwrap(), "/");
198        let long = format!("verikora://app/{}", "a".repeat(MAX_LINK));
199        assert_eq!(route(&rules(), &long), Err(LinkError::TooLong));
200    }
201}