Compare commits

..
Author SHA1 Message Date
Tunglies 6accebab3a perf(tray): drop the redundant full rebuild in update_part
update_part rebuilt the menu twice back to back: once without proxy groups,
then a spawned full update_menu. Keep the partial rebuild only.
2026-11-16 23:24:35 +08:00
Tunglies eacf138cc2 perf(config): write yaml headers in place and record selections without copying
- save_yaml_str takes an optional header prefix written as separate chunks,
  so the MB-scale serialized payload is never duplicated by format! just
  to prepend a comment (profiles/verge/clash/runtime yaml all benefit;
  file bytes unchanged)
- the runtime yaml string no longer round-trips through a prefixed copy;
  write_runtime_file adds the header when persisting
- record/forget selected nodes mutate the stored selection list in place
  instead of cloning it per click
2026-11-16 23:24:35 +08:00
Tunglies 4c82a6cddb perf(enhance): marshal scripts by value and diff fields by fingerprint
- scripts cross into boa via JsValue::from_json/to_json instead of the
  JSON text round-trip (config clone + json string + UTF-16 JsString +
  stringify + re-parse all disappear); size guards use an allocation-free
  approximate walk
- merge documents and tun/dns patches move values instead of deep-cloning
  whole sub-trees per pass
- authoritative-field snapshots hash dns/hosts/tun values instead of
  cloning them around every chain item (9 snapshots per enhance)
- proxy-name cleanup sets build from &str in one conversion
2026-11-16 23:24:35 +08:00
Tunglies 13bce76c51 fix: mechanical string conversions
- &String parameters become &str (event payload fields borrow &str; wire format unchanged)
- Cow/std-string double conversions collapse to a single Into
- sha256 digests format through a shared hex lookup table instead of one
  format! allocation per byte
