ps-ipc: line-delimited JSON over a named pipe whose ACL admits SYSTEM, Administrators and (with userControl) the interactive user; the caller is identified by impersonation, never by what it claims. A Unix socket stands in off Windows. ps-service (proxy-suite-service.exe): a Windows service, or --console. Keeps the configuration with revisions, runtime state and generated secrets; renders, checks with sing-box check before replacing what runs, and supervises the backends (restart with backoff, start limit, logs in a ring and a file, a Job Object on Windows). Enforces scopes, admin-only edits and secret redaction that round-trips. Fetches subscriptions and rule sets through the proxy or directly with upstream's redirect rules, on timers. ps-ctl (proxy-ctl.exe): status, restart, logs [-f], config get/set/ validate, and proxy on/off, outbounds, pin, mode, subs, rules, rulesets, tun and config. An end-to-end test runs it all offline: a sing-box Shadowsocks server, the service, proxy-ctl adding the outbound, a page fetched through the local proxy. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
126 lines
4.7 KiB
Rust
126 lines
4.7 KiB
Rust
//! The configuration, runtime state and generated secrets, as files.
|
|
|
|
use std::collections::BTreeMap;
|
|
|
|
use anyhow::{Context, Result};
|
|
use ps_core::config::Config;
|
|
use ps_core::render::{RuleSetFile, State};
|
|
use rand::Rng;
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
use crate::paths::{Paths, write_atomic};
|
|
|
|
/// What the service generated once and keeps.
|
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct Secrets {
|
|
pub clash_secret: String,
|
|
pub hop_user: String,
|
|
pub hop_password: String,
|
|
}
|
|
|
|
pub fn random_token(len: usize) -> String {
|
|
const CHARS: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
|
let mut rng = rand::rng();
|
|
(0..len).map(|_| CHARS[rng.random_range(0..CHARS.len())] as char).collect()
|
|
}
|
|
|
|
pub fn random_uuid() -> String {
|
|
let mut rng = rand::rng();
|
|
let b: [u8; 16] = rng.random();
|
|
format!(
|
|
"{:08x}-{:04x}-4{:03x}-{:04x}-{:012x}",
|
|
u32::from_be_bytes([b[0], b[1], b[2], b[3]]),
|
|
u16::from_be_bytes([b[4], b[5]]),
|
|
u16::from_be_bytes([b[6], b[7]]) & 0x0fff,
|
|
(u16::from_be_bytes([b[8], b[9]]) & 0x3fff) | 0x8000,
|
|
u64::from_be_bytes([0, 0, b[10], b[11], b[12], b[13], b[14], b[15]])
|
|
)
|
|
}
|
|
|
|
pub struct Store {
|
|
pub paths: Paths,
|
|
pub config: Config,
|
|
/// Bumped by every change of `config`: a client edits against a revision.
|
|
pub revision: u64,
|
|
pub state: State,
|
|
pub secrets: Secrets,
|
|
/// Each subscription's links as fetched last.
|
|
pub subscriptions: BTreeMap<String, Vec<String>>,
|
|
}
|
|
|
|
impl Store {
|
|
pub fn open(paths: Paths) -> Result<Self> {
|
|
paths.create_all().with_context(|| format!("creating {}", paths.root.display()))?;
|
|
let config = match std::fs::read_to_string(paths.config()) {
|
|
Ok(text) => Config::from_json(&text).with_context(|| format!("reading {}", paths.config().display()))?,
|
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Config::default(),
|
|
Err(e) => return Err(e).with_context(|| format!("reading {}", paths.config().display())),
|
|
};
|
|
let state = std::fs::read_to_string(paths.state())
|
|
.ok()
|
|
.and_then(|t| serde_json::from_str(&t).ok())
|
|
.unwrap_or_default();
|
|
let secrets = match std::fs::read_to_string(paths.secrets()).ok().and_then(|t| serde_json::from_str(&t).ok()) {
|
|
Some(s) => s,
|
|
None => {
|
|
let s = Secrets { clash_secret: random_token(32), hop_user: "hop".into(), hop_password: random_token(32) };
|
|
write_atomic(&paths.secrets(), serde_json::to_string_pretty(&s)?.as_bytes())?;
|
|
s
|
|
}
|
|
};
|
|
let mut store = Self { paths, config, revision: 1, state, secrets, subscriptions: BTreeMap::new() };
|
|
store.load_subscriptions();
|
|
Ok(store)
|
|
}
|
|
|
|
pub fn save_config(&mut self, config: Config) -> Result<()> {
|
|
write_atomic(&self.paths.config(), config.to_json_pretty().as_bytes())?;
|
|
self.config = config;
|
|
self.revision += 1;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn save_state(&self) -> Result<()> {
|
|
write_atomic(&self.paths.state(), serde_json::to_string_pretty(&self.state)?.as_bytes())?;
|
|
Ok(())
|
|
}
|
|
|
|
fn sub_path(&self, tag: &str) -> std::path::PathBuf {
|
|
self.paths.subscriptions().join(format!("{tag}.txt"))
|
|
}
|
|
|
|
fn load_subscriptions(&mut self) {
|
|
for sub in &self.config.proxy.subscriptions {
|
|
if let Ok(text) = std::fs::read_to_string(self.sub_path(&sub.tag)) {
|
|
self.subscriptions.insert(sub.tag.clone(), text.lines().map(str::to_owned).collect());
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn save_subscription(&mut self, tag: &str, lines: Vec<String>) -> Result<()> {
|
|
write_atomic(&self.sub_path(tag), lines.join("\n").as_bytes())?;
|
|
self.subscriptions.insert(tag.to_owned(), lines);
|
|
Ok(())
|
|
}
|
|
|
|
/// The downloaded rule sets, by tag.
|
|
pub fn rule_set_files(&self) -> BTreeMap<String, RuleSetFile> {
|
|
let mut out = BTreeMap::new();
|
|
let Ok(dir) = std::fs::read_dir(self.paths.rule_sets()) else { return out };
|
|
for entry in dir.flatten() {
|
|
let path = entry.path();
|
|
let (Some(stem), Some(ext)) = (path.file_stem().and_then(|s| s.to_str()), path.extension().and_then(|s| s.to_str())) else {
|
|
continue;
|
|
};
|
|
let format = match ext {
|
|
"srs" => ps_core::config::RuleSetFormat::Binary,
|
|
"json" => ps_core::config::RuleSetFormat::Source,
|
|
_ => continue,
|
|
};
|
|
out.insert(stem.to_owned(), RuleSetFile { path: path.to_string_lossy().into_owned(), format });
|
|
}
|
|
out
|
|
}
|
|
}
|