Files
proxy-suite-flake/windows/crates/ps-service/src/clash.rs
T
faumarayandClaude Opus 5.5 5a89b8d11d windows: autoProxy
As upstream's prober: the sites apps reach directly (the Clash API's
direct connections here; upstream's inbound access log) are probed
through each exit, direct first, every interval and at once for
proxy-ctl proxy auto learn. One blocked directly but reached through an
exit is routed through it: its exit's local rule-set, which sing-box
reloads. Upstream's judgement, ported and tested: block pages, the walk
over paths and exits, one exit per network first, strikes against exits
that refuse, a new egress discarding what was learned, rechecks once per
TTL. Blocks zapret can fix stay direct.

The config gains a loopback probe listener per exit (with the hop login,
pinned behind the loopback guard) and the learned rules after the user's.
proxy-ctl proxy auto list|probe|learn|forget|clear over new API requests
(autoProxy scope). Slow sites (slowBelowKiBps) are not routed yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 16:31:29 +03:00

97 lines
3.3 KiB
Rust

//! sing-box's Clash API on loopback: what selectors pick, and outbound latency.
use std::time::Duration;
use anyhow::{Context, Result, bail};
use serde_json::Value;
pub struct Clash {
base: String,
secret: String,
http: reqwest::Client,
}
fn encode(segment: &str) -> String {
let mut out = String::new();
for b in segment.bytes() {
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
out.push(b as char);
} else {
out.push_str(&format!("%{b:02X}"));
}
}
out
}
#[allow(dead_code, reason = "for switching the selection live, which is to come")]
impl Clash {
pub fn new(port: u16, secret: &str) -> Self {
let http = reqwest::Client::builder()
.no_proxy()
.timeout(Duration::from_secs(20))
.build()
.expect("an HTTP client");
Self { base: format!("http://127.0.0.1:{port}"), secret: secret.to_owned(), http }
}
async fn get(&self, path: &str) -> Result<Value> {
let resp = self.http.get(format!("{}{path}", self.base)).bearer_auth(&self.secret).send().await?;
let status = resp.status();
let body: Value = resp.json().await.unwrap_or(Value::Null);
if !status.is_success() {
bail!("{}", body["message"].as_str().unwrap_or(status.as_str()));
}
Ok(body)
}
/// The connections open now, with where each goes and through what.
pub async fn connections(&self) -> Result<Value> {
self.get("/connections").await
}
/// Every proxy (outbound or group) with what a selector holds now.
pub async fn proxies(&self) -> Result<Value> {
self.get("/proxies").await.map(|v| v["proxies"].clone())
}
/// What `group` (a selector or urltest) uses now.
pub async fn current(&self, group: &str) -> Result<Option<String>> {
let v = self.get(&format!("/proxies/{}", encode(group))).await?;
Ok(v["now"].as_str().map(str::to_owned))
}
/// Switches the selector `group` to `tag`, live.
pub async fn select(&self, group: &str, tag: &str) -> Result<()> {
let resp = self
.http
.put(format!("{}/proxies/{}", self.base, encode(group)))
.bearer_auth(&self.secret)
.json(&serde_json::json!({ "name": tag }))
.send()
.await
.context("the Clash API")?;
if !resp.status().is_success() {
let body: Value = resp.json().await.unwrap_or(Value::Null);
bail!("cannot switch {group} to {tag}: {}", body["message"].as_str().unwrap_or("refused"));
}
Ok(())
}
/// The delay to `url` through `tag`, in milliseconds.
pub async fn delay(&self, tag: &str, url: &str, timeout_ms: u32) -> Result<u32> {
let resp = self
.http
.get(format!("{}/proxies/{}/delay", self.base, encode(tag)))
.bearer_auth(&self.secret)
.query(&[("url", url), ("timeout", &timeout_ms.to_string())])
.send()
.await?;
let status = resp.status();
let body: Value = resp.json().await.unwrap_or(Value::Null);
if !status.is_success() {
bail!("{}", body["message"].as_str().unwrap_or("timed out"));
}
body["delay"].as_u64().map(|d| d as u32).context("no delay in the answer")
}
}