Files
proxy-suite-flake/windows/crates/ps-core/src/links/mod.rs
T
faumarayandClaude Opus 5.5 77d4cefe0e windows: share-link and subscription parsing, admin-only edits
ps-core::links ports upstream's proxy_url_parsers.py and proxy_parsing.py:
every scheme, each backend's refusals, XRay rendering, subscription
decoding, tags and the server checks. Upstream's build-outbound tests
are ported case for case, and tools/parity/links.py runs ~750 links
through both implementations: no differences.

config::privileged_changes names the edits only an administrator may
make: anything that runs a program, passes arguments through, or names
a local file, since the service runs as LocalSystem. Names that become
paths or service names are validated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 22:38:56 +03:00

176 lines
5.7 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Share links to backend outbounds: upstream's `scripts/proxy_url_parsers.py` and
//! `proxy_parsing.py`, ported with their checks and messages.
//!
//! A link becomes a sing-box-shaped outbound first; for XRay it is then rendered into XRay's
//! shape. Each parser refuses what the backend would refuse to start on, so one bad
//! subscription entry is skipped instead of taking every other outbound down with it.
//!
//! Upstream's `routing_mark` (Linux SO_MARK) has no Windows counterpart and is left out.
mod parsers;
pub mod py;
pub mod subscription;
mod xray;
use std::fmt;
use serde_json::{Map, Value};
pub use parsers::SCHEMES;
pub use xray::render_xray_outbound;
/// Which backend an outbound is built for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LinkBackend {
SingBox,
Xray,
}
impl LinkBackend {
pub fn as_str(self) -> &'static str {
match self {
Self::SingBox => "sing-box",
Self::Xray => "xray",
}
}
}
/// Why a link was refused. The message never quotes a credential.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LinkError {
/// The link is malformed, or the backend would refuse it.
Invalid(String),
/// A subscription entry whose server is this host, its link, or (unless allowed) a
/// private network: whichever backend reads it, it is skipped.
RefusedServer(String),
}
impl LinkError {
pub(crate) fn invalid(message: impl Into<String>) -> Self {
Self::Invalid(message.into())
}
pub fn message(&self) -> &str {
match self {
Self::Invalid(m) | Self::RefusedServer(m) => m,
}
}
}
impl fmt::Display for LinkError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.message())
}
}
impl std::error::Error for LinkError {}
pub type Result<T> = std::result::Result<T, LinkError>;
/// The scheme of a link, lowercased: what comes before `://`.
pub fn detect_scheme(url: &str) -> String {
url.split("://").next().unwrap_or("").to_lowercase()
}
/// Parses a link into a sing-box-shaped outbound tagged `tag`, checked against `backend`.
pub fn parse_url(url: &str, tag: &str, backend: LinkBackend) -> Result<Map<String, Value>> {
let scheme = detect_scheme(url);
parsers::parse(&scheme, url, tag, backend)
}
/// A link as the backend's outbound: sing-box's shape, or XRay's.
pub fn build_outbound(url: &str, tag: &str, backend: LinkBackend) -> Result<Value> {
let ob = parse_url(url, tag, backend)?;
finish_outbound(ob, backend)
}
pub(crate) fn finish_outbound(ob: Map<String, Value>, backend: LinkBackend) -> Result<Value> {
match backend {
LinkBackend::Xray => render_xray_outbound(&ob),
LinkBackend::SingBox => Ok(Value::Object(ob)),
}
}
/// Every key anywhere in `value`, lowercased.
fn all_keys(value: &Value) -> Vec<String> {
let mut found = Vec::new();
let mut stack = vec![value];
while let Some(item) = stack.pop() {
match item {
Value::Object(map) => {
for (k, v) in map {
found.push(py_lower(k));
stack.push(v);
}
}
Value::Array(list) => stack.extend(list),
_ => {}
}
}
found
}
/// `str.lower()`, which folds the Kelvin sign to `k` as Go's JSON decoding does.
fn py_lower(s: &str) -> String {
s.to_lowercase()
}
/// The keys anywhere in `value` that point a backend at a local file or program. The
/// backends run as SYSTEM here, and a share link is whatever a subscription serves: an xhttp
/// `extra` carries a whole streamSettings, where `certificateFile` is a file XRay reads and
/// `masterKeyLog` one it writes. Any non-ASCII key counts too: Go's JSON folds case, reading
/// "maſterKeyLog" as masterKeyLog.
pub fn local_file_keys(value: &Value) -> Vec<String> {
let mut keys: Vec<String> = all_keys(value)
.into_iter()
.filter(|k| {
!k.is_ascii()
|| k.ends_with("file")
|| k.ends_with("directory")
|| (k.ends_with("path") && k != "path")
|| matches!(k.as_str(), "masterkeylog" | "torrc" | "extra_args")
})
.collect();
keys.sort();
keys.dedup();
keys
}
/// Socket options a share link must not set: a mark or interface steers around the routing,
/// a dialerProxy chains elsewhere. Other socket options stay.
const SOCKET_KEYS: [&str; 5] = ["customsockopt", "dialerproxy", "interface", "mark", "tproxy"];
fn strip_socket_keys(value: &mut Value) {
match value {
Value::Object(map) => {
map.retain(|k, _| !SOCKET_KEYS.contains(&py_lower(k).as_str()));
for v in map.values_mut() {
strip_socket_keys(v);
}
}
Value::Array(list) => list.iter_mut().for_each(strip_socket_keys),
_ => {}
}
}
/// A JSON object carried in a link parameter (xhttp's `extra`), checked as upstream does.
fn parse_json_param(value: &str, name: &str) -> Result<Value> {
let mut parsed: Value = serde_json::from_str(value)
.map_err(|e| LinkError::invalid(format!("invalid {name} JSON: {e}")))?;
if !parsed.is_object() {
return Err(LinkError::invalid(format!("invalid {name} JSON: expected object")));
}
let unsafe_keys = local_file_keys(&parsed);
if !unsafe_keys.is_empty() {
return Err(LinkError::invalid(format!("{name} JSON names local files: {}", unsafe_keys.join(", "))));
}
strip_socket_keys(&mut parsed);
if all_keys(&parsed).iter().any(|k| k == "allowinsecure") {
return Err(LinkError::invalid(format!("{name} JSON sets allowInsecure, which XRay no longer accepts")));
}
Ok(parsed)
}
#[cfg(test)]
mod tests;