Compare commits

...
Author SHA1 Message Date
Tunglies 74b815db59 build(deps): update service IPC for kode-bridge 0.6.1 2026-12-04 17:27:32 +08:00
Tunglies e2ae9feb2a build(service): pin the IPC client without magic preflight 2026-12-04 17:21:35 +08:00
Tunglies 99def2004b build(service): pin the client-only IPC dependency cleanup 2026-12-04 17:12:35 +08:00
Tunglies 084f8d36a7 refactor(service)!: require the bundled epoch 3 service 2026-12-04 16:46:16 +08:00
Tunglies 112c5f0e13 build(service): pin the updated IPC tools and client 2026-12-04 16:03:29 +08:00
Tunglies 0cba206e13 refactor(service): use the negotiated protocol for active sessions 2026-12-04 16:00:39 +08:00
Tunglies 72c3653a8a fix(build): bundle service tools from the resolved IPC source 2026-12-04 15:38:22 +08:00
Tunglies 6f81fb91b3 refactor(core): manage sidecar execution in CVR 2026-12-04 15:38:22 +08:00
Tunglies c6c963e9da fix(core): require user action after service failure 2026-12-04 15:36:19 +08:00
Tunglies 287752daff refactor(sidecar): enable kill on drop for the managed child 2026-12-04 15:36:19 +08:00
Tunglies 06329c3337 refactor(backend): extract configuration and runtime capabilities (#8801)
* chore(clippy): scope crate lint policy

Keep panic-on-error lints at application target roots and scope signal dependencies to Linux.

* docs(agents): define Rust backend architecture boundaries

Document which layer owns Rust capabilities, fallible inputs, background work, and crate validation.

* refactor(draft): type async publication conflicts

Return typed conflicts for async Draft edits. Release the lock and edit permit before converting the error, and exercise overlapping updates.

* refactor(logging): use typed logger errors

Expose crate-owned logger errors and preserve the underlying error sources.

* refactor(subscription): extract response decoding

Keep HTTP and persistence in the app. Decode response metadata and framing in the crate, and fall back when the server filename is invalid.

* refactor(profile): extract profile models and index rules

Move profile models and index rules into the crate, preserving serialization and returning a typed missing-profile error.

* refactor(profile): separate subscription refresh and scheduling policy

Separate download and scheduling policy from the subscription use case while retaining the existing write path.

* refactor(subscription): decode deep links in the subscription crate

* refactor(profile): extract selected node recovery rules

* docs(agents): define dependencies between capability crates

* refactor(task): move retry primitives into the task crate

* refactor(backup): extract backup ZIP writing

* refactor(subscription): keep profile writes outside proxy fallback

* refactor(runtime-bundle): extract runtime bundle planning

Plan provider destinations and assets in the crate. Adapt the plan to the Service wire format at the call site.

* perf(runtime-bundle): share destination strings with tristr

Share destination storage within bundle planning and preserve the Service wire strings and provider readback.

* refactor(profile): extract script validation and execution

Share the Boa validation and execution API while preserving the save-side timeout and diagnostics.

* refactor(config): extract configuration renderer

Render from inputs supplied by the app, reuse the script crate, and preserve the default template fast path.

* refactor(proxy): extract proxy view and its use case

Project the Mihomo snapshot into the existing IPC DTO and move use-case orchestration out of the command.

* refactor(config): inject the profile script executor

* refactor(config): centralize Mihomo YAML output

* perf(runtime-bundle): read remote providers from borrowed configuration

* chore(clippy): scope crate lint policy

Keep panic-on-error lints at application target roots and scope signal dependencies to Linux.

* docs(agents): define Rust backend architecture boundaries

Document which layer owns Rust capabilities, fallible inputs, background work, and crate validation.

* refactor(draft): type async publication conflicts

Return typed conflicts for async Draft edits. Release the lock and edit permit before converting the error, and exercise overlapping updates.

* refactor(logging): use typed logger errors

Expose crate-owned logger errors and preserve the underlying error sources.

* refactor(subscription): extract response decoding

Keep HTTP and persistence in the app. Decode response metadata and framing in the crate, and fall back when the server filename is invalid.

* refactor(profile): extract profile models and index rules

Move profile models and index rules into the crate, preserving serialization and returning a typed missing-profile error.

* refactor(profile): separate subscription refresh and scheduling policy

Separate download and scheduling policy from the subscription use case while retaining the existing write path.

* refactor(subscription): decode deep links in the subscription crate

* refactor(profile): extract selected node recovery rules

* docs(agents): define dependencies between capability crates

* refactor(task): move retry primitives into the task crate

* refactor(backup): extract backup ZIP writing

* refactor(subscription): keep profile writes outside proxy fallback

* fix(profile): preserve delays for future update timestamps

* fix(subscription): preserve filenames from response headers and URL paths

* fix(subscription): separate deep link parameters from nested URLs

* refactor(profile): look up the refresh target once

* refactor(subscription): pass the proxy directly to each download

* refactor(profile): build companion options in one place

* refactor(profile): remove companions from the deleted profile

* style(profile): keep profile fields together

* refactor(profile): name index operations after what they change

* refactor(profile): call the core reload directly

* refactor(backup): move archive validation to the restore change

* refactor(config): name the runtime rendering step

* refactor(config): remove the unused runtime patch API

* refactor(config): accumulate profile keys and logs during rendering

* refactor(config): load cached chain items directly

* refactor(script): keep console state local to evaluation

* refactor(proxy): read group order and scope in one pass

* refactor(config): reuse sequence storage when applying profile edits

* refactor(proxy): collect provider snapshots in display order

* refactor(proxy): build the view from its input

* refactor(runtime-bundle): share provider section order

* fix(config): fill blank IPv6 fake IP ranges in TUN mode

* fix(config): keep runtime field sorting stable

* perf(config): reuse profile sequence storage during rendering

* fix(script): check the evaluated profile entry point

* fix(script): support runtime console methods during validation

* perf(script): count integer digits without formatting JSON

* perf(proxy): resolve unique members without building scope caches

* fix(runtime-bundle): reject mixed owners of a provider path

* perf(runtime-bundle): reuse the normalized destination buffer

* fix(script): reject oversized names before escaping
2026-12-03 23:24:11 +00:00
60 changed files with 3388 additions and 3268 deletions
+8 -8
View File
@@ -265,14 +265,6 @@ jobs:
node-version: '26.14.0'
cache: 'pnpm'
- name: Pnpm install and check
run: |
pnpm i
pnpm run prebuild ${{ matrix.target }}
- name: Release ${{ env.TAG_CHANNEL }} Version
run: pnpm release-version autobuild-latest
- name: 'Setup for linux'
run: |-
sudo ls -lR /etc/apt/
@@ -317,6 +309,14 @@ jobs:
gcc-arm-linux-gnueabihf \
g++-arm-linux-gnueabihf
- name: Pnpm install and check
run: |
pnpm i
pnpm run prebuild ${{ matrix.target }}
- name: Release ${{ env.TAG_CHANNEL }} Version
run: pnpm release-version autobuild-latest
- name: Tauri Build for Linux
run: |
export PKG_CONFIG_ALLOW_CROSS=1
+8 -8
View File
@@ -107,6 +107,14 @@ jobs:
node-version: '26.14.0'
cache: 'pnpm'
- name: Add Rust Target
if: github.event.inputs[matrix.input] == 'true'
run: |
# Ensure cross target is installed for the pinned toolchain; fallback without explicit toolchain if needed
rustup target add ${{ matrix.target }} --toolchain 1.100.1 || rustup target add ${{ matrix.target }}
rustup target list --installed
echo "Rust target ${{ matrix.target }} installed."
- name: Pnpm install and check
if: github.event.inputs[matrix.input] == 'true'
run: |
@@ -117,14 +125,6 @@ jobs:
if: github.event.inputs[matrix.input] == 'true'
run: pnpm release-version ${{ env.TAG_NAME }}
- name: Add Rust Target
if: github.event.inputs[matrix.input] == 'true'
run: |
# Ensure cross target is installed for the pinned toolchain; fallback without explicit toolchain if needed
rustup target add ${{ matrix.target }} --toolchain 1.100.1 || rustup target add ${{ matrix.target }}
rustup target list --installed
echo "Rust target ${{ matrix.target }} installed."
- name: Tauri build
if: github.event.inputs[matrix.input] == 'true'
uses: tauri-apps/tauri-action@v1
+5 -5
View File
@@ -333,11 +333,6 @@ jobs:
node-version: '26.14.0'
cache: 'pnpm'
- name: Pnpm install and check
run: |
pnpm i
pnpm run prebuild ${{ matrix.target }}
- name: 'Setup for linux'
run: |-
sudo ls -lR /etc/apt/
@@ -382,6 +377,11 @@ jobs:
gcc-arm-linux-gnueabihf \
g++-arm-linux-gnueabihf
- name: Pnpm install and check
run: |
pnpm i
pnpm run prebuild ${{ matrix.target }}
- name: Build for Linux
run: |
export PKG_CONFIG_ALLOW_CROSS=1
Generated
+57 -15
View File
@@ -1106,16 +1106,19 @@ dependencies = [
"async-trait",
"backon",
"base64 0.23.1",
"boa_engine",
"bytes",
"chrono",
"clash-verge-backup-archive",
"clash-verge-config-render",
"clash-verge-draft",
"clash-verge-i18n",
"clash-verge-limiter",
"clash-verge-logging",
"clash-verge-media-unlock",
"clash-verge-profile",
"clash-verge-profile-script",
"clash-verge-proxy-view",
"clash-verge-runtime-bundle",
"clash-verge-signal",
"clash-verge-subscription",
"clash-verge-task",
@@ -1195,6 +1198,19 @@ dependencies = [
"zip",
]
[[package]]
name = "clash-verge-config-render"
version = "0.1.0"
dependencies = [
"clash-verge-logging",
"log",
"serde",
"serde_json",
"serde_yaml_ng",
"tokio",
"tristr",
]
[[package]]
name = "clash-verge-draft"
version = "0.1.0"
@@ -1259,6 +1275,42 @@ dependencies = [
"tristr",
]
[[package]]
name = "clash-verge-profile-script"
version = "0.1.0"
dependencies = [
"boa_engine",
"clash-verge-logging",
"log",
"serde_json",
"serde_yaml_ng",
"tokio",
"tristr",
]
[[package]]
name = "clash-verge-proxy-view"
version = "0.1.0"
dependencies = [
"serde",
"specta",
"tristr",
]
[[package]]
name = "clash-verge-runtime-bundle"
version = "0.1.0"
dependencies = [
"clash-verge-logging",
"hex",
"log",
"serde_yaml_ng",
"sha2 0.11.2",
"thiserror 2.0.20",
"tokio",
"tristr",
]
[[package]]
name = "clash-verge-signal"
version = "0.1.0"
@@ -1290,8 +1342,8 @@ dependencies = [
[[package]]
name = "clash_verge_service_ipc"
version = "2.8.2"
source = "git+https://github.com/clash-verge-rev/clash-verge-service-ipc.git?branch=main#3e06ff153e9cb19ae20e0a61f861b371d3f7b2aa"
version = "2.8.3"
source = "git+https://github.com/clash-verge-rev/clash-verge-service-ipc.git?rev=fd00f5af2363517e67de57a7ead67737175ac376#fd00f5af2363517e67de57a7ead67737175ac376"
dependencies = [
"anyhow",
"kode-bridge",
@@ -3943,9 +3995,9 @@ dependencies = [
[[package]]
name = "kode-bridge"
version = "0.6.0"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b17456ae84ba9c0da0f189bf00d13019805b89563ba846cd15ccd8c4bd6a2713"
checksum = "e125a6b7f2e7ce5d560ce9517083e27549345a6492ca68194cd96b42e3b27acb"
dependencies = [
"bytes",
"futures",
@@ -3953,7 +4005,6 @@ dependencies = [
"httparse",
"libc",
"parking_lot 0.13.0",
"path-tree",
"pin-project-lite",
"rand 0.10.2",
"serde",
@@ -5105,15 +5156,6 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
[[package]]
name = "path-tree"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a97453bc21a968f722df730bfe11bd08745cb50d1300b0df2bda131dece136"
dependencies = [
"smallvec",
]
[[package]]
name = "pathsearch"
version = "0.2.0"
+11
View File
@@ -10,6 +10,10 @@ members = [
"crates/clash-verge-i18n",
"crates/clash-verge-limiter",
"crates/clash-verge-subscription",
"crates/clash-verge-runtime-bundle",
"crates/clash-verge-config-render",
"crates/clash-verge-profile-script",
"crates/clash-verge-proxy-view",
"crates/clash-verge-profile",
"crates/clash-verge-backup-archive",
]
@@ -56,6 +60,8 @@ muda = { git = "https://github.com/wonfen/muda.git", rev = "547de49352791653fbdf
tauri-plugin-wdio-webdriver = { git = "https://github.com/Tunglies/desktop-mobile.git", rev = "2745082c7f487c5e0c9568000b5a7ac24234d6e4" }
[workspace.dependencies]
clash-verge-config-render = { path = "crates/clash-verge-config-render" }
clash-verge-profile-script = { path = "crates/clash-verge-profile-script" }
clash-verge-draft = { path = "crates/clash-verge-draft" }
clash-verge-task = { path = "crates/clash-verge-task" }
clash-verge-media-unlock = { path = "crates/clash-verge-media-unlock" }
@@ -64,8 +70,11 @@ clash-verge-signal = { path = "crates/clash-verge-signal" }
clash-verge-i18n = { path = "crates/clash-verge-i18n" }
clash-verge-limiter = { path = "crates/clash-verge-limiter" }
clash-verge-subscription = { path = "crates/clash-verge-subscription" }
clash-verge-runtime-bundle = { path = "crates/clash-verge-runtime-bundle" }
clash-verge-proxy-view = { path = "crates/clash-verge-proxy-view" }
clash-verge-profile = { path = "crates/clash-verge-profile" }
clash-verge-backup-archive = { path = "crates/clash-verge-backup-archive" }
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", rev = "fd00f5af2363517e67de57a7ead67737175ac376", version = "2.8.3", default-features = false }
tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", branch = "main" }
tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" }
tracing = "0.1.44"
@@ -76,6 +85,7 @@ parking_lot = "0.13.0"
anyhow = "1.0.105"
thiserror = "2.0.20"
zip = "9.9.0"
boa_engine = "0.22.0"
futures = "0.3.34"
loom = "0.7.3"
proptest = "1.12.0"
@@ -102,6 +112,7 @@ serde = { version = "1.0.229" }
tristr = { git = "https://github.com/Tunglies/tristr", rev = "d849e5cff47a570849c2e1bada0a2b6481cf3378", default-features = false, features = ["serde", "specta"] }
serde_json = { version = "1.0.154" }
serde_yaml_ng = { version = "0.10.0" }
sha2 = "0.11.2"
specta = "=2.0.0-rc.26"
socket2 = "0.6.5"
+2
View File
@@ -23,6 +23,7 @@
GitHub, so they never reach users. -->
## v2.6.0
- 使用 2.6.x 服务模式时请安装随附的服务,2.5.x 客户端无法使用新版服务
- **Mihomo 内核升级至 v1.19.34**
<details>
@@ -49,6 +50,7 @@
**🖥️ Windows**
- 修复 Windows 服务启动失败后自动切换内核,现显示原因并等待用户选择
- 修复 Windows 普通用户因权限不足无法开启「开机自启」
**🍎 macOS**
@@ -0,0 +1,18 @@
[package]
name = "clash-verge-config-render"
version = "0.1.0"
edition = "2024"
[dependencies]
clash-verge-logging = { workspace = true }
log = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
serde_yaml_ng = { workspace = true }
tristr = { workspace = true }
[dev-dependencies]
tokio = { workspace = true }
[lints]
workspace = true
@@ -18,19 +18,21 @@ pub const HANDLE_FIELDS: [&str; 12] = [
pub const DEFAULT_FIELDS: [&str; 5] = ["proxies", "proxy-providers", "proxy-groups", "rule-providers", "rules"];
fn lowercase_key(key: &str) -> Value {
let mut key = String::from(key);
key.make_ascii_lowercase();
Value::from(key.as_str())
}
pub fn use_lowercase(config: Mapping) -> Mapping {
let mut lowercased = Mapping::new();
for (key, value) in config {
if let Some(key_str) = key.as_str() {
lowercased.insert(lowercase_key(key_str), value);
}
let mut key = match key {
Value::String(key) => key,
key => {
let Some(key) = key.as_str() else {
continue;
};
key.to_owned()
}
};
key.make_ascii_lowercase();
lowercased.insert(Value::String(key), value);
}
lowercased
}
@@ -39,7 +41,7 @@ pub fn use_sort(mut config: Mapping) -> Mapping {
let mut sorted = Mapping::new();
HANDLE_FIELDS.into_iter().for_each(|key| {
let key = Value::from(key);
if let Some(value) = config.remove(&key) {
if let Some(value) = config.shift_remove(&key) {
sorted.insert(key, value);
}
});
@@ -66,8 +68,8 @@ pub fn use_sort(mut config: Mapping) -> Mapping {
}
#[inline]
pub fn use_keys<'a>(config: &'a Mapping) -> impl Iterator<Item = String> + 'a {
config.iter().filter_map(|(key, _)| key.as_str()).map(|s: &str| {
pub(super) fn lowercase_config_keys(config: &Mapping) -> impl Iterator<Item = String> {
config.keys().filter_map(Value::as_str).map(|s: &str| {
let mut s: String = s.into();
s.make_ascii_lowercase();
s
File diff suppressed because it is too large Load Diff
@@ -32,7 +32,7 @@ pub fn use_merge(merge: Mapping, mut config: Mapping) -> Mapping {
}
#[test]
fn test_merge() -> anyhow::Result<()> {
fn test_merge() -> Result<(), serde_yaml_ng::Error> {
let merge = r"
prepend-rules:
- prepend
@@ -0,0 +1,81 @@
use super::{ResultLog, ScriptOutcome, field::use_lowercase};
use serde_yaml_ng::Mapping;
use tristr::alias::String;
type ScriptResult = (Mapping, Vec<String>, ResultLog);
/// Never fails: exceptions are logged and the input config is returned unchanged.
pub(super) async fn use_script<Fut: Future<Output = ScriptOutcome> + Send>(
script: String,
config: Mapping,
name: String,
execute: impl FnOnce(String, serde_json::Value, String) -> Fut + Send,
) -> ScriptResult {
// The template is identity-plus-lowercasing; skip the Boa round-trip.
if script == super::ITEM_SCRIPT {
return (use_lowercase(config), vec![], vec![]);
}
let json = match serde_json::to_value(&config) {
Ok(mut json) => {
if let Some(map) = json.as_object_mut() {
let mut lowered = serde_json::Map::with_capacity(map.len());
for (key, value) in std::mem::take(map) {
let mut key = key;
key.make_ascii_lowercase();
lowered.insert(key, value);
}
*map = lowered;
}
json
}
Err(err) => return (config, vec![], vec![("exception".into(), err.to_string().into())]),
};
let (outcome, mut logs) = execute(script, json, name).await;
match outcome {
Ok(result) => {
let result = use_lowercase(result);
// Compared against the config as handed in, not the lowercased copy the script saw.
let changed_keys = result
.iter()
.filter(|(key, value)| config.get(key) != Some(value))
.filter_map(|(key, _)| {
let mut key: String = key.as_str()?.into();
key.make_ascii_lowercase();
Some(key)
})
.collect();
(result, changed_keys, logs)
}
Err(reason) => {
logs.push(("exception".into(), reason.into()));
(config, vec![], logs)
}
}
}
#[cfg(test)]
mod tests {
use std::future::ready;
use super::{Mapping, use_script};
#[tokio::test]
async fn default_template_skips_the_executor() {
let mut called = false;
let mut config = Mapping::new();
config.insert("MiXeD".into(), true.into());
let (config, changed_keys, logs) =
use_script(crate::ITEM_SCRIPT.into(), config, "profile".into(), |_, _, _| {
called = true;
ready((Ok(Mapping::new()), vec![]))
})
.await;
assert!(!called);
assert_eq!(config["mixed"], serde_yaml_ng::Value::Bool(true));
assert!(changed_keys.is_empty());
assert!(logs.is_empty());
}
}
@@ -1,6 +1,7 @@
use serde::{Deserialize, Serialize};
use serde_yaml_ng::{Mapping, Sequence, Value};
use std::collections::HashSet;
use tristr::TriStr;
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SeqMap {
@@ -9,14 +10,12 @@ pub struct SeqMap {
pub delete: Vec<String>,
}
fn collect_proxy_names(seq: &Sequence) -> Vec<String> {
seq.iter()
.filter_map(|item| match item {
Value::Mapping(map) => map.get("name").and_then(Value::as_str).map(str::to_owned),
Value::String(name) => Some(name.to_owned()),
_ => None,
})
.collect()
fn proxy_name(proxy: &Value) -> Option<&str> {
match proxy {
Value::Mapping(proxy) => proxy.get("name").and_then(Value::as_str),
Value::String(name) => Some(name),
_ => None,
}
}
fn is_selector_group(group_map: &Mapping) -> bool {
@@ -34,41 +33,34 @@ pub fn use_seq(seq: SeqMap, mut config: Mapping, field: &str) -> Mapping {
} = seq;
let added_proxy_names = if field == "proxies" {
let mut names = collect_proxy_names(&prepend);
names.extend(collect_proxy_names(&append));
let mut seen = HashSet::new();
names
.into_iter()
.filter(|name| seen.insert(name.clone()))
.collect::<Vec<String>>()
prepend
.iter()
.chain(&append)
.filter_map(proxy_name)
.map(TriStr::from)
.collect::<Vec<_>>()
} else {
Vec::new()
};
let mut updated_items = Sequence::new();
updated_items.extend(prepend);
if let Some(Value::Sequence(existing_items)) = config.remove(field) {
// Filter out deleted items
let kept_items: Sequence = existing_items
.into_iter()
.filter(|item| {
if let Value::String(s) = item {
!delete.contains(s)
} else if let Value::Mapping(m) = item {
if let Some(Value::String(name)) = m.get("name") {
!delete.contains(name)
} else {
true
}
} else {
true
}
})
.collect();
updated_items.extend(kept_items);
let mut updated_items = match config.remove(field) {
Some(Value::Sequence(items)) => items,
_ => Sequence::new(),
};
if !delete.is_empty() {
updated_items.retain(|item| {
let name = match item {
Value::String(name) => Some(name),
Value::Mapping(mapping) => match mapping.get("name") {
Some(Value::String(name)) => Some(name),
_ => None,
},
_ => None,
};
name.is_none_or(|name| !delete.contains(name))
});
}
updated_items.splice(..0, prepend);
updated_items.extend(append);
config.insert(Value::String(field.into()), Value::Sequence(updated_items));
@@ -80,66 +72,57 @@ pub fn use_seq(seq: SeqMap, mut config: Mapping, field: &str) -> Mapping {
return config;
};
let Value::Sequence(proxy_groups) = proxy_groups_value else {
let Value::Sequence(mut proxy_groups) = proxy_groups_value else {
config.insert(Value::String("proxy-groups".into()), proxy_groups_value);
return config;
};
let mut updated_groups = Sequence::new();
let mut appended_to_selector = false;
for group in proxy_groups {
if let Value::Mapping(mut group_map) = group {
let mut group_proxies = match group_map.remove("proxies") {
Some(Value::Sequence(proxies)) => Some(
proxies
.into_iter()
.filter(|p| {
if let Value::String(name) = p {
!delete.contains(name)
} else {
true
}
})
.collect::<Sequence>(),
),
Some(value) => {
group_map.insert(Value::String("proxies".into()), value);
None
for group in &mut proxy_groups {
let Value::Mapping(group_map) = group else {
continue;
};
let mut group_proxies = match group_map.remove("proxies") {
Some(Value::Sequence(mut proxies)) => {
if !delete.is_empty() {
proxies.retain(|member| !matches!(member, Value::String(name) if delete.contains(name)));
}
None => None,
};
if !appended_to_selector && !added_proxy_names.is_empty() && is_selector_group(&group_map) {
let base_group_proxies = group_proxies.unwrap_or_else(Sequence::new);
let mut merged_proxies = Sequence::new();
let mut seen_proxy_names = HashSet::new();
for name in &added_proxy_names {
if seen_proxy_names.insert(name.clone()) {
merged_proxies.push(Value::String(name.clone()));
}
}
for value in base_group_proxies {
if let Value::String(name) = &value
&& !seen_proxy_names.insert(name.to_owned())
{
continue;
}
merged_proxies.push(value);
}
group_proxies = Some(merged_proxies);
appended_to_selector = true;
Some(proxies)
}
if let Some(group_proxies) = group_proxies {
group_map.insert(Value::String("proxies".into()), Value::Sequence(group_proxies));
Some(value) => {
group_map.insert(Value::String("proxies".into()), value);
None
}
updated_groups.push(Value::Mapping(group_map));
} else {
updated_groups.push(group);
None => None,
};
if !appended_to_selector && !added_proxy_names.is_empty() && is_selector_group(group_map) {
let base_group_proxies = group_proxies.unwrap_or_else(Sequence::new);
let mut merged_proxies = Sequence::new();
let mut seen_proxy_names = HashSet::new();
for name in &added_proxy_names {
if seen_proxy_names.insert(name.clone()) {
merged_proxies.push(Value::String(name.as_str().to_owned()));
}
}
for value in base_group_proxies {
if let Value::String(name) = &value
&& !seen_proxy_names.insert(TriStr::from(name.as_str()))
{
continue;
}
merged_proxies.push(value);
}
group_proxies = Some(merged_proxies);
appended_to_selector = true;
}
if let Some(group_proxies) = group_proxies {
group_map.insert(Value::String("proxies".into()), Value::Sequence(group_proxies));
}
}
config.insert(Value::String("proxy-groups".into()), Value::Sequence(updated_groups));
config.insert(Value::String("proxy-groups".into()), Value::Sequence(proxy_groups));
config
}
@@ -32,9 +32,7 @@ pub fn use_tun(mut config: Mapping, enable: bool) -> Mapping {
revise!(dns_val, "fake-ip-range", "198.18.0.1/16");
}
if ipv6_val && !dns_val.contains_key(Value::from("fake-ip-range6")) {
revise!(dns_val, "fake-ip-range6", "2001:2::0/64");
}
super::ensure_fake_ip_range6(&mut dns_val);
}
revise!(config, "dns", dns_val);
@@ -45,3 +43,20 @@ pub fn use_tun(mut config: Mapping, enable: bool) -> Mapping {
config
}
pub(super) const DEFAULT_MTU: u16 = 1500;
/// Saved dialog fields; `enable` belongs to the verge switch.
pub(super) const GUI_KEYS: &[&str] = &[
"stack",
"device",
"auto-route",
"route-exclude-address",
#[cfg(target_os = "linux")]
"auto-redirect",
"auto-detect-interface",
"dns-hijack",
"dns-mode",
"strict-route",
"mtu",
];
@@ -0,0 +1,16 @@
[package]
name = "clash-verge-profile-script"
version = "0.1.0"
edition = "2024"
[dependencies]
boa_engine = { workspace = true }
clash-verge-logging = { workspace = true }
log = { workspace = true }
serde_json = { workspace = true }
serde_yaml_ng = { workspace = true }
tokio = { workspace = true }
tristr = { workspace = true }
[lints]
workspace = true
@@ -1,79 +1,64 @@
use crate::{process::AsyncHandler, utils::tmpl};
use super::field::use_lowercase;
use anyhow::Result;
use boa_engine::{Context, JsString, JsValue, Source, js_string, native_function::NativeFunction, property::Attribute};
use clash_verge_logging::{Type, logging};
use parking_lot::Mutex;
use serde_yaml_ng::Mapping;
use std::sync::Arc;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use tristr::alias::String;
const MAX_OUTPUTS: usize = 1000;
const MAX_OUTPUT_SIZE: usize = 1024 * 1024; // 1MB
const MAX_PROFILE_NAME_BYTES: usize = 1024;
const MAX_JSON_SIZE: usize = 10 * 1024 * 1024; // 10MB
const MAX_LOOP_ITERATIONS: u64 = 10_000_000;
const SCRIPT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
type ScriptResult = (Mapping, Vec<String>, Vec<(String, String)>);
type EvalOutcome = (Result<Mapping, std::string::String>, Vec<(String, String)>);
/// Script logs are retained when evaluation or result conversion fails.
pub type ScriptLogs = Vec<(String, String)>;
/// Never fails: exceptions are logged and the input config is returned unchanged.
pub(super) async fn use_script(script: String, config: Mapping, name: String) -> ScriptResult {
// The template is identity-plus-lowercasing; skip the Boa round-trip.
if script == tmpl::ITEM_SCRIPT {
return (use_lowercase(config), vec![], vec![]);
type EvalOutcome = (Result<Mapping, std::string::String>, ScriptLogs);
#[derive(Debug, PartialEq, Eq)]
pub enum MainDeclaration {
Present,
Missing,
}
/// Evaluates the source and checks that the entry point is callable.
pub fn validate(source: &str) -> Result<MainDeclaration, std::string::String> {
let mut context = Context::default();
let _ = context.eval(Source::from_bytes(
"var console = Object.freeze({log(...data){},info(...data){},error(...data){},debug(...data){},warn(...data){},table(...data){}});",
));
context
.eval(Source::from_bytes(source))
.map_err(|err| err.to_string())?;
let has_main = context
.eval(Source::from_bytes("typeof main === 'function'"))
.map_err(|err| err.to_string())?
.to_boolean();
Ok(if has_main {
MainDeclaration::Present
} else {
MainDeclaration::Missing
})
}
/// Runs one script on the blocking pool. The timeout bounds waiting for its result.
pub async fn execute(script: String, config: serde_json::Value, name: String) -> EvalOutcome {
if json_approx_size(&config) > MAX_JSON_SIZE {
return (
Err("Configuration size exceeds maximum allowed size".to_owned()),
vec![],
);
}
let json = match serde_json::to_value(&config) {
Ok(mut json) => {
if let Some(map) = json.as_object_mut() {
let mut lowered = serde_json::Map::with_capacity(map.len());
for (key, value) in std::mem::take(map) {
let mut key = key;
key.make_ascii_lowercase();
lowered.insert(key, value);
}
*map = lowered;
}
if json_approx_size(&json) <= MAX_JSON_SIZE {
json
} else {
let message = "Configuration size exceeds maximum allowed size";
return (config, vec![], vec![("exception".into(), message.into())]);
}
}
Err(err) => return (config, vec![], vec![("exception".into(), err.to_string().into())]),
};
let evaluated = AsyncHandler::spawn_blocking(move || eval_script(&script, &json, &name));
let (outcome, mut logs) = match tokio::time::timeout(SCRIPT_TIMEOUT, evaluated).await {
let evaluated = tokio::task::spawn_blocking(move || eval_script(&script, &config, &name));
match tokio::time::timeout(SCRIPT_TIMEOUT, evaluated).await {
Ok(Ok(evaluated)) => evaluated,
Ok(Err(join_err)) => (Err(format!("script task panicked: {join_err}")), vec![]),
Err(_elapsed) => (
Err(_) => (
Err(format!("script execution timed out after {SCRIPT_TIMEOUT:?}")),
vec![],
),
};
match outcome {
Ok(result) => {
// Compared against the config as handed in, not the lowercased copy the script saw.
let changed_keys = result
.iter()
.filter(|(key, value)| config.get(key) != Some(value))
.filter_map(|(key, _)| {
let mut key: String = key.as_str()?.into();
key.make_ascii_lowercase();
Some(key)
})
.collect();
(result, changed_keys, logs)
}
Err(reason) => {
logs.push(("exception".into(), reason.into()));
(config, vec![], logs)
}
}
}
@@ -85,13 +70,11 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) ->
.runtime_limits_mut()
.set_loop_iteration_limit(MAX_LOOP_ITERATIONS);
let outputs = Arc::new(Mutex::new(vec![]));
let total_size = Arc::new(Mutex::new(0usize));
let outputs_clone = Arc::clone(&outputs);
let total_size_clone = Arc::clone(&total_size);
let bail = |reason: std::string::String| (Err(reason), outputs.lock().to_vec());
let logs = Rc::new(RefCell::new(Vec::new()));
let console_logs = Rc::clone(&logs);
let logged_bytes = Cell::new(0);
let take_logs = || logs.take();
let bail = |reason: std::string::String| (Err(reason), take_logs());
let _ = context.register_global_builtin_callable("__verge_log__".into(), 2, unsafe {
NativeFunction::from_closure(move |_: &JsValue, args: &[JsValue], context: &mut Context| {
@@ -111,23 +94,21 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) ->
boa_engine::JsError::from_opaque(JsString::from("Failed to convert data to string").into())
})?;
// 检查输出限制
if outputs_clone.lock().len() >= MAX_OUTPUTS {
let mut entries = console_logs.borrow_mut();
if entries.len() >= MAX_OUTPUTS {
return Err(boa_engine::JsError::from_opaque(
JsString::from("Maximum number of log outputs exceeded").into(),
));
}
let mut size = total_size_clone.lock();
let new_size = *size + level.len() + data.len();
let new_size = logged_bytes.get() + level.len() + data.len();
if new_size > MAX_OUTPUT_SIZE {
return Err(boa_engine::JsError::from_opaque(
JsString::from("Maximum output size exceeded").into(),
));
}
*size = new_size;
drop(size);
outputs_clone.lock().push((level.into(), data.into()));
logged_bytes.set(new_size);
entries.push((level.into(), data.into()));
Ok(JsValue::undefined())
})
});
@@ -151,16 +132,14 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) ->
return bail(format!("failed to bind config for script: {err}"));
}
// 仅处理 name 参数中的特殊字符
let safe_name = escape_js_string_for_single_quote(name);
if safe_name.len() > 1024 {
let Some(escaped_profile_name) = escape_profile_name(name) else {
return bail("Name parameter too long".to_owned());
}
};
let code = format!(
r"try{{
{script};
main(globalThis.__verge_config__,'{safe_name}')
main(globalThis.__verge_config__,'{escaped_profile_name}')
}} catch(err) {{
`__error_flag__ ${{err.toString()}}`
}}"
@@ -214,7 +193,7 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) ->
}
match serde_json::from_value::<Mapping>(result) {
Ok(config) => (Ok(use_lowercase(config)), outputs.lock().to_vec()),
Ok(config) => (Ok(config), take_logs()),
Err(err) => {
logging!(
error,
@@ -235,21 +214,92 @@ fn json_approx_size(value: &serde_json::Value) -> usize {
.map(|(key, value)| key.len() + 4 + json_approx_size(value))
.sum(),
serde_json::Value::Array(items) => items.iter().map(json_approx_size).sum(),
serde_json::Value::Number(n) => n.to_string().len(),
serde_json::Value::Number(n) => {
if let Some(n) = n.as_u64() {
n.checked_ilog10().unwrap_or(0) as usize + 1
} else if let Some(n) = n.as_i64() {
n.unsigned_abs().checked_ilog10().unwrap_or(0) as usize + 2
} else {
n.to_string().len()
}
}
serde_json::Value::Bool(_) | serde_json::Value::Null => 4,
}
}
// 安全地转义字符串
fn escape_js_string_for_single_quote(s: &str) -> String {
// 限制处理的字符串长度
if s.len() > 10240 {
return s[..10240].replace('\\', "\\\\").replace('\'', "\\'").into();
fn escape_profile_name(name: &str) -> Option<String> {
if name.len() > MAX_PROFILE_NAME_BYTES {
return None;
}
let escaped = name
.replace('\\', "\\\\")
.replace('\'', "\\'")
.replace('\n', "\\n")
.replace('\r', "\\r");
(escaped.len() <= MAX_PROFILE_NAME_BYTES).then(|| escaped.into())
}
#[cfg(test)]
mod tests {
use super::{MainDeclaration, eval_script, validate};
#[test]
fn profile_name_limit_counts_escaped_bytes() {
assert!(super::escape_profile_name(&"订阅".repeat(171)).is_none());
assert!(super::escape_profile_name(&"'".repeat(512)).is_some());
assert!(super::escape_profile_name(&"'".repeat(513)).is_none());
}
s.replace('\\', "\\\\")
.replace('\'', "\\'")
.replace('\n', "\\n") // 添加换行符转义
.replace('\r', "\\r") // 添加回车转义
.into()
#[test]
fn numeric_size_matches_the_rendered_number() {
for number in [
0.into(),
10.into(),
(-10).into(),
i64::MIN.into(),
u64::MAX.into(),
serde_json::json!(1.25),
] {
assert_eq!(super::json_approx_size(&number), number.to_string().len());
}
}
#[test]
fn console_entries_survive_a_script_error() {
let (result, logs) = eval_script(
"function main() { console.log(1); console.warn(2); throw Error(); }",
&serde_json::json!({}),
&"profile".into(),
);
assert!(result.is_err());
assert_eq!(logs, [("log".into(), "1".into()), ("warn".into(), "2".into())]);
}
#[test]
fn validation_checks_the_evaluated_main_binding() {
assert_eq!(
validate("const main = config => config;"),
Ok(MainDeclaration::Present)
);
assert_eq!(validate("// function main goes here"), Ok(MainDeclaration::Missing));
assert_eq!(validate("const main = 42;"), Ok(MainDeclaration::Missing));
}
#[test]
fn validation_supports_console_methods_at_top_level() {
assert_eq!(
validate("console.warn('setup'); console.table([1]); function main(config) { return config; }"),
Ok(MainDeclaration::Present)
);
}
#[test]
fn validation_distinguishes_missing_main_from_evaluation_failure() {
assert_eq!(
validate("console.log('setup'); const main = config => config;"),
Ok(MainDeclaration::Present)
);
assert_eq!(validate("console.log('setup');"), Ok(MainDeclaration::Missing));
assert!(validate("throw new Error('setup failed'); function main(config) { return config; }").is_err());
}
}
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "clash-verge-proxy-view"
version = "0.1.0"
edition = "2024"
[dependencies]
serde = { workspace = true, features = ["derive"] }
specta = { workspace = true, features = ["derive"] }
tristr = { workspace = true }
[lints]
workspace = true
@@ -1,15 +1,40 @@
use std::collections::{BTreeMap, BTreeSet};
use std::collections::{BTreeMap, BTreeSet, HashMap};
use serde::Serialize;
use tauri_plugin_mihomo::models::{
DelayHistory, Proxies, Proxy, ProxyProvider, ProxyProviders, ProxyType, VehicleType,
};
use tristr::alias::String;
pub struct ProxyViewInput {
pub runtime_group_order: Vec<String>,
pub group_scopes: BTreeMap<String, GroupScope>,
pub proxies: Proxies,
pub providers: Option<ProxyProviders>,
pub proxies: HashMap<String, ProxySnapshot>,
pub providers: Option<BTreeMap<String, ProviderSnapshot>>,
}
pub struct ProxySnapshot {
pub name: String,
pub proxy_type: String,
pub all: Option<Vec<String>>,
pub fixed: Option<String>,
pub hidden: Option<bool>,
pub icon: Option<String>,
pub now: Option<String>,
pub test_url: Option<String>,
pub id: Option<String>,
pub history: Vec<DelayHistory>,
pub capabilities: ProxyCapabilities,
}
pub struct ProviderSnapshot {
pub vehicle_type: ProxyProviderVehicleType,
pub proxies: Vec<ProxySnapshot>,
pub updated_at: Option<String>,
pub subscription_info: Option<ProxySubscriptionInfo>,
}
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)]
pub struct DelayHistory {
pub time: String,
pub delay: u16,
}
/// The providers a group draws from (Mihomo order) and its `exclude-type` entries.
@@ -18,8 +43,6 @@ pub struct GroupScope {
pub exclude_types: Vec<String>,
}
pub struct ProxyViewBuilder;
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct ProxyViewV1 {
@@ -62,8 +85,7 @@ pub struct ProxyCapabilities {
pub struct ProxyGroupView {
pub name: String,
#[serde(rename = "type")]
#[specta(type = String)]
pub proxy_type: ProxyType,
pub proxy_type: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub now: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -74,7 +96,6 @@ pub struct ProxyGroupView {
pub icon: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub test_url: Option<String>,
#[specta(type = Vec<crate::ipc::DelayHistory>)]
pub history: Vec<DelayHistory>,
#[serde(flatten)]
pub capabilities: ProxyCapabilities,
@@ -87,9 +108,7 @@ pub struct ProxyNodeView {
pub record_id: String,
pub name: String,
#[serde(rename = "type")]
#[specta(type = String)]
pub proxy_type: ProxyType,
#[specta(type = Vec<crate::ipc::DelayHistory>)]
pub proxy_type: String,
pub history: Vec<DelayHistory>,
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
@@ -190,8 +209,8 @@ struct MemberResolver<'a> {
impl<'a> MemberResolver<'a> {
/// Same-name records in the order Mihomo lists them in `group`: `use` order, after `exclude-type`.
fn scoped_candidates(&self, group: &str, name: &str) -> Vec<&'a String> {
let (Some(scope), Some(candidates)) = (self.group_scopes.get(group), self.provider_candidates.get(name)) else {
fn scoped_candidates(&self, group: &str, candidates: &'a [(String, String)]) -> Vec<&'a String> {
let Some(scope) = self.group_scopes.get(group) else {
return Vec::new();
};
scope
@@ -200,17 +219,23 @@ impl<'a> MemberResolver<'a> {
.flat_map(|provider| candidates.iter().filter(move |(owner, _)| owner == provider))
.map(|(_, record_id)| record_id)
.filter(|record_id| {
!self.records.get(*record_id).is_some_and(|node| {
scope
.exclude_types
.iter()
.any(|excluded| excluded.eq_ignore_ascii_case(node.proxy_type.as_str()))
})
scope.exclude_types.is_empty()
|| !self.records.get(*record_id).is_some_and(|node| {
scope
.exclude_types
.iter()
.any(|excluded| excluded.eq_ignore_ascii_case(node.proxy_type.as_str()))
})
})
.collect()
}
fn resolve(&self, name: String, scoped: Option<&String>) -> ProxyMemberRef {
fn resolve(
&self,
group: &str,
name: String,
seen: &mut BTreeMap<String, (usize, Vec<&'a String>)>,
) -> ProxyMemberRef {
if self.group_names.contains(&name) {
ProxyMemberRef::Group { name }
} else if let Some(record_id) = self.core_node_ids.get(&name) {
@@ -225,16 +250,30 @@ impl<'a> MemberResolver<'a> {
}
} else {
let candidates = self.provider_candidates.get(&name).map_or(&[][..], Vec::as_slice);
match (scoped, candidates) {
(Some(record_id), _) | (None, [(_, record_id)]) => ProxyMemberRef::Node {
let record_id = match candidates {
[(_, record_id)] => Some(record_id),
[] => {
return ProxyMemberRef::Unresolved {
name,
reason: ProxyMemberUnresolvedReason::Missing,
};
}
_ => {
// The n-th occurrence in Mihomo's member list selects the n-th scoped candidate.
let (occurrence, scoped) = seen
.entry(name.clone())
.or_insert_with(|| (0, self.scoped_candidates(group, candidates)));
let record_id = scoped.get(*occurrence).or_else(|| scoped.first()).copied();
*occurrence += 1;
record_id
}
};
match record_id {
Some(record_id) => ProxyMemberRef::Node {
name,
record_id: record_id.clone(),
},
(None, []) => ProxyMemberRef::Unresolved {
name,
reason: ProxyMemberUnresolvedReason::Missing,
},
(None, _) => ProxyMemberRef::Unresolved {
None => ProxyMemberRef::Unresolved {
name,
reason: ProxyMemberUnresolvedReason::Ambiguous,
},
@@ -243,14 +282,14 @@ impl<'a> MemberResolver<'a> {
}
}
impl ProxyViewBuilder {
pub fn build(input: ProxyViewInput) -> ProxyViewV1 {
let ProxyViewInput {
impl ProxyViewInput {
pub fn into_view(self) -> ProxyViewV1 {
let Self {
runtime_group_order,
group_scopes,
proxies,
providers,
} = input;
} = self;
let provider_state = if providers.is_some() {
ProxyViewProviderState::Ready
} else {
@@ -270,7 +309,7 @@ impl ProxyViewBuilder {
let global = core_groups
.remove("GLOBAL")
.map(|proxy| build_group("GLOBAL".to_owned(), proxy, &resolver));
.map(|proxy| build_group("GLOBAL".into(), proxy, &resolver));
let (groups, order_source) = build_ordered_groups(core_groups, runtime_group_order, &resolver);
let direct = core_node_ids.get("DIRECT").cloned();
let standalone = build_standalone(&core_node_ids);
@@ -289,11 +328,13 @@ impl ProxyViewBuilder {
}
}
fn partition_core(proxies: Proxies) -> (BTreeMap<String, Proxy>, BTreeMap<String, Proxy>) {
fn partition_core(
proxies: HashMap<String, ProxySnapshot>,
) -> (BTreeMap<String, ProxySnapshot>, BTreeMap<String, ProxySnapshot>) {
let mut groups = BTreeMap::new();
let mut nodes = BTreeMap::new();
for (name, proxy) in proxies.proxies {
for (name, proxy) in proxies {
if proxy.all.is_some() {
groups.insert(name, proxy);
} else {
@@ -305,13 +346,13 @@ fn partition_core(proxies: Proxies) -> (BTreeMap<String, Proxy>, BTreeMap<String
}
fn build_core_records(
core_nodes: BTreeMap<String, Proxy>,
core_nodes: BTreeMap<String, ProxySnapshot>,
) -> (BTreeMap<String, ProxyNodeView>, BTreeMap<String, String>) {
let mut records = BTreeMap::new();
let mut ids = BTreeMap::new();
for (index, (name, proxy)) in core_nodes.into_iter().enumerate() {
let record_id = format!("c:{index}");
let record_id: String = format!("c:{index}").into();
ids.insert(name.clone(), record_id.clone());
records.insert(
record_id.clone(),
@@ -328,32 +369,24 @@ fn build_core_records(
}
fn build_provider_records(
providers: Option<ProxyProviders>,
providers: Option<BTreeMap<String, ProviderSnapshot>>,
records: &mut BTreeMap<String, ProxyNodeView>,
) -> (Vec<ProxyProviderView>, ProviderCandidates) {
let providers = providers.map_or_default(|providers| providers.providers.into_iter().collect::<BTreeMap<_, _>>());
let mut views = Vec::new();
let mut candidates = BTreeMap::new();
for (provider_name, provider) in providers {
let ProxyProvider {
for (provider_name, provider) in providers.into_iter().flatten() {
let ProviderSnapshot {
vehicle_type,
proxies,
updated_at,
subscription_info,
..
} = provider;
let vehicle_type = match vehicle_type {
VehicleType::HTTP => ProxyProviderVehicleType::Http,
VehicleType::File => ProxyProviderVehicleType::File,
VehicleType::Inline => ProxyProviderVehicleType::Inline,
_ => continue,
};
let provider_index = views.len();
let mut proxy_record_ids = Vec::new();
for (member_index, proxy) in proxies.into_iter().enumerate() {
let record_id = format!("p:{provider_index}:{member_index}");
let record_id: String = format!("p:{provider_index}:{member_index}").into();
let proxy_name = proxy.name.clone();
let node_name = proxy.name.clone();
candidates
@@ -379,12 +412,7 @@ fn build_provider_records(
name: provider_name,
vehicle_type,
updated_at,
subscription_info: subscription_info.map(|subscription_info| ProxySubscriptionInfo {
upload: subscription_info.upload,
download: subscription_info.download,
total: subscription_info.total,
expire: subscription_info.expire,
}),
subscription_info,
proxy_record_ids,
});
}
@@ -392,8 +420,8 @@ fn build_provider_records(
(views, candidates)
}
fn build_group(name: String, proxy: Proxy, resolver: &MemberResolver<'_>) -> ProxyGroupView {
let Proxy {
fn build_group(name: String, proxy: ProxySnapshot, resolver: &MemberResolver<'_>) -> ProxyGroupView {
let ProxySnapshot {
all,
fixed,
hidden,
@@ -401,27 +429,15 @@ fn build_group(name: String, proxy: Proxy, resolver: &MemberResolver<'_>) -> Pro
now,
test_url,
history,
udp,
xudp,
tfo,
mptcp,
smux,
capabilities,
proxy_type,
..
} = proxy;
// The n-th occurrence of a name in `all` is the n-th scoped candidate.
let mut seen = BTreeMap::<String, (usize, Vec<&String>)>::new();
let mut seen = BTreeMap::new();
let members = all
.unwrap_or_default()
.into_iter()
.map(|member| {
let (occurrence, scoped) = seen
.entry(member.clone())
.or_insert_with(|| (0, resolver.scoped_candidates(&name, &member)));
let picked = scoped.get(*occurrence).or_else(|| scoped.first()).copied();
*occurrence += 1;
resolver.resolve(member, picked)
})
.map(|member| resolver.resolve(&name, member, &mut seen))
.collect();
ProxyGroupView {
@@ -433,29 +449,19 @@ fn build_group(name: String, proxy: Proxy, resolver: &MemberResolver<'_>) -> Pro
icon,
test_url,
history,
capabilities: ProxyCapabilities {
udp,
xudp,
tfo,
mptcp,
smux,
},
capabilities,
members,
}
}
fn build_node(record_id: String, name: String, proxy: Proxy, source: ProxyNodeSource) -> ProxyNodeView {
let Proxy {
fn build_node(record_id: String, name: String, proxy: ProxySnapshot, source: ProxyNodeSource) -> ProxyNodeView {
let ProxySnapshot {
id,
hidden,
icon,
test_url,
history,
udp,
xudp,
tfo,
mptcp,
smux,
capabilities,
proxy_type,
..
} = proxy;
@@ -469,19 +475,13 @@ fn build_node(record_id: String, name: String, proxy: Proxy, source: ProxyNodeSo
hidden,
icon,
test_url,
capabilities: ProxyCapabilities {
udp,
xudp,
tfo,
mptcp,
smux,
},
capabilities,
source,
}
}
fn build_ordered_groups(
mut core_groups: BTreeMap<String, Proxy>,
mut core_groups: BTreeMap<String, ProxySnapshot>,
runtime_group_order: Vec<String>,
resolver: &MemberResolver<'_>,
) -> (Vec<ProxyGroupView>, ProxyViewOrderSource) {
@@ -0,0 +1,17 @@
[package]
name = "clash-verge-runtime-bundle"
version = "0.1.0"
edition = "2024"
[dependencies]
thiserror = { workspace = true }
clash-verge-logging = { workspace = true }
hex = "0.4.3"
log = { workspace = true }
serde_yaml_ng = { workspace = true }
sha2 = { workspace = true }
tristr = { workspace = true }
tokio = { workspace = true, features = ["fs"] }
[lints]
workspace = true
@@ -0,0 +1,43 @@
use std::path::PathBuf;
#[derive(Debug, thiserror::Error)]
pub enum RuntimeBundleError {
#[error(transparent)]
Io(#[from] std::io::Error),
#[error("failed to read runtime config {path:?}")]
ReadConfig {
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error("failed to parse runtime config {path:?}")]
ParseConfig {
path: PathBuf,
#[source]
source: serde_yaml_ng::Error,
},
#[error("runtime config has no parent directory")]
MissingConfigDirectory,
#[error("runtime provider destination {0:?} is declared for two different sources")]
DifferentSources(String),
#[error("runtime provider destination {0:?} is claimed more than once")]
DuplicateDestination(String),
#[error("local runtime provider is unavailable: {path:?}")]
LocalProviderUnavailable {
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error("local runtime provider is outside the config root: {0:?}")]
LocalProviderOutsideRoot(PathBuf),
#[error("runtime provider destination traverses outside the runtime")]
DestinationOutsideRuntime,
#[error("runtime provider path has no existing ancestor: {0:?}")]
MissingAncestor(PathBuf),
#[error("runtime provider path is outside the config root: {0:?}")]
ProviderOutsideRoot(PathBuf),
#[error("local runtime provider destination traverses outside the runtime")]
LocalDestinationOutsideRuntime,
#[error("local runtime provider destination is empty")]
EmptyDestination,
}
@@ -1,12 +1,17 @@
use anyhow::{Context as _, Result, bail};
mod error;
pub use error::RuntimeBundleError;
use clash_verge_logging::{Type, logging};
use clash_verge_service_ipc::{RemoteProvider, RuntimeAsset, RuntimeBundle};
use serde_yaml_ng::{Mapping, Value};
use sha2::{Digest as _, Sha256};
use std::collections::{BTreeMap, HashSet};
use std::path::{Component, Path, PathBuf, Prefix};
use tristr::TriStr;
pub(crate) const GEO_ASSETS: &[&str] = &[
const PROVIDER_SECTIONS: [&str; 2] = ["proxy-providers", "rule-providers"];
pub const GEO_ASSETS: &[&str] = &[
"Country.mmdb",
"ASN.mmdb",
"geoip.dat",
@@ -17,42 +22,62 @@ pub(crate) const GEO_ASSETS: &[&str] = &[
/// Provider identity used by the runtime config and core API.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RemoteProviderRef {
pub struct RemoteProviderRef {
pub section: &'static str,
pub name: String,
pub provider: RemoteProvider,
pub destination: TriStr,
pub url: String,
}
struct RuntimeParts {
config: Value,
assets: Vec<RuntimeAsset>,
remote_providers: Vec<RemoteProviderRef>,
pub struct RuntimeAsset {
pub source: String,
pub destination: TriStr,
}
pub(crate) async fn collect_runtime_bundle(config_file: &Path, core_path: &Path) -> Result<RuntimeBundle> {
pub struct RuntimeBundlePlan {
pub config: Value,
pub assets: Vec<RuntimeAsset>,
pub remote_providers: Vec<RemoteProviderRef>,
}
type Result<T> = std::result::Result<T, RuntimeBundleError>;
pub async fn collect_runtime_bundle(config_file: &Path) -> Result<RuntimeBundlePlan> {
let yaml = tokio::fs::read_to_string(config_file)
.await
.with_context(|| format!("failed to read runtime config {config_file:?}"))?;
let config: Value =
serde_yaml_ng::from_str(&yaml).with_context(|| format!("failed to parse runtime config {config_file:?}"))?;
let config_root = config_file
.parent()
.ok_or_else(|| anyhow::anyhow!("runtime config has no parent directory"))?;
let parts = collect_runtime_parts(config, config_root)?;
Ok(RuntimeBundle {
yaml: serde_yaml_ng::to_string(&parts.config).context("failed to serialize service runtime config")?,
assets: parts.assets,
remote_providers: parts
.remote_providers
.into_iter()
.map(|declared| declared.provider)
.collect(),
core_path: core_path.to_string_lossy().into_owned(),
})
.map_err(|source| RuntimeBundleError::ReadConfig {
path: config_file.to_owned(),
source,
})?;
let config: Value = serde_yaml_ng::from_str(&yaml).map_err(|source| RuntimeBundleError::ParseConfig {
path: config_file.to_owned(),
source,
})?;
let config_root = config_file.parent().ok_or(RuntimeBundleError::MissingConfigDirectory)?;
collect_runtime_parts(config, config_root)
}
pub(crate) fn remote_providers_of(config: &Mapping, config_root: &Path) -> Result<Vec<RemoteProviderRef>> {
Ok(collect_runtime_parts(Value::Mapping(config.clone()), config_root)?.remote_providers)
pub fn remote_providers_of(config: &Mapping, config_root: &Path) -> Result<Vec<RemoteProviderRef>> {
let config_root = std::fs::canonicalize(config_root)?;
let mut destinations = HashSet::new();
let mut remote_providers = Vec::new();
for section in PROVIDER_SECTIONS {
let Some(providers) = config.get(section).and_then(Value::as_mapping) else {
continue;
};
for (name, provider) in providers {
plan_provider(
section,
name,
provider,
&config_root,
&mut destinations,
None,
&mut remote_providers,
)?;
}
}
Ok(remote_providers)
}
#[derive(Default)]
@@ -61,11 +86,11 @@ struct ProviderPathOwners {
local: bool,
}
pub(crate) fn resolve_provider_path_conflicts(config: &mut Mapping, config_root: &Path) -> Result<()> {
pub fn resolve_provider_path_conflicts(config: &mut Mapping, config_root: &Path) -> Result<()> {
let config_root = std::fs::canonicalize(config_root)?;
let mut paths = BTreeMap::<String, ProviderPathOwners>::new();
let mut reserved: HashSet<String> = GEO_ASSETS.iter().map(|name| (*name).to_owned()).collect();
for section in ["proxy-providers", "rule-providers"] {
let mut paths = BTreeMap::<TriStr, ProviderPathOwners>::new();
let mut reserved: HashSet<TriStr> = GEO_ASSETS.iter().copied().map(TriStr::from).collect();
for section in PROVIDER_SECTIONS {
let Some(providers) = config.get(section).and_then(Value::as_mapping) else {
continue;
};
@@ -84,6 +109,7 @@ pub(crate) fn resolve_provider_path_conflicts(config: &mut Mapping, config_root:
let Ok(destination) = destination else {
continue;
};
let destination = TriStr::from(destination.as_str());
reserved.insert(destination.clone());
let owners = paths.entry(destination).or_default();
match (is_remote, provider.get("url").and_then(Value::as_str)) {
@@ -117,12 +143,12 @@ pub(crate) fn resolve_provider_path_conflicts(config: &mut Mapping, config_root:
Ok(())
}
fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut HashSet<String>) -> String {
fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut HashSet<TriStr>) -> String {
let mut digest = Sha256::new();
digest.update(destination.as_bytes());
digest.update([0]);
digest.update(url.as_bytes());
let digest: String = crate::utils::help::hex_encode(&digest.finalize());
let digest = hex::encode(digest.finalize());
let path = Path::new(destination);
let extension = path
.extension()
@@ -134,7 +160,7 @@ fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut Ha
.with_file_name(format!("cvr-{digest}{suffix}{extension}"))
.to_string_lossy()
.replace('\\', "/");
if reserved.insert(candidate.clone()) {
if reserved.insert(TriStr::from(candidate.as_str())) {
return candidate;
}
sequence += 1;
@@ -142,40 +168,34 @@ fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut Ha
}
}
fn collect_runtime_parts(mut config: Value, config_root: &Path) -> Result<RuntimeParts> {
fn collect_runtime_parts(mut config: Value, config_root: &Path) -> Result<RuntimeBundlePlan> {
let config_root = std::fs::canonicalize(config_root)?;
let mut assets = Vec::new();
let mut destinations = HashSet::new();
let mut remote_providers = Vec::new();
collect_provider_assets(
&mut config,
"proxy-providers",
&config_root,
&mut destinations,
&mut assets,
&mut remote_providers,
)?;
collect_provider_assets(
&mut config,
"rule-providers",
&config_root,
&mut destinations,
&mut assets,
&mut remote_providers,
)?;
for section in PROVIDER_SECTIONS {
collect_provider_assets(
&mut config,
section,
&config_root,
&mut destinations,
&mut assets,
&mut remote_providers,
)?;
}
collect_ssh_private_keys(&mut config, &config_root, &mut destinations, &mut assets);
for filename in GEO_ASSETS {
let source = config_root.join(filename);
if source.is_file() && destinations.insert((*filename).to_string()) {
if source.is_file() && destinations.insert(TriStr::from(*filename)) {
assets.push(RuntimeAsset {
source: std::fs::canonicalize(&source)?.to_string_lossy().into_owned(),
destination: (*filename).to_string(),
destination: (*filename).into(),
});
}
}
Ok(RuntimeParts {
Ok(RuntimeBundlePlan {
config,
assets,
remote_providers,
@@ -188,7 +208,7 @@ fn collect_provider_assets(
config: &mut Value,
section: &'static str,
config_root: &Path,
destinations: &mut HashSet<String>,
destinations: &mut HashSet<TriStr>,
assets: &mut Vec<RuntimeAsset>,
remote_providers: &mut Vec<RemoteProviderRef>,
) -> Result<()> {
@@ -201,80 +221,105 @@ fn collect_provider_assets(
};
for (name, provider) in providers.iter_mut() {
let Some(provider) = provider.as_mapping_mut() else {
continue;
};
let Some(raw_path) = provider.get("path").and_then(Value::as_str) else {
continue;
};
// Match mihomo's `type` classification and leave malformed-but-accepted providers untouched.
let is_remote = provider.get("type").and_then(Value::as_str) == Some("http");
let url = provider.get("url").and_then(Value::as_str).map(str::to_owned);
let destination = match (is_remote, url) {
(true, Some(url)) => {
let destination = provider_destination(config_root, raw_path)?;
// Reserve remote destinations too; copied and downloaded files must not collide.
if let Some(destination) = plan_provider(
section,
name,
provider,
config_root,
destinations,
Some(assets),
remote_providers,
)? && let Some(provider) = provider.as_mapping_mut()
{
provider.insert(Value::String("path".to_owned()), Value::String(destination));
}
}
Ok(())
}
fn plan_provider(
section: &'static str,
name: &Value,
provider: &Value,
config_root: &Path,
destinations: &mut HashSet<TriStr>,
assets: Option<&mut Vec<RuntimeAsset>>,
remote_providers: &mut Vec<RemoteProviderRef>,
) -> Result<Option<String>> {
let Some(raw_path) = provider
.as_mapping()
.and_then(|provider| provider.get("path"))
.and_then(Value::as_str)
else {
return Ok(None);
};
// Match mihomo's `type` classification and leave malformed-but-accepted providers untouched.
let is_remote = provider.get("type").and_then(Value::as_str) == Some("http");
let url = provider.get("url").and_then(Value::as_str);
let destination = match (is_remote, url) {
(true, Some(url)) => {
let destination = provider_destination(config_root, raw_path)?;
// Reserve remote destinations too; copied and downloaded files must not collide.
let reserved = TriStr::from(destination.as_str());
if destinations.insert(reserved.clone()) {
remote_providers.push(RemoteProviderRef {
section,
name: name.as_str().unwrap_or_default().to_owned(),
destination: reserved,
url: url.to_owned(),
});
} else {
match remote_providers
.iter()
.find(|declared| declared.provider.destination == destination)
.find(|declared| declared.destination == destination)
{
Some(declared) if declared.provider.url == url => {}
Some(_) => {
bail!("runtime provider destination {destination:?} is declared for two different sources")
}
None => {
if !destinations.insert(destination.clone()) {
bail!("runtime provider destination {destination:?} is claimed more than once");
}
remote_providers.push(RemoteProviderRef {
section,
name: name.as_str().unwrap_or_default().to_owned(),
provider: RemoteProvider {
destination: destination.clone(),
url,
},
});
}
Some(declared) if declared.url == url => {}
Some(_) => return Err(RuntimeBundleError::DifferentSources(destination)),
None => return Err(RuntimeBundleError::DuplicateDestination(destination)),
}
destination
}
(true, None) => {
destination
}
(true, None) => {
logging!(
warn,
Type::Config,
"remote provider {name:?} declares no url; leaving its path to the core"
);
return Ok(None);
}
(false, _) => {
let Ok(source) = local_provider_source(config_root, raw_path) else {
logging!(
warn,
Type::Config,
"remote provider {name:?} declares no url; leaving its path to the core"
"local provider {name:?} is unavailable at {raw_path:?}; leaving its path to the core"
);
continue;
}
(false, _) => {
let Ok(source) = local_provider_source(config_root, raw_path) else {
logging!(
warn,
Type::Config,
"local provider {name:?} is unavailable at {raw_path:?}; leaving its path to the core"
);
continue;
};
let destination = destination_below_root(config_root, &source)?;
if destinations.insert(destination.clone()) {
return Ok(None);
};
let destination = destination_below_root(config_root, &source)?;
let reserved = TriStr::from(destination.as_str());
if destinations.insert(reserved.clone()) {
if let Some(assets) = assets {
assets.push(RuntimeAsset {
source: source.to_string_lossy().into_owned(),
destination: destination.clone(),
destination: reserved,
});
}
destination
} else if remote_providers.iter().any(|provider| provider.destination == reserved) {
return Err(RuntimeBundleError::DuplicateDestination(destination));
}
};
provider.insert(Value::String("path".to_owned()), Value::String(destination));
}
Ok(())
destination
}
};
Ok(Some(destination))
}
/// Stages file-based ssh keys, which mihomo resolves against the core home directory.
fn collect_ssh_private_keys(
config: &mut Value,
config_root: &Path,
destinations: &mut HashSet<String>,
destinations: &mut HashSet<TriStr>,
assets: &mut Vec<RuntimeAsset>,
) {
let Some(config) = config.as_mapping_mut() else {
@@ -325,7 +370,7 @@ fn collect_ssh_private_keys(
let destination = allocate_provider_destination("ssh-private-key", &source, destinations);
assets.push(RuntimeAsset {
source,
destination: destination.clone(),
destination: TriStr::from(destination.as_str()),
});
proxy.insert(Value::String("private-key".to_owned()), Value::String(destination));
}
@@ -347,10 +392,13 @@ fn local_provider_source(config_root: &Path, raw_path: &str) -> Result<PathBuf>
config_root.join(path)
};
let canonical_source =
std::fs::canonicalize(&source).with_context(|| format!("local runtime provider is unavailable: {source:?}"))?;
std::fs::canonicalize(&source).map_err(|error| RuntimeBundleError::LocalProviderUnavailable {
path: source,
source: error,
})?;
canonical_source
.strip_prefix(config_root)
.map_err(|_| anyhow::anyhow!("local runtime provider is outside the config root: {canonical_source:?}"))?;
.map_err(|_| RuntimeBundleError::LocalProviderOutsideRoot(canonical_source.clone()))?;
Ok(canonical_source)
}
@@ -360,7 +408,7 @@ fn provider_destination(config_root: &Path, raw_path: &str) -> Result<String> {
.components()
.any(|component| matches!(component, Component::ParentDir))
{
bail!("runtime provider destination traverses outside the runtime");
return Err(RuntimeBundleError::DestinationOutsideRuntime);
}
if path.is_absolute() {
let normalized = canonicalize_with_missing_tail(path)?;
@@ -376,11 +424,11 @@ fn canonicalize_with_missing_tail(path: &Path) -> Result<PathBuf> {
while !ancestor.exists() {
let name = ancestor
.file_name()
.ok_or_else(|| anyhow::anyhow!("runtime provider path has no existing ancestor: {path:?}"))?;
.ok_or_else(|| RuntimeBundleError::MissingAncestor(path.to_owned()))?;
tail.push(name.to_owned());
ancestor = ancestor
.parent()
.ok_or_else(|| anyhow::anyhow!("runtime provider path has no existing ancestor: {path:?}"))?;
.ok_or_else(|| RuntimeBundleError::MissingAncestor(path.to_owned()))?;
}
let mut normalized = std::fs::canonicalize(ancestor)?;
for component in tail.iter().rev() {
@@ -392,31 +440,60 @@ fn canonicalize_with_missing_tail(path: &Path) -> Result<PathBuf> {
fn destination_below_root(config_root: &Path, path: &Path) -> Result<String> {
let relative = path
.strip_prefix(config_root)
.map_err(|_| anyhow::anyhow!("runtime provider path is outside the config root: {path:?}"))?;
.map_err(|_| RuntimeBundleError::ProviderOutsideRoot(path.to_owned()))?;
normalized_destination(relative)
}
fn normalized_destination(relative: &Path) -> Result<String> {
let mut destination = PathBuf::new();
let mut destination = PathBuf::with_capacity(relative.as_os_str().len());
for component in relative.components() {
match component {
Component::Normal(component) => destination.push(component),
Component::CurDir => {}
_ => bail!("local runtime provider destination traverses outside the runtime"),
_ => return Err(RuntimeBundleError::LocalDestinationOutsideRuntime),
}
}
if destination.as_os_str().is_empty() {
bail!("local runtime provider destination is empty");
return Err(RuntimeBundleError::EmptyDestination);
}
let destination = destination
.into_os_string()
.into_string()
.unwrap_or_else(|path| path.to_string_lossy().into_owned());
if destination.contains('\\') {
Ok(destination.replace('\\', "/"))
} else {
Ok(destination)
}
Ok(destination.to_string_lossy().replace('\\', "/"))
}
#[cfg(test)]
mod tests {
use super::{collect_runtime_bundle, remote_providers_of, resolve_provider_path_conflicts};
#[test]
fn local_and_remote_providers_cannot_claim_the_same_file() -> Result<(), Box<dyn std::error::Error>> {
let root = std::env::temp_dir().join(format!("clash-verge-mixed-providers-{}", std::process::id()));
std::fs::create_dir_all(&root)?;
std::fs::write(root.join("shared.yaml"), "payload: []")?;
let local = "type: file, path: ./shared.yaml";
let remote = "type: http, url: 'https://example.com/provider', path: shared.yaml";
for (proxy, rule) in [(local, remote), (remote, local)] {
let config = serde_yaml_ng::from_str(&format!(
"proxy-providers: {{a: {{{proxy}}}}}\nrule-providers: {{b: {{{rule}}}}}"
))?;
assert!(matches!(
remote_providers_of(&config, &root),
Err(super::RuntimeBundleError::DuplicateDestination(path)) if path == "shared.yaml"
));
}
std::fs::remove_dir_all(root)?;
Ok(())
}
#[tokio::test]
async fn conflicting_sources_get_separate_paths_in_config_bundle_and_readback() -> anyhow::Result<()> {
async fn conflicting_sources_get_separate_paths_in_config_bundle_and_readback()
-> std::result::Result<(), Box<dyn std::error::Error>> {
let root = std::env::temp_dir().join(format!("clash-verge-provider-paths-{}", std::process::id()));
std::fs::create_dir_all(&root)?;
let mut config: serde_yaml_ng::Mapping = serde_yaml_ng::from_str(
@@ -433,7 +510,7 @@ mod tests {
resolve_provider_path_conflicts(&mut config, &root)?;
let config_file = root.join("config.yaml");
std::fs::write(&config_file, serde_yaml_ng::to_string(&config)?)?;
let bundle = collect_runtime_bundle(&config_file, &root.join("mihomo")).await?;
let bundle = collect_runtime_bundle(&config_file).await?;
let paths = &config["rule-providers"];
assert_ne!(paths["AppleDev"]["path"], paths["mirror"]["path"]);
resolve_provider_path_conflicts(&mut reordered, &root)?;
@@ -448,14 +525,14 @@ mod tests {
"resolving an already generated config must be idempotent"
);
assert_eq!(serde_yaml_ng::from_str::<serde_yaml_ng::Mapping>(&bundle.yaml)?, config);
assert_eq!(bundle.config.as_mapping(), Some(&config));
let readback = remote_providers_of(&config, &root)?;
assert_eq!(bundle.remote_providers.len(), 2);
for declared in readback {
assert!(bundle.remote_providers.contains(&declared.provider));
assert!(bundle.remote_providers.contains(&declared));
assert_eq!(
config[declared.section][&declared.name]["path"],
declared.provider.destination
declared.destination.as_str()
);
assert_eq!(
config[declared.section][&declared.name]["url"],
@@ -467,7 +544,8 @@ mod tests {
}
#[test]
fn allocated_provider_paths_do_not_claim_another_declared_path() -> anyhow::Result<()> {
fn allocated_provider_paths_do_not_claim_another_declared_path()
-> std::result::Result<(), Box<dyn std::error::Error>> {
let root = std::env::temp_dir();
let original: serde_yaml_ng::Mapping = serde_yaml_ng::from_str(
"proxy-providers:\n a:\n type: http\n url: https://one.example/p.yaml\n path: ./providers/shared.yaml\nrule-providers:\n b:\n type: http\n url: https://two.example/r.yaml\n path: ./providers/shared.yaml\n",
@@ -489,7 +567,8 @@ mod tests {
}
#[test]
fn provider_path_resolution_leaves_shared_sources_and_local_files_unchanged() -> anyhow::Result<()> {
fn provider_path_resolution_leaves_shared_sources_and_local_files_unchanged()
-> std::result::Result<(), Box<dyn std::error::Error>> {
let mut config: serde_yaml_ng::Mapping = serde_yaml_ng::from_str(
"rule-providers:\n a:\n type: http\n url: https://one.example/r.yaml\n path: ./rules/shared.yaml\n b:\n type: http\n url: https://one.example/r.yaml\n path: ./rules/shared.yaml\n local:\n type: file\n path: ./rules/local.yaml\n remote:\n type: http\n url: https://two.example/r.yaml\n path: ./rules/local.yaml\n mirror:\n type: http\n url: https://three.example/r.yaml\n path: ./rules/local.yaml\n",
)?;
@@ -500,7 +579,8 @@ mod tests {
}
#[tokio::test]
async fn collects_only_local_providers_and_existing_geo_assets() -> anyhow::Result<()> {
async fn collects_only_local_providers_and_existing_geo_assets()
-> std::result::Result<(), Box<dyn std::error::Error>> {
let root = std::env::temp_dir().join(format!("clash-verge-runtime-bundle-{}", std::process::id()));
std::fs::create_dir_all(root.join("providers"))?;
std::fs::write(root.join("providers/local.yaml"), b"proxies: []\n")?;
@@ -516,12 +596,10 @@ mod tests {
absolute_remote.display()
),
)?;
let core = root.join("mihomo");
std::fs::write(&core, b"core")?;
let bundle = collect_runtime_bundle(&config, &core).await?;
let bundle = collect_runtime_bundle(&config).await?;
let bundled_config: serde_yaml_ng::Value = serde_yaml_ng::from_str(&bundle.yaml)?;
let bundled_config = &bundle.config;
assert_eq!(
bundled_config["proxy-providers"]["local"]["path"].as_str(),
Some("providers/local.yaml")
@@ -530,7 +608,7 @@ mod tests {
bundled_config["proxy-providers"]["remote"]["path"].as_str(),
Some("providers/remote.yaml")
);
assert!(!bundle.yaml.contains(&root.to_string_lossy().into_owned()));
assert!(!serde_yaml_ng::to_string(bundled_config)?.contains(root.to_string_lossy().as_ref()));
assert!(
bundle
.assets
@@ -560,7 +638,8 @@ mod tests {
}
#[tokio::test]
async fn two_names_for_one_remote_file_are_folded_rather_than_refused() -> anyhow::Result<()> {
async fn two_names_for_one_remote_file_are_folded_rather_than_refused()
-> std::result::Result<(), Box<dyn std::error::Error>> {
// Identical repeats are one service-side file and are safe to fold.
let root = std::env::temp_dir().join(format!("clash-verge-bundle-dup-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
@@ -570,10 +649,8 @@ mod tests {
&config,
"rule-providers:\n a:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n b:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n",
)?;
let core = root.join("mihomo");
std::fs::write(&core, b"core")?;
let bundle = collect_runtime_bundle(&config, &core).await?;
let bundle = collect_runtime_bundle(&config).await?;
assert_eq!(bundle.remote_providers.len(), 1, "one file, declared twice");
assert_eq!(bundle.remote_providers[0].destination, "rules/x.yaml");
@@ -582,7 +659,7 @@ mod tests {
}
#[tokio::test]
async fn two_sources_for_one_remote_file_are_refused() -> anyhow::Result<()> {
async fn two_sources_for_one_remote_file_are_refused() -> std::result::Result<(), Box<dyn std::error::Error>> {
let root = std::env::temp_dir().join(format!("clash-verge-bundle-conflict-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root)?;
@@ -591,11 +668,9 @@ mod tests {
&config,
"rule-providers:\n a:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n b:\n type: http\n url: https://two.example/x.yaml\n path: ./rules/x.yaml\n",
)?;
let core = root.join("mihomo");
std::fs::write(&core, b"core")?;
let Err(error) = collect_runtime_bundle(&config, &core).await else {
anyhow::bail!("two sources cannot own one file");
let Err(error) = collect_runtime_bundle(&config).await else {
return Err("two sources cannot own one file".into());
};
assert!(error.to_string().contains("two different sources"), "{error}");
@@ -604,7 +679,8 @@ mod tests {
}
#[tokio::test]
async fn an_odd_provider_is_left_alone_instead_of_failing_the_whole_bundle() -> anyhow::Result<()> {
async fn an_odd_provider_is_left_alone_instead_of_failing_the_whole_bundle()
-> std::result::Result<(), Box<dyn std::error::Error>> {
// Odd providers accepted by mihomo must not block the rest of the bundle.
let root = std::env::temp_dir().join(format!("clash-verge-bundle-odd-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
@@ -614,10 +690,8 @@ mod tests {
&config,
"rule-providers:\n nourl:\n type: http\n path: ./rules/nourl.yaml\n missing:\n type: inline\n url: https://one.example/i.yaml\n path: ./rules/missing.yaml\n good:\n type: http\n url: https://one.example/g.yaml\n path: ./rules/g.yaml\n",
)?;
let core = root.join("mihomo");
std::fs::write(&core, b"core")?;
let bundle = collect_runtime_bundle(&config, &core).await?;
let bundle = collect_runtime_bundle(&config).await?;
assert_eq!(
bundle.remote_providers.len(),
@@ -625,9 +699,8 @@ mod tests {
"only the provider that could be classified is declared"
);
assert_eq!(bundle.remote_providers[0].destination, "rules/g.yaml");
let reserialized: serde_yaml_ng::Value = serde_yaml_ng::from_str(&bundle.yaml)?;
assert_eq!(
reserialized["rule-providers"]["nourl"]["path"].as_str(),
bundle.config["rule-providers"]["nourl"]["path"].as_str(),
Some("./rules/nourl.yaml"),
"an unclassifiable provider keeps the path the core was given"
);
@@ -636,13 +709,13 @@ mod tests {
}
#[tokio::test]
async fn rejects_provider_paths_outside_the_config_root() -> anyhow::Result<()> {
async fn rejects_provider_paths_outside_the_config_root() -> std::result::Result<(), Box<dyn std::error::Error>> {
let root = std::env::temp_dir().join(format!("clash-verge-runtime-bundle-outside-{}", std::process::id()));
std::fs::create_dir_all(&root)?;
let config = root.join("config.yaml");
let outside = root
.parent()
.ok_or_else(|| anyhow::anyhow!("test root has no parent"))?
.ok_or("test root has no parent")?
.join(format!("outside-{}.yaml", std::process::id()));
std::fs::write(
&config,
@@ -651,11 +724,9 @@ mod tests {
outside.display()
),
)?;
let core = root.join("mihomo");
std::fs::write(&core, b"core")?;
let Err(error) = collect_runtime_bundle(&config, &core).await else {
anyhow::bail!("outside provider path must be rejected");
let Err(error) = collect_runtime_bundle(&config).await else {
return Err("outside provider path must be rejected".into());
};
assert!(error.to_string().contains("outside the config root"));
+20 -17
View File
@@ -9,7 +9,7 @@ import AdmZip from 'adm-zip'
import { HttpsProxyAgent } from 'https-proxy-agent'
import { extract } from 'tar'
import { resolveServiceRelease } from './service-release.mjs'
import { resolveServiceBundle as serviceBundleFromMetadata } from './service-release.mjs'
import { log_debug, log_error, log_info, log_success } from './utils.mjs'
/** Prepares platform resources, caching versions and unchanged files unless `--force` is used. */
@@ -581,23 +581,30 @@ async function resolveServiceBundle() {
}
})
const cargoManifest = await fsp.readFile(
path.join(cwd, 'src-tauri', 'Cargo.toml'),
'utf8',
const metadata = JSON.parse(
execFileSync(
'cargo',
[
'metadata',
'--locked',
'--format-version',
'1',
'--filter-platform',
SIDECAR_HOST,
],
{ cwd, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 },
),
)
const serviceDependency = cargoManifest
.split(/\r?\n/)
.find((line) => line.trimStart().startsWith('clash_verge_service_ipc ='))
const sourcePath = serviceDependency?.match(/\bpath\s*=\s*"([^"]+)"/)?.[1]
if (sourcePath) {
const manifest = path.resolve(cwd, 'src-tauri', sourcePath, 'Cargo.toml')
const bundle = serviceBundleFromMetadata(metadata, SIDECAR_HOST, platform)
if (bundle.manifest) {
const targetDirectory = path.join(cwd, 'target', 'bundled-service')
execFileSync(
'cargo',
[
'build',
'--locked',
'--manifest-path',
manifest,
bundle.manifest,
'--target-dir',
targetDirectory,
'--target',
@@ -605,7 +612,7 @@ async function resolveServiceBundle() {
'--release',
'--features',
'standalone,client',
'--bins',
...SERVICE_BINARIES.flatMap((name) => ['--bin', name]),
],
{ stdio: 'inherit' },
)
@@ -620,11 +627,7 @@ async function resolveServiceBundle() {
}
return
}
const { archiveFile, downloadURL } = resolveServiceRelease(
cargoManifest,
SIDECAR_HOST,
platform,
)
const { archiveFile, downloadURL } = bundle
const tempDir = path.join(TEMP_DIR, 'clash-verge-service-ipc')
const tempArchive = path.join(tempDir, archiveFile)
+24 -11
View File
@@ -1,22 +1,35 @@
const SERVICE_URL_PREFIX =
'https://github.com/clash-verge-rev/clash-verge-service-ipc/releases/download'
export function resolveServiceRelease(cargoManifest, host, platform) {
const dependency = cargoManifest
.split(/\r?\n/)
.find((line) => line.trimStart().startsWith('clash_verge_service_ipc ='))
const packageVersion = dependency?.match(/\bversion\s*=\s*"([^"]+)"/)?.[1]
if (!packageVersion) {
throw new Error(
'clash_verge_service_ipc dependency must declare an inline version',
)
export function resolveServiceBundle(metadata, host, platform) {
const app = metadata.packages.find(
(pkg) =>
pkg.name === 'clash-verge' && metadata.workspace_members.includes(pkg.id),
)
const dependency = app?.dependencies.find(
(dep) => dep.name === 'clash_verge_service_ipc',
)
const edge = metadata.resolve.nodes
.find((node) => node.id === app?.id)
?.deps.find((dep) => dep.name === 'clash_verge_service_ipc')
const service = metadata.packages.find((pkg) => pkg.id === edge?.pkg)
if (!service || !dependency) {
throw new Error('Cargo did not resolve the desktop IPC client dependency')
}
if (!service.source || new URL(service.source).searchParams.has('rev')) {
return { manifest: service.manifest_path }
}
const version = `v${packageVersion}`
const declared = dependency.req.replace(/^[=^]/, '')
if (declared !== service.version) {
throw new Error(
`Service release version ${declared} differs from the resolved IPC client ${service.version}`,
)
}
const version = `v${declared}`
const archiveExt = platform === 'win32' ? 'zip' : 'tar.gz'
const archiveFile = `clash-verge-service-ipc-${version}-${host}.${archiveExt}`
return {
version,
archiveFile,
downloadURL: `${SERVICE_URL_PREFIX}/${version}/${archiveFile}`,
}
+7 -6
View File
@@ -37,6 +37,10 @@ clash-verge-logging = { workspace = true }
clash-verge-i18n = { workspace = true }
clash-verge-limiter = { workspace = true }
clash-verge-subscription = { workspace = true }
clash-verge-runtime-bundle = { workspace = true }
clash-verge-config-render = { workspace = true }
clash-verge-profile-script = { workspace = true }
clash-verge-proxy-view = { workspace = true }
clash-verge-profile = { workspace = true }
clash-verge-backup-archive = { workspace = true }
tauri-plugin-clash-verge-sysinfo = { workspace = true }
@@ -64,7 +68,6 @@ dirs = "7.0.0"
dunce = "1.0.5"
nanoid = "0.5"
chrono = { workspace = true }
boa_engine = "0.22.0"
http-body-util = "0.1.5"
percent-encoding = "2.3.2"
reqwest = { workspace = true }
@@ -83,7 +86,7 @@ flate2 = "1.1.11"
reqwest_dav = "0.4.0"
aes-gcm = { version = "0.11.1" }
base64 = "0.23.1"
sha2 = "0.11.2"
sha2 = { workspace = true }
getrandom = "0.4.3"
futures = { workspace = true }
gethostname = "1.1.0"
@@ -94,9 +97,7 @@ tracing = { workspace = true }
tauri-plugin-devtools = { version = "2.2.3", optional = true }
tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", rev = "7e4fa8642cf6c394ed88b5a969420d8eab60087f" }
async-trait = "0.1.92"
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", branch = "main", version = "2.8.2", features = [
"client",
] }
clash_verge_service_ipc = { workspace = true, features = ["client"] }
arc-swap = "1.9.5"
tokio-rustls = "0.26.6"
rustls = { version = "0.23.47", features = ["ring"] }
@@ -104,7 +105,7 @@ webpki-roots = "1.0.12"
dark-light = "3.0.0"
bytes = "1.12.2"
tokio-util = { version = "0.7.20", features = ["time"] }
specta = { version = "=2.0.0-rc.26", features = ["derive", "function", "serde_json"] }
specta = { workspace = true, features = ["derive", "function", "serde_json"] }
tauri-specta = { version = "=2.0.0-rc.26", features = ["derive", "typescript"] }
specta-typescript = "=0.0.13"
+3 -3
View File
@@ -1,10 +1,10 @@
use super::{CmdResult, CommandFailure, WithErrorCode as _, proxy_aware_coded_error, proxy_aware_error};
use crate::core::notify::NoticeStatus;
use crate::feat;
use crate::utils::{dirs, yaml_emitter};
use crate::utils::dirs;
use crate::{
cmd::StringifyErr as _,
config::{ClashInfo, Config, profiles::save_committed_profiles},
config::{ClashInfo, Config, mihomo_yaml, profiles::save_committed_profiles},
constants,
core::{
CoreManager, handle,
@@ -132,7 +132,7 @@ pub async fn save_dns_config(dns_config: crate::ipc::YamlMapping) -> CmdResult {
let dns_path = dirs::app_home_dir().stringify_err()?.join(constants::files::DNS_CONFIG);
let yaml_str = yaml_emitter::to_mihomo_config_string(&dns_config.0).stringify_err()?;
let yaml_str = mihomo_yaml::serialize_for_export(&dns_config.0).stringify_err()?;
fs::write(&dns_path, yaml_str).await.stringify_err()?;
logging!(info, Type::Config, "DNS config saved to {dns_path:?}");
+10 -92
View File
@@ -1,14 +1,6 @@
use super::CmdResult;
use crate::{
cmd::StringifyErr as _,
config::Config,
core::{
handle::Handle,
proxy_view::{GroupScope, ProxyViewBuilder, ProxyViewInput, ProxyViewV1},
},
};
use serde_yaml_ng::Mapping;
use std::collections::{BTreeMap, HashSet};
use crate::{cmd::StringifyErr as _, config::Config, core::handle::Handle};
use clash_verge_proxy_view::ProxyViewV1;
/// Merges one selection pair into fresh backend state to avoid stale-list overwrites.
#[tauri::command]
@@ -27,90 +19,16 @@ pub async fn switch_proxy_node(group_name: String, proxy_name: String, unfix: bo
.stringify_err()
}
fn runtime_group_order(config: Option<&Mapping>) -> Vec<String> {
let mut seen = HashSet::new();
config
.and_then(|config| config.get("proxy-groups"))
.and_then(|groups| groups.as_sequence())
.into_iter()
.flatten()
.filter_map(|group| group.get("name"))
.filter_map(|name| name.as_str())
.filter(|name| !name.is_empty() && *name != "GLOBAL")
.filter(|name| seen.insert(*name))
.map(str::to_owned)
.collect()
}
/// Mirrors Mihomo: `include-all`/`include-all-providers` replace `use` with every provider, sorted.
fn runtime_group_scopes(config: Option<&Mapping>) -> BTreeMap<String, GroupScope> {
let Some(config) = config else {
return BTreeMap::new();
};
let mut all_providers = config
.get("proxy-providers")
.and_then(|providers| providers.as_mapping())
.into_iter()
.flat_map(|providers| providers.keys())
.filter_map(|name| name.as_str())
.map(str::to_owned)
.collect::<Vec<_>>();
all_providers.sort();
let flag = |group: &Mapping, key: &str| group.get(key).and_then(|value| value.as_bool()) == Some(true);
config
.get("proxy-groups")
.and_then(|groups| groups.as_sequence())
.into_iter()
.flatten()
.filter_map(|group| group.as_mapping())
.filter_map(|group| {
let name = group.get("name")?.as_str()?.to_owned();
let providers = if flag(group, "include-all") || flag(group, "include-all-providers") {
all_providers.clone()
} else {
group
.get("use")
.and_then(|providers| providers.as_sequence())
.into_iter()
.flatten()
.filter_map(|provider| provider.as_str())
.map(str::to_owned)
.collect()
};
let exclude_types = group
.get("exclude-type")
.and_then(|types| types.as_str())
.filter(|types| !types.is_empty())
.map_or_default(|types| types.split('|').map(str::to_owned).collect());
Some((
name,
GroupScope {
providers,
exclude_types,
},
))
})
.collect()
}
#[tauri::command]
#[specta::specta]
pub async fn get_proxy_view() -> CmdResult<ProxyViewV1> {
let runtime = Config::runtime().await;
let latest_runtime = runtime.latest_arc();
let runtime_group_order = runtime_group_order(latest_runtime.config.as_ref());
let group_scopes = runtime_group_scopes(latest_runtime.config.as_ref());
let runtime = Config::runtime().await.latest_arc();
let mihomo = Handle::mihomo();
let (proxies, providers) = tokio::join!(mihomo.get_proxies(), mihomo.get_proxy_providers(),);
let proxies = proxies.stringify_err()?;
Ok(ProxyViewBuilder::build(ProxyViewInput {
runtime_group_order,
group_scopes,
proxies,
providers: providers.ok(),
}))
crate::feat::proxy_view::load_proxy_view(
runtime.config.as_ref(),
mihomo.get_proxies(),
mihomo.get_proxy_providers(),
)
.await
.stringify_err()
}
+7 -3
View File
@@ -1,5 +1,9 @@
use super::CmdResult;
use crate::{cmd::StringifyErr as _, config::Config, core::CoreManager, utils::yaml_emitter};
use crate::{
cmd::StringifyErr as _,
config::{Config, mihomo_yaml},
core::CoreManager,
};
use anyhow::{Context as _, anyhow};
use std::collections::HashMap;
use tristr::alias::String;
@@ -24,7 +28,7 @@ pub async fn get_runtime_yaml() -> CmdResult<std::string::String> {
let config = runtime.config.as_ref();
config
.ok_or_else(|| anyhow!("failed to parse config to yaml file"))
.and_then(|config| yaml_emitter::to_mihomo_config_string(config).context("failed to convert config to yaml"))
.and_then(|config| mihomo_yaml::serialize_for_export(config).context("failed to convert config to yaml"))
.stringify_err()
}
@@ -87,7 +91,7 @@ pub async fn get_runtime_proxy_chain_config(
config.insert("proxies".into(), proxies_chain);
yaml_emitter::to_mihomo_config_string(&config)
mihomo_yaml::serialize_for_export(&config)
.context("YAML generation failed")
.stringify_err()
} else {
+6 -135
View File
@@ -8,17 +8,7 @@ use crate::{
},
};
#[derive(Debug, PartialEq, Eq, serde::Serialize, specta::Type)]
#[serde(tag = "status", rename_all = "camelCase")]
pub enum ServiceInstallOutcome {
Installed,
#[cfg_attr(not(any(windows, test)), allow(dead_code))]
Sidecar {
reason: String,
},
}
async fn execute_service_operation_sync(status: ServiceStatus, error_code: &str) -> CmdResult<ServiceInstallOutcome> {
async fn execute_service_operation_sync(status: ServiceStatus, error_code: &str) -> CmdResult {
let manager = CoreManager::global();
let result = {
let _lifecycle = manager.lifecycle_lock.lock().await;
@@ -33,56 +23,12 @@ async fn execute_service_operation_sync(status: ServiceStatus, error_code: &str)
}
SERVICE_MANAGER.handle_service_status(status).await
};
#[cfg(windows)]
return finish_service_installation(result, error_code, async |reason| {
manager.continue_with_sidecar(Some(reason)).await
})
.await;
#[cfg(not(windows))]
result
.map(|()| ServiceInstallOutcome::Installed)
.map_err(|error| proxy_aware_coded_error(&error, error_code))
}
#[cfg(any(windows, test))]
async fn finish_service_installation<Fallback>(
installation: anyhow::Result<()>,
error_code: &str,
fallback: Fallback,
) -> CmdResult<ServiceInstallOutcome>
where
Fallback: AsyncFnOnce(&str) -> anyhow::Result<()>,
{
let Err(error) = installation else {
return Ok(ServiceInstallOutcome::Installed);
};
let Some(failure) = error.downcast_ref::<clash_verge_service_ipc::management::InstallationVerificationError>()
else {
return Err(proxy_aware_coded_error(&error, error_code));
};
let reasons = failure
.status
.cores
.iter()
.filter_map(|core| match &core.availability {
clash_verge_service_ipc::CoreAvailability::Rejected { reason } => Some(format!("{}: {reason}", core.name)),
_ => None,
})
.collect::<Vec<_>>();
if reasons.is_empty() {
return Err(proxy_aware_coded_error(&error, error_code));
}
let reason = reasons.join("\n");
fallback(reason.as_str())
.await
.map_err(|error| proxy_aware_coded_error(&error, "SERVICE_SIDECAR_FAILED"))?;
Ok(ServiceInstallOutcome::Sidecar { reason })
result.map_err(|error| proxy_aware_coded_error(&error, error_code))
}
#[tauri::command]
#[specta::specta]
pub async fn install_service() -> CmdResult<ServiceInstallOutcome> {
pub async fn install_service() -> CmdResult {
execute_service_operation_sync(ServiceStatus::InstallRequired, "SERVICE_INSTALL_FAILED").await
}
@@ -97,13 +43,13 @@ pub async fn uninstall_service() -> CmdResult {
#[tauri::command]
#[specta::specta]
pub async fn reinstall_service() -> CmdResult<ServiceInstallOutcome> {
pub async fn reinstall_service() -> CmdResult {
execute_service_operation_sync(ServiceStatus::ReinstallRequired, "SERVICE_REINSTALL_FAILED").await
}
#[tauri::command]
#[specta::specta]
pub async fn repair_service() -> CmdResult<ServiceInstallOutcome> {
pub async fn repair_service() -> CmdResult {
execute_service_operation_sync(ServiceStatus::ForceReinstallRequired, "SERVICE_REPAIR_FAILED").await
}
@@ -111,7 +57,7 @@ pub async fn repair_service() -> CmdResult<ServiceInstallOutcome> {
#[specta::specta]
pub async fn continue_with_sidecar() -> CmdResult {
crate::core::CoreManager::global()
.continue_with_sidecar(None)
.continue_with_sidecar()
.await
.map_err(|error| proxy_aware_coded_error(&error, "SERVICE_SIDECAR_FAILED"))
}
@@ -122,12 +68,6 @@ pub fn get_sidecar_failure() -> crate::core::notification::SidecarFailureSnapsho
crate::core::notification::sidecar_failure_snapshot()
}
#[tauri::command]
#[specta::specta]
pub fn take_service_fallback_notice() -> Option<crate::core::service::ServiceFallbackNotice> {
crate::core::service::take_service_fallback_notice()
}
#[tauri::command]
#[specta::specta]
pub fn get_core_startup_error() -> Option<crate::core::manager::CoreFailure> {
@@ -153,72 +93,3 @@ pub fn sync_runtime_providers() {
request_runtime_provider_sync(timing::RUNTIME_PROVIDER_SETTLE);
}
}
#[cfg(test)]
#[allow(clippy::expect_used, reason = "tests assert by panicking")]
mod tests {
use super::{ServiceInstallOutcome, finish_service_installation};
use clash_verge_service_ipc::{
CoreAvailability, CoreInspection, InstallationStatus, ProtocolInfo, management::InstallationVerificationError,
};
use std::cell::Cell;
#[tokio::test]
async fn rejected_installation_reports_sidecar_only_after_successful_continuation() {
let reason = "core path C:\\ is writable by Everyone";
for (availability, fallback_ready) in [
(None, false),
(Some(CoreAvailability::Missing), false),
(Some(CoreAvailability::DigestMismatch), false),
(Some(CoreAvailability::Rejected { reason: reason.into() }), false),
(Some(CoreAvailability::Rejected { reason: reason.into() }), true),
] {
let fallback_called = Cell::new(false);
let rejected = matches!(&availability, Some(CoreAvailability::Rejected { .. }));
let error = match availability {
Some(availability) => anyhow::Error::new(InstallationVerificationError {
status: InstallationStatus {
service_sha256: String::new(),
protocol: ProtocolInfo::current(),
cores: vec![CoreInspection {
name: "verge-mihomo.exe".into(),
availability,
}],
core_busy: false,
},
}),
None => anyhow::anyhow!("{reason}"),
}
.context("install service failed");
let result = finish_service_installation(Err(error), "SERVICE_INSTALL_FAILED", async |_| {
fallback_called.set(true);
anyhow::ensure!(fallback_ready, "another core is running");
Ok(())
})
.await;
assert_eq!(fallback_called.get(), rejected);
if rejected && fallback_ready {
assert_eq!(
result,
Ok(ServiceInstallOutcome::Sidecar {
reason: format!("verge-mihomo.exe: {reason}")
})
);
} else {
let error = result.expect_err("an unavailable fallback must remain an error");
assert_eq!(
error.code.as_deref(),
Some(if rejected {
"SERVICE_SIDECAR_FAILED"
} else {
"SERVICE_INSTALL_FAILED"
})
);
if rejected {
assert!(error.detail.contains("another core is running"));
}
}
}
}
}
+4 -1
View File
@@ -1,3 +1,4 @@
use super::mihomo_yaml;
use crate::constants::{network, tun as tun_const};
use crate::utils::dirs::{path_to_str, sidecar_ipc_path};
use crate::utils::{dirs, help};
@@ -150,7 +151,9 @@ impl IClashTemp {
}
pub async fn save_config(&self) -> Result<()> {
help::save_yaml(&dirs::clash_path()?, &self.0, Some("# Generated by Clash Verge")).await
let path = dirs::clash_path()?;
let yaml = mihomo_yaml::serialize(&self.0)?;
help::save_yaml_str(&path, &yaml, Some("# Generated by Clash Verge")).await
}
pub fn get_mixed_port(&self) -> u16 {
+4 -4
View File
@@ -1,4 +1,4 @@
use super::{IClashTemp, IProfiles, IVerge, MixedPort};
use super::{IClashTemp, IProfiles, IVerge, MixedPort, mihomo_yaml};
use crate::core::notify::NoticeStatus;
use crate::{
config::{
@@ -11,7 +11,6 @@ use crate::{
CoreManager,
handle::{self, Handle},
listener::MIXED_PORT_KEY,
runtime_bundle::resolve_provider_path_conflicts,
tray,
validate::CoreConfigValidator,
},
@@ -23,6 +22,7 @@ use anyhow::{Result, anyhow};
use backon::{ExponentialBuilder, Retryable as _};
use clash_verge_draft::Draft;
use clash_verge_logging::{Type, logging, logging_error};
use clash_verge_runtime_bundle::resolve_provider_path_conflicts;
use serde_yaml_ng::{Mapping, Value};
use std::{collections::HashSet, path::PathBuf};
use tokio::sync::{Mutex, MutexGuard, OnceCell};
@@ -230,7 +230,7 @@ impl Config {
{
return Ok(std::sync::Arc::clone(cached));
}
let yaml_str = std::sync::Arc::new(serde_yaml_ng::to_string(config)?);
let yaml_str = std::sync::Arc::new(mihomo_yaml::serialize(config)?);
*RUNTIME_YAML_CACHE.lock() = Some((key, std::sync::Arc::clone(&yaml_str)));
Ok(yaml_str)
})
@@ -250,7 +250,7 @@ impl Config {
}
pub(crate) async fn generate_with_profiles(profiles: &IProfiles) -> Result<()> {
let (mut config, exists_keys, logs, dns_override) = enhance::enhance(profiles).await?;
let (mut config, exists_keys, logs, dns_override) = enhance::render_runtime_config(profiles).await?;
resolve_provider_path_conflicts(&mut config, &dirs::app_home_dir()?)?;
sanitize_tunnels_proxy(&mut config);
@@ -1,9 +1,10 @@
use serde::Serialize;
use serde_yaml_ng::Result;
pub fn to_mihomo_config_string<T: Serialize>(data: &T) -> Result<String> {
let yaml = serde_yaml_ng::to_string(data)?;
Ok(quote_fake_ip_filter_wildcards(&yaml))
pub(crate) use serde_yaml_ng::to_string as serialize;
pub(crate) fn serialize_for_export<T: Serialize>(data: &T) -> Result<String> {
Ok(quote_fake_ip_filter_wildcards(&serialize(data)?))
}
fn quote_fake_ip_filter_wildcards(yaml: &str) -> String {
@@ -12,7 +13,7 @@ fn quote_fake_ip_filter_wildcards(yaml: &str) -> String {
let mut fake_ip_filter_indent = 0;
for line in yaml.lines() {
let indent = leading_spaces(line);
let indent = line.len() - line.trim_start_matches(' ').len();
let trimmed = &line[indent..];
if in_fake_ip_filter && indent <= fake_ip_filter_indent && !trimmed.starts_with("- ") {
@@ -22,54 +23,47 @@ fn quote_fake_ip_filter_wildcards(yaml: &str) -> String {
if !in_fake_ip_filter && trimmed == "fake-ip-filter:" {
in_fake_ip_filter = true;
fake_ip_filter_indent = indent;
}
if in_fake_ip_filter
&& indent >= fake_ip_filter_indent
&& let Some(item) = trimmed.strip_prefix("- ")
&& needs_quotes(item)
{
result.push_str(&line[..indent + 2]);
push_quoted(&mut result, item);
} else {
result.push_str(line);
result.push('\n');
continue;
}
if in_fake_ip_filter && indent >= fake_ip_filter_indent && trimmed.starts_with("- ") {
result.push_str(&line[..indent]);
result.push_str("- ");
result.push_str(&quote_wildcard_item(&trimmed[2..]));
result.push('\n');
continue;
}
result.push_str(line);
result.push('\n');
}
result
}
fn leading_spaces(line: &str) -> usize {
line.len() - line.trim_start_matches(' ').len()
fn needs_quotes(item: &str) -> bool {
!item.starts_with(['"', '\'']) && (item.contains('*') || item.starts_with(['+', '.']))
}
fn quote_wildcard_item(item: &str) -> String {
if !item.starts_with('\"') && !item.starts_with('\'') && contains_wildcard(item) {
quote_string(item)
} else {
item.to_string()
fn push_quoted(output: &mut String, item: &str) {
output.push('\'');
for (index, part) in item.split('\'').enumerate() {
if index != 0 {
output.push_str("''");
}
output.push_str(part);
}
}
fn quote_string(s: &str) -> String {
"\'".to_string() + s.replace('\'', "''").as_str() + "\'"
}
fn contains_wildcard(value: &str) -> bool {
value.contains('*') || value.starts_with('+') || value.starts_with('.')
output.push('\'');
}
#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
use super::to_mihomo_config_string;
use super::serialize_for_export;
fn roundtrip(input: &str) {
let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(input).expect("input yaml should parse");
let output = to_mihomo_config_string(&value).expect("yaml should serialize");
let output = serialize_for_export(&value).expect("yaml should serialize");
let reparsed: serde_yaml_ng::Value = serde_yaml_ng::from_str(&output).expect("serialized yaml should parse");
assert_eq!(reparsed, value);
@@ -90,7 +84,7 @@ dns:
roundtrip(input);
let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(input).expect("input yaml should parse");
let output = to_mihomo_config_string(&value).expect("yaml should serialize");
let output = serialize_for_export(&value).expect("yaml should serialize");
assert!(output.contains("- '*.lan'"));
assert!(output.contains("- '+.market.xiaomi.com'"));
+1
View File
@@ -3,6 +3,7 @@ mod clash;
mod config;
pub(crate) mod dns;
mod encrypt;
pub(crate) mod mihomo_yaml;
mod mixed_port;
mod port;
mod prfitem;
-37
View File
@@ -2,10 +2,6 @@ use serde_yaml_ng::{Mapping, Value};
use std::collections::{HashMap, HashSet};
use tristr::alias::String;
use crate::enhance::field::use_keys;
const PATCH_CONFIG_INNER: [&str; 5] = ["allow-lan", "ipv6", "log-level", "unified-delay", "tunnels"];
#[derive(Default, Clone)]
pub struct IRuntime {
pub config: Option<Mapping>,
@@ -17,39 +13,6 @@ pub struct IRuntime {
}
impl IRuntime {
#[inline]
pub fn patch_config(&mut self, patch: &Mapping) {
let config = if let Some(config) = self.config.as_mut() {
config
} else {
return;
};
for key in PATCH_CONFIG_INNER.iter() {
if let Some(value) = patch.get(key) {
config.insert((*key).into(), value.clone());
}
}
let Some(patch_tun) = patch.get("tun") else {
return;
};
let tun_key = Value::from("tun");
if !matches!(config.get(&tun_key), Some(Value::Mapping(_))) {
config.insert(tun_key.clone(), Value::Mapping(Mapping::new()));
}
if let (Some(patch_tun_mapping), Some(Value::Mapping(tun))) = (patch_tun.as_mapping(), config.get_mut(&tun_key))
{
for key in use_keys(patch_tun_mapping) {
if let Some(value) = patch_tun_mapping.get(key.as_str()) {
tun.insert(Value::from(key.as_str()), value.clone());
}
}
}
}
/// Rebuilds `dialer-proxy` links from an ordered proxy chain, or removes them for `None`.
#[inline]
pub fn update_proxy_chain_config(&mut self, proxy_chain_config: Option<Value>) {
-17
View File
@@ -64,22 +64,5 @@ pub mod files {
pub mod tun {
pub const DEFAULT_STACK: &str = "mips";
pub const DEFAULT_MTU: u16 = 1500;
pub const DNS_HIJACK: &[&str] = &["any:53"];
/// Saved dialog fields; `enable` belongs to the verge switch.
pub const GUI_KEYS: &[&str] = &[
"stack",
"device",
"auto-route",
"route-exclude-address",
#[cfg(target_os = "linux")]
"auto-redirect",
"auto-detect-interface",
"dns-hijack",
"dns-mode",
"strict-route",
"mtu",
];
}
+8 -7
View File
@@ -2,7 +2,7 @@ use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode};
use crate::core::notify::NoticeStatus;
use crate::core::service::StageRequest;
use crate::{
config::{Config, IProfiles, profiles::save_profiles, runtime::IRuntime},
config::{Config, IProfiles, mihomo_yaml, profiles::save_profiles, runtime::IRuntime},
constants::timing,
core::{
handle,
@@ -88,8 +88,8 @@ fn plan_config_application(attempt: &StageAttempt) -> ConfigApplication {
}
}
async fn ask_to_stage(path: &std::path::Path) -> StageAttempt {
match crate::core::service::stage_runtime_by_service(path).await {
async fn ask_to_stage(path: &std::path::Path, session: &clash_verge_service_ipc::OwnerSessionProof) -> StageAttempt {
match crate::core::service::stage_runtime_by_service(path, session).await {
Ok(StageRequest::Answered(outcome)) => StageAttempt::Answered(outcome),
Ok(StageRequest::Refused { code, message }) => {
let message = message.into();
@@ -170,7 +170,8 @@ impl CoreManager {
}
});
help::save_yaml(&runtime_path, &clash_config, Some("# Clash Verge Runtime")).await?;
let yaml = mihomo_yaml::serialize(clash_config)?;
help::save_yaml_str(&runtime_path, &yaml, Some("# Clash Verge Runtime")).await?;
handle::Handle::notice(status, message);
Ok(())
}
@@ -432,10 +433,10 @@ impl CoreManager {
}
async fn attempt_staging(&self, path: &std::path::Path) -> StageAttempt {
if !crate::core::service::active_service_supports_runtime_staging() {
let Ok(session) = crate::core::service::active_service_session() else {
return StageAttempt::Unsupported;
}
stage_with_confirmation(timing::STAGE_CONFIRM_TIMEOUT, || ask_to_stage(path)).await
};
stage_with_confirmation(timing::STAGE_CONFIRM_TIMEOUT, || ask_to_stage(path, &session)).await
}
/// Reload the Core from `path`, and replace the Core if it will not take it.
+15 -174
View File
@@ -188,48 +188,6 @@ where
apply_proxy().await
}
#[cfg(any(target_os = "windows", test))]
async fn run_service_start_with_sidecar_fallback<Start, StartFuture, Check, CheckFuture, Fallback, FallbackFuture>(
start_service: Start,
confirm_idle: Check,
start_sidecar: Fallback,
record_unavailable: impl FnOnce(std::string::String),
) -> Result<()>
where
Start: FnOnce() -> StartFuture,
StartFuture: std::future::Future<Output = Result<()>>,
Check: FnOnce() -> CheckFuture,
CheckFuture: std::future::Future<Output = Result<()>>,
Fallback: FnOnce(anyhow::Error) -> FallbackFuture,
FallbackFuture: std::future::Future<Output = Result<()>>,
{
let Err(error) = start_service().await else {
return Ok(());
};
let refusal = error.downcast_ref::<crate::core::service::ServiceStartRefusal>();
let location_refused = refusal.is_some_and(|refusal| {
refusal.code == clash_verge_service_ipc::ServiceErrorCode::InvalidInstallLocation as u16
});
if refusal.is_some() && !location_refused {
return Err(error);
}
// A lost start response can hide a running core; the shared check must resolve occupancy.
if let Err(probe_error) = confirm_idle().await {
let error = error.context(format!("Sidecar fallback was not safe: {probe_error:#}"));
record_unavailable(format!("{error:#}"));
return Err(error);
}
logging!(
warn,
Type::Core,
"Service could not start the core; falling back to Sidecar: {error:#}"
);
let reason = format!("{error:#}");
start_sidecar(error)
.await
.map_err(|error| error.context(format!("Sidecar fallback failed after Service failure: {reason}")))
}
async fn run_sidecar_termination_transition<Clear, ClearFuture, Terminate, TerminateFuture>(
clear_proxy: Clear,
terminate_sidecar: Terminate,
@@ -326,11 +284,7 @@ where
start_sidecar().await
}
fn report_sidecar_failure(error: anyhow::Error, service_rejection: Option<&str>) -> anyhow::Error {
let error = match service_rejection {
Some(reason) => error.context(format!("Service core rejected: {reason}; Sidecar fallback failed")),
None => error,
};
fn report_sidecar_failure(error: anyhow::Error) -> anyhow::Error {
// Proxy failures have their own pending state and recovery dialog.
if SysproxyFailure::from_chain(&error).is_none() {
crate::core::notification::record_sidecar_failure(format!("{error:#}").into());
@@ -368,12 +322,11 @@ impl CoreManager {
}
#[tracing::instrument(skip_all, level = "info", fields(status = tracing::field::Empty, tun_disabled = false, readiness_generation = tracing::field::Empty))]
pub async fn continue_with_sidecar(&self, service_rejection: Option<&str>) -> Result<()> {
pub async fn continue_with_sidecar(&self) -> Result<()> {
if !self.try_start_config_update() {
return Err(report_sidecar_failure(
anyhow::anyhow!("configuration update is already running"),
service_rejection,
));
return Err(report_sidecar_failure(anyhow::anyhow!(
"configuration update is already running"
)));
}
let _config_update = DropGuard::new((), |()| {
self.finish_config_update();
@@ -390,11 +343,8 @@ impl CoreManager {
if !can_allow_sidecar_for_session(&mode, &status) {
anyhow::bail!("Sidecar continuation is not allowed from {mode:?} / {status:?}");
}
#[cfg(target_os = "windows")]
if matches!(*mode, RunningMode::NotRunning) {
clash_verge_service_ipc::execution::check_sidecar_available()
.await
.map_err(super::state::explain_core_occupancy)?;
crate::core::service::release_service_core_for_sidecar().await?;
}
if !matches!(status, ServiceStatus::SidecarAllowed) {
SERVICE_MANAGER.allow_sidecar_for_session()?;
@@ -447,7 +397,7 @@ impl CoreManager {
Ok(())
}
.await;
result.map_err(|error| report_sidecar_failure(error, service_rejection))
result.map_err(report_sidecar_failure)
}
#[tracing::instrument(skip_all, level = "info", fields(readiness_generation = tracing::field::Empty))]
@@ -463,6 +413,7 @@ impl CoreManager {
let _life = self.lifecycle_lock.lock().await;
self.controlled_stop_core_inner().await?;
crate::core::service::release_service_core_for_sidecar().await?;
let result = run_uninstall_transition(
|| async {
@@ -638,8 +589,6 @@ impl CoreManager {
self.rollback_failed_start().await;
#[cfg(target_os = "macos")]
crate::utils::resolve::dns::sync_public_dns().await;
#[cfg(target_os = "windows")]
self.try_sidecar_after_service_unavailable().await?;
return Ok(());
}
if Handle::global().is_exiting() {
@@ -648,27 +597,15 @@ impl CoreManager {
}
let result = match startup {
StartupDecision::Service => {
#[cfg(target_os = "windows")]
StartupDecision::Service => self.start_core_by_service().await.inspect_err(|error| {
if error
.downcast_ref::<crate::core::service::ServiceStartRefusal>()
.is_none()
{
run_service_start_with_sidecar_fallback(
|| self.start_core_by_service(),
|| async {
clash_verge_service_ipc::execution::check_sidecar_available()
.await
.map_err(super::state::explain_core_occupancy)
},
|error| self.start_sidecar_after_service_failure(error),
|reason| {
crate::core::runstate::RUN_STATE
.observe(crate::core::runstate::ServiceHealth::Unavailable(reason));
},
)
.await
crate::core::runstate::RUN_STATE
.observe(crate::core::runstate::ServiceHealth::Unavailable(format!("{error:#}")));
}
#[cfg(not(target_os = "windows"))]
self.start_core_by_service().await
}
}),
StartupDecision::Sidecar => self.start_core_by_sidecar().await,
StartupDecision::Wait => Ok(()),
};
@@ -684,53 +621,6 @@ impl CoreManager {
result
}
#[cfg(target_os = "windows")]
async fn try_sidecar_after_service_unavailable(&self) -> Result<()> {
use crate::core::runstate::{RUN_STATE, ServiceHealth};
let state = RUN_STATE.state();
if state.pending.is_some() || state.op_in_flight || Handle::global().is_exiting() {
return Ok(());
}
let reason = match state.health {
ServiceHealth::Unavailable(reason) => reason,
ServiceHealth::VersionMismatch => "registered service is unavailable or incompatible".to_owned(),
_ => return Ok(()),
};
if let Err(error) = clash_verge_service_ipc::execution::check_sidecar_available()
.await
.map_err(super::state::explain_core_occupancy)
{
logging!(
warn,
Type::Core,
"Service unavailable ({reason}); Sidecar fallback withheld: {error:#}"
);
return Ok(());
}
self.start_sidecar_after_service_failure(anyhow::anyhow!(reason)).await
}
#[cfg(target_os = "windows")]
async fn start_sidecar_after_service_failure(&self, error: anyhow::Error) -> Result<()> {
use crate::core::runstate::RUN_STATE;
if Handle::global().is_exiting() {
return Err(error.context("application exited before Sidecar fallback"));
}
let reason = format!("{error:#}");
RUN_STATE.allow_sidecar_after_service_refusal(reason.clone())?;
logging!(warn, Type::Core, "Starting Sidecar with Service unavailable: {reason}");
let result = self.start_core_by_sidecar().await;
if result.is_err() {
SERVICE_MANAGER.withdraw_sidecar_allowance();
self.rollback_failed_start().await;
} else {
crate::core::service::notify_service_fallback(&reason);
}
result.map_err(|error| error.context(format!("Service failure before Sidecar startup: {reason}")))
}
#[tracing::instrument(skip_all, level = "info", fields(mode = ?*self.get_running_mode()))]
pub async fn stop_core(&self) -> Result<()> {
let _life = self.lifecycle_lock.lock().await;
@@ -846,13 +736,6 @@ impl CoreManager {
let is_admin = is_current_app_handle_admin(Handle::app_handle());
if !should_wait_for_service(tun_enabled, service_ready, is_admin) {
if tun_enabled && !service_ready && is_admin {
logging!(
info,
Type::Core,
"service unavailable while app is elevated; starting sidecar immediately"
);
}
return;
}
@@ -865,8 +748,6 @@ impl CoreManager {
return;
}
// Failing to become ready is not fatal here: the caller falls back to Sidecar, and a
// transient transport failure must not overwrite the last confirmed install state.
let attempts = (timing::SERVICE_WAIT_MAX.as_millis() / timing::SERVICE_WAIT_INTERVAL.as_millis()) as usize;
let wait = crate::core::runstate::RUN_STATE.await_ready(attempts, timing::SERVICE_WAIT_INTERVAL);
let _ = tokio::time::timeout(timing::SERVICE_WAIT_MAX, wait).await;
@@ -1410,46 +1291,6 @@ mod tests {
}
}
#[tokio::test]
async fn blocked_windows_fallback_records_failure_without_starting_sidecar() {
use crate::core::runstate::{FakeEnv, RunStateStore, ServiceHealth};
for idle in [false, true] {
let store = RunStateStore::new(FakeEnv::new());
store.observe(ServiceHealth::Ready);
let started = AtomicBool::new(false);
let result = super::run_service_start_with_sidecar_fallback(
|| async {
Err(crate::core::service::ServiceStartRefusal {
code: clash_verge_service_ipc::ServiceErrorCode::InvalidInstallLocation as u16,
core_path: "verge-mihomo.exe".into(),
message: "no administrator-approved copy is installed".into(),
}
.into())
},
|| async move {
anyhow::ensure!(idle, "another core is running");
Ok(())
},
|_| async {
started.store(true, Ordering::SeqCst);
Ok(())
},
|reason| store.observe(ServiceHealth::Unavailable(reason)),
)
.await;
assert_eq!(started.load(Ordering::SeqCst), idle);
assert_eq!(result.is_ok(), idle);
assert!(!store.state().sidecar_allowed);
if !idle {
assert!(store.state().service_needs_attention());
assert!(!store.state().service_usable());
assert!(result.is_err_and(|error| format!("{error:#}").contains("another core is running")));
}
}
}
#[test]
fn failed_service_install_can_continue_with_an_existing_sidecar() {
assert!(can_allow_sidecar_for_session(
+113 -80
View File
@@ -11,30 +11,18 @@ use crate::{
use anyhow::{Context as _, Result};
use clash_verge_logging::Type;
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
use futures::{
FutureExt as _,
future::{Map, Shared},
};
use futures::{FutureExt as _, future::Shared};
use log::Level;
use std::num::NonZeroUsize;
use std::path::Path;
use std::sync::Arc;
use tauri_plugin_mihomo::MihomoExt as _;
use tauri_plugin_shell::ShellExt as _;
use tauri_plugin_shell::process::CommandChild;
use tokio::task::{JoinError, JoinHandle};
pub(super) fn explain_core_occupancy(error: anyhow::Error) -> anyhow::Error {
let detail = error.to_string();
if detail.starts_with("process verge-mihomo") && detail.ends_with("; refusing a second core") {
error.context(clash_verge_i18n::t!("core.alreadyRunning").into_owned())
} else {
error
}
}
use tokio::sync::oneshot;
#[cfg(target_os = "windows")]
fn sidecar_config_without_tun(yaml: &str) -> Result<std::string::String> {
use crate::config::mihomo_yaml;
use serde_yaml_ng::{Mapping, Value};
let mut config: Mapping = serde_yaml_ng::from_str(yaml)?;
@@ -47,7 +35,7 @@ fn sidecar_config_without_tun(yaml: &str) -> Result<std::string::String> {
tun.as_mapping_mut()
.context("invalid Sidecar TUN configuration")?
.insert(Value::from("enable"), Value::Bool(false));
Ok(serde_yaml_ng::to_string(&config)?)
Ok(mihomo_yaml::serialize(&config)?)
}
const SIDECAR_READINESS_ATTEMPTS: usize = 30;
@@ -145,18 +133,10 @@ fn should_clear_terminated_sidecar(
matches!(running_mode, RunningMode::Sidecar) && current_generation == Some(terminated_generation)
}
type ShareExitResult = fn(Result<(), JoinError>) -> Result<(), Arc<JoinError>>;
type SidecarExit = Shared<Map<JoinHandle<()>, ShareExitResult>>;
fn share_exit(exit: JoinHandle<()>) -> SidecarExit {
let share_error: ShareExitResult = |result| result.map_err(Arc::new);
exit.map(share_error).shared()
}
#[derive(Debug, Default)]
pub(super) struct SidecarSession {
process: Option<SidecarProcess>,
exit: Option<SidecarExit>,
exit: Option<Shared<oneshot::Receiver<()>>>,
}
#[derive(Debug)]
@@ -194,10 +174,7 @@ impl CoreManager {
#[tracing::instrument(skip_all, level = "info", fields(pid = tracing::field::Empty))]
pub(super) async fn start_core_by_sidecar(&self) -> Result<()> {
self.wait_for_sidecar_exit().await?;
let execution = clash_verge_service_ipc::execution::reserve_sidecar()
.await
.inspect_err(service::record_residual_service)
.map_err(explain_core_occupancy)?;
service::require_service_core_released()?;
self.core_stopped();
let sidecar_ipc = dirs::sidecar_ipc_path()?;
@@ -220,13 +197,11 @@ impl CoreManager {
#[cfg(unix)]
discard_unwritable_core_cache(&config_dir);
#[cfg(unix)]
let previous_mask = unsafe { tauri_plugin_clash_verge_sysinfo::libc::umask(0o077) };
let command = app_handle
.shell()
.sidecar(clash_core.as_str())
.map_err(|error| anyhow::anyhow!("failed to build sidecar command for core {clash_core:?}: {error:#}"))?;
let command = command.args([
let command = command.kill_on_drop(true).args([
"-d",
dirs::path_to_str(&config_dir)?,
"-f",
@@ -243,6 +218,13 @@ impl CoreManager {
"LISTEN_NAMEDPIPE_SDDL",
crate::core::owner_identity::current_user_pipe_sddl()?,
);
#[cfg(unix)]
let restore_mask = std::mem::DropGuard::new(
unsafe { tauri_plugin_clash_verge_sysinfo::libc::umask(0o077) },
|mask| {
unsafe { tauri_plugin_clash_verge_sysinfo::libc::umask(mask) };
},
);
let (mut rx, child) = command.spawn().map_err(|error| {
anyhow::anyhow!(
"failed to start sidecar core {clash_core:?} with config {} and data directory {}: {error:#}",
@@ -250,35 +232,10 @@ impl CoreManager {
config_dir.display()
)
})?;
let (terminated, termination) = tokio::sync::oneshot::channel();
let exit = execution.release_after_exit(child.pid(), termination);
self.sidecar.lock().exit = Some(share_exit(exit));
#[cfg(target_os = "windows")]
let job = {
match create_and_assign_sidecar_job(child.pid()) {
Ok(job) => job,
Err(job_error) => {
let pid = child.pid();
let error = match child.kill() {
Ok(()) => job_error,
Err(kill_error) => anyhow::anyhow!(
"failed to configure Job Object for sidecar PID {pid}: \
{job_error:#}; failed to terminate child: {kill_error:#}"
),
};
logging!(error, Type::Core, "Failed to start sidecar: {error:#}");
return Err(error);
}
}
};
#[cfg(unix)]
unsafe {
tauri_plugin_clash_verge_sysinfo::libc::umask(previous_mask)
};
drop(restore_mask);
let (terminated, termination) = oneshot::channel();
self.sidecar.lock().exit = Some(termination.shared());
let pid = child.pid();
tracing::Span::current().record("pid", pid);
@@ -316,6 +273,30 @@ impl CoreManager {
}
});
#[cfg(target_os = "windows")]
let job = {
match create_and_assign_sidecar_job(child.pid()) {
Ok(job) => job,
Err(job_error) => {
let pid = child.pid();
let error = match child.kill() {
Ok(()) => {
self.sidecar.lock().exit.take();
job_error
}
Err(kill_error) => anyhow::anyhow!(
"failed to configure Job Object for sidecar PID {pid}: \
{job_error:#}; failed to terminate child: {kill_error:#}"
),
};
logging!(error, Type::Core, "Failed to start sidecar: {error:#}");
return Err(error);
}
}
};
let readiness = poll_sidecar_readiness(SIDECAR_READINESS_ATTEMPTS, SIDECAR_READINESS_INTERVAL, || async {
tokio::time::timeout(SIDECAR_READINESS_PROBE_TIMEOUT, async {
handle::Handle::mihomo().get_version().await
@@ -329,7 +310,10 @@ impl CoreManager {
proxy_control::stop_guard().await;
self.core_stopped();
return match child.kill() {
Ok(()) => Err(readiness_error),
Ok(()) => {
self.sidecar.lock().exit.take();
Err(readiness_error)
}
Err(kill_error) => Err(anyhow::anyhow!(
"{readiness_error:#}; failed to terminate unready sidecar PID {pid}: {kill_error:#}"
)),
@@ -357,8 +341,11 @@ impl CoreManager {
#[cfg(target_os = "windows")]
drop(process.job);
if let Err(error) = process.child.kill() {
logging!(warn, Type::Core, "failed to terminate sidecar PID {pid}: {error:#}");
match process.child.kill() {
Ok(()) => {
self.sidecar.lock().exit.take();
}
Err(error) => logging!(warn, Type::Core, "failed to terminate sidecar PID {pid}: {error:#}"),
}
}
let result = self.wait_for_sidecar_exit().await;
@@ -392,12 +379,13 @@ impl CoreManager {
#[tracing::instrument(skip_all, level = "info", fields(config_file = %config_file.display()))]
pub(super) async fn start_core_by_service_with_config(&self, config_file: &Path) -> Result<()> {
// 交接时等待 sidecar 释放 ext-controller 通道。
self.wait_for_sidecar_exit().await?;
let start = tokio::sync::OnceCell::new();
#[cfg(target_os = "windows")]
{
use crate::constants::timing;
retry_service_start(timing::SERVICE_START_RETRIES, timing::SERVICE_START_RETRY_DELAY, || {
service::run_core_by_service(config_file)
service::run_core_by_service(config_file, &start)
})
.await?;
self.mark_core_ready();
@@ -409,7 +397,7 @@ impl CoreManager {
#[cfg(not(target_os = "windows"))]
{
service::run_core_by_service(config_file).await?;
service::run_core_by_service(config_file, &start).await?;
self.mark_core_ready();
self.core_started(RunningMode::Service);
self.restore_selected_nodes().await;
@@ -555,20 +543,6 @@ mod readiness_tests {
time::Duration,
};
#[test]
fn core_occupancy_explanation_preserves_the_original_error() {
for detail in [
"process verge-mihomo remains after IPC failure; refusing a second core",
"process verge-mihomo-alpha.exe (PID 123) is still running; refusing a second core",
] {
let error = super::explain_core_occupancy(anyhow::anyhow!(detail));
assert_eq!(error.to_string(), clash_verge_i18n::t!("core.alreadyRunning"));
assert_eq!(error.root_cause().to_string(), detail);
}
let error = super::explain_core_occupancy(anyhow::anyhow!("could not inspect remaining cores"));
assert_eq!(error.to_string(), "could not inspect remaining cores");
}
#[tokio::test]
async fn sidecar_readiness_poll_is_bounded_and_accepts_a_real_api_response() -> anyhow::Result<()> {
let attempts = Arc::new(AtomicUsize::new(0));
@@ -729,6 +703,65 @@ mod tests {
Ok(())
}
#[test]
fn forced_parent_exit_releases_the_sidecar_job() -> Result<()> {
use std::io::{BufRead as _, BufReader, Write as _};
use std::os::windows::io::{AsRawHandle as _, FromRawHandle as _, OwnedHandle};
use windows_sys::Win32::{
Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT},
System::Threading::{OpenProcess, PROCESS_SYNCHRONIZE, WaitForSingleObject},
};
const HELPER: &str = "CVR_TEST_SIDECAR_JOB_PARENT";
if std::env::var_os(HELPER).is_some() {
let mut child = spawn_long_lived()?;
let _job = create_and_assign_sidecar_job(child.id()).inspect_err(|_| {
let _ = child.kill();
let _ = child.wait();
})?;
println!("\nSIDECAR_PID={}", child.id());
std::io::stdout().flush()?;
std::io::stdin().read_line(&mut String::new())?;
return Ok(());
}
let mut parent = std::mem::DropGuard::new(
Command::new(std::env::current_exe()?)
.args(["forced_parent_exit_releases_the_sidecar_job", "--nocapture"])
.env(HELPER, "1")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()?,
|mut parent| {
let _ = parent.kill();
let _ = parent.wait();
},
);
let stdout = parent
.stdout
.take()
.ok_or_else(|| anyhow::anyhow!("missing helper stdout"))?;
let mut pid = None;
for line in BufReader::new(stdout).lines() {
if let Some(value) = line?.strip_prefix("SIDECAR_PID=") {
pid = Some(value.parse()?);
break;
}
}
let pid = pid.ok_or_else(|| anyhow::anyhow!("helper did not report its child"))?;
let raw = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 0, pid) };
anyhow::ensure!(!raw.is_null(), "could not open helper child {pid}");
let child = unsafe { OwnedHandle::from_raw_handle(raw) };
assert_eq!(unsafe { WaitForSingleObject(child.as_raw_handle(), 0) }, WAIT_TIMEOUT);
parent.kill()?;
parent.wait()?;
assert_eq!(
unsafe { WaitForSingleObject(child.as_raw_handle(), 5000) },
WAIT_OBJECT_0
);
Ok(())
}
#[test]
fn returns_err_for_invalid_pid() {
// Windows PIDs are multiples of four; this one is effectively impossible.
-2
View File
@@ -11,9 +11,7 @@ pub mod network_watch;
pub mod notify;
pub(crate) mod owner_identity;
pub mod proxy_control;
pub mod proxy_view;
pub mod runstate;
pub(crate) mod runtime_bundle;
pub mod service;
pub mod sysopt;
pub mod timer;
+1 -6
View File
@@ -19,9 +19,6 @@ pub enum NoticeStatus {
ServiceCoreRepairRequired,
#[serde(rename = "service_core::app_data_not_owned")]
ServiceCoreAppDataNotOwned,
#[serde(rename = "service_core::sidecar_fallback")]
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
ServiceCoreSidecarFallback,
#[serde(rename = "dns_override::auto_disabled")]
DnsOverrideAutoDisabled,
#[serde(rename = "enhance::discarded_keys")]
@@ -81,14 +78,13 @@ impl NoticeStatus {
/// test both derive their variant list from here; expected strings stay
/// hand-written in the test so renames cannot slip through.
#[cfg(test)]
pub const ALL: [Self; 33] = [
pub const ALL: [Self; 32] = [
Self::ImportSubUrlOk,
Self::ImportSubUrlError,
Self::SetConfigError,
Self::CoreStartError,
Self::ServiceCoreRepairRequired,
Self::ServiceCoreAppDataNotOwned,
Self::ServiceCoreSidecarFallback,
Self::DnsOverrideAutoDisabled,
Self::EnhanceDiscardedKeys,
Self::TunModeAutoDisabled,
@@ -132,7 +128,6 @@ mod tests {
"core_start::error",
"service_core::repair_required",
"service_core::app_data_not_owned",
"service_core::sidecar_fallback",
"dns_override::auto_disabled",
"enhance::discarded_keys",
"tun_mode::auto_disabled",
+2 -2
View File
@@ -390,10 +390,10 @@ fn service_proxy_config(verge: &IVerge, mixed_port: u16, pac_port: u16) -> Resul
/// the write's, so it stays a failure.
fn service_apply_result(requested: &MacosProxyConfig, outcome: ProxyApplyOutcome) -> Result<()> {
match outcome {
ProxyApplyOutcome::Applied | ProxyApplyOutcome::NotRequested => Ok(()),
ProxyApplyOutcome::Applied => Ok(()),
// Direct fallback satisfies a disable request.
ProxyApplyOutcome::DirectFallback { .. } if matches!(requested, MacosProxyConfig::Disabled) => Ok(()),
// Older helpers encode a failed service lookup as fallback even when no OS write occurred.
// The service reports a missing network service as fallback before any OS write.
#[cfg(target_os = "macos")]
ProxyApplyOutcome::DirectFallback { message }
if message == sysproxy::Error::NoActiveNetworkService.to_string() =>
+2 -10
View File
@@ -67,17 +67,9 @@ impl RunStateEnv for RealEnv {
}
async fn trusted_install_evidence(&self) -> Result<bool> {
let registered = tokio::task::spawn_blocking(crate::core::service::trusted_service_evidence)
tokio::task::spawn_blocking(crate::core::service::trusted_service_evidence)
.await
.context("service registration probe did not finish")??;
// A helper that outlived its registration is a broken Service, not an absent one.
#[cfg(unix)]
if !registered && let Err(error) = clash_verge_service_ipc::execution::check_sidecar_available().await {
return Ok(error
.downcast_ref::<clash_verge_service_ipc::execution::ResidualServiceError>()
.is_some());
}
Ok(registered)
.context("service registration probe did not finish")?
}
fn is_elevated(&self) -> bool {
+1 -16
View File
@@ -24,7 +24,7 @@ pub use env::FakeEnv;
pub use env::{RealEnv, RunStateEnv};
pub use health::{PendingAction, RunState, RunStateView, ServiceHealth};
pub use owner::{OwnerRecoveryReason, OwnerSample, OwnerStep, OwnerWatch};
pub use probe::{CORE_REJECTED_PREFIX, ServiceVersionCheck, ServiceVersionReply, classify_service_version_reply};
pub use probe::{ServiceVersionCheck, ServiceVersionReply, classify_service_version_reply};
use crate::core::manager::RunningMode;
use health::StoredService;
@@ -336,21 +336,6 @@ impl<E: RunStateEnv> RunStateStore<E> {
Ok(())
}
#[cfg(target_os = "windows")]
pub fn allow_sidecar_after_service_refusal(&self, reason: String) -> Result<()> {
let mut state = self.service.lock();
if state.operation_running || state.service.pending.is_some() {
bail!("cannot fall back while a service operation is pending");
}
// Publish the refusal and allowance together so it never asks the UI for a repair.
state.service.health = ServiceHealth::Unavailable(reason);
state.service.allow_sidecar();
state.bump();
drop(state);
self.announce();
Ok(())
}
/// Requests installation only for a confirmed absent Service.
pub fn require_install_for_session(&self) -> Result<()> {
let mut state = self.service.lock();
+216 -172
View File
@@ -1,7 +1,7 @@
use crate::core::notify::NoticeStatus;
use crate::utils::dirs;
use crate::{
config::{Config, runtime::IRuntime},
config::{Config, mihomo_yaml, runtime::IRuntime},
constants,
core::{
CoreManager,
@@ -10,10 +10,9 @@ use crate::{
owner_identity::current_owner_credentials,
proxy_control,
runstate::{
CORE_REJECTED_PREFIX, OwnerRecoveryReason, OwnerSample, OwnerStep, OwnerWatch, PendingAction, RUN_STATE,
ReadyWaitError, RunState, RunStateEnv, RunStateStore, ServiceHealth,
OwnerRecoveryReason, OwnerSample, OwnerStep, OwnerWatch, PendingAction, RUN_STATE, ReadyWaitError,
RunState, RunStateEnv, RunStateStore, ServiceHealth,
},
runtime_bundle::{GEO_ASSETS, RemoteProviderRef, collect_runtime_bundle, remote_providers_of},
tray::Tray,
},
process::AsyncHandler,
@@ -21,9 +20,10 @@ use crate::{
use anyhow::{Context as _, Result, anyhow, bail};
use clash_verge_draft::Draft;
use clash_verge_logging::{Type, logging};
use clash_verge_runtime_bundle::{GEO_ASSETS, RemoteProviderRef, collect_runtime_bundle, remote_providers_of};
use clash_verge_service_ipc::{
MacosProxyConfig, OwnerCredentials, OwnerIdentity, OwnerSessionProof, ProtocolInfo, ProxyApplyOutcome,
RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode, ServiceStatusSnapshot,
MacosProxyConfig, OwnerCredentials, OwnerIdentity, OwnerSessionProof, ProxyApplyOutcome, RemoteProvider,
RuntimeAsset, RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode, ServiceStatusSnapshot,
StageRuntimeOutcome, StartClashRequest, WriterConfig,
};
use clash_verge_task::scheduled_task::{self, Mailbox, Next, ScheduledTask};
@@ -44,45 +44,21 @@ use std::{
use tokio::{sync::watch, time::Instant};
static OWNER_MONITOR_GENERATION: AtomicU64 = AtomicU64::new(0);
static ACTIVE_SERVICE_SESSION: Mutex<Option<ActiveServiceSession>> = Mutex::new(None);
static PENDING_SERVICE_FALLBACK_NOTICE: Mutex<Option<String>> = Mutex::new(None);
static PENDING_SERVICE_START: Mutex<Option<PendingServiceStart>> = Mutex::new(None);
static ACTIVE_SERVICE_SESSION: Mutex<Option<Arc<OwnerSessionProof>>> = Mutex::new(None);
static PENDING_SERVICE_REPAIR_NOTICE: AtomicBool = AtomicBool::new(false);
static PENDING_SERVICE_OWNER_NOTICE: Mutex<Option<String>> = Mutex::new(None);
/// Why the Service was unavailable when the core fell back to Sidecar.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, specta::Type)]
#[serde(tag = "kind", content = "reason", rename_all = "camelCase")]
pub enum ServiceFallbackNotice {
Unavailable,
CoreRejected(String),
NotAutoStarted,
}
#[cfg(windows)]
/// The release installer registers AutoStart.
const SERVICE_NOT_AUTO_STARTED: &str = "the Windows service is stopped and no longer starts with Windows";
#[cfg(windows)]
pub(crate) fn is_not_auto_started(reason: &str) -> bool {
// Detection prefixes its own context to the reason.
reason.contains(SERVICE_NOT_AUTO_STARTED)
}
#[cfg(target_os = "windows")]
pub(crate) fn notify_service_fallback(reason: &str) {
*PENDING_SERVICE_FALLBACK_NOTICE.lock() = Some(reason.to_owned());
Handle::notice(NoticeStatus::ServiceCoreSidecarFallback, "");
}
pub(crate) fn take_service_fallback_notice() -> Option<ServiceFallbackNotice> {
let reason = PENDING_SERVICE_FALLBACK_NOTICE.lock().take()?;
Some(if reason.starts_with(CORE_REJECTED_PREFIX) {
ServiceFallbackNotice::CoreRejected(reason)
} else if is_not_auto_started(&reason) {
ServiceFallbackNotice::NotAutoStarted
} else {
ServiceFallbackNotice::Unavailable
})
}
pub(crate) fn take_service_repair_notice() -> bool {
PENDING_SERVICE_REPAIR_NOTICE.swap(false, Ordering::Relaxed)
}
@@ -100,14 +76,27 @@ fn app_data_owner_command(credentials: &OwnerCredentials) -> Option<String> {
Some(format!("sudo chown -R {uid}:{gid} '{path}'"))
}
/// Capabilities of the service session that owns the running Core.
/// They are discarded with that session rather than cached across service upgrades.
#[derive(Clone)]
struct ActiveServiceSession {
proof: Arc<OwnerSessionProof>,
supports_runtime_staging: bool,
supports_runtime_file_read: bool,
supports_runtime_geo_read: bool,
struct PendingServiceStart {
token: String,
service_replaced: bool,
}
impl PendingServiceStart {
const fn new(token: String) -> Self {
Self {
token,
service_replaced: false,
}
}
const fn released_after_repair(&self, status: &ServiceStatusSnapshot) -> bool {
self.service_replaced
&& !status.is_active
&& status.active_generation.is_none()
&& status.core_pid.is_none()
&& !status.desired_core_should_be_running
}
}
fn generate_service_session_token() -> Result<String> {
@@ -125,89 +114,14 @@ fn generate_service_session_token() -> Result<String> {
pub(crate) fn active_service_session() -> Result<Arc<OwnerSessionProof>> {
ACTIVE_SERVICE_SESSION
.lock()
.as_ref()
.map(|session| Arc::clone(&session.proof))
.clone()
.context("service owner session is not active")
}
/// Returns false unless the active service session explicitly supports in-place staging.
pub(crate) fn active_service_supports_runtime_staging() -> bool {
ACTIVE_SERVICE_SESSION
.lock()
.as_ref()
.is_some_and(|session| session.supports_runtime_staging)
}
pub(crate) fn active_service_supports_runtime_file_read() -> bool {
ACTIVE_SERVICE_SESSION
.lock()
.as_ref()
.is_some_and(|session| session.supports_runtime_file_read)
}
fn active_service_supports_runtime_geo_read() -> bool {
ACTIVE_SERVICE_SESSION
.lock()
.as_ref()
.is_some_and(|session| session.supports_runtime_geo_read)
}
pub(crate) fn clear_active_service_session() {
ACTIVE_SERVICE_SESSION.lock().take();
}
#[derive(Clone, Copy, Default)]
struct ServiceCapabilities {
runtime_staging: bool,
runtime_file_read: bool,
runtime_geo_read: bool,
}
impl ServiceCapabilities {
const fn of(info: &ProtocolInfo) -> Self {
Self {
runtime_staging: info.supports_runtime_staging(),
runtime_file_read: info.supports_runtime_file_read(),
runtime_geo_read: info.supports_runtime_geo_read(),
}
}
}
/// Failed capability probes must not block startup.
#[tracing::instrument(skip_all, level = "info", fields(supported = tracing::field::Empty))]
async fn probe_service_capabilities() -> ServiceCapabilities {
match clash_verge_service_ipc::get_version().await {
Ok(response) if response.code == 0 => {
let capabilities = response
.data
.as_ref()
.map_or_else(ServiceCapabilities::default, ServiceCapabilities::of);
tracing::Span::current().record("supported", capabilities.runtime_staging);
capabilities
}
Ok(response) => {
tracing::Span::current().record("supported", false);
logging!(
warn,
Type::Service,
"服务协议查询返回 {}: {};配置变更将走重启路径",
response.code,
response.message
);
ServiceCapabilities::default()
}
Err(error) => {
tracing::Span::current().record("supported", false);
logging!(
warn,
Type::Service,
"无法查询服务协议版本: {error:#};配置变更将走重启路径"
);
ServiceCapabilities::default()
}
}
}
fn session_matches_status(proof: &OwnerSessionProof, is_active: bool, active_generation: Option<u64>) -> bool {
is_active && active_generation == Some(proof.generation)
}
@@ -600,7 +514,26 @@ pub(crate) fn run_privileged_service_action(action: PendingAction) -> Result<()>
PendingAction::Reinstall => (reinstall_service, "reinstall service"),
PendingAction::ForceReinstall => (force_reinstall_service, "force reinstall service"),
};
tokio::task::block_in_place(operation).with_context(|| format!("{label} failed"))
tokio::task::block_in_place(|| {
let pending_token = match action {
PendingAction::Reinstall | PendingAction::ForceReinstall => PENDING_SERVICE_START
.lock()
.as_ref()
.map(|pending| pending.token.clone()),
PendingAction::Install | PendingAction::Uninstall => None,
};
operation().with_context(|| format!("{label} failed"))?;
// Full repair acquires the stopped-service guard before replacing the daemon.
if let Some(token) = pending_token
&& let Some(pending) = PENDING_SERVICE_START
.lock()
.as_mut()
.filter(|pending| pending.token == token)
{
pending.service_replaced = true;
}
Ok(())
})
}
/// Builds the same runtime bundle description for both service start and staging.
@@ -611,7 +544,27 @@ async fn collect_service_runtime_bundle(config_file: &Path) -> Result<RuntimeBun
let bin_ext = if cfg!(windows) { ".exe" } else { "" };
let bin_path = service_core_path(&clash_core, bin_ext)?;
collect_runtime_bundle(config_file, &bin_path).await
let plan = collect_runtime_bundle(config_file).await?;
Ok(RuntimeBundle {
yaml: mihomo_yaml::serialize(&plan.config).context("failed to serialize service runtime config")?,
assets: plan
.assets
.into_iter()
.map(|asset| RuntimeAsset {
source: asset.source,
destination: asset.destination.into(),
})
.collect(),
remote_providers: plan
.remote_providers
.into_iter()
.map(|provider| RemoteProvider {
destination: provider.destination.into(),
url: provider.url,
})
.collect(),
core_path: bin_path.to_string_lossy().into_owned(),
})
}
/// A staging response whose refusal code tells callers whether a fresh start can help.
@@ -628,12 +581,11 @@ impl StageRequest {
}
/// Requests in-place staging. `Err` means no answer; refusals are returned for caller policy.
pub(super) async fn stage_runtime_by_service(config_file: &Path) -> Result<StageRequest> {
let session = active_service_session()?;
pub(super) async fn stage_runtime_by_service(config_file: &Path, session: &OwnerSessionProof) -> Result<StageRequest> {
let credentials = current_owner_credentials()?;
let runtime = collect_service_runtime_bundle(config_file).await?;
let response = clash_verge_service_ipc::stage_runtime(&credentials, &session, &runtime)
let response = clash_verge_service_ipc::stage_runtime(&credentials, session, &runtime)
.await
.context("无法连接到Clash Verge Service")?;
if response.code > 0 {
@@ -680,27 +632,86 @@ fn record_service_start_refusal<E: RunStateEnv>(
refusal.into()
}
/// Sidecar stays blocked until a reinstall replaces the residual helper, so ask for repair.
pub(super) fn record_residual_service(error: &anyhow::Error) {
if let Some(residual) = error.downcast_ref::<clash_verge_service_ipc::execution::ResidualServiceError>() {
RUN_STATE.observe(ServiceHealth::Unavailable(residual.to_string()));
pub(super) fn require_service_core_released() -> Result<()> {
anyhow::ensure!(
PENDING_SERVICE_START.lock().is_none() && ACTIVE_SERVICE_SESSION.lock().is_none(),
"the previous Service core has not confirmed exit"
);
Ok(())
}
pub(super) async fn release_service_core_for_sidecar() -> Result<()> {
let pending = PENDING_SERVICE_START.lock().clone();
if pending.is_none() {
if active_service_session().is_ok() {
return stop_core_by_service().await;
}
if matches!(RUN_STATE.state().health, ServiceHealth::NotInstalled) {
return Ok(());
}
}
let credentials = current_owner_credentials()?;
let status = tokio::time::timeout(
Duration::from_secs(2),
clash_verge_service_ipc::get_status(&credentials),
)
.await
.context("timed out confirming the previous Service core exited")??;
anyhow::ensure!(status.code == 0, "Service status failed: {}", status.message);
let status = status.data.context("Service omitted owner status")?;
let Some(pending) = pending else {
anyhow::ensure!(
!status.is_active || (status.core_pid.is_none() && !status.desired_core_should_be_running),
"the Service is running or recovering this owner's core; stop it before switching"
);
return Ok(());
};
if pending.released_after_repair(&status) {
PENDING_SERVICE_START.lock().take();
clear_active_service_session();
return Ok(());
}
// A lost Start reply may have committed. Only its proposed token can stop that generation.
let generation = status
.active_generation
.context("the previous Service start has not confirmed exit; repair the Service before switching")?;
let stopped = clash_verge_service_ipc::stop_clash(
&credentials,
&OwnerSessionProof {
generation,
token: pending.token,
},
)
.await?;
anyhow::ensure!(
stopped.code == 0,
"could not confirm Service core exit: {}",
stopped.message
);
PENDING_SERVICE_START.lock().take();
clear_active_service_session();
Ok(())
}
/// 尝试使用服务启动core
#[tracing::instrument(skip_all, level = "info", fields(generation = tracing::field::Empty, staging = tracing::field::Empty, code = tracing::field::Empty, outcome = tracing::field::Empty))]
pub(super) async fn start_with_existing_service(config_file: &Path) -> Result<()> {
clear_active_service_session();
#[tracing::instrument(skip_all, level = "info", fields(generation = tracing::field::Empty, code = tracing::field::Empty, outcome = tracing::field::Empty))]
async fn start_with_existing_service(
config_file: &Path,
start: &tokio::sync::OnceCell<StartClashRequest>,
) -> Result<()> {
let credentials = current_owner_credentials()?;
let runtime = collect_service_runtime_bundle(config_file).await?;
let request = StartClashRequest {
runtime,
proposed_session_token: generate_service_session_token()?,
macos_proxy: None,
};
let response = match clash_verge_service_ipc::start_clash(&credentials, &request).await {
let request = start
.get_or_try_init(|| async {
Ok::<_, anyhow::Error>(StartClashRequest {
runtime: collect_service_runtime_bundle(config_file).await?,
proposed_session_token: generate_service_session_token()?,
})
})
.await?;
let previous = PENDING_SERVICE_START
.lock()
.replace(PendingServiceStart::new(request.proposed_session_token.clone()));
let response = match clash_verge_service_ipc::start_clash(&credentials, request).await {
Ok(response) => response,
Err(error) => {
tracing::Span::current().record("outcome", "ipc-unreachable");
@@ -712,6 +723,16 @@ pub(super) async fn start_with_existing_service(config_file: &Path) -> Result<()
if response.code > 0 {
tracing::Span::current().record("code", response.code);
tracing::Span::current().record("outcome", "refused");
if matches!(response.code,
code if code == ServiceErrorCode::InvalidInstallLocation as u16
|| code == ServiceErrorCode::InvalidRuntimeAsset as u16
|| code == ServiceErrorCode::AppDataRootNotOwned as u16
|| code == ServiceErrorCode::UnauthorizedOwner as u16
|| code == ServiceErrorCode::ProtocolMismatch as u16
|| code == ServiceErrorCode::ProxyClearFailed as u16
) {
*PENDING_SERVICE_START.lock() = previous;
}
let err_msg = response.message;
logging!(
error,
@@ -734,43 +755,39 @@ pub(super) async fn start_with_existing_service(config_file: &Path) -> Result<()
&RUN_STATE,
ServiceStartRefusal {
code: response.code,
core_path: request.runtime.core_path,
core_path: request.runtime.core_path.clone(),
message: err_msg,
},
));
}
let result = response.data.context("Clash Verge Service 未返回会话信息")?;
tracing::Span::current().record("generation", result.session.generation);
let capabilities = probe_service_capabilities().await;
tracing::Span::current().record("staging", capabilities.runtime_staging);
*ACTIVE_SERVICE_SESSION.lock() = Some(ActiveServiceSession {
proof: Arc::new(OwnerSessionProof {
generation: result.session.generation,
token: request.proposed_session_token,
}),
supports_runtime_staging: capabilities.runtime_staging,
supports_runtime_file_read: capabilities.runtime_file_read,
supports_runtime_geo_read: capabilities.runtime_geo_read,
});
tracing::Span::current().record("generation", result.generation);
*ACTIVE_SERVICE_SESSION.lock() = Some(Arc::new(OwnerSessionProof {
generation: result.generation,
token: request.proposed_session_token.clone(),
}));
PENDING_SERVICE_START.lock().take();
// PAC follows the Running Mode; the caller opens it via `core_started(Service)`.
start_owner_monitor();
tracing::Span::current().record("outcome", "started");
PENDING_SERVICE_FALLBACK_NOTICE.lock().take();
PENDING_SERVICE_REPAIR_NOTICE.store(false, Ordering::Relaxed);
PENDING_SERVICE_OWNER_NOTICE.lock().take();
logging!(
info,
Type::Service,
"服务成功启动核心 (session generation {})",
result.session.generation
result.generation
);
Ok(())
}
// 以服务启动core
pub(super) async fn run_core_by_service(config_file: &Path) -> Result<()> {
pub(super) async fn run_core_by_service(
config_file: &Path,
start: &tokio::sync::OnceCell<StartClashRequest>,
) -> Result<()> {
SERVICE_MANAGER.refresh().await?;
let status = SERVICE_MANAGER.current().await;
@@ -779,7 +796,7 @@ pub(super) async fn run_core_by_service(config_file: &Path) -> Result<()> {
}
logging!(info, Type::Service, "服务已运行且版本匹配,直接使用");
start_with_existing_service(config_file).await
start_with_existing_service(config_file, start).await
}
async fn capture_generation_before<F, Fut, T>(generation: &AtomicU64, operation: F) -> (u64, T)
@@ -936,11 +953,10 @@ type ProviderLoadTimes = HashMap<(&'static str, String), Option<u64>>;
#[tracing::instrument(level = "info", fields(synced = tracing::field::Empty, pending = tracing::field::Empty))]
async fn sync_runtime_providers_by_service() -> Result<ProviderSync> {
if !active_service_supports_runtime_file_read() {
let Ok(session) = active_service_session() else {
return Ok(ProviderSync::default());
}
};
let credentials = current_owner_credentials()?;
let session = active_service_session()?;
let app_dir = dirs::app_home_dir()?;
let runtime = Config::runtime().await;
let mut outcome = ProviderSync::default();
@@ -948,7 +964,7 @@ async fn sync_runtime_providers_by_service() -> Result<ProviderSync> {
let loaded_before = provider_load_times().await;
let mut fetched = Vec::new();
for declared in applied_remote_providers(&runtime, &app_dir)? {
let (temp, file) = match create_sync_temp(&app_dir.join(&declared.provider.destination)).await {
let (temp, file) = match create_sync_temp(&app_dir.join(declared.destination.as_str())).await {
Ok(created) => created,
Err(error) => {
logging!(warn, Type::Service, "{error:#}");
@@ -956,7 +972,7 @@ async fn sync_runtime_providers_by_service() -> Result<ProviderSync> {
continue;
}
};
match fetch_runtime_file(&credentials, &session, &declared.provider.destination, file).await {
match fetch_runtime_file(&credentials, &session, &declared.destination, file).await {
Ok(Fetch::Complete { len, mtime_ns }) => fetched.push(FetchedCache {
declared,
temp,
@@ -977,7 +993,7 @@ async fn sync_runtime_providers_by_service() -> Result<ProviderSync> {
warn,
Type::Service,
"failed to read provider cache {} into {}: {error:#}",
declared.provider.destination,
declared.destination,
temp.display()
);
outcome.pending += 1;
@@ -1026,14 +1042,10 @@ async fn sync_runtime_providers_by_service() -> Result<ProviderSync> {
/// Pulls geo databases the service core rewrote, because validation reads the app dir.
pub(crate) async fn sync_runtime_geo_by_service() {
if !active_service_supports_runtime_geo_read() {
let Ok(session) = active_service_session() else {
return;
}
let (Ok(credentials), Ok(session), Ok(app_dir)) = (
current_owner_credentials(),
active_service_session(),
dirs::app_home_dir(),
) else {
};
let (Ok(credentials), Ok(app_dir)) = (current_owner_credentials(), dirs::app_home_dir()) else {
return;
};
for asset in GEO_ASSETS {
@@ -1088,7 +1100,7 @@ async fn sync_runtime_geo(
fn applied_remote_providers(runtime: &Draft<IRuntime>, app_dir: &Path) -> Result<Vec<RemoteProviderRef>> {
let applied = runtime.data_arc();
match applied.config.as_ref() {
Some(config) => remote_providers_of(config, app_dir),
Some(config) => remote_providers_of(config, app_dir).map_err(Into::into),
None => Ok(Vec::new()),
}
}
@@ -1117,7 +1129,7 @@ async fn publish_fetched(
};
let mut synced = 0;
for cache in fetched {
let target = app_dir.join(&cache.declared.provider.destination);
let target = app_dir.join(cache.declared.destination.as_str());
if !declared.contains(&cache.declared) || same_contents(&cache.temp, &target).await {
remove_temp(&cache.temp).await;
continue;
@@ -1194,7 +1206,7 @@ async fn recheck_identity(
cache: &FetchedCache,
) -> Result<Fetch> {
let request = RuntimeFileRequest {
destination: cache.declared.provider.destination.to_owned(),
destination: cache.declared.destination.as_str().to_owned(),
offset: cache.len,
};
Ok(match read_chunk(credentials, session, &request).await? {
@@ -1621,7 +1633,7 @@ fn session_matches_active_status(is_active: bool, active_generation: Option<u64>
ACTIVE_SERVICE_SESSION
.lock()
.as_ref()
.is_some_and(|session| session_matches_status(&session.proof, is_active, active_generation))
.is_some_and(|session| session_matches_status(session, is_active, active_generation))
}
fn cancel_owner_monitors() {
@@ -1689,6 +1701,11 @@ async fn recover_after_owner_loss_while_locked(reason: OwnerRecoveryReason) {
if policy.reset_system_proxy {
clear_proxy_after_owner_loss().await;
}
if matches!(reason, OwnerRecoveryReason::TransportFailure)
&& let Ok(session) = active_service_session()
{
*PENDING_SERVICE_START.lock() = Some(PendingServiceStart::new(session.token.clone()));
}
clear_active_service_session();
CoreManager::global().core_stopped();
// A displaced Service may still run TUN for its new owner, and DNS settings are system-wide.
@@ -1975,6 +1992,33 @@ mod tests {
ServiceStatus::from_run_state(&store.settled().await)
}
#[test]
fn an_idle_snapshot_releases_an_ambiguous_start_only_after_repair() {
let mut pending = super::PendingServiceStart::new("lost-reply".into());
let mut status = clash_verge_service_ipc::ServiceStatusSnapshot {
is_active: false,
active_generation: None,
core_pid: None,
desired_core_should_be_running: false,
service_state: clash_verge_service_ipc::ServiceLifecycleState::Running,
core_started_at: None,
last_core_exit_reason: None,
restart_count: 0,
last_recovery_at: None,
desired_generation: 0,
desired_updated_at: 0,
desired_persistence_error: None,
};
assert!(!pending.released_after_repair(&status));
pending.service_replaced = true;
assert!(pending.released_after_repair(&status));
status.active_generation = Some(1);
assert!(!pending.released_after_repair(&status));
status.active_generation = None;
status.desired_core_should_be_running = true;
assert!(!pending.released_after_repair(&status));
}
#[test]
fn mismatched_active_generation_displaces_local_session() {
let proof = OwnerSessionProof {
+6 -19
View File
@@ -17,6 +17,7 @@ use crate::core::handle;
use crate::singleton;
use crate::utils::{dirs, help};
use clash_verge_logging::{Type, logging};
use clash_verge_profile_script::MainDeclaration;
const SYNTAX_CHECK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
@@ -33,7 +34,7 @@ async fn validation_fingerprint(yaml: &str) -> u64 {
.into_iter();
// The test run reads geo databases from the app dir; a geo update must revalidate.
let geo = dirs::app_home_dir().into_iter().flat_map(|dir| {
super::runtime_bundle::GEO_ASSETS
clash_verge_runtime_bundle::GEO_ASSETS
.iter()
.map(move |asset| dir.join(asset))
});
@@ -257,22 +258,8 @@ impl CoreConfigValidator {
};
logging!(debug, Type::Validate, "验证脚本文件: {}", path);
let has_main =
content.contains("function main") || content.contains("const main") || content.contains("let main");
// Boa parsing is pure CPU; keep it off the async worker, with a timeout.
let syntax = crate::process::AsyncHandler::spawn_blocking(move || {
use boa_engine::{Context, Source};
let mut context = Context::default();
let _ = context.eval(Source::from_bytes(
"var console = Object.freeze({log(...data){},info(...data){},error(...data){},debug(...data){}});",
));
context
.eval(Source::from_bytes(&content))
.map(|_| ())
.map_err(|err| err.to_string())
});
let syntax =
crate::process::AsyncHandler::spawn_blocking(move || clash_verge_profile_script::validate(&content));
let result = match tokio::time::timeout(SYNTAX_CHECK_TIMEOUT, syntax).await {
Ok(Ok(evaluated)) => evaluated,
Ok(Err(join_err)) => Err(format!("syntax check task failed: {join_err}")),
@@ -280,10 +267,10 @@ impl CoreConfigValidator {
};
match result {
Ok(()) => {
Ok(main) => {
logging!(debug, Type::Validate, "脚本语法验证通过: {}", path);
if !has_main {
if main == MainDeclaration::Missing {
let error_msg = "Script must contain a main function";
logging!(warn, Type::Validate, "脚本缺少main函数: {}", path);
return Ok(ValidationOutcome::invalid_from_message(error_msg));
+40 -68
View File
@@ -1,31 +1,14 @@
use super::SeqMap;
use crate::{
config::PrfItem,
utils::{dirs, help},
};
use clash_verge_config_render::{ChainItem, ChainType, SeqMap};
use parking_lot::Mutex;
use serde_yaml_ng::Mapping;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, LazyLock};
use std::time::SystemTime;
use tokio::fs;
use tristr::alias::String;
#[derive(Debug)]
pub struct ChainItem {
pub uid: String,
pub data: ChainType,
}
#[derive(Debug)]
pub enum ChainType {
Merge(Mapping),
Script(String),
Rules(SeqMap),
Proxies(SeqMap),
Groups(SeqMap),
}
struct CachedChain {
mtime: SystemTime,
@@ -35,56 +18,45 @@ struct CachedChain {
static CHAIN_CACHE: LazyLock<Mutex<HashMap<PathBuf, CachedChain>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
// Helper trait to allow async conversion
pub trait AsyncChainItemFrom {
async fn from_async(item: &PrfItem) -> Option<Arc<ChainItem>>;
}
pub(super) async fn load_chain_item(item: &PrfItem) -> Option<Arc<ChainItem>> {
let itype = item.itype.as_ref()?.as_str();
let file = item.file.as_ref()?;
let path = dirs::app_profiles_dir().ok()?.join(file.as_str());
impl AsyncChainItemFrom for Option<Arc<ChainItem>> {
async fn from_async(item: &PrfItem) -> Self {
let itype = item.itype.as_ref()?.as_str();
let file = item.file.clone()?;
let uid = item.uid.clone().unwrap_or_else(|| "".into());
let path = dirs::app_profiles_dir().ok()?.join(file.as_str());
let meta = fs::metadata(&path).await.ok()?;
let (mtime, len) = (meta.modified().ok()?, meta.len());
if let Some(cached) = CHAIN_CACHE.lock().get(&path)
&& cached.mtime == mtime
&& cached.len == len
{
return Some(Arc::clone(&cached.item));
}
let loaded = Arc::new(match itype {
"script" => Some(ChainItem {
uid,
data: ChainType::Script(fs::read_to_string(&path).await.ok()?.as_str().into()),
}),
"merge" => Some(ChainItem {
uid,
data: ChainType::Merge(help::read_mapping(&path).await.ok()?),
}),
"rules" | "proxies" | "groups" => {
let seq_map = help::read_yaml::<SeqMap>(&path).await.ok()?;
let data = match itype {
"rules" => ChainType::Rules(seq_map),
"proxies" => ChainType::Proxies(seq_map),
_ => ChainType::Groups(seq_map),
};
Some(ChainItem { uid, data })
}
_ => None,
}?);
CHAIN_CACHE.lock().insert(
path,
CachedChain {
mtime,
len,
item: Arc::clone(&loaded),
},
);
Some(loaded)
let meta = fs::metadata(&path).await.ok()?;
let (mtime, len) = (meta.modified().ok()?, meta.len());
if let Some(cached) = CHAIN_CACHE.lock().get(&path)
&& cached.mtime == mtime
&& cached.len == len
{
return Some(Arc::clone(&cached.item));
}
let data = match itype {
"script" => ChainType::Script(fs::read_to_string(&path).await.ok()?.into()),
"merge" => ChainType::Merge(help::read_mapping(&path).await.ok()?),
"rules" | "proxies" | "groups" => {
let seq_map = help::read_yaml::<SeqMap>(&path).await.ok()?;
match itype {
"rules" => ChainType::Rules(seq_map),
"proxies" => ChainType::Proxies(seq_map),
_ => ChainType::Groups(seq_map),
}
}
_ => return None,
};
let loaded = Arc::new(ChainItem {
uid: item.uid.clone().unwrap_or_default(),
data,
});
CHAIN_CACHE.lock().insert(
path,
CachedChain {
mtime,
len,
item: Arc::clone(&loaded),
},
);
Some(loaded)
}
File diff suppressed because it is too large Load Diff
+1
View File
@@ -9,6 +9,7 @@ mod icon;
mod listener;
mod profile;
mod proxy;
pub(crate) mod proxy_view;
mod subscription;
mod tun;
mod window;
+170
View File
@@ -0,0 +1,170 @@
mod groups;
use clash_verge_proxy_view::{
DelayHistory, ProviderSnapshot, ProxyCapabilities, ProxyProviderVehicleType, ProxySnapshot, ProxySubscriptionInfo,
ProxyViewInput, ProxyViewV1,
};
use serde_yaml_ng::Mapping;
use std::future::Future;
use tauri_plugin_mihomo::{
Result,
models::{Proxies, Proxy, ProxyProvider, ProxyProviders, ProxyType, VehicleType},
};
pub(crate) async fn load_proxy_view(
config: Option<&Mapping>,
proxies: impl Future<Output = Result<Proxies>>,
providers: impl Future<Output = Result<ProxyProviders>>,
) -> Result<ProxyViewV1> {
let (runtime_group_order, group_scopes) = groups::runtime_groups(config);
let (proxies, providers) = tokio::join!(proxies, providers);
let proxies = proxies?;
Ok(ProxyViewInput {
runtime_group_order,
group_scopes,
proxies: proxies
.proxies
.into_iter()
.map(|(name, proxy)| (name.into(), proxy_snapshot(proxy)))
.collect(),
providers: providers.ok().map(|providers| {
providers
.providers
.into_iter()
.filter_map(|(name, provider)| provider_snapshot(provider).map(|snapshot| (name.into(), snapshot)))
.collect()
}),
}
.into_view())
}
fn proxy_snapshot(proxy: Proxy) -> ProxySnapshot {
ProxySnapshot {
name: proxy.name.into(),
proxy_type: match proxy.proxy_type {
ProxyType::Unknown(value) => value.into(),
proxy_type => proxy_type.as_str().into(),
},
all: proxy.all.map(|all| all.into_iter().map(Into::into).collect()),
fixed: proxy.fixed.map(Into::into),
hidden: proxy.hidden,
icon: proxy.icon.map(Into::into),
now: proxy.now.map(Into::into),
test_url: proxy.test_url.map(Into::into),
id: proxy.id.map(Into::into),
history: proxy
.history
.into_iter()
.map(|entry| DelayHistory {
time: entry.time.into(),
delay: entry.delay,
})
.collect(),
capabilities: ProxyCapabilities {
udp: proxy.udp,
xudp: proxy.xudp,
tfo: proxy.tfo,
mptcp: proxy.mptcp,
smux: proxy.smux,
},
}
}
fn provider_snapshot(provider: ProxyProvider) -> Option<ProviderSnapshot> {
let vehicle_type = match provider.vehicle_type {
VehicleType::HTTP => ProxyProviderVehicleType::Http,
VehicleType::File => ProxyProviderVehicleType::File,
VehicleType::Inline => ProxyProviderVehicleType::Inline,
_ => return None,
};
Some(ProviderSnapshot {
vehicle_type,
proxies: provider.proxies.into_iter().map(proxy_snapshot).collect(),
updated_at: provider.updated_at.map(Into::into),
subscription_info: provider.subscription_info.map(|info| ProxySubscriptionInfo {
upload: info.upload,
download: info.download,
total: info.total,
expire: info.expire,
}),
})
}
#[cfg(test)]
mod tests {
use super::*;
use clash_verge_proxy_view::{
ProxyMemberRef, ProxyMemberUnresolvedReason, ProxyNodeSource, ProxyViewProviderState,
};
use std::future::ready;
use tauri_plugin_mihomo::Error;
#[tokio::test]
async fn preserves_scoped_members_and_global_when_providers_are_unavailable() -> anyhow::Result<()> {
let config = serde_yaml_ng::from_str(
"proxy-providers: {z: {}, a: {}}\n\
proxy-groups:\n\
- {name: GLOBAL}\n\
- {name: Select, use: [a]}\n\
- {name: Another}\n\
- {name: Select, use: [a], include-all-providers: true, exclude-type: Direct}",
)?;
let proxies = r#"{"proxies":{
"GLOBAL":{"type":"Selector","all":["Select"]},
"Select":{"type":"Selector","all":["shared"]},
"Another":{"type":"Selector","all":[]}
}}"#;
let providers = serde_json::from_str(
r#"{"providers":{
"a":{"vehicleType":"HTTP","proxies":[{"name":"shared","type":"Direct"}]},
"z":{"vehicleType":"File","proxies":[{"name":"shared","type":"Shadowsocks"}]}
}}"#,
)?;
let available = load_proxy_view(
Some(&config),
ready(Ok(serde_json::from_str(proxies)?)),
ready(Ok(providers)),
)
.await?;
let unavailable = load_proxy_view(
Some(&config),
ready(Ok(serde_json::from_str(proxies)?)),
ready(Err(Error::FailedResponse("providers unavailable".into()))),
)
.await?;
for view in [&available, &unavailable] {
assert_eq!(
view.global.as_ref().map(|global| global.members.as_slice()),
Some([ProxyMemberRef::Group { name: "Select".into() }].as_slice())
);
assert_eq!(view.groups.len(), 2);
assert_eq!(view.groups[1].name.as_str(), "Another");
assert_eq!(view.groups[0].name.as_str(), "Select");
}
assert_eq!(available.provider_state, ProxyViewProviderState::Ready);
let [ProxyMemberRef::Node { record_id, .. }] = available.groups[0].members.as_slice() else {
anyhow::bail!("expected the scoped provider member");
};
assert_eq!(
available.records.get(record_id).map(|record| &record.source),
Some(&ProxyNodeSource::Provider {
provider_name: "z".into(),
proxy_name: "shared".into(),
})
);
assert_eq!(unavailable.provider_state, ProxyViewProviderState::Unavailable);
assert_eq!(
unavailable.groups[0].members,
[ProxyMemberRef::Unresolved {
name: "shared".into(),
reason: ProxyMemberUnresolvedReason::ProviderUnavailable,
}]
);
Ok(())
}
}
+61
View File
@@ -0,0 +1,61 @@
use clash_verge_proxy_view::GroupScope;
use serde_yaml_ng::Mapping;
use std::collections::BTreeMap;
use tristr::alias::String as ViewString;
pub(super) fn runtime_groups(config: Option<&Mapping>) -> (Vec<ViewString>, BTreeMap<ViewString, GroupScope>) {
let mut order = Vec::new();
let mut scopes = BTreeMap::new();
let Some(config) = config else { return (order, scopes) };
let Some(groups) = config.get("proxy-groups").and_then(|groups| groups.as_sequence()) else {
return (order, scopes);
};
let mut all_providers = None;
let flag = |group: &Mapping, key: &str| group.get(key).and_then(|value| value.as_bool()) == Some(true);
for group in groups.iter().filter_map(|group| group.as_mapping()) {
let Some(name) = group.get("name").and_then(|name| name.as_str()) else {
continue;
};
let name = ViewString::from(name);
// Mihomo sorts all providers when either flag replaces the explicit use list.
let providers = if flag(group, "include-all") || flag(group, "include-all-providers") {
all_providers
.get_or_insert_with(|| {
let mut names = config
.get("proxy-providers")
.and_then(|providers| providers.as_mapping())
.into_iter()
.flat_map(|providers| providers.keys())
.filter_map(|name| name.as_str())
.map(ViewString::from)
.collect::<Vec<_>>();
names.sort();
names
})
.clone()
} else {
group
.get("use")
.and_then(|providers| providers.as_sequence())
.into_iter()
.flatten()
.filter_map(|provider| provider.as_str())
.map(ViewString::from)
.collect()
};
let exclude_types = group
.get("exclude-type")
.and_then(|types| types.as_str())
.filter(|types| !types.is_empty())
.map_or_default(|types| types.split('|').map(ViewString::from).collect());
let scope = GroupScope {
providers,
exclude_types,
};
if scopes.insert(name.clone(), scope).is_none() && !name.is_empty() && name != "GLOBAL" {
order.push(name);
}
}
(order, scopes)
}
-7
View File
@@ -51,7 +51,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
cmd::apply_dns_config,
cmd::set_dns_override,
cmd::take_dns_override_notice,
cmd::take_service_fallback_notice,
cmd::get_core_startup_error,
cmd::take_service_repair_notice,
cmd::take_service_owner_notice,
@@ -165,12 +164,6 @@ impl From<network_interface::NetworkInterface> for NetworkInterfaceView {
}
}
#[derive(serde::Serialize, serde::Deserialize, specta::Type)]
pub struct DelayHistory {
pub time: String,
pub delay: u16,
}
fn platform_types() -> specta::Types {
use specta::datatype::{DataType, Fields};
let mut types = specta::Types::default().register::<crate::config::IVerge>();
-1
View File
@@ -21,4 +21,3 @@ pub mod tmpl;
#[cfg(target_os = "macos")]
pub mod tray_speed;
pub mod window_manager;
pub mod yaml_emitter;
+1 -6
View File
@@ -17,12 +17,7 @@ pub const ITEM_MERGE_EMPTY: &str = "# Profile Enhancement Merge Template for Cla
";
pub const ITEM_SCRIPT: &str = "// Define main function (script entry)
function main(config, profileName) {
return config;
}
";
pub use clash_verge_config_render::ITEM_SCRIPT;
pub const ITEM_RULES: &str = "# Profile Enhancement Rules Template for Clash Verge
@@ -60,34 +60,20 @@ it.each([
},
)
it('reports the permission refusal and finishes after installation falls back to Sidecar', async () => {
store.runState = {
service: 'notInstalled',
mode: 'NotRunning',
} as unknown as RunState
const reason = 'core path C:\\ is writable by Everyone'
vi.mocked(installService).mockResolvedValue({ status: 'sidecar', reason })
vi.mocked(getRuntimeState).mockResolvedValue({
service: 'unavailable',
mode: 'Sidecar',
sidecarAllowed: true,
serviceNeedsAttention: false,
} as RunState)
const dialog = ServiceMigrationDialog()
dialog.props.onOk()
await vi.waitFor(() => {
expect(showNotice.warning).toHaveBeenCalledWith(
'settings.feedback.notifications.clashService.permissionFallback',
{ reason },
0,
)
})
it('leaves the choice open when installation fails', async () => {
store.runState = { service: 'notInstalled', mode: 'NotRunning' } as RunState
const error = new Error('core path is writable by Everyone')
vi.mocked(installService).mockRejectedValue(error)
vi.mocked(getRuntimeState).mockResolvedValue(store.runState)
ServiceMigrationDialog().props.onOk()
await vi.waitFor(() => expect(getRuntimeState).toHaveBeenCalled())
expect(showNotice.error).toHaveBeenCalledWith(
'layout.components.serviceMigration.errors.actionFailed',
error,
)
expect(restartCore).not.toHaveBeenCalled()
expect(showNotice.error).not.toHaveBeenCalled()
expect(showNotice.success).not.toHaveBeenCalled()
expect(vi.mocked(useState).mock.results[2].value[1]).toHaveBeenLastCalledWith(
expect(vi.mocked(useState).mock.results[2].value[1]).not.toHaveBeenCalledWith(
false,
)
})
@@ -9,7 +9,6 @@ import {
reinstallService,
repairService,
restartCore,
type ServiceInstallOutcome,
} from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
@@ -70,26 +69,26 @@ export const ServiceMigrationDialog = () => {
const handleServiceAction = async () => {
setLoading(true)
setWorkflowIncomplete(true)
let outcome: ServiceInstallOutcome | undefined
let installed = false
try {
if (remedy === 'install') {
const result = await mutate(() => installService(), {
id: 'install-service',
errorNotice: false,
})
if (result.ok) outcome = result.value
installed = result.ok
} else if (remedy === 'repair') {
const result = await mutate(() => repairService(), {
id: 'repair-service',
errorNotice: false,
})
if (result.ok) outcome = result.value
installed = result.ok
} else {
const result = await mutate(() => reinstallService(), {
id: 'reinstall-service',
errorNotice: false,
})
if (result.ok) outcome = result.value
installed = result.ok
}
} catch (error) {
showNotice.error(
@@ -108,21 +107,10 @@ export const ServiceMigrationDialog = () => {
error,
)
}
if (!outcome || !initialRefreshSucceeded) {
if (!installed || !initialRefreshSucceeded) {
setLoading(false)
return
}
if (outcome.status === 'sidecar') {
setWorkflowIncomplete(false)
setLoading(false)
showNotice.warning(
'settings.feedback.notifications.clashService.permissionFallback',
{ reason: outcome.reason },
0,
)
return
}
let restartSucceeded = false
try {
const result = await mutate(() => restartCore(), {
@@ -214,6 +202,9 @@ export const ServiceMigrationDialog = () => {
? 'layout.components.serviceMigration.message'
: 'layout.components.serviceMigration.unavailableMessage',
)}
{!showCheckingMessage && runState?.serviceUnavailableReason && (
<div>{runState.serviceUnavailableReason}</div>
)}
</Alert>
</BaseDialog>
)
@@ -11,7 +11,6 @@ import {
restartCore,
type FailedOperation,
type PendingFailure,
type ServiceInstallOutcome,
} from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
@@ -23,7 +22,6 @@ import {
type ServiceRequestReason,
} from '@/services/service-request'
import { useAppReads } from '@/store/app-store-context'
import getSystem from '@/utils/get-system'
type Remedy = 'installAndRestart' | 'reinstallAndRestart' | 'restartOnly'
@@ -105,30 +103,20 @@ export const SysproxyPrivilegeDialog = () => {
const handleFix = async () => {
try {
let outcome: ServiceInstallOutcome | undefined
if (remedy === 'reinstallAndRestart') {
setStep('installing')
const result = await mutate(() => reinstallService(), {
id: 'reinstall-service',
errorNotice: false,
})
if (result.ok) outcome = result.value
if (!result.ok) return
} else if (remedy === 'installAndRestart') {
setStep('installing')
const result = await mutate(() => installService(), {
id: 'install-service',
errorNotice: false,
})
if (result.ok) outcome = result.value
}
if (outcome?.status === 'sidecar') {
showNotice.warning(
'settings.feedback.notifications.clashService.permissionFallback',
{ reason: outcome.reason },
0,
)
close()
return
if (!result.ok) return
}
setStep('restarting')
await mutate(() => restartCore(), {
@@ -137,14 +125,7 @@ export const SysproxyPrivilegeDialog = () => {
})
const runState = await readRunState()
const usingAdminFallback =
remedy !== 'reinstallAndRestart' &&
getSystem() === 'windows' &&
runState.mode === 'Sidecar' &&
runState.isAdmin &&
runState.sidecarAllowed &&
runState.service === 'unavailable'
if (runState.mode === 'Service' || usingAdminFallback) {
if (runState.mode === 'Service') {
if (restoring !== undefined) {
setStep('applying')
await mutate(() => patchVergeConfig(restoring), {
@@ -152,15 +133,13 @@ export const SysproxyPrivilegeDialog = () => {
errorNotice: false,
})
}
if (!usingAdminFallback) {
showNotice.success(
remedy === 'reinstallAndRestart'
? 'layout.components.serviceMigration.success'
: restoring === undefined
? 'settings.sections.proxyControl.messages.installedCheckProxy'
: 'settings.sections.proxyControl.messages.installedProxyRestored',
)
}
showNotice.success(
remedy === 'reinstallAndRestart'
? 'layout.components.serviceMigration.success'
: restoring === undefined
? 'settings.sections.proxyControl.messages.installedCheckProxy'
: 'settings.sections.proxyControl.messages.installedProxyRestored',
)
close()
} else {
showNotice.error(
-8
View File
@@ -33,14 +33,6 @@ export const useServiceInstaller = () => {
'settings.statuses.clashService.installing',
)
if (!installResult.ok) return
if (installResult.value.status === 'sidecar') {
showNotice.warning(
'settings.feedback.notifications.clashService.permissionFallback',
{ reason: installResult.value.reason },
0,
)
return
}
showNotice.success(
'settings.feedback.notifications.clashService.installSuccess',
)
+3 -20
View File
@@ -44,12 +44,10 @@ export const commands = {
getSidecarFailure: () =>
__TAURI_INVOKE<SidecarFailureSnapshot_Serialize>('get_sidecar_failure'),
entryLightweightMode: () => __TAURI_INVOKE<null>('entry_lightweight_mode'),
installService: () =>
__TAURI_INVOKE<ServiceInstallOutcome>('install_service'),
installService: () => __TAURI_INVOKE<null>('install_service'),
uninstallService: () => __TAURI_INVOKE<null>('uninstall_service'),
reinstallService: () =>
__TAURI_INVOKE<ServiceInstallOutcome>('reinstall_service'),
repairService: () => __TAURI_INVOKE<ServiceInstallOutcome>('repair_service'),
reinstallService: () => __TAURI_INVOKE<null>('reinstall_service'),
repairService: () => __TAURI_INVOKE<null>('repair_service'),
continueWithSidecar: () => __TAURI_INVOKE<null>('continue_with_sidecar'),
syncRuntimeProviders: () => __TAURI_INVOKE<void>('sync_runtime_providers'),
getClashInfo: () => __TAURI_INVOKE<ClashInfo_Serialize>('get_clash_info'),
@@ -99,10 +97,6 @@ export const commands = {
}),
takeDnsOverrideNotice: () =>
__TAURI_INVOKE<boolean>('take_dns_override_notice'),
takeServiceFallbackNotice: () =>
__TAURI_INVOKE<ServiceFallbackNotice | null>(
'take_service_fallback_notice',
),
getCoreStartupError: () =>
__TAURI_INVOKE<CoreFailure | null>('get_core_startup_error'),
takeServiceRepairNotice: () =>
@@ -627,7 +621,6 @@ export type NoticeStatus =
| 'core_start::error'
| 'service_core::repair_required'
| 'service_core::app_data_not_owned'
| 'service_core::sidecar_fallback'
| 'dns_override::auto_disabled'
| 'enhance::discarded_keys'
| 'tun_mode::auto_disabled'
@@ -1040,12 +1033,6 @@ export type SaveProxyPortsOutcome =
| { status: 'saved' }
| { status: 'conflict'; port: number; transport: ListenerTransport }
/** Why the Service was unavailable when the core fell back to Sidecar. */
export type ServiceFallbackNotice =
| { kind: 'unavailable' }
| { kind: 'coreRejected'; reason: string }
| { kind: 'notAutoStarted' }
export type ServiceHealthKind =
| 'unknown'
| 'ready'
@@ -1053,10 +1040,6 @@ export type ServiceHealthKind =
| 'versionMismatch'
| 'unavailable'
export type ServiceInstallOutcome =
| { status: 'installed' }
| { status: 'sidecar'; reason: string }
/** A removal has a revision too, so a delayed read cannot restore a resolved failure. */
export type SidecarFailureSnapshot =
| SidecarFailureSnapshot_Serialize
@@ -4,7 +4,6 @@ import {
type RunState,
getCoreStartupError,
takeDnsOverrideNotice,
takeServiceFallbackNotice,
takeServiceRepairNotice,
} from '@/services/cmds'
import { showNotice } from '@/services/notice-service'
@@ -24,7 +23,6 @@ vi.mock('@/services/cmds', () => ({
getPendingFailures: vi.fn().mockResolvedValue([]),
takeDiscardedKeysNotice: vi.fn().mockResolvedValue(null),
takeDnsOverrideNotice: vi.fn().mockResolvedValue(false),
takeServiceFallbackNotice: vi.fn().mockResolvedValue(null),
takeServiceRepairNotice: vi.fn().mockResolvedValue(false),
takeServiceOwnerNotice: vi.fn().mockResolvedValue(null),
}))
@@ -179,22 +177,3 @@ it('offers service reinstallation for a startup path refusal even before listene
reason: 'serviceLocationRefused',
})
})
it('explains a startup core rejection instead of the generic fallback notice', async () => {
const reason =
'approved core was rejected: core path "C:\\" has an untrusted write ACE'
vi.mocked(takeServiceFallbackNotice)
.mockResolvedValueOnce({ kind: 'coreRejected', reason })
.mockResolvedValue(null)
const bus = await mountBus()
bus.onSubscribed()
bus.handlers['verge://notice-message'](['service_core::sidecar_fallback', ''])
await flush()
expect(showNotice.warning).toHaveBeenCalledExactlyOnceWith(
'settings.feedback.notifications.clashService.permissionFallback',
{ reason },
0,
)
})
-1
View File
@@ -92,7 +92,6 @@ export const createEventBus = (deps: BusHandlerDeps) => {
deps.readPendingFailures()
deps.handleNotice(['dns_override::auto_disabled', ''])
deps.handleNotice(['enhance::discarded_keys', ''])
deps.handleNotice(['service_core::sidecar_fallback', ''])
deps.handleNotice(['service_core::repair_required', ''])
deps.handleNotice(['service_core::app_data_not_owned', ''])
deps.handleNotice(['core_start::error', ''])
-5
View File
@@ -23,7 +23,6 @@ export type {
FailedOperation,
PendingFailure,
SidecarFailureSnapshot,
ServiceInstallOutcome,
ProxyPortSettings,
ListenerTransport,
ListenerProbe,
@@ -234,10 +233,6 @@ export async function takeDnsOverrideNotice() {
return commands.takeDnsOverrideNotice()
}
export async function takeServiceFallbackNotice() {
return commands.takeServiceFallbackNotice()
}
export async function getCoreStartupError() {
return commands.getCoreStartupError()
}
-25
View File
@@ -4,7 +4,6 @@ import {
getCoreStartupError,
takeDiscardedKeysNotice,
takeDnsOverrideNotice,
takeServiceFallbackNotice,
takeServiceOwnerNotice,
takeServiceRepairNotice,
} from '@/services/cmds'
@@ -111,30 +110,6 @@ const handlers: Record<
console.error('Failed to read the pending service owner notice', error)
})
},
'service_core::sidecar_fallback': () => {
void takeServiceFallbackNotice()
.then((notice) => {
if (notice?.kind === 'coreRejected') {
showNotice.warning(
'settings.feedback.notifications.clashService.permissionFallback',
{ reason: notice.reason },
0,
)
} else if (notice?.kind === 'notAutoStarted') {
requestService({ reason: 'serviceNotAutoStarted' })
} else if (notice) {
showNotice.warning(
'settings.feedback.notifications.clashService.sidecarFallback',
)
}
})
.catch((error) => {
console.error(
'Failed to read the pending service fallback notice',
error,
)
})
},
'dns_override::auto_disabled': () => {
void takeDnsOverrideNotice()
.then((pending) => {