proxy_pilot/core/xray/
vless.rs1use std::collections::HashMap;
2
3use serde_json::{Value, json};
4
5use crate::error::{PilotError, Result};
6
7#[derive(Debug, Clone)]
8pub struct ParsedVless {
9 pub name: String,
10 pub outbound_tag: String,
11 pub outbound_json: Value,
12}
13
14pub fn parse_vless_uri(uri: &str) -> Result<ParsedVless> {
16 let rest = uri
17 .trim()
18 .strip_prefix("vless://")
19 .ok_or_else(|| PilotError::Config("URI must start with vless://".into()))?;
20
21 let (without_frag, raw_name) = match rest.split_once('#') {
22 Some((left, frag)) => (left, percent_decode(frag)),
23 None => (rest, String::new()),
24 };
25
26 let (authority, query_str) = match without_frag.split_once('?') {
27 Some((left, q)) => (left, q),
28 None => (without_frag, ""),
29 };
30
31 let (uuid, host_port) = authority
32 .split_once('@')
33 .ok_or_else(|| PilotError::Config("vless URI missing '@' separator".into()))?;
34 if uuid.trim().is_empty() {
35 return Err(PilotError::Config("vless URI has empty uuid".into()));
36 }
37
38 let (raw_host, port_str) = host_port
39 .rsplit_once(':')
40 .ok_or_else(|| PilotError::Config("vless URI missing ':port'".into()))?;
41 let host = raw_host.trim_start_matches('[').trim_end_matches(']');
42 if host.is_empty() {
43 return Err(PilotError::Config("vless URI has empty host".into()));
44 }
45 let port: u16 = port_str
46 .parse()
47 .map_err(|_| PilotError::Config(format!("invalid port in vless URI: {port_str}")))?;
48 if port == 0 {
49 return Err(PilotError::Config("vless URI port must be > 0".into()));
50 }
51
52 let params = parse_query(query_str);
53 let name = if raw_name.trim().is_empty() {
54 format!("{host}:{port}")
55 } else {
56 raw_name.trim().to_string()
57 };
58 let outbound_tag = sanitize_tag(&name, host, port);
59 let outbound_json = build_xray_outbound(&outbound_tag, uuid, host, port, ¶ms);
60
61 Ok(ParsedVless {
62 name,
63 outbound_tag,
64 outbound_json,
65 })
66}
67
68fn build_xray_outbound(
69 tag: &str,
70 uuid: &str,
71 host: &str,
72 port: u16,
73 params: &HashMap<String, String>,
74) -> Value {
75 let encryption = params
76 .get("encryption")
77 .map(String::as_str)
78 .unwrap_or("none");
79 let flow = params.get("flow").map(String::as_str).unwrap_or("");
80 let network = params.get("type").map(String::as_str).unwrap_or("tcp");
81 let security = params.get("security").map(String::as_str).unwrap_or("none");
82
83 let mut stream = json!({
84 "network": network,
85 "security": security,
86 });
87
88 if security == "reality" {
89 stream["realitySettings"] = json!({
90 "serverName": params.get("sni").cloned().unwrap_or_default(),
91 "fingerprint": params.get("fp").cloned().unwrap_or_else(|| "chrome".into()),
92 "publicKey": params.get("pbk").cloned().unwrap_or_default(),
93 "shortId": params.get("sid").cloned().unwrap_or_default(),
94 "spiderX": params.get("spx").cloned().unwrap_or_else(|| "/".into()),
95 });
96 } else if security == "tls" {
97 stream["tlsSettings"] = json!({
98 "serverName": params.get("sni").cloned().unwrap_or_else(|| host.to_string()),
99 "fingerprint": params.get("fp").cloned().unwrap_or_else(|| "chrome".into()),
100 });
101 }
102
103 json!({
104 "tag": tag,
105 "protocol": "vless",
106 "settings": {
107 "vnext": [{
108 "address": host,
109 "port": port,
110 "users": [{
111 "id": uuid,
112 "encryption": encryption,
113 "flow": flow,
114 }]
115 }]
116 },
117 "streamSettings": stream,
118 })
119}
120
121fn parse_query(query: &str) -> HashMap<String, String> {
122 query
123 .split('&')
124 .filter_map(|pair| pair.split_once('='))
125 .map(|(k, v)| (k.to_string(), percent_decode(v)))
126 .collect()
127}
128
129fn sanitize_tag(name: &str, host: &str, port: u16) -> String {
130 let ascii: String = name
131 .chars()
132 .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_')
133 .collect();
134 if ascii.is_empty() {
135 format!("vless-{host}-{port}")
136 } else {
137 format!("vless-{ascii}")
138 }
139}
140
141fn percent_decode(input: &str) -> String {
142 let bytes = input.as_bytes();
143 let mut out = Vec::with_capacity(bytes.len());
144 let mut i = 0;
145 while i < bytes.len() {
146 if bytes[i] == b'%'
147 && i + 2 < bytes.len()
148 && let Ok(hex_str) = std::str::from_utf8(&bytes[i + 1..i + 3])
149 && let Ok(val) = u8::from_str_radix(hex_str, 16)
150 {
151 out.push(val);
152 i += 3;
153 continue;
154 }
155 out.push(bytes[i]);
156 i += 1;
157 }
158 String::from_utf8_lossy(&out).into_owned()
159}
160
161#[cfg(test)]
162mod tests {
163 use super::*;
164
165 #[test]
166 fn parses_vless_reality_uri() {
167 let uri = "vless://00000000-0000-0000-0000-000000000001@example.com:443?encryption=none&flow=xtls-rprx-vision&security=reality&sni=example.org&fp=chrome&pbk=TEST_PBK&sid=abcd1234&type=tcp#Paris-1";
168 let parsed = parse_vless_uri(uri).unwrap();
169 assert_eq!(parsed.name, "Paris-1");
170 assert_eq!(parsed.outbound_tag, "vless-Paris-1");
171 assert_eq!(parsed.outbound_json["protocol"], "vless");
172 assert_eq!(
173 parsed.outbound_json["streamSettings"]["realitySettings"]["publicKey"],
174 "TEST_PBK"
175 );
176 }
177
178 #[test]
179 fn rejects_non_vless_uri() {
180 assert!(parse_vless_uri("https://example.com").is_err());
181 }
182
183 #[test]
184 fn rejects_empty_uuid_host_and_zero_port() {
185 assert!(parse_vless_uri("vless://@example.com:443").is_err());
186 assert!(parse_vless_uri("vless://uuid@:443").is_err());
187 assert!(parse_vless_uri("vless://uuid@example.com:0").is_err());
188 }
189
190 #[test]
191 fn parses_ipv6_host_without_brackets() {
192 let parsed =
193 parse_vless_uri("vless://00000000-0000-0000-0000-000000000001@[2001:db8::1]:443#v6")
194 .unwrap();
195 assert_eq!(
196 parsed.outbound_json["settings"]["vnext"][0]["address"],
197 "2001:db8::1"
198 );
199 }
200}