cosmic_applet_avestruz/
links.rs1use nostr_sdk::prelude::Url;
11
12#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum OpenError {
15 NotWeb,
17 Failed(String),
19}
20
21fn is_web(url: &str) -> bool {
23 Url::parse(url).is_ok_and(|parsed| matches!(parsed.scheme(), "http" | "https"))
24}
25
26pub 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}