Files
proxy-suite-flake/windows/crates/ps-service/src/api.rs
T
faumarayandClaude Opus 5.5 803e18db9d windows: zapret2's 16 KB cutoff probe
Upstream's cutoff.nix and cutoff-probe.template.sh: z2k-detect (built from
z2k's pinned source for Windows, in zapret2-extras) finds the networks this
line cuts after ~16 KB, and with z2k's own strategies a whitelisted name per
network; z2k-tcp16.lua inside winws2 reads the maps (Z2K_TCP16_*, their
digest in the environment so a new map restarts winws2); what no name fixes
goes to the zapret-cutoff rule-set for the proxy (cutoff.proxyFallback).

Upstream keeps zapret2 off the probe with an nft cgroup rule. Here
z2k-detect is patched to dial from a local port range
(Z2K_TCP16_LOCAL_PORTS, 44000-47999, below Windows' dynamic range) and
winws2 gets --wf-raw-filter leaving that range alone; under the TUN the
probe and the service's own lookups of the line's network go direct.

Rounds as upstream's timer: 5 min after start, every 10 min, probing when
the line's network (ipinfo.io and ifconfig.co agreeing) changed or a day
passed. Request::ZapretCutoff, proxy-ctl zapret cutoff [probe], a card on
the DPI page. Verified live on a line that cuts (25 networks, a name for
each), the Windows z2k-detect under Wine, winws2 --dry-run and --wf-save
with the filter. gui-shot's scroll takes a count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 23:12:43 +03:00

804 lines
34 KiB
Rust

//! The API: who may do what, and doing it.
use ps_core::config::{Config, Issue, Scope, Severity, privileged_changes, validate};
use ps_core::render::RouteMode;
use ps_ipc::transport::{Conn, Server};
use ps_ipc::{Peer, Request, Response};
use serde_json::{Value, json};
use crate::service::{self, Shared};
/// What stands in for a secret a caller may not read. Sent back unchanged, it keeps the
/// value it hides.
pub const REDACTED: &str = "\u{2022}\u{2022}\u{2022}redacted\u{2022}\u{2022}\u{2022}";
/// Option paths holding secrets (`*`: any key or list entry).
const SECRET_PATHS: [&str; 19] = [
"proxy.outbounds.*.url",
"proxy.outbounds.*.singBoxJson",
"proxy.outbounds.*.xrayJson",
"proxy.subscriptions.*.url",
"proxy.listener.auth.password",
"amneziaWg.profiles.*.config",
"amneziaWg.profiles.*.vpn",
"amneziaWg.profiles.*.settings.privateKey",
"amneziaWg.profiles.*.settings.peers.*.presharedKey",
"amneziaWg.profiles.*.settings.obfuscation.headerProtectionKey",
"warp.config",
"warp.devices.*.config",
"tgWsProxy.secret",
"inbounds.users.*.uuid",
"inbounds.users.*.password",
"inbounds.listeners.*.serverPassword",
"inbounds.listeners.*.reality.privateKey",
"inbounds.listeners.*.hysteria.salamander.password",
"inbounds.listeners.*.xrayJson",
];
fn redact_at(value: &mut Value, path: &[&str]) {
let Some((head, rest)) = path.split_first() else {
if !value.is_null() {
*value = REDACTED.into();
}
return;
};
match value {
Value::Object(map) => {
if *head == "*" {
map.values_mut().for_each(|v| redact_at(v, rest));
} else if let Some(v) = map.get_mut(*head) {
redact_at(v, rest);
}
}
Value::Array(list) if *head == "*" => list.iter_mut().for_each(|v| redact_at(v, rest)),
_ => {}
}
}
pub fn redact(config: &Config) -> Value {
let mut v = serde_json::to_value(config).expect("the config serializes");
for p in SECRET_PATHS {
redact_at(&mut v, &p.split('.').collect::<Vec<_>>());
}
v
}
/// The entry of `old` a list entry of `new` stands for: by its tag or name, else its index.
fn counterpart<'a>(old: &'a [Value], new: &Value, index: usize) -> Option<&'a Value> {
for key in ["tag", "name"] {
if let Some(id) = new.get(key).filter(|v| v.is_string()) {
return old.iter().find(|o| o.get(key) == Some(id));
}
}
old.get(index)
}
fn unredact_at(new: &mut Value, old: Option<&Value>, path: &[&str]) {
let Some((head, rest)) = path.split_first() else {
if new.as_str() == Some(REDACTED) {
*new = old.cloned().unwrap_or(Value::Null);
}
return;
};
match new {
Value::Object(map) => {
let old_map = old.and_then(Value::as_object);
if *head == "*" {
for (k, v) in map.iter_mut() {
unredact_at(v, old_map.and_then(|m| m.get(k)), rest);
}
} else if let Some(v) = map.get_mut(*head) {
unredact_at(v, old_map.and_then(|m| m.get(*head)), rest);
}
}
Value::Array(list) if *head == "*" => {
let old_list = old.and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]);
for (i, v) in list.iter_mut().enumerate() {
let o = counterpart(old_list, v, i).cloned();
unredact_at(v, o.as_ref(), rest);
}
}
_ => {}
}
}
/// `new` with every placeholder replaced by the value it hid in `old`.
pub fn unredact(new: &mut Value, old: &Config) {
let old = serde_json::to_value(old).expect("the config serializes");
for p in SECRET_PATHS {
unredact_at(new, Some(&old), &p.split('.').collect::<Vec<_>>());
}
}
/// Whether `peer` may use `scope`, under `cfg.userControl`.
fn allowed(cfg: &Config, peer: &Peer, scope: Option<Scope>) -> Result<(), String> {
if peer.admin {
return Ok(());
}
let Some(scope) = scope else { return Ok(()) };
let uc = &cfg.user_control;
if !uc.enable {
return Err("this needs an administrator (userControl is off)".into());
}
if uc.scopes.is_empty() || uc.scopes.contains(&scope) {
Ok(())
} else {
Err(format!("this needs the {scope:?} scope, which userControl does not give").to_lowercase())
}
}
fn scope_of(req: &Request) -> Option<Scope> {
match req {
Request::ConfigSet { .. } => Some(Scope::Config),
Request::Pin { .. } | Request::Mode { .. } | Request::RuleSetsUpdate => Some(Scope::Routing),
Request::Disable { .. } | Request::SubsUpdate { .. } | Request::Test { .. } => Some(Scope::Outbounds),
// Backend logs name the sites visited (at info), and errors may quote what was dialled.
Request::RenderedConfig | Request::Logs { .. } | Request::TgLinks => Some(Scope::Secrets),
// An update runs only the project's own setup program, checked: no more than a restart.
Request::Restart { .. } | Request::Start { .. } | Request::Stop { .. } | Request::UpdateInstall => Some(Scope::Services),
Request::WlList | Request::WlLink { .. } | Request::WlAuth { .. } | Request::WlJoin { .. } | Request::WlNew { .. } => Some(Scope::WhitelistBypass),
Request::AutoList | Request::AutoProbe { .. } | Request::AutoLearn { .. } | Request::AutoForget { .. } => Some(Scope::AutoProxy),
Request::AwgList | Request::AwgSet { .. } => Some(Scope::AmneziaWg),
Request::AwgLog { .. } => Some(Scope::Secrets),
Request::ZapretCutoff { .. } => Some(Scope::Zapret),
_ => None,
}
}
/// Re-applies whitelist-bypass, so a unit that waited starts, and restarts `unit` on what
/// was just left for it.
async fn wl_restart(s: &mut service::Service, unit: &str) -> Response {
let started = |s: &service::Service| s.sup.status().into_iter().find(|u| u.name == unit).map(|u| u.since);
let before = started(s);
if let Err(e) = s.apply_wl().await {
return Response::err(format!("{e:#}"));
}
// Unless the apply (re)started it on a new spec, or it does not run (off, or its proxy is).
let after = started(s);
if after.is_some() && after == before {
s.sup.restart(unit);
}
Response::ok(json!({ "unit": unit, "state": s.sup.state_of(unit).as_str() }))
}
fn has_secrets(cfg: &Config, peer: &Peer) -> bool {
allowed(cfg, peer, Some(Scope::Secrets)).is_ok()
}
fn issues_json(issues: &[Issue]) -> Value {
serde_json::to_value(issues).unwrap()
}
/// Serves the API until the process ends.
pub async fn serve(mut server: Server, shared: Shared) {
loop {
match server.accept().await {
Ok(conn) => {
let shared = shared.clone();
tokio::spawn(async move { connection(conn, shared).await });
}
Err(e) => {
tracing::warn!("accepting a client: {e}");
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
}
}
}
}
async fn connection(mut conn: Conn, shared: Shared) {
loop {
let req: Request = match conn.read_json().await {
Ok(Some(r)) => r,
Ok(None) => return,
Err(e) => {
let _ = conn.write_json(&Response::err(format!("bad request: {e}"))).await;
return;
}
};
let peer = conn.peer();
// Every request, streamed or not, is authorized here before anything is done for it.
let denied = {
let s = shared.lock().await;
allowed(s.cfg(), &peer, scope_of(&req)).err()
};
if let Some(e) = denied {
if conn.write_json(&Response::err(e)).await.is_err() {
return;
}
continue;
}
if let Request::Logs { unit, lines, follow: true } = &req {
follow_logs(&mut conn, &shared, unit.clone(), *lines).await;
return;
}
let resp = handle(req, &peer, &shared).await;
if conn.write_json(&resp).await.is_err() {
return;
}
}
}
async fn follow_logs(conn: &mut Conn, shared: &Shared, unit: Option<String>, lines: usize) {
let (backlog, mut feed) = {
let s = shared.lock().await;
(s.sup.tail(unit.as_deref(), lines), s.sup.subscribe())
};
for line in backlog {
if conn.write_json(&Response::partial(json!(line))).await.is_err() {
return;
}
}
loop {
match feed.recv().await {
Ok(line) if unit.as_ref().is_none_or(|u| *u == line.unit) => {
if conn.write_json(&Response::partial(json!(line))).await.is_err() {
return;
}
}
Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
Err(_) => return,
}
}
}
/// Does what `req` asks; the caller has authorized it (`connection`).
pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
match req {
Request::Status => Response::ok(shared.lock().await.status()),
Request::ConfigGet => {
let s = shared.lock().await;
let config = if has_secrets(s.cfg(), peer) { serde_json::to_value(s.cfg()).unwrap() } else { redact(s.cfg()) };
Response::ok(json!({ "config": config, "revision": s.store.revision, "redacted": !has_secrets(s.cfg(), peer) }))
}
Request::ConfigValidate { config } => match serde_json::from_value::<Config>(config) {
Ok(cfg) => Response::ok(json!({ "issues": issues_json(&validate(&cfg)) })),
Err(e) => Response::err(format!("not a configuration: {e}")),
},
Request::ConfigSet { mut config, base } => {
let mut s = shared.lock().await;
if let Some(base) = base
&& base != s.store.revision
{
return Response::err(format!("the configuration changed since revision {base} (now {}): read it again", s.store.revision));
}
unredact(&mut config, s.cfg());
let new: Config = match serde_json::from_value(config) {
Ok(c) => c,
Err(e) => return Response::err(format!("not a configuration: {e}")),
};
let issues = validate(&new);
if issues.iter().any(|i| i.severity == Severity::Error) {
return Response { ok: false, error: Some("the configuration has errors".into()), data: json!({ "issues": issues_json(&issues) }), more: false };
}
if !peer.admin {
let privileged = privileged_changes(s.cfg(), &new);
if !privileged.is_empty() {
return Response {
ok: false,
error: Some(format!("only an administrator may change {}", privileged.join(", "))),
data: json!({ "privileged": privileged }),
more: false,
};
}
}
let subs_before: Vec<String> = s.cfg().proxy.subscriptions.iter().map(|x| x.tag.clone()).collect();
if let Err(e) = s.store.save_config(new) {
return Response::err(format!("cannot save the configuration: {e}"));
}
tracing::info!("configuration revision {} set by {}", s.store.revision, peer.user);
let new_subs: Vec<String> =
s.cfg().proxy.subscriptions.iter().map(|x| x.tag.clone()).filter(|t| !subs_before.contains(t)).collect();
let applied = s.apply().await;
let revision = s.store.revision;
drop(s);
// A new subscription is fetched at once, as upstream fetches on first start.
for tag in new_subs {
let shared = shared.clone();
tokio::spawn(async move { service::update_subscriptions(&shared, Some(&tag)).await });
}
{
let shared = shared.clone();
tokio::spawn(async move { service::update_rule_sets(&shared, true).await });
}
{
let shared = shared.clone();
tokio::spawn(async move { service::register_warp(&shared).await });
}
Response::ok(json!({
"revision": revision,
"issues": issues_json(&issues),
"applied": applied.as_ref().map(|_| true).unwrap_or(false),
"error": applied.err().map(|e| e.to_string()),
}))
}
Request::StateGet => Response::ok(serde_json::to_value(&shared.lock().await.store.state).unwrap()),
Request::Pin { tag, group } => {
let mut s = shared.lock().await;
match group {
Some(g) => match tag {
Some(t) => {
s.store.state.group_pins.insert(g, t);
}
None => {
s.store.state.group_pins.remove(&g);
}
},
None => s.store.state.pin = tag,
}
finish_state(&mut s).await
}
Request::Disable { tag, disabled } => {
let mut s = shared.lock().await;
s.store.state.disabled.retain(|t| *t != tag);
if disabled {
s.store.state.disabled.push(tag);
}
finish_state(&mut s).await
}
Request::Mode { mode } => {
let mut s = shared.lock().await;
s.store.state.route_mode = match mode.as_deref() {
None | Some("default") => None,
Some(m) => match serde_json::from_value::<RouteMode>(json!(m)) {
Ok(m) => Some(m),
Err(_) => return Response::err(format!("unknown mode '{m}': default, whitelist, blacklist, all-proxy or all-bypass")),
},
};
finish_state(&mut s).await
}
Request::Outbounds => {
let s = shared.lock().await;
let secrets = has_secrets(s.cfg(), peer);
match &s.last {
Some(r) => {
let mut inv = serde_json::to_value(&r.inventory).unwrap();
if !secrets {
inv["links"] = json!({});
}
Response::ok(json!({ "inventory": inv, "warnings": r.warnings }))
}
None => Response::err(s.last_error.clone().unwrap_or_else(|| "the proxy is not running".into())),
}
}
Request::RenderedConfig => {
let s = shared.lock().await;
match &s.last {
Some(r) => Response::ok(json!({ "sing-box": r.sing_box, "xray": r.xray })),
None => Response::err("nothing rendered yet"),
}
}
Request::Restart { units } => {
let mut s = shared.lock().await;
let names = if units.is_empty() { s.sup.names() } else { units };
let mut missing = Vec::new();
for n in &names {
if !s.sup.restart(n) {
missing.push(n.clone());
}
}
if missing.is_empty() { Response::ok(json!({ "restarted": names })) } else { Response::err(format!("no such unit: {}", missing.join(", "))) }
}
Request::Start { unit } | Request::Stop { unit } if unit != service::SOCKS_UNIT && unit != "proxy-suite-tun" => {
Response::err(format!("unit '{unit}' cannot be started or stopped on its own"))
}
Request::Start { unit } => {
let mut s = shared.lock().await;
if unit == "proxy-suite-tun" {
if !s.cfg().proxy.tun.enable {
return Response::err("the global TUN is off in the configuration (proxy.tun.enable)");
}
s.tun = true;
}
s.proxy_on = true;
applied(s.apply().await)
}
Request::Stop { unit } => {
let mut s = shared.lock().await;
if unit == "proxy-suite-tun" {
s.tun = false;
} else {
s.proxy_on = false;
}
applied(s.apply().await)
}
Request::Logs { unit, lines, .. } => {
let s = shared.lock().await;
Response::ok(json!(s.sup.tail(unit.as_deref(), lines)))
}
Request::SubsUpdate { tag } => {
let results = service::update_subscriptions(shared, tag.as_deref()).await;
Response::ok(json!(results.into_iter().map(|(t, r)| match r {
Ok(n) => json!({ "tag": t, "links": n }),
Err(e) => json!({ "tag": t, "error": e }),
}).collect::<Vec<_>>()))
}
Request::RuleSetsUpdate => {
let results = service::update_rule_sets(shared, false).await;
Response::ok(json!(results.into_iter().map(|(t, r)| match r {
Ok(()) => json!({ "tag": t }),
Err(e) => json!({ "tag": t, "error": e }),
}).collect::<Vec<_>>()))
}
Request::Test { tags } => {
let (clash, tags, url) = {
let s = shared.lock().await;
let Some(r) = &s.last else { return Response::err("the proxy is not running") };
let tags = if tags.is_empty() { r.inventory.exits.clone() } else { tags };
(
crate::clash::Clash::new(s.cfg().proxy.sing_box.clash_api_port, &s.store.secrets.clash_secret),
tags,
s.cfg().proxy.url_test.url.clone(),
)
};
let mut out = Vec::new();
for t in tags {
out.push(match clash.delay(&t, &url, 5000).await {
Ok(ms) => json!({ "tag": t, "delay": ms }),
Err(e) => json!({ "tag": t, "error": e.to_string() }),
});
}
Response::ok(json!(out))
}
Request::Components => {
let s = shared.lock().await;
let bin = s.paths().bin();
let list: Vec<Value> = ps_core::components::manifest()
.components
.iter()
.map(|(name, c)| {
json!({
"name": name,
"version": c.version,
"installed": crate::install::installed_version(&bin, name),
"license": c.license,
"homepage": c.homepage,
"bundled": c.bundled,
})
})
.collect();
Response::ok(json!(list))
}
Request::ZapretPresets => {
let s = shared.lock().await;
let bats: Vec<String> = std::fs::read_dir(s.paths().bin().join("zapret"))
.into_iter()
.flatten()
.filter_map(|e| e.ok()?.file_name().into_string().ok())
.collect();
Response::ok(json!({
"presets": ps_core::zapret::presets(&bats),
"current": s.cfg().zapret.discord_youtube.config_name,
}))
}
Request::TgLinks => {
let s = shared.lock().await;
match crate::tg::secret(s.cfg(), s.paths()) {
Ok(secret) => Response::ok(json!({ "links": crate::tg::links(s.cfg(), &secret) })),
Err(e) => Response::err(format!("tg-ws-proxy's secret: {e:#}")),
}
}
Request::WlList => {
let s = shared.lock().await;
let wl = &s.cfg().whitelist_bypass;
let state = |unit: String| if wl.enable { s.sup.state_of(&unit).as_str() } else { "off" };
let mut list: Vec<Value> = wl
.creators
.iter()
.map(|(name, c)| json!({ "name": name, "role": "creator", "platform": c.platform.as_str(), "state": state(format!("{}{name}", crate::wl::CREATOR_PREFIX)) }))
.collect();
list.extend(wl.joiners.iter().map(|(name, j)| {
json!({ "name": name, "role": "joiner", "platform": j.platform.as_str(), "state": state(format!("{}{name}", crate::wl::JOINER_PREFIX)) })
}));
Response::ok(json!(list))
}
Request::WlLink { name } => {
let s = shared.lock().await;
if !s.cfg().whitelist_bypass.creators.contains_key(&name) {
return Response::err(format!("no whitelist-bypass creator '{name}'"));
}
match crate::wl::last_link(s.paths(), &name) {
Some(link) => Response::ok(json!({ "link": link })),
None => Response::err(format!("{name} has no call yet: see proxy-ctl logs {}{name}", crate::wl::CREATOR_PREFIX)),
}
}
Request::WlAuth { name, login } => {
let mut s = shared.lock().await;
if !s.cfg().whitelist_bypass.creators.contains_key(&name) {
return Response::err(format!("no whitelist-bypass creator '{name}'"));
}
if login.len() > 1 << 20 || serde_json::from_str::<Value>(&login).is_err() {
return Response::err("not a cookies export (or a login): not valid JSON");
}
let file = match crate::wl::state_file(s.paths(), &name, ".cookies.json") {
Ok(f) => f,
Err(e) => return Response::err(format!("{e:#}")),
};
if let Err(e) = crate::wl::write_private(&file, login.as_bytes()) {
return Response::err(format!("{e:#}"));
}
wl_restart(&mut s, &format!("{}{name}", crate::wl::CREATOR_PREFIX)).await
}
Request::WlJoin { name, link } => {
let mut s = shared.lock().await;
if !s.cfg().whitelist_bypass.joiners.contains_key(&name) {
return Response::err(format!("no whitelist-bypass joiner '{name}'"));
}
let link = link.trim();
let link = match crate::wl::clean_link(link) {
Ok(l) if l == link => l,
_ => return Response::err("a call link is one word: a room id, a slug or a URL"),
};
let file = match crate::wl::state_file(s.paths(), &name, ".join") {
Ok(f) => f,
Err(e) => return Response::err(format!("{e:#}")),
};
if let Err(e) = crate::wl::write_private(&file, format!("{link}\n").as_bytes()) {
return Response::err(format!("{e:#}"));
}
wl_restart(&mut s, &format!("{}{name}", crate::wl::JOINER_PREFIX)).await
}
Request::WlNew { name } => {
let mut s = shared.lock().await;
let Some(c) = s.cfg().whitelist_bypass.creators.get(&name) else {
return Response::err(format!("no whitelist-bypass creator '{name}'"));
};
if c.link_file.is_some() {
return Response::err(format!("{name} rejoins the call its linkFile sets: change that instead"));
}
let file = match crate::wl::state_file(s.paths(), &name, ".link") {
Ok(f) => f,
Err(e) => return Response::err(format!("{e:#}")),
};
if let Err(e) = std::fs::remove_file(&file)
&& e.kind() != std::io::ErrorKind::NotFound
{
return Response::err(format!("removing {}: {e}", file.display()));
}
wl_restart(&mut s, &format!("{}{name}", crate::wl::CREATOR_PREFIX)).await
}
Request::AutoList => {
let s = shared.lock().await;
let exits = crate::autoproxy::exits(&s);
Response::ok(crate::autoproxy::listing(s.paths(), exits.as_ref(), &s.cfg().proxy.auto_proxy, has_secrets(s.cfg(), peer)))
}
Request::AutoProbe { target, exits, via, keep_going } => {
let Some(probe_exits) = crate::autoproxy::exits(&*shared.lock().await) else {
return Response::err("autoProxy is not running: it needs proxy.autoProxy.enable and the local proxy on");
};
// The network, outside the lock.
match probe_exits.probe(&target, exits.as_deref(), via.as_deref(), keep_going).await {
Ok(p) => Response::ok(serde_json::to_value(&p).unwrap()),
Err(e) => Response::err(format!("{e:#}")),
}
}
Request::AutoLearn { hosts } => {
let s = shared.lock().await;
if crate::autoproxy::exits(&s).is_none() {
return Response::err("autoProxy is not running: it needs proxy.autoProxy.enable and the local proxy on");
}
let bad: Vec<&String> = hosts.iter().filter(|h| !ps_core::autoproxy::host_ok(h.trim())).collect();
if !bad.is_empty() {
return Response::err(format!("not host names: {}", bad.iter().map(|h| h.as_str()).collect::<Vec<_>>().join(", ")));
}
let opts = &s.cfg().proxy.auto_proxy;
let skipped: Vec<&String> = hosts.iter().filter(|h| crate::autoproxy::excluded(opts, &h.trim().to_ascii_lowercase())).collect();
if !skipped.is_empty() {
return Response::err(format!(
"in proxy.autoProxy.exclude, never probed: {}",
skipped.iter().map(|h| h.as_str()).collect::<Vec<_>>().join(", ")
));
}
let queued = {
let mut r = s.ap.requests.lock().unwrap();
// Bounded: every request is a probe.
let room = 10_000usize.saturating_sub(r.len());
r.extend(hosts.iter().take(room).map(|h| h.trim().to_owned()));
hosts.len().min(room)
};
s.ap.wake.notify_one();
Response::ok(json!({ "queued": queued }))
}
Request::AutoForget { domain } => match crate::autoproxy::edit(shared, domain.as_deref()).await {
Ok(()) => Response::ok(json!({ "forgot": domain.unwrap_or_else(|| "everything".into()) })),
Err(e) => Response::err(format!("{e:#}")),
},
Request::AwgList => {
let s = shared.lock().await;
let cfg = s.cfg();
let vpns = crate::awgvpn::profiles(cfg);
let list: Vec<Value> = cfg
.amnezia_wg
.profiles
.iter()
.map(|(name, p)| match vpns.iter().find(|v| &v.name == name) {
Some(v) => json!({ "name": name, "kind": "vpn", "interface": v.iface, "autostart": v.autostart, "state": crate::awgvpn::state(&v.iface) }),
None => json!({
"name": name,
"kind": match p.as_outbound { Some(ps_core::config::AwgOutboundKind::SingBox) => "singBox", Some(_) => "userspace", None => "vpn" },
"state": if cfg.amnezia_wg.enable { "outbound" } else { "off" },
}),
})
.collect();
Response::ok(json!({ "enabled": cfg.amnezia_wg.enable, "profiles": list }))
}
Request::AwgSet { name, on } => {
let s = shared.lock().await;
let Some(vpn) = crate::awgvpn::profiles(s.cfg()).into_iter().find(|v| v.name == name) else {
return Response::err(format!("no system-wide AmneziaWG profile '{name}' (is amneziaWg.enable on, and the profile without asOutbound?)"));
};
// The SCM's calls wait for the tunnel: not in the async runtime's threads.
let iface = vpn.iface.clone();
let r = tokio::task::spawn_blocking(move || if on { crate::awgvpn::start(&iface) } else { crate::awgvpn::stop(&iface) }).await;
match r {
Ok(Ok(())) => Response::ok(json!({ "name": name, "state": crate::awgvpn::state(&vpn.iface) })),
Ok(Err(e)) => Response::err(format!("{e:#}")),
Err(e) => Response::err(e.to_string()),
}
}
Request::AwgLog { name, lines } => {
let s = shared.lock().await;
let Some(vpn) = crate::awgvpn::profiles(s.cfg()).into_iter().find(|v| v.name == name) else {
return Response::err(format!("no system-wide AmneziaWG profile '{name}'"));
};
Response::ok(json!({ "lines": crate::awgvpn::log_tail(s.paths(), &vpn.iface, lines.min(2000)) }))
}
Request::ZapretCutoff { probe } => {
let s = shared.lock().await;
if probe {
if !crate::cutoff::enabled(s.cfg()) {
return Response::err("the cutoff probe needs zapret.engine = \"zapret2\" with zapret2.cutoff.enable");
}
crate::cutoff::request_probe();
}
Response::ok(crate::cutoff::status(s.cfg(), s.paths()))
}
Request::UpdateCheck => {
let routes = shared.lock().await.fetch_routes(true);
match crate::update::check(&routes).await {
Ok(r) => Response::ok(json!({ "current": env!("CARGO_PKG_VERSION"), "available": r.map(|r| r.to_json()) })),
Err(e) => Response::err(format!("{e:#}")),
}
}
Request::UpdateInstall => {
let (routes, dir) = {
let s = shared.lock().await;
(s.fetch_routes(true), s.paths().updates())
};
match crate::update::install(&routes, &dir).await {
Ok(r) => Response::ok(r.to_json()),
Err(e) => Response::err(format!("{e:#}")),
}
}
Request::ComponentsInstall { names } => {
// Programs the service runs as SYSTEM: an administrator's call, whatever the scopes.
if !peer.admin {
return Response::err("installing components needs an administrator");
}
let manifest = ps_core::components::manifest();
let wanted: Vec<String> = if names.is_empty() {
manifest.components.iter().filter(|(_, c)| !c.bundled).map(|(n, _)| n.clone()).collect()
} else {
names
};
let (bin, cache, routes) = {
let s = shared.lock().await;
(s.paths().bin(), s.paths().root.join("downloads"), s.fetch_routes(true))
};
let mut results = Vec::new();
for name in wanted {
let Some(comp) = manifest.components.get(&name) else {
results.push(json!({ "name": name, "error": "no such component" }));
continue;
};
// What runs from it must let go of its files first.
shared.lock().await.sup.stop_all().await;
let r = crate::install::install(&bin, &name, comp, &routes, &cache).await;
results.push(match r {
Ok(()) => json!({ "name": name, "version": comp.version }),
Err(e) => json!({ "name": name, "error": format!("{e:#}") }),
});
}
let _ = shared.lock().await.apply().await;
Response::ok(json!(results))
}
}
}
fn applied(r: anyhow::Result<()>) -> Response {
match r {
Ok(()) => Response::ok(Value::Null),
Err(e) => Response::err(e.to_string()),
}
}
async fn finish_state(s: &mut tokio::sync::MutexGuard<'_, service::Service>) -> Response {
if let Err(e) = s.store.save_state() {
return Response::err(format!("cannot save the state: {e}"));
}
applied(s.apply().await)
}
#[cfg(test)]
mod tests {
use super::*;
use ps_core::config::Outbound;
#[test]
fn redaction_round_trips_by_tag() {
let mut cfg = Config::default();
cfg.proxy.outbounds = vec![
Outbound { tag: "a".into(), url: Some("hy2://secret-a@a:443".into()), ..Default::default() },
Outbound { tag: "b".into(), url: Some("hy2://secret-b@b:443".into()), ..Default::default() },
];
cfg.proxy.listener.auth.password = Some("pw".into());
let mut shown = redact(&cfg);
assert_eq!(shown["proxy"]["outbounds"][0]["url"], REDACTED);
assert_eq!(shown["proxy"]["listener"]["auth"]["password"], REDACTED);
// The client reorders and adds one; the hidden values follow their tags.
let list = shown["proxy"]["outbounds"].as_array_mut().unwrap();
list.swap(0, 1);
list.push(json!({ "tag": "c", "url": "hy2://new@c:443" }));
unredact(&mut shown, &cfg);
let back: Config = serde_json::from_value(shown).unwrap();
assert_eq!(back.proxy.outbounds[0].url.as_deref(), Some("hy2://secret-b@b:443"));
assert_eq!(back.proxy.outbounds[1].url.as_deref(), Some("hy2://secret-a@a:443"));
assert_eq!(back.proxy.outbounds[2].url.as_deref(), Some("hy2://new@c:443"));
assert_eq!(back.proxy.listener.auth.password.as_deref(), Some("pw"));
}
#[test]
fn following_logs_needs_the_secrets_scope_too() {
assert_eq!(scope_of(&Request::Logs { unit: None, lines: 10, follow: true }), Some(Scope::Secrets));
assert_eq!(scope_of(&Request::Logs { unit: None, lines: 10, follow: false }), Some(Scope::Secrets));
}
#[test]
fn scopes_follow_user_control() {
let mut cfg = Config::default();
let user = Peer { admin: false, user: "u".into() };
assert!(allowed(&cfg, &user, Some(Scope::Routing)).is_ok());
cfg.user_control.scopes = vec![Scope::Routing];
assert!(allowed(&cfg, &user, Some(Scope::Routing)).is_ok());
assert!(allowed(&cfg, &user, Some(Scope::Config)).is_err());
cfg.user_control.enable = false;
assert!(allowed(&cfg, &user, Some(Scope::Routing)).is_err());
assert!(allowed(&cfg, &Peer { admin: true, user: "a".into() }, Some(Scope::Config)).is_ok());
}
}