- i18n placeholder replacement only allocates when the placeholder exists
2026-11-16 23:24:35 +08:00
❤是纱雾酱哟~ 65042b8887 chore(deps): updates agentic workflows to v1.3.0 (#8665)
* chore(deps): update gh-aw extension version to v1.3.0

- Also bump the `with.version` value

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>

* chore(deps): updates agentic workflows to v1.3.0

- Recompiles the workflow lockfiles and updates pinned action and container image digests to align with the latest
  agentic workflow tooling and firewall releases.
- Adopts automatic model routing, improved API quota and credit guardrail handling, and cleaner prompt initialization
  to make automated PR reviews more cost-effective and resilient.

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>

---------

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
2026-11-16 14:55:41 +00:00
renovate[bot]andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> d1649fcc8d chore(deps): update rust crate zip to 9.6.0 (#8664)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-16 14:54:34 +00:00
renovate[bot]andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 368e41f48a chore(deps): update github/gh-aw-actions action to v1.3.0 (#8661)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-16 14:06:32 +00:00
29 changed files with 671 additions and 396 deletions
+58 -13
View File
@@ -5,10 +5,10 @@
"version": "v9.0.0",
"sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3"
},
"github/gh-aw-actions/setup@v1.2.2": {
"github/gh-aw-actions/setup@v1.3.0": {
"repo": "github/gh-aw-actions/setup",
"version": "v1.2.2",
"sha": "53d0749e19424a918acd82b4d140264ce48f2f14"
"version": "v1.3.0",
"sha": "8126d6cb07dea9221848de275af8a41474d839ca"
}
},
"containers": {
@@ -32,6 +32,16 @@
"digest": "sha256:2c78aaba1c108e130e2d6d01e4f2cca334ea04c53e6f258913ac34173fe7e3b2",
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.28.23@sha256:2c78aaba1c108e130e2d6d01e4f2cca334ea04c53e6f258913ac34173fe7e3b2"
},
"ghcr.io/github/gh-aw-firewall/agent:0.29.11": {
"image": "ghcr.io/github/gh-aw-firewall/agent:0.29.11",
"digest": "sha256:8774a73c351395b41d2ad0af4ddb4689007c67de3cd08bd9f43bb8a0e300690e",
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.29.11@sha256:8774a73c351395b41d2ad0af4ddb4689007c67de3cd08bd9f43bb8a0e300690e"
},
"ghcr.io/github/gh-aw-firewall/agent:0.29.14": {
"image": "ghcr.io/github/gh-aw-firewall/agent:0.29.14",
"digest": "sha256:7f649a02f2cc235325ab512f546854e0fad32b7abdc6c24c5475ddc0639e0aaa",
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.29.14@sha256:7f649a02f2cc235325ab512f546854e0fad32b7abdc6c24c5475ddc0639e0aaa"
},
"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13": {
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13",
"digest": "sha256:61f12dcff38eb008b645d87a5541763452f409d9040eb243718764944167b1a2",
@@ -52,6 +62,31 @@
"digest": "sha256:c15c3d1208df10c5b588a3657be53742aa982ae0909d1eb1812525268794ca64",
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.23@sha256:c15c3d1208df10c5b588a3657be53742aa982ae0909d1eb1812525268794ca64"
},
"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.11": {
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.11",
"digest": "sha256:88d2d0e315a504d93fd4fb8847fd0f6b7f4469f41a6fc6047b3dc9654c56ab2c",
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.11@sha256:88d2d0e315a504d93fd4fb8847fd0f6b7f4469f41a6fc6047b3dc9654c56ab2c"
},
"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14": {
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14",
"digest": "sha256:136785634c9207d7328c701d31d53941542ef307840bda6b348274c8842557c0",
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.14@sha256:136785634c9207d7328c701d31d53941542ef307840bda6b348274c8842557c0"
},
"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11": {
"image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11",
"digest": "sha256:97782bc0d8ff7f80f19ae2fdc5e1668517aa732a6fa077e64b8d3919238496d2",
"pinned_image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11@sha256:97782bc0d8ff7f80f19ae2fdc5e1668517aa732a6fa077e64b8d3919238496d2"
},
"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.14": {
"image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.14",
"digest": "sha256:3f9cf5c56bfea6f845ac7a213f4bbbac8c5e16ea1587599fae898da3ab6a6e12",
"pinned_image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.14@sha256:3f9cf5c56bfea6f845ac7a213f4bbbac8c5e16ea1587599fae898da3ab6a6e12"
},
"ghcr.io/github/gh-aw-firewall/router:0.29.14": {
"image": "ghcr.io/github/gh-aw-firewall/router:0.29.14",
"digest": "sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0",
"pinned_image": "ghcr.io/github/gh-aw-firewall/router:0.29.14@sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0"
},
"ghcr.io/github/gh-aw-firewall/squid:0.28.13": {
"image": "ghcr.io/github/gh-aw-firewall/squid:0.28.13",
"digest": "sha256:58a8dc5be3fbafeef7da0532c38bd9047f86bf1b3c4cfd7d9b7d8d28e80a2b56",
@@ -72,20 +107,30 @@
"digest": "sha256:02ffc56dd40158223064ef03a78c2d9717473c93723b4e403d455ea6f0b09ae0",
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.28.23@sha256:02ffc56dd40158223064ef03a78c2d9717473c93723b4e403d455ea6f0b09ae0"
},
"ghcr.io/github/gh-aw-mcpg:v0.4.25": {
"image": "ghcr.io/github/gh-aw-mcpg:v0.4.25",
"digest": "sha256:9be0a86220e807a0ecc89e53d7453468f7a53fbc6b3d1efd2299025ffe01d086",
"pinned_image": "ghcr.io/github/gh-aw-mcpg:v0.4.25@sha256:9be0a86220e807a0ecc89e53d7453468f7a53fbc6b3d1efd2299025ffe01d086"
"ghcr.io/github/gh-aw-firewall/squid:0.29.11": {
"image": "ghcr.io/github/gh-aw-firewall/squid:0.29.11",
"digest": "sha256:861739ecf924dd2db5e5fb652db2ad82aaafd1615623297ddabc8f41a36b2847",
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.11@sha256:861739ecf924dd2db5e5fb652db2ad82aaafd1615623297ddabc8f41a36b2847"
},
"ghcr.io/github/gh-aw-firewall/squid:0.29.14": {
"image": "ghcr.io/github/gh-aw-firewall/squid:0.29.14",
"digest": "sha256:878b9c1aaeca076004bf2157dd2be28586b68b2b3d69c3ff8fd2b5add2a3126c",
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.14@sha256:878b9c1aaeca076004bf2157dd2be28586b68b2b3d69c3ff8fd2b5add2a3126c"
},
"ghcr.io/github/gh-aw-mcpg:v0.5.10": {
"image": "ghcr.io/github/gh-aw-mcpg:v0.5.10",
"digest": "sha256:629ddcd68a48ab02e7db8af527d2756c6db563b00c1d31d8aa8fcbac96f01c59",
"pinned_image": "ghcr.io/github/gh-aw-mcpg:v0.5.10@sha256:629ddcd68a48ab02e7db8af527d2756c6db563b00c1d31d8aa8fcbac96f01c59"
},
"ghcr.io/github/gh-aw-node": {
"image": "ghcr.io/github/gh-aw-node",
"digest": "sha256:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e",
"pinned_image": "ghcr.io/github/gh-aw-node@sha256:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e"
"digest": "sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f",
"pinned_image": "ghcr.io/github/gh-aw-node@sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f"
},
"ghcr.io/github/github-mcp-server:v1.12.2": {
"image": "ghcr.io/github/github-mcp-server:v1.12.2",
"digest": "sha256:508a0857ec762b1ab1cece29193345b501fab1dd9d1228a7b617062954cecac6",
"pinned_image": "ghcr.io/github/github-mcp-server:v1.12.2@sha256:508a0857ec762b1ab1cece29193345b501fab1dd9d1228a7b617062954cecac6"
"ghcr.io/github/github-mcp-server:v2.1.0": {
"image": "ghcr.io/github/github-mcp-server:v2.1.0",
"digest": "sha256:f6056fc10bfffcc8c81a6417a2e9ca12808647e8dd6049642a4feaadee0e0f8a",
"pinned_image": "ghcr.io/github/github-mcp-server:v2.1.0@sha256:f6056fc10bfffcc8c81a6417a2e9ca12808647e8dd6049642a4feaadee0e0f8a"
}
}
}
+2 -2
View File
@@ -31,9 +31,9 @@ jobs:
with:
persist-credentials: false
- name: Install gh-aw extension
uses: github/gh-aw-actions/setup-cli@862164f9ffbcce2e24e5397da938e3b19f839dce # v1.2.3
uses: github/gh-aw-actions/setup-cli@8126d6cb07dea9221848de275af8a41474d839ca # v1.3.0
with:
version: v1.2.2
version: v1.3.0
- name: Install Rust Stable
uses: dtolnay/rust-toolchain@stable
with:
File diff suppressed because one or more lines are too long
+115 -66
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Generated
+31 -19
View File
@@ -4356,6 +4356,18 @@ dependencies = [
"libc",
]
[[package]]
name = "nix"
version = "0.32.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77730ed34f01f4990cb2ea67fec715ecebc6fab9a6396cf83c5529b13f581bdc"
dependencies = [
"bitflags 2.13.2",
"cfg-if",
"cfg_aliases",
"libc",
]
[[package]]
name = "nohash-hasher"
version = "0.2.0"
@@ -4882,7 +4894,7 @@ checksum = "9cf20a545b305cf1da722b236b5155c9bb35f1d5ceb28c048bd96ca842f41b5b"
dependencies = [
"android_system_properties",
"log",
"nix",
"nix 0.31.3",
"objc2",
"objc2-foundation",
"objc2-ui-kit",
@@ -7237,9 +7249,9 @@ checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
[[package]]
name = "tauri"
version = "2.12.6"
version = "2.12.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c2a5cad3827d1fa46c206a6bcaee8ca14203e9b0aaabe447dd4acef33ecd065"
checksum = "5fb0244332cfb9cee7e2a568bf5da29a36ed8fdbd717f6f47a66b6b7b358c072"
dependencies = [
"anyhow",
"bytes",
@@ -7292,9 +7304,9 @@ dependencies = [
[[package]]
name = "tauri-build"
version = "2.7.5"
version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e03658bfc9cb60f96a05b7d07a7f7cdfbf4c30b1bbfcb5cf6b5342cc2c9e0bc"
checksum = "adddb0e648752aaac5da9c3c3c6a68e1e87cab55e3b757b18a9441ef8c3ac614"
dependencies = [
"anyhow",
"cargo_toml",
@@ -7315,9 +7327,9 @@ dependencies = [
[[package]]
name = "tauri-codegen"
version = "2.7.5"
version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c454a15120b885bf57d0cb9ab218c01e12bc672f793452cb6527b460db883aa"
checksum = "fb37631cf71dab5e8ab55e1bdd701e18a52653d90b78e71d0e5598b1e0a61316"
dependencies = [
"base64 0.23.1",
"brotli",
@@ -7330,7 +7342,7 @@ dependencies = [
"semver 1.0.28",
"serde",
"serde_json",
"sha2 0.11.1",
"sha2 0.10.9",
"syn 2.0.119",
"tauri-utils",
"thiserror 2.0.20",
@@ -7342,9 +7354,9 @@ dependencies = [
[[package]]
name = "tauri-macros"
version = "2.7.5"
version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8f7513896f637528ec27ff76effd90638b1cdfa77499fae3db078043aed7ecb"
checksum = "0cc38db58854c10fb5f91a887ed8bf82d3239bb92b5d8db86eda09e96d9963d1"
dependencies = [
"heck 0.5.0",
"proc-macro2",
@@ -7717,9 +7729,9 @@ dependencies = [
[[package]]
name = "tauri-runtime"
version = "2.12.3"
version = "2.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c4b2a71c4bf51cde5cdcf1b45d7943282c7c669d3d26f7a324cce25f1b53e75"
checksum = "7c55766d99cea69055904d1735b93c2049302b2e09effd462120deb5581d78e9"
dependencies = [
"cookie",
"dpi",
@@ -7742,9 +7754,9 @@ dependencies = [
[[package]]
name = "tauri-runtime-wry"
version = "2.12.4"
version = "2.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d9be5e7af9560a4a60cdd441389a066cdd3e7c5d464a006ae34cb276cc78abd"
checksum = "e1aa9d8b7a120f879f44fdc1053f7b7dbf416bf0bbc6a72b714dec46b782b52f"
dependencies = [
"gtk",
"http",
@@ -7800,9 +7812,9 @@ dependencies = [
[[package]]
name = "tauri-utils"
version = "2.10.3"
version = "2.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6bf649f12d6fb11e1867214973cd37d89786ae2c0904f79b787b1db4fdcd14c"
checksum = "362ab21cd4cc713f2a02b1a9b5688198b1541cfb6907c4281e9190e0f0ef4aa3"
dependencies = [
"anyhow",
"brotli",
@@ -10127,9 +10139,9 @@ dependencies = [
[[package]]
name = "zip"
version = "9.5.1"
version = "9.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3476fd497ac8af5b1ec7b51acab7bef380f7e8dd8e0487595bafd839417a302"
checksum = "80cc68510ea7553c30a69c732de5278e94183f68765af6c642dbccefd6ec777e"
dependencies = [
"aes",
"bzip2",
@@ -10143,7 +10155,7 @@ dependencies = [
"libc",
"lzma-rust2",
"memchr",
"nix",
"nix 0.32.0",
"pbkdf2",
"ppmd-rust",
"sha1 0.11.0",
+1 -1
View File
@@ -61,7 +61,7 @@ tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", bra
tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" }
tracing = "0.1.44"
tauri = { version = "2.12.6" }
tauri = { version = "2.12.5" }
tauri-plugin-clipboard-manager = "2.5.0"
parking_lot = "0.13.0"
anyhow = "1.0.104"
+2 -2
View File
@@ -29,7 +29,7 @@ perf-harness = ["dep:tauri-plugin-wdio-webdriver"]
identifier = "io.github.clash-verge-rev.clash-verge-rev"
[build-dependencies]
tauri-build = { version = "2.7.5", features = [] }
tauri-build = { version = "2.7.4", features = [] }
[dependencies]
clash-verge-draft = { workspace = true }
@@ -77,7 +77,7 @@ tauri-plugin-dialog = "2.8.4"
tauri-plugin-fs = "2.7.1"
tauri-plugin-deep-link = "2.6.3"
tauri-plugin-window-state = "2.5.0"
zip = "9.5.1"
zip = "9.6.0"
flate2 = "1.1.11"
reqwest_dav = "0.3.3"
aes-gcm = { version = "0.11.1" }
+2 -2
View File
@@ -210,10 +210,10 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
Ok(())
}
async fn restore_previous_profile(prev_profile: &String) -> CmdResult<()> {
async fn restore_previous_profile(prev_profile: &str) -> CmdResult<()> {
logging!(info, Type::Cmd, "尝试恢复到之前的配置: {}", prev_profile);
let restore_profiles = IProfiles {
current: Some(prev_profile.to_owned()),
current: Some(prev_profile.into()),
items: None,
};
Config::profiles()
+2 -2
View File
@@ -216,7 +216,7 @@ impl Config {
.or_else(|| runtime_data.config.as_ref())
.ok_or_else(|| anyhow!("failed to generate runtime config, might need to restart application"))?;
let yaml_str = serde_yaml_ng::to_string(config)?;
Ok(format!("# Generated by Clash Verge\n\n{}", yaml_str))
Ok(yaml_str)
})
.await
.map_err(|join| anyhow!("runtime serialization task failed: {join}"))?
@@ -224,7 +224,7 @@ impl Config {
pub(crate) async fn write_runtime_file(yaml: &str) -> Result<PathBuf> {
let path = dirs::app_home_dir()?.join(files::RUNTIME_CONFIG);
help::save_yaml_str(&path, yaml).await?;
help::save_yaml_str(&path, yaml, Some("# Generated by Clash Verge")).await?;
Ok(path)
}
+2 -3
View File
@@ -1,4 +1,5 @@
use crate::core::notify::NoticeStatus;
use crate::utils::help;
use anyhow::Result;
use clash_verge_draft::DraftTransaction;
use serde::{Deserialize, Serialize};
@@ -49,9 +50,7 @@ pub(crate) fn dns_override_source(profile_uid: &str, config: &Mapping) -> Result
digest.update(profile_uid.as_bytes());
digest.update([0]);
digest.update(serde_json::to_vec(&canonical)?);
Ok(Some(
digest.finalize().iter().map(|byte| format!("{byte:02x}")).collect(),
))
Ok(Some(help::hex_encode(&digest.finalize()).into()))
}
#[derive(Debug, Clone)]
+1 -1
View File
@@ -26,7 +26,7 @@ pub(super) fn normalize_profile_home_url(raw: &str) -> Option<String> {
}
url.host_str()?;
Some(url.to_string().into())
Some(url.as_str().into())
}
#[derive(Debug, Clone, Deserialize, Serialize, Default, specta::Type)]
+12 -8
View File
@@ -605,7 +605,7 @@ async fn fetch_proxies_with_timeout() -> Result<Proxies> {
.map_err(Into::into)
}
async fn select_node_with_timeout(group_name: &String, node: &String) -> Result<()> {
async fn select_node_with_timeout(group_name: &str, node: &str) -> Result<()> {
tokio::time::timeout(MIHOMO_OPERATION_TIMEOUT, async {
handle::Handle::mihomo().select_node_for_group(group_name, node).await
})
@@ -761,7 +761,7 @@ pub(crate) async fn record_selected_node(group_name: &str, node: &str) -> Result
return Ok((profiles, false));
};
let mut selected = item.selected.clone().unwrap_or_default();
let selected = item.selected.get_or_insert_with(Vec::new);
match selected
.iter_mut()
.find(|entry| entry.name.as_ref() == Some(&group_name))
@@ -770,14 +770,13 @@ pub(crate) async fn record_selected_node(group_name: &str, node: &str) -> Result
if entry.now.as_ref() == Some(&node) {
return Ok((profiles, false));
}
entry.now = Some(node);
entry.now = Some(node.clone());
}
None => selected.push(PrfSelected {
name: Some(group_name),
now: Some(node),
}),
}
item.selected = Some(selected);
profiles.save_file().await?;
Ok((profiles, true))
})
@@ -796,12 +795,17 @@ pub(crate) async fn forget_selected_node(group_name: &str) -> Result<()> {
return Ok((profiles, false));
};
let mut selected = item.selected.clone().unwrap_or_default();
let Some(mut selected) = item.selected.take() else {
return Ok((profiles, false));
};
if !remove_selected_node(&mut selected, group_name) {
item.selected = Some(selected);
return Ok((profiles, false));
}
item.selected = (!selected.is_empty()).then_some(selected);
if !selected.is_empty() {
item.selected = Some(selected);
}
profiles.save_file().await?;
Ok((profiles, true))
})
@@ -809,7 +813,7 @@ pub(crate) async fn forget_selected_node(group_name: &str) -> Result<()> {
}
async fn persist_reconciled_selected(
profile_uid: &String,
profile_uid: &str,
original_selected: &[PrfSelected],
selected: Vec<PrfSelected>,
generation: u64,
@@ -818,7 +822,7 @@ async fn persist_reconciled_selected(
return Ok(());
}
let profile_uid = profile_uid.clone();
let profile_uid = String::from(profile_uid);
let original_selected = original_selected.to_vec();
persist_selected_update(false, move |mut profiles| async move {
if !is_activation_current(generation) || profiles.current.as_ref() != Some(&profile_uid) {
+6 -3
View File
@@ -42,9 +42,12 @@ pub async fn notify_event<'a>(event: NotificationEvent<'a>) {
}
NotificationEvent::ClashModeChanged { mode } => {
let title = clash_verge_i18n::t!("notifications.clashModeChanged.title");
let body = clash_verge_i18n::t!("notifications.clashModeChanged.body")
.replace("{mode}", mode)
.into();
let body = clash_verge_i18n::t!("notifications.clashModeChanged.body");
let body = if body.contains("{mode}") {
body.replace("{mode}", mode).into()
} else {
body
};
notify(title, body);
}
NotificationEvent::SystemProxyToggled(enabled) => {
+5 -4
View File
@@ -1,5 +1,6 @@
use super::NoticeStatus;
use crate::{APP_HANDLE, singleton};
#[cfg(target_os = "macos")]
use smartstring::alias::String;
use std::sync::{
Arc,
@@ -55,21 +56,21 @@ impl Handle {
Self::send_event(FrontendEvent::RunStateChanged { state: state.clone() });
}
pub fn notify_profile_changed(profile_id: &String) {
pub fn notify_profile_changed(profile_id: &str) {
Self::send_event(FrontendEvent::ProfileChanged {
current_profile_id: profile_id,
});
}
pub fn notify_timer_updated(profile_index: &String) {
pub fn notify_timer_updated(profile_index: &str) {
Self::send_event(FrontendEvent::TimerUpdated { profile_index });
}
pub fn notify_profile_update_started(uid: &String) {
pub fn notify_profile_update_started(uid: &str) {
Self::send_event(FrontendEvent::ProfileUpdateStarted { uid });
}
pub fn notify_profile_update_completed(uid: &String) {
pub fn notify_profile_update_completed(uid: &str) {
Self::send_event(FrontendEvent::ProfileUpdateCompleted { uid });
}
+5 -5
View File
@@ -20,16 +20,16 @@ pub enum FrontendEvent<'a> {
message: Arc<str>,
},
ProfileChanged {
current_profile_id: &'a String,
current_profile_id: &'a str,
},
TimerUpdated {
profile_index: &'a String,
profile_index: &'a str,
},
ProfileUpdateStarted {
uid: &'a String,
uid: &'a str,
},
ProfileUpdateCompleted {
uid: &'a String,
uid: &'a str,
},
RunStateChanged {
state: crate::core::runstate::RunStateView,
@@ -369,7 +369,7 @@ mod wire_tests {
/// One sample per `FrontendEvent` variant, paired with its wire name and payload.
#[cfg(test)]
fn sample_frontend_events(uid: &String) -> Vec<(FrontendEvent<'_>, &'static str, serde_json::Value)> {
fn sample_frontend_events(uid: &str) -> Vec<(FrontendEvent<'_>, &'static str, serde_json::Value)> {
let state = crate::core::runstate::RunState {
health: Default::default(),
pending: None,
+1 -1
View File
@@ -122,7 +122,7 @@ fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut Ha
digest.update(destination.as_bytes());
digest.update([0]);
digest.update(url.as_bytes());
let digest: String = digest.finalize().iter().map(|byte| format!("{byte:02x}")).collect();
let digest: String = crate::utils::help::hex_encode(&digest.finalize());
let path = Path::new(destination);
let extension = path
.extension()
+1 -1
View File
@@ -458,7 +458,7 @@ impl Timer {
}
}
fn emit_update_event(uid: &String, is_start: bool) {
fn emit_update_event(uid: &str, is_start: bool) {
if is_start {
super::handle::Handle::notify_profile_update_started(uid);
} else {
-3
View File
@@ -342,9 +342,6 @@ impl Tray {
let verge = Config::verge().await.data_arc();
let app_handle = handle::Handle::app_handle();
self.update_menu_internal(app_handle, false).await?;
AsyncHandler::spawn(|| async {
logging_error!(Type::Tray, Self::global().update_menu().await);
});
self.update_icon(&verge).await?;
#[cfg(target_os = "macos")]
self.update_speed_task(verge.enable_tray_speed.unwrap_or(false));
+1 -1
View File
@@ -435,7 +435,7 @@ impl CoreConfigValidator {
}
let check_path = dirs::app_home_dir()?.join(crate::constants::files::CHECK_CONFIG);
help::save_yaml_str(&check_path, yaml).await?;
help::save_yaml_str(&check_path, yaml, None).await?;
let outcome = Self::validate_config_internal_outcome(dirs::path_to_str(&check_path)?).await?;
if outcome.is_valid() {
*LAST_VALIDATED.lock() = Some(fingerprint);
+3 -3
View File
@@ -24,12 +24,12 @@ fn lowercase_key(key: &str) -> Value {
Value::from(key.as_str())
}
pub fn use_lowercase(config: &Mapping) -> Mapping {
pub fn use_lowercase(config: Mapping) -> Mapping {
let mut lowercased = Mapping::new();
for (key, value) in config.iter() {
for (key, value) in config {
if let Some(key_str) = key.as_str() {
lowercased.insert(lowercase_key(key_str), value.clone());
lowercased.insert(lowercase_key(key_str), value);
}
}
lowercased
+3 -3
View File
@@ -16,7 +16,7 @@ fn deep_merge(a: &mut Value, b: Value) {
}
}
pub fn use_merge(merge: &Mapping, mut config: Mapping) -> Mapping {
pub fn use_merge(merge: Mapping, mut config: Mapping) -> Mapping {
for (key, value) in use_lowercase(merge) {
match (config.get_mut(&key), value) {
(Some(Value::Mapping(existing)), Value::Mapping(overlay)) if key.as_str() == Some("dns") => {
@@ -79,7 +79,7 @@ fn test_merge() -> anyhow::Result<()> {
let merge = serde_yaml_ng::from_str::<Mapping>(merge)?;
let config = serde_yaml_ng::from_str::<Mapping>(config)?;
let result = use_merge(&merge, config);
let result = use_merge(merge.clone(), config);
assert_eq!(result["dns"]["nameserver-policy"], merge["dns"]["nameserver-policy"]);
assert_eq!(result["dns"]["fallback-filter"], merge["dns"]["fallback-filter"]);
assert_eq!(result["hosts"], merge["hosts"]);
@@ -91,7 +91,7 @@ fn test_merge() -> anyhow::Result<()> {
let cleared = serde_yaml_ng::from_str::<Mapping>(
"dns: {enable: false, nameserver-policy: {}, fallback-filter: {}, nameserver: []}\nhosts: {}",
)?;
let result = use_merge(&cleared, result);
let result = use_merge(cleared.clone(), result);
assert_eq!(result["dns"], cleared["dns"]);
assert_eq!(result["hosts"], cleared["hosts"]);
+81 -47
View File
@@ -28,6 +28,7 @@ use parking_lot::Mutex;
use serde_yaml_ng::{Mapping, Value};
use smartstring::alias::String;
use std::collections::{HashMap, HashSet};
use std::hash::{Hash as _, Hasher as _};
use tokio::fs;
type ResultLog = Vec<(String, String)>;
@@ -236,13 +237,13 @@ async fn process_override_items(
mut result_map: HashMap<String, ResultLog>,
merge_item: ChainItem,
script_item: ChainItem,
profile_name: &String,
profile_name: &str,
authoritative: &AuthoritativeFields,
) -> (Mapping, Vec<String>, HashMap<String, ResultLog>) {
if let ChainType::Merge(merge) = merge_item.data {
exists_keys.extend(use_keys(&merge));
let before = authoritative.current(&config);
config = use_merge(&merge, config);
config = use_merge(merge, config);
let notes: ResultLog = authoritative
.overridden(&before, &authoritative.current(&config))
.into_iter()
@@ -255,7 +256,7 @@ async fn process_override_items(
if let ChainType::Script(script) = script_item.data {
let before = authoritative.current(&config);
let (res_config, changed_keys, mut logs) = use_script(script, config, profile_name.clone()).await;
let (res_config, changed_keys, mut logs) = use_script(script, config, profile_name.into()).await;
exists_keys.extend(changed_keys);
config = res_config;
logs.extend(
@@ -320,15 +321,45 @@ struct AuthoritativeFields {
tun: Mapping,
dns: Mapping,
hosts: Option<Value>,
fingerprints: FieldFingerprints,
}
#[derive(Default)]
struct FieldFingerprints {
control_plane: Vec<Option<u64>>,
tun: Vec<Option<u64>>,
dns: Vec<Option<u64>>,
hosts: Option<u64>,
}
fn fingerprint(value: Option<&Value>) -> Option<u64> {
let value = value?;
let mut hasher = std::collections::hash_map::DefaultHasher::new();
value.hash(&mut hasher);
Some(hasher.finish())
}
impl AuthoritativeFields {
fn capture(config: &Mapping, gui_tun_keys: &[Value], mut dns_settings: Mapping) -> Self {
let control_plane = snapshot_control_plane(config);
let tun = snapshot_tun(config, gui_tun_keys);
let dns = take_mapping(&mut dns_settings, "dns");
let hosts = dns_settings.remove("hosts");
let fingerprints = FieldFingerprints {
control_plane: CONTROL_PLANE_KEYS
.iter()
.map(|&key| fingerprint(control_plane.get(Value::from(key))))
.collect(),
tun: tun.iter().map(|(_, value)| fingerprint(Some(value))).collect(),
dns: dns.iter().map(|(_, value)| fingerprint(Some(value))).collect(),
hosts: fingerprint(hosts.as_ref()),
};
Self {
control_plane: snapshot_control_plane(config),
tun: snapshot_tun(config, gui_tun_keys),
dns: take_mapping(&mut dns_settings, "dns"),
hosts: dns_settings.remove("hosts"),
control_plane,
tun,
dns,
hosts,
fingerprints,
}
}
@@ -346,43 +377,50 @@ impl AuthoritativeFields {
config
}
/// The owned values as `config` holds them now, for diffing one override.
fn current(&self, config: &Mapping) -> Self {
let tun_keys: Vec<Value> = self.tun.keys().cloned().collect();
/// What `config` holds now, for diffing one override.
fn current(&self, config: &Mapping) -> FieldFingerprints {
let tun = config.get("tun").and_then(Value::as_mapping);
let dns = config.get("dns").and_then(Value::as_mapping);
Self {
control_plane: snapshot_control_plane(config),
tun: snapshot_tun(config, &tun_keys),
FieldFingerprints {
control_plane: CONTROL_PLANE_KEYS
.iter()
.map(|&key| fingerprint(config.get(key)))
.collect(),
tun: self
.tun
.keys()
.map(|key| fingerprint(tun.and_then(|map| map.get(key))))
.collect(),
dns: self
.dns
.keys()
.filter_map(|key| Some((key.clone(), dns?.get(key)?.clone())))
.map(|key| fingerprint(dns.and_then(|map| map.get(key))))
.collect(),
hosts: self.hosts.as_ref().and_then(|_| config.get("hosts")).cloned(),
hosts: self.hosts.as_ref().and_then(|_| fingerprint(config.get("hosts"))),
}
}
/// Owned keys an override moved off the app value; `enforce` discards those writes.
fn overridden(&self, before: &Self, after: &Self) -> Vec<String> {
fn overridden(&self, before: &FieldFingerprints, after: &FieldFingerprints) -> Vec<String> {
let mut keys = Vec::new();
for &key in CONTROL_PLANE_KEYS {
if before.control_plane.get(key) != after.control_plane.get(key)
&& after.control_plane.get(key) != self.control_plane.get(key)
for (index, &key) in CONTROL_PLANE_KEYS.iter().enumerate() {
if before.control_plane[index] != after.control_plane[index]
&& after.control_plane[index] != self.fingerprints.control_plane[index]
{
keys.push(key.into());
}
}
for key in self.tun.keys() {
if before.tun.get(key) != after.tun.get(key) && after.tun.get(key) != self.tun.get(key) {
for (index, key) in self.tun.keys().enumerate() {
if before.tun[index] != after.tun[index] && after.tun[index] != self.fingerprints.tun[index] {
keys.push(format!("tun.{}", key.as_str().unwrap_or_default()).into());
}
}
for key in self.dns.keys() {
if before.dns.get(key) != after.dns.get(key) && after.dns.get(key) != self.dns.get(key) {
for (index, key) in self.dns.keys().enumerate() {
if before.dns[index] != after.dns[index] && after.dns[index] != self.fingerprints.dns[index] {
keys.push(format!("dns.{}", key.as_str().unwrap_or_default()).into());
}
}
if self.hosts.is_some() && before.hosts != after.hosts && after.hosts != self.hosts {
if self.hosts.is_some() && before.hosts != after.hosts && after.hosts != self.fingerprints.hosts {
keys.push("hosts".into());
}
keys
@@ -553,16 +591,15 @@ fn merge_default_config(
) -> Mapping {
for (key, value) in clash_config.into_iter() {
if key.as_str() == Some("tun") {
let mut tun = config.get_mut("tun").map_or_else(Mapping::new, |val| {
val.as_mapping().cloned().unwrap_or_else(Mapping::new)
});
let patch_tun = value.as_mapping().cloned().unwrap_or_else(Mapping::new);
for (key, value) in patch_tun.into_iter() {
if !value.is_null() {
tun.insert(key, value);
if let Value::Mapping(patch_tun) = value {
let mut tun = take_mapping(&mut config, "tun");
for (key, value) in patch_tun {
if !value.is_null() {
tun.insert(key, value);
}
}
config.insert(Value::from("tun"), Value::Mapping(tun));
}
config.insert("tun".into(), tun.into());
} else {
if key.as_str() == Some("socks-port") && !socks_enabled {
config.remove("socks-port");
@@ -617,7 +654,7 @@ fn merge_default_config(
fn apply_builtin_scripts(mut config: Mapping, enable_builtin: bool) -> Mapping {
if enable_builtin {
// The JS path saw a lowercased view; lowercase once, only when the builtin runs.
config = use_lowercase(&config);
config = use_lowercase(config);
logging!(debug, Type::Core, "run builtin script verge_hy_alpn");
config = builtin_hy_alpn(config);
}
@@ -649,11 +686,8 @@ fn cleanup_proxy_groups(mut config: Mapping) -> Mapping {
.map_or_default(|seq| {
seq.iter()
.filter_map(|item| match item {
Value::Mapping(map) => map
.get("name")
.and_then(Value::as_str)
.map(|name| name.to_owned().into()),
Value::String(name) => Some(name.to_owned().into()),
Value::Mapping(map) => map.get("name").and_then(Value::as_str).map(Into::into),
Value::String(name) => Some(name.as_str().into()),
_ => None,
})
.collect::<HashSet<String>>()
@@ -872,7 +906,7 @@ pub async fn enhance(
result_map,
global_merge,
global_script,
&profile_name,
profile_name.as_str(),
&authoritative,
)
.await;
@@ -883,12 +917,12 @@ pub async fn enhance(
result_map,
merge_item,
script_item,
&profile_name,
profile_name.as_str(),
&authoritative,
)
.await;
notify_discarded_keys(authoritative.overridden(&authoritative, &authoritative.current(&config)));
notify_discarded_keys(authoritative.overridden(&authoritative.fingerprints, &authoritative.current(&config)));
let config = authoritative.enforce(config);
let config = ensure_tun_default_mtu(config);
let config = ensure_lan_bind_address(config);
@@ -1407,7 +1441,7 @@ mod tests {
uid: uid.into(),
data: ChainType::Merge(merge.clone()),
};
let profile_name = "test-profile".into();
let profile_name = "test-profile";
let (config, keys, logs) = process_override_items(
config,
vec![],
@@ -1417,7 +1451,7 @@ mod tests {
uid: "global-script".into(),
data: ChainType::Script(script.into()),
},
&profile_name,
profile_name,
&authoritative,
)
.await;
@@ -1430,7 +1464,7 @@ mod tests {
uid: "profile-script".into(),
data: ChainType::Script(script.into()),
},
&profile_name,
profile_name,
&authoritative,
)
.await;
@@ -1506,7 +1540,7 @@ mod tests {
),
};
let profile_name = "test-profile".into();
let profile_name = "test-profile";
let authoritative = AuthoritativeFields::capture(&config, &[], Mapping::new());
let (config, exists_keys, result_map) = process_override_items(
config,
@@ -1514,7 +1548,7 @@ mod tests {
HashMap::new(),
global_merge,
global_script,
&profile_name,
profile_name,
&authoritative,
)
.await;
@@ -1524,7 +1558,7 @@ mod tests {
result_map,
profile_merge,
profile_script,
&profile_name,
profile_name,
&authoritative,
)
.await;
+79 -48
View File
@@ -1,7 +1,7 @@
use crate::{process::AsyncHandler, utils::tmpl};
use super::field::use_lowercase;
use anyhow::{Error, Result};
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;
@@ -22,14 +22,26 @@ type EvalOutcome = (Result<Mapping, std::string::String>, Vec<(String, String)>)
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![]);
return (use_lowercase(config), vec![], vec![]);
}
let json = match serde_json::to_string(&use_lowercase(&config)) {
Ok(json) if json.len() <= MAX_JSON_SIZE => json,
Ok(_) => {
let message = "Configuration size exceeds maximum allowed size";
return (config, vec![], vec![("exception".into(), message.into())]);
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())]),
};
@@ -66,7 +78,7 @@ pub(super) async fn use_script(script: String, config: Mapping, name: String) ->
}
/// Console logs survive every failure path.
fn eval_script(script: &str, config_json: &str, name: &String) -> EvalOutcome {
fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) -> EvalOutcome {
let mut context = Context::default();
context
@@ -131,12 +143,11 @@ fn eval_script(script: &str, config_json: &str, name: &String) -> EvalOutcome {
});"#,
));
// Bind the JSON instead of embedding it in program source; Boa's parser never chews it.
if let Err(err) = context.register_global_property(
js_string!("__verge_config__"),
JsValue::from(JsString::from(config_json)),
Attribute::all(),
) {
let config_value = match JsValue::from_json(config_json, &mut context) {
Ok(value) => value,
Err(err) => return bail(format!("failed to bind config for script: {err}")),
};
if let Err(err) = context.register_global_property(js_string!("__verge_config__"), config_value, Attribute::all()) {
return bail(format!("failed to bind config for script: {err}"));
}
@@ -149,31 +160,61 @@ fn eval_script(script: &str, config_json: &str, name: &String) -> EvalOutcome {
let code = format!(
r"try{{
{script};
JSON.stringify(main(JSON.parse(globalThis.__verge_config__),'{safe_name}')||'')
main(globalThis.__verge_config__,'{safe_name}')
}} catch(err) {{
`__error_flag__ ${{err.toString()}}`
}}"
);
let result = match context.eval(Source::from_bytes(code.as_str())) {
Ok(result) if result.is_string() => result,
_ => return bail("main function should return object".to_owned()),
};
let result = match result.to_string(&mut context) {
Ok(result) => result,
Err(e) => return bail(format!("Failed to convert JS result to string: {e}")),
Err(err) => {
logging!(
error,
Type::Config,
"Script execution error: {err}. Script name: {name}"
);
return bail("Script execution failed".to_owned());
}
};
let result = match result.to_std_string() {
Ok(result) => result,
Err(_) => return bail("Failed to convert JS string to std string".to_owned()),
// The JS wrapper funnels exceptions into a marker string; surface its text.
if result.is_string() {
let text = result
.to_string(&mut context)
.ok()
.and_then(|text| text.to_std_string().ok())
.unwrap_or_default();
if text.trim_start().starts_with("__error_flag__") {
logging!(
error,
Type::Config,
"Script execution error: {}. Script name: {name}",
text.trim_start()["__error_flag__".len()..].trim()
);
return bail("Script execution failed".to_owned());
}
}
if !result.is_object() {
return bail("main function should return object".to_owned());
}
let result = match result.to_json(&mut context) {
Ok(Some(result)) => result,
Ok(None) => return bail("main function should return object".to_owned()),
Err(err) => {
logging!(
error,
Type::Config,
"Script execution error: {err}. Script name: {name}"
);
return bail("Script execution failed".to_owned());
}
};
if result.len() > MAX_JSON_SIZE {
if json_approx_size(&result) > MAX_JSON_SIZE {
return bail("Script result exceeds maximum allowed size".to_owned());
}
match parse_json_safely(&result) {
Ok(config) => (Ok(use_lowercase(&config)), outputs.lock().to_vec()),
match serde_json::from_value::<Mapping>(result) {
Ok(config) => (Ok(use_lowercase(config)), outputs.lock().to_vec()),
Err(err) => {
logging!(
error,
@@ -185,27 +226,17 @@ fn eval_script(script: &str, config_json: &str, name: &String) -> EvalOutcome {
}
}
fn parse_json_safely(json_str: &str) -> Result<Mapping, Error> {
if json_str.len() > MAX_JSON_SIZE {
anyhow::bail!("JSON string too large");
}
let json_str = strip_outer_quotes(json_str);
Ok(serde_json::from_str::<Mapping>(json_str)?)
}
// 安全地移除外层引号
fn strip_outer_quotes(s: &str) -> &str {
let s = s.trim();
if s.len() < 2 {
return s;
}
if (s.starts_with('"') && s.ends_with('"')) || (s.starts_with('\'') && s.ends_with('\'')) {
&s[1..s.len() - 1]
} else {
s
/// Serialized-size estimate without building the serialized string; a DoS guard, not an exact byte count.
fn json_approx_size(value: &serde_json::Value) -> usize {
match value {
serde_json::Value::String(s) => s.len() + 2,
serde_json::Value::Object(map) => map
.iter()
.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::Bool(_) | serde_json::Value::Null => 4,
}
}
+2 -10
View File
@@ -8,18 +8,10 @@ macro_rules! revise {
}
pub fn use_tun(mut config: Mapping, enable: bool) -> Mapping {
let tun_key = Value::from("tun");
let tun_val = config.get(&tun_key);
let mut tun_val = tun_val.map_or_else(Mapping::new, |val| {
val.as_mapping().cloned().unwrap_or_else(Mapping::new)
});
let mut tun_val = super::take_mapping(&mut config, "tun");
if enable {
let dns_key = Value::from("dns");
let dns_val = config.get(&dns_key);
let mut dns_val = dns_val.map_or_else(Mapping::new, |val| {
val.as_mapping().cloned().unwrap_or_else(Mapping::new)
});
let mut dns_val = super::take_mapping(&mut config, "dns");
let ipv6_key = Value::from("ipv6");
let ipv6_val = config.get(&ipv6_key).and_then(|v| v.as_bool()).unwrap_or(false);
+2 -2
View File
@@ -123,7 +123,7 @@ pub async fn list_wevdav_backup() -> Result<Vec<ListFile>> {
}
pub async fn delete_webdav_backup(filename: String) -> Result<()> {
let name = filename.to_string();
let name = filename.clone();
backup::WebDavClient::global().delete(filename).await.map_err(|err| {
logging!(
error,
@@ -165,7 +165,7 @@ pub async fn restore_webdav_backup(filename: String) -> Result<()> {
let backup_storage_path = app_home_dir()
.map_err(|e| anyhow::anyhow!("Failed to get app home dir: {e}"))?
.join(filename.as_str());
let name = filename.to_string();
let name = filename.clone();
backup::WebDavClient::global()
.download(filename, backup_storage_path.clone())
.await
+5 -5
View File
@@ -103,7 +103,7 @@ pub async fn switch_proxy_node(group_name: &str, proxy_name: &str, unfix: bool)
Ok(())
}
async fn should_update_profile(uid: &String, ignore_auto_update: bool) -> Result<Option<(String, Option<PrfOption>)>> {
async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result<Option<(String, Option<PrfOption>)>> {
let profiles = Config::profiles().await;
let profiles = profiles.latest_arc();
let item = profiles.get_item(uid)?;
@@ -138,8 +138,8 @@ async fn should_update_profile(uid: &String, ignore_auto_update: bool) -> Result
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, strategy = tracing::field::Empty, configured_elapsed = tracing::field::Empty, clash_elapsed = tracing::field::Empty, system_elapsed = tracing::field::Empty))]
async fn perform_profile_update(
uid: &String,
url: &String,
uid: &str,
url: &str,
opt: Option<&PrfOption>,
option: Option<&PrfOption>,
is_mannual_trigger: bool,
@@ -234,7 +234,7 @@ async fn perform_profile_update(
}
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, manual = is_mannual_trigger))]
pub async fn update_profile(uid: &String, option: Option<&PrfOption>, is_mannual_trigger: bool) -> Result<()> {
pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_mannual_trigger: bool) -> Result<()> {
let url_opt = should_update_profile(uid, is_mannual_trigger).await?;
let profile_persisted = match url_opt {
@@ -245,7 +245,7 @@ pub async fn update_profile(uid: &String, option: Option<&PrfOption>, is_mannual
None => false,
};
let profiles = Config::profiles().await;
let is_current = profiles.latest_arc().current.as_ref() == Some(uid);
let is_current = profiles.latest_arc().current.as_deref() == Some(uid);
let should_refresh = is_current || (!profile_persisted && is_mannual_trigger);
if should_refresh {
+22 -10
View File
@@ -137,16 +137,11 @@ fn is_short_id(key: &Value) -> bool {
pub async fn save_yaml<T: Serialize + Sync>(path: &Path, data: &T, prefix: Option<&str>) -> Result<()> {
let data_str = with_encryption(|| async { serde_yaml_ng::to_string(data) }).await?;
let yaml_str = match prefix {
Some(prefix) => format!("{prefix}\n\n{data_str}"),
None => data_str,
};
save_yaml_str(path, &yaml_str).await
save_yaml_str(path, &data_str, prefix).await
}
/// Atomic replace with pre-serialized content; the payload must not need the encryption scope.
pub async fn save_yaml_str(path: &Path, yaml_str: &str) -> Result<()> {
pub async fn save_yaml_str(path: &Path, yaml_str: &str, prefix: Option<&str>) -> Result<()> {
let (temporary, file) = loop {
let temporary = path.with_extension(format!("tmp-{}-{}", std::process::id(), nanoid!()));
match std::fs::OpenOptions::new()
@@ -172,9 +167,16 @@ pub async fn save_yaml_str(path: &Path, yaml_str: &str) -> Result<()> {
let _ = std::fs::remove_file(path);
});
let mut file = tokio::fs::File::from_std(file);
file.write_all(yaml_str.as_bytes())
.await
.with_context(|| format!("failed to write temporary file for \"{}\"", path.display()))?;
async fn write_chunk(file: &mut tokio::fs::File, bytes: &[u8], path: &Path) -> Result<()> {
file.write_all(bytes)
.await
.with_context(|| format!("failed to write temporary file for \"{}\"", path.display()))
}
if let Some(prefix) = prefix {
write_chunk(&mut file, prefix.as_bytes(), path).await?;
write_chunk(&mut file, b"\n\n", path).await?;
}
write_chunk(&mut file, yaml_str.as_bytes(), path).await?;
file.flush()
.await
.with_context(|| format!("failed to flush temporary file for \"{}\"", path.display()))?;
@@ -220,6 +222,16 @@ pub fn parse_str<T: FromStr>(target: &str, key: &str) -> Option<T> {
})
}
pub fn hex_encode(bytes: &[u8]) -> String {
const HEX: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(bytes.len() * 2);
for &byte in bytes {
out.push(HEX[usize::from(byte >> 4)] as char);
out.push(HEX[usize::from(byte & 0x0f)] as char);
}
out
}
/// Masks query values and token-like path segments for logging.
pub fn mask_url(url: &str) -> String {
let (path_part, query_part) = match url.find('?') {
+3 -3
View File
@@ -47,7 +47,7 @@ fn extract_subscription_info(link_parsed: &Url) -> Option<(std::string::String,
let name = link_parsed
.query_pairs()
.find(|(key, _)| key == "name")
.map(|(_, value)| value.into_owned().into());
.map(|(_, value)| value.into());
let url = extract_subscription_url(link_parsed)?;
Some((url, name))
}
@@ -123,7 +123,7 @@ async fn fetch_profile_item(url: &str, name: Option<&String>) -> Option<PrfItem>
}
}
async fn post_import_updates(uid: &String, had_current_profile: bool) {
async fn post_import_updates(uid: &str, had_current_profile: bool) {
handle::Handle::refresh_verge();
handle::Handle::notify_profile_changed(uid);
@@ -131,7 +131,7 @@ async fn post_import_updates(uid: &String, had_current_profile: bool) {
false
} else {
let profiles = Config::profiles().await;
profiles.latest_arc().current.as_ref() == Some(uid)
profiles.latest_arc().current.as_deref() == Some(uid)
};
if should_update_core {