Skip to main content

cosmic_applet_avestruz/
links.rs

1// SPDX-License-Identifier: MIT
2
3//! Opening a link in the system's browser.
4//!
5//! Every address opened comes from somebody else: whoever wrote a note, or
6//! a remote signer asking for approval. Only web links are handed over.
7//! `file:` and every other scheme the desktop would act on are refused
8//! here, whatever the caller let through.
9
10use nostr_sdk::prelude::Url;
11
12/// Why a link was not opened.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum OpenError {
15    /// It is not a web address.
16    NotWeb,
17    /// The desktop could not open it.
18    Failed(String),
19}
20
21/// Whether `url` is a web address: `http` or `https`.
22fn is_web(url: &str) -> bool {
23    Url::parse(url).is_ok_and(|parsed| matches!(parsed.scheme(), "http" | "https"))
24}
25
26/// Open `url` in the system's browser, if it is a web address.
27pub fn open_in_browser(url: &str) -> Result<(), OpenError> {
28    if !is_web(url) {
29        return Err(OpenError::NotWeb);
30    }
31    open::that_detached(url).map_err(|e| OpenError::Failed(e.to_string()))
32}
33
34#[cfg(test)]
35mod tests {
36    use super::{OpenError, is_web, open_in_browser};
37
38    #[test]
39    fn only_web_addresses_are_opened() {
40        assert!(is_web("https://example.com/a?b=c"));
41        assert!(is_web("http://example.com"));
42
43        for other in ["file:///etc/passwd", "javascript:alert(1)", "mailto:a@example.com", "example.com", "", "ssh://host"] {
44            assert!(!is_web(other), "{other}");
45            assert_eq!(open_in_browser(other), Err(OpenError::NotWeb), "{other}");
46        }
47    }
48}