windows: ps-client shared by proxy-ctl and the app; the app's first window

- ps-client: the service's client side, moved out of proxy-ctl: calls,
  configuration edits against the revision read (retried on a concurrent
  change), log following, and the edits themselves as functions on the
  configuration (outbounds, subscriptions, rules, zapret, tg-ws-proxy),
  now unit-tested. proxy-ctl does what it did, through it; a refused log
  follow is now an error instead of nothing.
- ps-gui: proxy-suite, the desktop app on GPUI (gpui-kit 0.8.1); only a
  first window yet. Not in default-members: plain cargo build/test and the
  release workflow's tests leave GPUI out.
- tools/gui-shot.sh: runs the app on Xvfb with Mesa's software Vulkan and
  screenshots it, to check the GUI on Linux without a display.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-10-27 01:13:28 +03:00
1 parent da6aafaf1d
commit 4ae30dac3c
12 files changed
+7453 -275

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
[package]
name = "ps-client"
description = "Proxy Suite for Windows: the service's client side, for proxy-ctl and the app"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
ps-core.workspace = true
ps-ipc.workspace = true
anyhow.workspace = true
serde_json.workspace = true
[dev-dependencies]
tokio.workspace = true
+276
View File
@@ -0,0 +1,276 @@
//! The configuration edits proxy-ctl and the app make, on the configuration as JSON (what
//! `config-get` returns). Each can be made again on a newer configuration, which
//! [`Client::edit`](crate::Client::edit) does when another change came first.
use anyhow::{Result, anyhow, bail};
use serde_json::{Value, json};
/// The list at `path`, made (with the objects above it) when missing.
pub fn arr<'a>(v: &'a mut Value, path: &[&str]) -> &'a mut Vec<Value> {
let mut cur = v;
for p in path {
if cur.get(*p).is_none_or(Value::is_null) {
cur[*p] = if *p == path[path.len() - 1] { json!([]) } else { json!({}) };
}
cur = cur.get_mut(*p).unwrap();
}
cur.as_array_mut().expect("a list")
}
/// A tag for a link without one: its remark, else its host.
pub fn link_tag(link: &str) -> String {
if let Some((_, remark)) = link.split_once('#') {
let t = ps_core::links::subscription::slugify_tag(&ps_core::links::py::unquote(remark));
if t != "proxy" {
return t;
}
}
let host = link.split("://").nth(1).unwrap_or("").split(['@']).last().unwrap_or("").split([':', '/', '?', '#']).next().unwrap_or("");
let t = ps_core::links::subscription::slugify_tag(host);
if t.is_empty() { "outbound".into() } else { t }
}
/// A tag for a subscription without one: its host.
pub fn subscription_tag(url: &str) -> String {
let host = ps_core::links::subscription::url_parts::split(url).ok().and_then(|u| u.hostname).unwrap_or_else(|| "sub".into());
ps_core::links::subscription::slugify_tag(&host)
}
/// What an outbound is made from: a share link, or a backend's own JSON for one.
#[derive(Debug, Clone, PartialEq)]
pub enum OutboundSource {
Link(String),
SingBoxJson(Value),
XrayJson(Value),
}
impl OutboundSource {
/// A link, or JSON (XRay's has a `protocol`, sing-box's a `type`). A link is checked
/// here: the service would only say it left the outbound out.
pub fn parse(text: &str) -> Result<Self> {
let text = text.trim();
if text.starts_with('{') {
let json: Value = serde_json::from_str(text).map_err(|e| anyhow!("not JSON: {e}"))?;
return Ok(if json.get("protocol").is_some() { Self::XrayJson(json) } else { Self::SingBoxJson(json) });
}
ps_core::links::build_outbound(text, "check", ps_core::links::LinkBackend::SingBox)
.or_else(|_| ps_core::links::build_outbound(text, "check", ps_core::links::LinkBackend::Xray))
.map_err(|e| anyhow!("{e}"))?;
Ok(Self::Link(text.to_owned()))
}
}
pub fn add_outbound(c: &mut Value, tag: &str, source: &OutboundSource, detour: Option<&str>) -> Result<()> {
let list = arr(c, &["proxy", "outbounds"]);
if list.iter().any(|o| o["tag"] == tag) {
bail!("an outbound '{tag}' exists");
}
let mut ob = match source {
OutboundSource::Link(link) => json!({ "tag": tag, "url": link }),
OutboundSource::SingBoxJson(j) => json!({ "tag": tag, "singBoxJson": j }),
OutboundSource::XrayJson(j) => json!({ "tag": tag, "xrayJson": j }),
};
if let Some(d) = detour {
ob["detour"] = d.into();
}
list.push(ob);
Ok(())
}
pub fn remove_outbound(c: &mut Value, tag: &str) -> Result<()> {
let list = arr(c, &["proxy", "outbounds"]);
let before = list.len();
list.retain(|o| o["tag"] != tag);
if list.len() == before {
bail!("no outbound '{tag}' in the configuration");
}
Ok(())
}
pub fn add_subscription(c: &mut Value, tag: &str, url: &str) -> Result<()> {
let list = arr(c, &["proxy", "subscriptions"]);
if list.iter().any(|s| s["tag"] == tag) {
bail!("a subscription '{tag}' exists");
}
list.push(json!({ "tag": tag, "url": url }));
Ok(())
}
pub fn remove_subscription(c: &mut Value, tag: &str) -> Result<()> {
let list = arr(c, &["proxy", "subscriptions"]);
let before = list.len();
list.retain(|s| s["tag"] != tag);
if list.len() == before {
bail!("no subscription '{tag}'");
}
Ok(())
}
/// A rule's matches, sorted into their kinds: domains, addresses, `geosite:`, `geoip:`,
/// `ruleset:` and `process:` ones.
pub fn sort_matches(matches: &[String]) -> Value {
let mut m = json!({ "domains": [], "ips": [], "geosites": [], "geoips": [], "ruleSets": [], "processNames": [] });
for x in matches {
let (key, value) = if let Some(v) = x.strip_prefix("geosite:") {
("geosites", v.to_owned())
} else if let Some(v) = x.strip_prefix("geoip:") {
("geoips", v.to_owned())
} else if let Some(v) = x.strip_prefix("ruleset:") {
("ruleSets", v.to_owned())
} else if let Some(v) = x.strip_prefix("process:") {
("processNames", v.to_owned())
} else if x.parse::<std::net::IpAddr>().is_ok() || x.split_once('/').is_some_and(|(a, _)| a.parse::<std::net::IpAddr>().is_ok()) {
("ips", x.clone())
} else {
("domains", x.trim_start_matches('.').to_lowercase())
};
m[key].as_array_mut().unwrap().push(value.into());
}
m
}
/// Sends `matches` to `target`: into the rule called `name` (the target's name without
/// one), extended if it exists, made with priority 50 if not.
pub fn add_rule(c: &mut Value, target: &str, matches: &[String], name: Option<&str>, priority: Option<i64>) -> Result<()> {
if matches.is_empty() {
bail!("a rule needs something to match");
}
let m = sort_matches(matches);
let name = name.unwrap_or(target);
let list = arr(c, &["proxy", "routing", "rules"]);
if let Some(rule) = list.iter_mut().find(|r| r["name"] == name) {
for (k, v) in m.as_object().unwrap() {
let mut merged = rule[k.as_str()].as_array().cloned().unwrap_or_default();
for x in v.as_array().unwrap() {
if !merged.contains(x) {
merged.push(x.clone());
}
}
rule[k.as_str()] = Value::Array(merged);
}
rule["outbound"] = target.into();
if let Some(p) = priority {
rule["priority"] = p.into();
}
} else {
let mut rule = m;
rule["name"] = name.into();
rule["outbound"] = target.into();
rule["priority"] = priority.unwrap_or(50).into();
list.push(rule);
}
Ok(())
}
pub fn remove_rule(c: &mut Value, name: &str) -> Result<()> {
let list = arr(c, &["proxy", "routing", "rules"]);
let before = list.len();
list.retain(|r| r["name"] != name);
if list.len() == before {
bail!("no rule named '{name}'");
}
Ok(())
}
pub fn set_rule_disabled(c: &mut Value, name: &str, disabled: bool) -> Result<()> {
if name.is_empty() {
bail!("a rule name");
}
let list = arr(c, &["proxy", "routing", "rules"]);
let rule = list.iter_mut().find(|r| r["name"] == name).ok_or_else(|| anyhow!("no rule named '{name}'"))?;
rule["disabled"] = disabled.into();
Ok(())
}
pub fn set_proxy_enabled(c: &mut Value, on: bool) {
c["proxy"]["enable"] = on.into();
}
pub fn set_tun_enabled(c: &mut Value, on: bool) {
c["proxy"]["tun"]["enable"] = on.into();
}
pub fn set_zapret_enabled(c: &mut Value, on: bool) {
c["zapret"]["enable"] = on.into();
}
/// The DPI bypass's engine: `zapret` (Flowseal's presets) or `zapret2`.
pub fn set_zapret_engine(c: &mut Value, engine: &str) -> Result<()> {
if !matches!(engine, "zapret" | "zapret2") {
bail!("the engine is zapret or zapret2");
}
c["zapret"]["engine"] = engine.into();
Ok(())
}
/// The zapret-discord-youtube preset, e.g. "general (ALT9)".
pub fn set_zapret_preset(c: &mut Value, name: &str) {
c["zapret"]["zapret-discord-youtube"]["configName"] = name.into();
}
/// Which game traffic zapret handles: all, tcp, udp or null.
pub fn set_game_filter(c: &mut Value, filter: &str) -> Result<()> {
if !matches!(filter, "all" | "tcp" | "udp" | "null") {
bail!("the game filter is all, tcp, udp or null");
}
c["zapret"]["zapret-discord-youtube"]["gameFilter"] = filter.into();
Ok(())
}
pub fn set_tg_ws_proxy_enabled(c: &mut Value, on: bool) {
c["tgWsProxy"]["enable"] = on.into();
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn outbounds_are_added_once_and_removed() {
let mut c = json!({});
let src = OutboundSource::parse("ss://YWVzLTEyOC1nY206cGFzcw@1.2.3.4:8388#My%20Server").unwrap();
add_outbound(&mut c, "nl", &src, Some("hop")).unwrap();
assert_eq!(c["proxy"]["outbounds"][0]["detour"], "hop");
assert!(add_outbound(&mut c, "nl", &src, None).is_err());
remove_outbound(&mut c, "nl").unwrap();
assert!(remove_outbound(&mut c, "nl").is_err());
}
#[test]
fn sources_are_links_or_either_json() {
assert!(matches!(OutboundSource::parse(r#"{"protocol":"vless"}"#).unwrap(), OutboundSource::XrayJson(_)));
assert!(matches!(OutboundSource::parse(r#" {"type":"vless"}"#).unwrap(), OutboundSource::SingBoxJson(_)));
assert!(OutboundSource::parse("not a link").is_err());
}
#[test]
fn tags_come_from_the_remark_or_the_host() {
assert_eq!(link_tag("ss://x@1.2.3.4:8388#My%20Server"), "My-Server");
assert_eq!(link_tag("vless://id@example.com:443?security=tls"), "example-com");
}
#[test]
fn rules_are_extended_by_name() {
let mut c = json!({});
add_rule(&mut c, "direct", &["Example.com".into(), "10.0.0.0/8".into(), "process:steam.exe".into()], None, None).unwrap();
add_rule(&mut c, "direct", &["example.com".into(), "geosite:cn".into()], None, Some(10)).unwrap();
let r = &c["proxy"]["routing"]["rules"][0];
assert_eq!(r["domains"], json!(["example.com"]));
assert_eq!(r["ips"], json!(["10.0.0.0/8"]));
assert_eq!(r["processNames"], json!(["steam.exe"]));
assert_eq!(r["geosites"], json!(["cn"]));
assert_eq!(r["priority"], 10);
set_rule_disabled(&mut c, "direct", true).unwrap();
assert_eq!(c["proxy"]["routing"]["rules"][0]["disabled"], true);
}
#[test]
fn zapret_settings_are_checked() {
let mut c = json!({});
assert!(set_game_filter(&mut c, "everything").is_err());
set_game_filter(&mut c, "udp").unwrap();
assert!(set_zapret_engine(&mut c, "goodbyedpi").is_err());
set_zapret_engine(&mut c, "zapret2").unwrap();
assert_eq!(c["zapret"], json!({ "engine": "zapret2", "zapret-discord-youtube": { "gameFilter": "udp" } }));
}
}
+129
View File
@@ -0,0 +1,129 @@
//! The service's client side, shared by proxy-ctl and the app: requests, configuration
//! edits made against the revision they read, and the edits both make ([`edits`]).
pub mod edits;
use anyhow::{Result, bail};
use ps_ipc::transport::{self, Address};
use ps_ipc::{Request, Response};
use serde_json::Value;
/// What a configuration edit got back: the new revision, the validator's notes, and the
/// error applying it, when it was saved but did not apply.
#[derive(Debug, Clone, Default)]
pub struct Saved {
pub revision: Option<u64>,
pub issues: Vec<Issue>,
pub apply_error: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Issue {
pub severity: String,
pub path: String,
pub message: String,
}
impl std::fmt::Display for Issue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}: {}", self.severity, self.path, self.message)
}
}
/// The validator's notes in a response's data.
pub fn issues(data: &Value) -> Vec<Issue> {
data["issues"]
.as_array()
.into_iter()
.flatten()
.map(|i| Issue {
severity: i["severity"].as_str().unwrap_or("").to_owned(),
path: i["path"].as_str().unwrap_or("").to_owned(),
message: i["message"].as_str().unwrap_or("").to_owned(),
})
.collect()
}
#[derive(Debug, Clone)]
pub struct Client {
pub addr: Address,
}
impl Client {
pub fn new(addr: Address) -> Self {
Self { addr }
}
/// One request; a refusal is an error carrying the service's words and its notes.
pub async fn call(&self, req: Request) -> Result<Value> {
let resp: Response = transport::call(&self.addr, &req).await?;
if !resp.ok {
let mut msg = resp.error.unwrap_or_else(|| "failed".into());
for i in issues(&resp.data) {
msg.push_str(&format!("\n {i}"));
}
bail!(msg);
}
Ok(resp.data)
}
/// Reads the configuration, lets `edit` change it, and writes it back against the
/// revision read; a concurrent change is read again and `edit` made again.
pub async fn edit(&self, edit: impl Fn(&mut Value) -> Result<()>) -> Result<Saved> {
for _ in 0..3 {
let got = self.call(Request::ConfigGet).await?;
let mut config = got["config"].clone();
edit(&mut config)?;
match self.call(Request::ConfigSet { config, base: got["revision"].as_u64() }).await {
Err(e) if e.to_string().contains("changed since revision") => continue,
other => {
let r = other?;
return Ok(Saved {
revision: r["revision"].as_u64(),
issues: issues(&r),
apply_error: r["error"].as_str().map(str::to_owned),
});
}
}
}
bail!("the configuration kept changing; try again")
}
/// Log lines (every unit's without `unit`) as `(unit, line)`, the last `lines` and, with
/// `follow`, each new one, until `each` says stop.
pub async fn logs(&self, unit: Option<String>, lines: usize, follow: bool, mut each: impl FnMut(&str, &str) -> bool) -> Result<()> {
let mut take = |r: Response| {
let one = |l: &Value| (l["unit"].as_str().unwrap_or("").to_owned(), l["line"].as_str().unwrap_or("").to_owned());
match &r.data {
Value::Array(ls) => ls.iter().map(one).all(|(u, l)| each(&u, &l)),
d if d.is_object() => {
let (u, l) = one(d);
each(&u, &l)
}
_ => true,
}
};
let req = Request::Logs { unit, lines, follow };
if follow {
let mut refused = None;
transport::stream(&self.addr, &req, |r| {
if !r.ok {
refused = Some(r.error.unwrap_or_else(|| "failed".into()));
return false;
}
take(r)
})
.await?;
if let Some(e) = refused {
bail!(e);
}
} else {
let r = transport::call(&self.addr, &req).await?;
if !r.ok {
bail!(r.error.unwrap_or_else(|| "failed".into()));
}
take(r);
}
Ok(())
}
}