refactor(subscription): decode deep links in the subscription crate

This commit is contained in:
Tunglies
2026-11-30 19:09:13 +08:00
parent f338f1625a
commit c95c8ac2ce
3 changed files with 65 additions and 44 deletions
@@ -0,0 +1,59 @@
use percent_encoding::percent_decode_str;
use std::borrow::Cow;
use url::Url;
pub struct SubscriptionLink<'a> {
pub url: Cow<'a, str>,
pub name: Option<Cow<'a, str>>,
}
pub fn decode_subscription_link(link: &Url) -> Option<SubscriptionLink<'_>> {
if !matches!(link.scheme(), "clash" | "clash-verge") {
return None;
}
// The embedded URL can contain unescaped query separators of its own.
let raw_url = link.query()?.split_once("url=")?.1.trim();
let name = link.query_pairs().find(|(key, _)| key == "name").map(|(_, name)| name);
Some(SubscriptionLink {
url: decode_subscription_url(raw_url),
name,
})
}
fn decode_subscription_url(raw_url: &str) -> Cow<'_, str> {
let mut candidate = Cow::Borrowed(raw_url);
if Url::parse(raw_url).is_ok() {
return candidate;
}
for _ in 0..2 {
let decoded = percent_decode_str(&candidate).decode_utf8_lossy();
if decoded == candidate {
break;
}
candidate = Cow::Owned(decoded.into_owned());
if Url::parse(&candidate).is_ok() {
break;
}
}
candidate
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn preserves_nested_query_separators_and_decodes_wrapped_links() -> Result<(), url::ParseError> {
let plain = Url::parse("clash://install-config?name=Work%20VPN&url=https://example.invalid/sub?a=1&b=2")?;
let link = decode_subscription_link(&plain).expect("plain subscription link");
assert_eq!(link.name.as_deref(), Some("Work VPN"));
assert!(matches!(link.url, Cow::Borrowed("https://example.invalid/sub?a=1&b=2")));
let encoded = Url::parse("clash-verge://install-config?url=https%253A%252F%252Fexample.invalid%252Fsub")?;
let link = decode_subscription_link(&encoded).expect("double-encoded subscription link");
assert_eq!(link.url, "https://example.invalid/sub");
Ok(())
}
}
@@ -1,5 +1,7 @@
mod deep_link;
mod error;
pub use deep_link::{SubscriptionLink, decode_subscription_link};
pub use error::SubscriptionError;
use http::HeaderMap;
+4 -44
View File
@@ -1,6 +1,5 @@
use crate::core::notify::NoticeStatus;
use anyhow::Result;
use percent_encoding::percent_decode_str;
use tauri::Url;
use tristr::alias::String;
@@ -10,6 +9,7 @@ use crate::{
utils::help,
};
use clash_verge_logging::{Type, logging, logging_error};
use clash_verge_subscription::decode_subscription_link;
pub(super) async fn resolve_scheme(param: &str) -> Result<()> {
let param_str = if param.starts_with("[") && param.len() > 4 {
@@ -26,7 +26,7 @@ pub(super) async fn resolve_scheme(param: &str) -> Result<()> {
let link_parsed = Url::parse(param_str)
.map_err(|e| anyhow::anyhow!("failed to parse deep link: {e:?}, param: {masked_deep_link}"))?;
let Some((url, name)) = extract_subscription_info(&link_parsed) else {
let Some(link) = decode_subscription_link(&link_parsed) else {
logging!(
warn,
Type::Config,
@@ -35,51 +35,11 @@ pub(super) async fn resolve_scheme(param: &str) -> Result<()> {
return Ok(());
};
import_subscription(&url, name.as_ref()).await;
let name = link.name.map(String::from);
import_subscription(&link.url, name.as_ref()).await;
Ok(())
}
fn extract_subscription_info(link_parsed: &Url) -> Option<(std::string::String, Option<String>)> {
if !matches!(link_parsed.scheme(), "clash" | "clash-verge") {
return None;
}
let name = link_parsed
.query_pairs()
.find(|(key, _)| key == "name")
.map(|(_, value)| value.into());
let url = extract_subscription_url(link_parsed)?;
Some((url, name))
}
fn extract_subscription_url(link_parsed: &Url) -> Option<std::string::String> {
let query = link_parsed.query()?;
let prefix = "url=";
let pos = query.find(prefix)?;
let raw_url = query[pos + prefix.len()..].trim();
Some(decode_subscription_url(raw_url))
}
fn decode_subscription_url(raw_url: &str) -> std::string::String {
// Avoid double-decoding nested subscription URLs; decode only when needed.
if Url::parse(raw_url).is_ok() {
return raw_url.to_string();
}
let mut candidate = raw_url.to_string();
for _ in 0..2 {
let next = percent_decode_str(&candidate).decode_utf8_lossy().to_string();
if next == candidate {
break;
}
candidate = next;
if Url::parse(&candidate).is_ok() {
break;
}
}
candidate
}
async fn import_subscription(url: &str, name: Option<&String>) {
let had_current_profile = {
let profiles = Config::profiles().await;