Compare commits

..
55 changed files with 1862 additions and 782 deletions
+13 -58
View File
@@ -5,10 +5,10 @@
"version": "v9.0.0",
"sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3"
},
"github/gh-aw-actions/setup@v1.3.0": {
"github/gh-aw-actions/setup@v1.2.2": {
"repo": "github/gh-aw-actions/setup",
"version": "v1.3.0",
"sha": "8126d6cb07dea9221848de275af8a41474d839ca"
"version": "v1.2.2",
"sha": "53d0749e19424a918acd82b4d140264ce48f2f14"
}
},
"containers": {
@@ -32,16 +32,6 @@
"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",
@@ -62,31 +52,6 @@
"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",
@@ -107,30 +72,20 @@
"digest": "sha256:02ffc56dd40158223064ef03a78c2d9717473c93723b4e403d455ea6f0b09ae0",
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.28.23@sha256:02ffc56dd40158223064ef03a78c2d9717473c93723b4e403d455ea6f0b09ae0"
},
"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-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-node": {
"image": "ghcr.io/github/gh-aw-node",
"digest": "sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f",
"pinned_image": "ghcr.io/github/gh-aw-node@sha256:1fe145873f46e4dded511319d2a91dbaed5bb4d9c43d93fdc383198d1bf02b7f"
"digest": "sha256:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e",
"pinned_image": "ghcr.io/github/gh-aw-node@sha256:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e"
},
"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"
"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"
}
}
}
+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@8126d6cb07dea9221848de275af8a41474d839ca # v1.3.0
uses: github/gh-aw-actions/setup-cli@862164f9ffbcce2e24e5397da938e3b19f839dce # v1.2.3
with:
version: v1.3.0
version: v1.2.2
- name: Install Rust Stable
uses: dtolnay/rust-toolchain@stable
with:
File diff suppressed because one or more lines are too long
+66 -115
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 -44
View File
@@ -912,7 +912,7 @@ checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9"
dependencies = [
"semver 1.0.28",
"serde",
"toml 1.2.1+spec-1.1.0",
"toml 1.1.6+spec-1.1.0",
]
[[package]]
@@ -1223,8 +1223,8 @@ dependencies = [
[[package]]
name = "clash_verge_service_ipc"
version = "2.8.1"
source = "git+https://github.com/clash-verge-rev/clash-verge-service-ipc.git?tag=v2.8.1#9d4ea7d27fb3c43804bd18f3bb3b686528763239"
version = "2.7.7"
source = "git+https://github.com/clash-verge-rev/clash-verge-service-ipc.git?tag=v2.7.7#3ed29700b093190b5e7addcaa892e77f172af544"
dependencies = [
"anyhow",
"kode-bridge",
@@ -2202,7 +2202,7 @@ dependencies = [
"cc",
"memchr",
"rustc_version 0.4.1",
"toml 1.2.1+spec-1.1.0",
"toml 1.1.6+spec-1.1.0",
"vswhom",
"winreg 0.55.0",
]
@@ -3877,16 +3877,16 @@ dependencies = [
[[package]]
name = "kode-bridge"
version = "0.6.0"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b17456ae84ba9c0da0f189bf00d13019805b89563ba846cd15ccd8c4bd6a2713"
checksum = "cdb14ea1ba42eebb57b46bcdd67a20f11a3f076d846ddf772c68d7439f6c6eca"
dependencies = [
"bytes",
"futures",
"http",
"httparse",
"libc",
"parking_lot 0.13.0",
"parking_lot 0.12.5",
"path-tree",
"pin-project-lite",
"rand 0.10.2",
@@ -3896,7 +3896,7 @@ dependencies = [
"tokio",
"tokio-stream",
"tokio-util",
"toml 1.2.1+spec-1.1.0",
"toml 1.1.6+spec-1.1.0",
"tracing",
"url",
"windows-sys 0.61.2",
@@ -4356,18 +4356,6 @@ 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"
@@ -4894,7 +4882,7 @@ checksum = "9cf20a545b305cf1da722b236b5155c9bb35f1d5ceb28c048bd96ca842f41b5b"
dependencies = [
"android_system_properties",
"log",
"nix 0.31.3",
"nix",
"objc2",
"objc2-foundation",
"objc2-ui-kit",
@@ -6533,9 +6521,9 @@ dependencies = [
[[package]]
name = "serde_spanned"
version = "1.1.3"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"
checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26"
dependencies = [
"serde_core",
]
@@ -7098,12 +7086,11 @@ dependencies = [
[[package]]
name = "sysproxy"
version = "0.7.2"
source = "git+https://github.com/clash-verge-rev/sysproxy-rs.git?rev=2c9d0a538052aac6e44ad413156a6e848da262b9#2c9d0a538052aac6e44ad413156a6e848da262b9"
version = "0.7.1"
source = "git+https://github.com/clash-verge-rev/sysproxy-rs.git?branch=main#89ad876a0942c049ae72e1472f9fc3ed62023c5e"
dependencies = [
"iptools",
"log",
"serde",
"system-configuration",
"thiserror 2.0.20",
"tokio",
@@ -7157,7 +7144,7 @@ dependencies = [
"cfg-expr 0.20.9",
"heck 0.5.0",
"pkg-config",
"toml 1.2.1+spec-1.1.0",
"toml 1.1.6+spec-1.1.0",
"version-compare",
]
@@ -7511,7 +7498,7 @@ dependencies = [
"tauri-plugin",
"tauri-utils",
"thiserror 2.0.20",
"toml 1.2.1+spec-1.1.0",
"toml 1.1.6+spec-1.1.0",
"url",
]
@@ -7841,7 +7828,7 @@ dependencies = [
"serde_with",
"swift-rs",
"thiserror 2.0.20",
"toml 1.2.1+spec-1.1.0",
"toml 1.1.6+spec-1.1.0",
"url",
"urlpattern",
"uuid",
@@ -7856,7 +7843,7 @@ checksum = "cc65d45c68858bfe420dd29e834b5d15dbecf8a07a8a16cf4d532c7b1f69d4b6"
dependencies = [
"dunce",
"embed-resource",
"toml 1.2.1+spec-1.1.0",
"toml 1.1.6+spec-1.1.0",
]
[[package]]
@@ -8222,14 +8209,14 @@ dependencies = [
[[package]]
name = "toml"
version = "1.2.1+spec-1.1.0"
version = "1.1.6+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7"
checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a"
dependencies = [
"indexmap 2.14.0",
"serde_core",
"serde_spanned 1.1.3",
"toml_datetime 1.1.3+spec-1.1.0",
"serde_spanned 1.1.1",
"toml_datetime 1.1.1+spec-1.1.0",
"toml_parser",
"toml_writer",
"winnow 1.0.4",
@@ -8246,9 +8233,9 @@ dependencies = [
[[package]]
name = "toml_datetime"
version = "1.1.3+spec-1.1.0"
version = "1.1.1+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"
checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"
dependencies = [
"serde_core",
]
@@ -8296,16 +8283,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6975367e4d2ef766d86af01ffad14b622fecc8d4357a998fbc4deb6e9bacaf9b"
dependencies = [
"indexmap 2.14.0",
"toml_datetime 1.1.3+spec-1.1.0",
"toml_datetime 1.1.1+spec-1.1.0",
"toml_parser",
"winnow 1.0.4",
]
[[package]]
name = "toml_parser"
version = "1.1.5+spec-1.1.0"
version = "1.1.3+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56"
dependencies = [
"winnow 1.0.4",
]
@@ -8318,9 +8305,9 @@ checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"
[[package]]
name = "toml_writer"
version = "1.2.0+spec-1.1.0"
version = "1.1.2+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"
[[package]]
name = "tonic"
@@ -10139,9 +10126,9 @@ dependencies = [
[[package]]
name = "zip"
version = "9.6.0"
version = "9.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80cc68510ea7553c30a69c732de5278e94183f68765af6c642dbccefd6ec777e"
checksum = "e3476fd497ac8af5b1ec7b51acab7bef380f7e8dd8e0487595bafd839417a302"
dependencies = [
"aes",
"bzip2",
@@ -10155,7 +10142,7 @@ dependencies = [
"libc",
"lzma-rust2",
"memchr",
"nix 0.32.0",
"nix",
"pbkdf2",
"ppmd-rust",
"sha1 0.11.0",
+2 -4
View File
@@ -37,6 +37,7 @@
- 修复断开链式代理时清空已选节点,导致再次连接需要重新选择
- 修复「连接」页表格排序时表头换行、标题位置跳动
- 修复「TUN 设置」未手动保存时,界面显示的默认 MTU 1500 未生效
- 修复连接详情较窄时操作按钮偏离右侧
**🍎 macOS**
@@ -44,16 +45,13 @@
- 修复 macOS 断网时误报代理已回退直连,恢复联网后自动重试系统代理
- 修复 macOS 切换主题后标题栏保留原有深浅色
**🐧 Linux**
- 修复 Linux OpenRC 环境下服务安装失败
</details>
<details>
<summary><strong> ✨ 新增功能 </strong></summary>
- 新增连接页面按网络协议(TCP/UDP)筛选连接
- 新增从连接详情设置域名、进程或源/目标 IP 规则,支持识别主域、匹配子域、自定义 IP 网段及修改已有规则
</details>
+1
View File
@@ -82,6 +82,7 @@
"rehype-sanitize": "^6.0.0",
"swr": "^2.5.1",
"tauri-plugin-mihomo-api": "github:clash-verge-rev/tauri-plugin-mihomo#main",
"tldts": "7.4.19",
"types-pac": "^1.0.3",
"validator": "^13.15.35"
},
+16
View File
@@ -295,6 +295,9 @@ importers:
tauri-plugin-mihomo-api:
specifier: github:clash-verge-rev/tauri-plugin-mihomo#main
version: https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/e49bbedcc67d60da2c10e81bc6433b0f8e8fa232
tldts:
specifier: 7.4.19
version: 7.4.19
types-pac:
specifier: ^1.0.3
version: 1.0.3
@@ -4035,6 +4038,13 @@ packages:
resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}
engines: {node: '>=12.0.0'}
tldts-core@7.5.2:
resolution: {integrity: sha512-8W1topazDwhMKbm2I83IPa57Ow5VUxFgLbXv42+vSILnv8FY5OHvdEY/tS6WoWeMbxkHZQhra5cmeFHriKptSQ==}
tldts@7.4.19:
resolution: {integrity: sha512-48dH6aSpQnpbzDUc4vIQZ1VjB8tkK+e8c1yx05/SZK+rkssgjEOlxDd/yU8/a4vGYQ9vRgJr9dwMq9TJ0b3X2Q==}
hasBin: true
trim-lines@3.0.1:
resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==}
@@ -8138,6 +8148,12 @@ snapshots:
fdir: 6.5.0(picomatch@4.0.7)
picomatch: 4.0.7
tldts-core@7.5.2: {}
tldts@7.4.19:
dependencies:
tldts-core: 7.5.2
trim-lines@3.0.1: {}
trough@2.2.0: {}
-50
View File
@@ -46,58 +46,8 @@ function run(command, args, options = {}) {
})
}
async function checkDevelopmentServiceVersion() {
const [guiOutput, daemonOutput] = await Promise.all([
run(
'cargo',
[
'metadata',
'--locked',
'--format-version=1',
'--manifest-path',
join(repositoryRoot, 'Cargo.toml'),
],
{ stdio: ['inherit', 'pipe', 'inherit'] },
),
run(
'cargo',
[
'metadata',
'--locked',
'--no-deps',
'--format-version=1',
'--manifest-path',
serviceManifest,
],
{ stdio: ['inherit', 'pipe', 'inherit'] },
),
])
const gui = JSON.parse(guiOutput)
const daemon = JSON.parse(daemonOutput).packages.find(
(pkg) => resolve(pkg.manifest_path) === serviceManifest,
)
const app = gui.packages.find(
(pkg) =>
resolve(pkg.manifest_path) ===
join(repositoryRoot, 'src-tauri', 'Cargo.toml'),
)
const dependency = gui.resolve?.nodes
.find((node) => node.id === app?.id)
?.deps.find((dep) => dep.name === 'clash_verge_service_ipc')
const sdk = gui.packages.find((pkg) => pkg.id === dependency?.pkg)
if (!daemon || !sdk)
throw new Error('Cargo did not resolve the development Service and GUI SDK')
if (daemon.version !== sdk.version) {
throw new Error(
`Development Service ${daemon.version} does not match the resolved GUI SDK ${sdk.version} (${sdk.manifest_path}). ` +
'Align the GUI dependency explicitly before starting development. Building the sibling daemon does not update the SDK.',
)
}
}
export async function prepareDevelopmentService() {
await access(serviceManifest)
await checkDevelopmentServiceVersion()
const output = await run(
'cargo',
[
+3 -3
View File
@@ -67,7 +67,7 @@ boa_engine = "0.22.0"
http-body-util = "0.1.5"
percent-encoding = "2.3.2"
reqwest = { workspace = true }
sysproxy = { git = "https://github.com/clash-verge-rev/sysproxy-rs.git", rev = "2c9d0a538052aac6e44ad413156a6e848da262b9", version = "0.7.2", features = [
sysproxy = { git = "https://github.com/clash-verge-rev/sysproxy-rs.git", branch = "main", features = [
"guard",
] }
network-interface = { version = "2.0.5", features = ["serde"] }
@@ -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.6.0"
zip = "9.5.1"
flate2 = "1.1.11"
reqwest_dav = "0.3.3"
aes-gcm = { version = "0.11.1" }
@@ -93,7 +93,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 = "e49bbedcc67d60da2c10e81bc6433b0f8e8fa232" }
async-trait = "0.1.92"
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", tag = "v2.8.1", version = "2.8.1", features = [
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", tag = "v2.7.7", version = "2.7.7", features = [
"client",
] }
arc-swap = "1.9.5"
+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: &str) -> CmdResult<()> {
async fn restore_previous_profile(prev_profile: &String) -> CmdResult<()> {
logging!(info, Type::Cmd, "尝试恢复到之前的配置: {}", prev_profile);
let restore_profiles = IProfiles {
current: Some(prev_profile.into()),
current: Some(prev_profile.to_owned()),
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(yaml_str)
Ok(format!("# Generated by Clash Verge\n\n{}", 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, Some("# Generated by Clash Verge")).await?;
help::save_yaml_str(&path, yaml).await?;
Ok(path)
}
+3 -2
View File
@@ -1,5 +1,4 @@
use crate::core::notify::NoticeStatus;
use crate::utils::help;
use anyhow::Result;
use clash_verge_draft::DraftTransaction;
use serde::{Deserialize, Serialize};
@@ -50,7 +49,9 @@ 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(help::hex_encode(&digest.finalize()).into()))
Ok(Some(
digest.finalize().iter().map(|byte| format!("{byte:02x}")).collect(),
))
}
#[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.as_str().into())
Some(url.to_string().into())
}
#[derive(Debug, Clone, Deserialize, Serialize, Default, specta::Type)]
+8 -12
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: &str, node: &str) -> Result<()> {
async fn select_node_with_timeout(group_name: &String, node: &String) -> 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 selected = item.selected.get_or_insert_with(Vec::new);
let mut selected = item.selected.clone().unwrap_or_default();
match selected
.iter_mut()
.find(|entry| entry.name.as_ref() == Some(&group_name))
@@ -770,13 +770,14 @@ 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.clone());
entry.now = Some(node);
}
None => selected.push(PrfSelected {
name: Some(group_name),
now: Some(node),
}),
}
item.selected = Some(selected);
profiles.save_file().await?;
Ok((profiles, true))
})
@@ -795,17 +796,12 @@ pub(crate) async fn forget_selected_node(group_name: &str) -> Result<()> {
return Ok((profiles, false));
};
let Some(mut selected) = item.selected.take() else {
return Ok((profiles, false));
};
let mut selected = item.selected.clone().unwrap_or_default();
if !remove_selected_node(&mut selected, group_name) {
item.selected = Some(selected);
return Ok((profiles, false));
}
if !selected.is_empty() {
item.selected = Some(selected);
}
item.selected = (!selected.is_empty()).then_some(selected);
profiles.save_file().await?;
Ok((profiles, true))
})
@@ -813,7 +809,7 @@ pub(crate) async fn forget_selected_node(group_name: &str) -> Result<()> {
}
async fn persist_reconciled_selected(
profile_uid: &str,
profile_uid: &String,
original_selected: &[PrfSelected],
selected: Vec<PrfSelected>,
generation: u64,
@@ -822,7 +818,7 @@ async fn persist_reconciled_selected(
return Ok(());
}
let profile_uid = String::from(profile_uid);
let profile_uid = profile_uid.clone();
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) {
+3 -6
View File
@@ -42,12 +42,9 @@ 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");
let body = if body.contains("{mode}") {
body.replace("{mode}", mode).into()
} else {
body
};
let body = clash_verge_i18n::t!("notifications.clashModeChanged.body")
.replace("{mode}", mode)
.into();
notify(title, body);
}
NotificationEvent::SystemProxyToggled(enabled) => {
+4 -5
View File
@@ -1,6 +1,5 @@
use super::NoticeStatus;
use crate::{APP_HANDLE, singleton};
#[cfg(target_os = "macos")]
use smartstring::alias::String;
use std::sync::{
Arc,
@@ -56,21 +55,21 @@ impl Handle {
Self::send_event(FrontendEvent::RunStateChanged { state: state.clone() });
}
pub fn notify_profile_changed(profile_id: &str) {
pub fn notify_profile_changed(profile_id: &String) {
Self::send_event(FrontendEvent::ProfileChanged {
current_profile_id: profile_id,
});
}
pub fn notify_timer_updated(profile_index: &str) {
pub fn notify_timer_updated(profile_index: &String) {
Self::send_event(FrontendEvent::TimerUpdated { profile_index });
}
pub fn notify_profile_update_started(uid: &str) {
pub fn notify_profile_update_started(uid: &String) {
Self::send_event(FrontendEvent::ProfileUpdateStarted { uid });
}
pub fn notify_profile_update_completed(uid: &str) {
pub fn notify_profile_update_completed(uid: &String) {
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 str,
current_profile_id: &'a String,
},
TimerUpdated {
profile_index: &'a str,
profile_index: &'a String,
},
ProfileUpdateStarted {
uid: &'a str,
uid: &'a String,
},
ProfileUpdateCompleted {
uid: &'a str,
uid: &'a String,
},
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: &str) -> Vec<(FrontendEvent<'_>, &'static str, serde_json::Value)> {
fn sample_frontend_events(uid: &String) -> 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 = crate::utils::help::hex_encode(&digest.finalize());
let digest: String = digest.finalize().iter().map(|byte| format!("{byte:02x}")).collect();
let path = Path::new(destination);
let extension = path
.extension()
-6
View File
@@ -334,12 +334,6 @@ pub(crate) fn service_stop_reason() -> Result<Option<&'static str>> {
#[cfg(target_os = "linux")]
pub(crate) fn trusted_service_evidence() -> Result<bool> {
// Without systemd, the installer registers an OpenRC script instead of a unit.
if !Path::new("/run/systemd/system").exists() && Path::new("/run/openrc").exists() {
return Ok(Path::new("/etc/init.d")
.join(clash_verge_service_ipc::SERVICE_SLUG)
.exists());
}
let unit = format!("{}.service", clash_verge_service_ipc::SERVICE_SLUG);
let output = StdCommand::new("systemctl")
.args(["show", "--property=LoadState", "--value", &unit])
+1 -1
View File
@@ -458,7 +458,7 @@ impl Timer {
}
}
fn emit_update_event(uid: &str, is_start: bool) {
fn emit_update_event(uid: &String, is_start: bool) {
if is_start {
super::handle::Handle::notify_profile_update_started(uid);
} else {
+3
View File
@@ -342,6 +342,9 @@ 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, None).await?;
help::save_yaml_str(&check_path, yaml).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 {
for (key, value) in config.iter() {
if let Some(key_str) = key.as_str() {
lowercased.insert(lowercase_key(key_str), value);
lowercased.insert(lowercase_key(key_str), value.clone());
}
}
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.clone(), config);
let result = use_merge(&merge, 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.clone(), result);
let result = use_merge(&cleared, result);
assert_eq!(result["dns"], cleared["dns"]);
assert_eq!(result["hosts"], cleared["hosts"]);
+47 -81
View File
@@ -28,7 +28,6 @@ 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)>;
@@ -237,13 +236,13 @@ async fn process_override_items(
mut result_map: HashMap<String, ResultLog>,
merge_item: ChainItem,
script_item: ChainItem,
profile_name: &str,
profile_name: &String,
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()
@@ -256,7 +255,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.into()).await;
let (res_config, changed_keys, mut logs) = use_script(script, config, profile_name.clone()).await;
exists_keys.extend(changed_keys);
config = res_config;
logs.extend(
@@ -321,45 +320,15 @@ 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,
tun,
dns,
hosts,
fingerprints,
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"),
}
}
@@ -377,50 +346,43 @@ impl AuthoritativeFields {
config
}
/// What `config` holds now, for diffing one override.
fn current(&self, config: &Mapping) -> FieldFingerprints {
let tun = config.get("tun").and_then(Value::as_mapping);
/// 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();
let dns = config.get("dns").and_then(Value::as_mapping);
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(),
Self {
control_plane: snapshot_control_plane(config),
tun: snapshot_tun(config, &tun_keys),
dns: self
.dns
.keys()
.map(|key| fingerprint(dns.and_then(|map| map.get(key))))
.filter_map(|key| Some((key.clone(), dns?.get(key)?.clone())))
.collect(),
hosts: self.hosts.as_ref().and_then(|_| fingerprint(config.get("hosts"))),
hosts: self.hosts.as_ref().and_then(|_| config.get("hosts")).cloned(),
}
}
/// Owned keys an override moved off the app value; `enforce` discards those writes.
fn overridden(&self, before: &FieldFingerprints, after: &FieldFingerprints) -> Vec<String> {
fn overridden(&self, before: &Self, after: &Self) -> Vec<String> {
let mut keys = Vec::new();
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]
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)
{
keys.push(key.into());
}
}
for (index, key) in self.tun.keys().enumerate() {
if before.tun[index] != after.tun[index] && after.tun[index] != self.fingerprints.tun[index] {
for key in self.tun.keys() {
if before.tun.get(key) != after.tun.get(key) && after.tun.get(key) != self.tun.get(key) {
keys.push(format!("tun.{}", key.as_str().unwrap_or_default()).into());
}
}
for (index, key) in self.dns.keys().enumerate() {
if before.dns[index] != after.dns[index] && after.dns[index] != self.fingerprints.dns[index] {
for key in self.dns.keys() {
if before.dns.get(key) != after.dns.get(key) && after.dns.get(key) != self.dns.get(key) {
keys.push(format!("dns.{}", key.as_str().unwrap_or_default()).into());
}
}
if self.hosts.is_some() && before.hosts != after.hosts && after.hosts != self.fingerprints.hosts {
if self.hosts.is_some() && before.hosts != after.hosts && after.hosts != self.hosts {
keys.push("hosts".into());
}
keys
@@ -591,15 +553,16 @@ fn merge_default_config(
) -> Mapping {
for (key, value) in clash_config.into_iter() {
if key.as_str() == Some("tun") {
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);
}
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);
}
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");
@@ -654,7 +617,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);
}
@@ -686,8 +649,11 @@ 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(Into::into),
Value::String(name) => Some(name.as_str().into()),
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()),
_ => None,
})
.collect::<HashSet<String>>()
@@ -906,7 +872,7 @@ pub async fn enhance(
result_map,
global_merge,
global_script,
profile_name.as_str(),
&profile_name,
&authoritative,
)
.await;
@@ -917,12 +883,12 @@ pub async fn enhance(
result_map,
merge_item,
script_item,
profile_name.as_str(),
&profile_name,
&authoritative,
)
.await;
notify_discarded_keys(authoritative.overridden(&authoritative.fingerprints, &authoritative.current(&config)));
notify_discarded_keys(authoritative.overridden(&authoritative, &authoritative.current(&config)));
let config = authoritative.enforce(config);
let config = ensure_tun_default_mtu(config);
let config = ensure_lan_bind_address(config);
@@ -1441,7 +1407,7 @@ mod tests {
uid: uid.into(),
data: ChainType::Merge(merge.clone()),
};
let profile_name = "test-profile";
let profile_name = "test-profile".into();
let (config, keys, logs) = process_override_items(
config,
vec![],
@@ -1451,7 +1417,7 @@ mod tests {
uid: "global-script".into(),
data: ChainType::Script(script.into()),
},
profile_name,
&profile_name,
&authoritative,
)
.await;
@@ -1464,7 +1430,7 @@ mod tests {
uid: "profile-script".into(),
data: ChainType::Script(script.into()),
},
profile_name,
&profile_name,
&authoritative,
)
.await;
@@ -1540,7 +1506,7 @@ mod tests {
),
};
let profile_name = "test-profile";
let profile_name = "test-profile".into();
let authoritative = AuthoritativeFields::capture(&config, &[], Mapping::new());
let (config, exists_keys, result_map) = process_override_items(
config,
@@ -1548,7 +1514,7 @@ mod tests {
HashMap::new(),
global_merge,
global_script,
profile_name,
&profile_name,
&authoritative,
)
.await;
@@ -1558,7 +1524,7 @@ mod tests {
result_map,
profile_merge,
profile_script,
profile_name,
&profile_name,
&authoritative,
)
.await;
+48 -79
View File
@@ -1,7 +1,7 @@
use crate::{process::AsyncHandler, utils::tmpl};
use super::field::use_lowercase;
use anyhow::Result;
use anyhow::{Error, 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,26 +22,14 @@ 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_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())]);
}
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())]);
}
Err(err) => return (config, vec![], vec![("exception".into(), err.to_string().into())]),
};
@@ -78,7 +66,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: &serde_json::Value, name: &String) -> EvalOutcome {
fn eval_script(script: &str, config_json: &str, name: &String) -> EvalOutcome {
let mut context = Context::default();
context
@@ -143,11 +131,12 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) ->
});"#,
));
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()) {
// 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(),
) {
return bail(format!("failed to bind config for script: {err}"));
}
@@ -160,61 +149,31 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) ->
let code = format!(
r"try{{
{script};
main(globalThis.__verge_config__,'{safe_name}')
JSON.stringify(main(JSON.parse(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(err) => {
logging!(
error,
Type::Config,
"Script execution error: {err}. Script name: {name}"
);
return bail("Script execution failed".to_owned());
}
Err(e) => return bail(format!("Failed to convert JS result to string: {e}")),
};
// 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());
}
let result = match result.to_std_string() {
Ok(result) => result,
Err(_) => return bail("Failed to convert JS string to std string".to_owned()),
};
if json_approx_size(&result) > MAX_JSON_SIZE {
if result.len() > MAX_JSON_SIZE {
return bail("Script result exceeds maximum allowed size".to_owned());
}
match serde_json::from_value::<Mapping>(result) {
Ok(config) => (Ok(use_lowercase(config)), outputs.lock().to_vec()),
match parse_json_safely(&result) {
Ok(config) => (Ok(use_lowercase(&config)), outputs.lock().to_vec()),
Err(err) => {
logging!(
error,
@@ -226,17 +185,27 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) ->
}
}
/// 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,
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
}
}
+10 -2
View File
@@ -8,10 +8,18 @@ macro_rules! revise {
}
pub fn use_tun(mut config: Mapping, enable: bool) -> Mapping {
let mut tun_val = super::take_mapping(&mut config, "tun");
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)
});
if enable {
let mut dns_val = super::take_mapping(&mut config, "dns");
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 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.clone();
let name = filename.to_string();
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.clone();
let name = filename.to_string();
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: &str, ignore_auto_update: bool) -> Result<Option<(String, Option<PrfOption>)>> {
async fn should_update_profile(uid: &String, 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: &str, ignore_auto_update: bool) -> Result<Op
#[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: &str,
url: &str,
uid: &String,
url: &String,
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: &str, option: Option<&PrfOption>, is_mannual_trigger: bool) -> Result<()> {
pub async fn update_profile(uid: &String, 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: &str, option: Option<&PrfOption>, is_mannual_tr
None => false,
};
let profiles = Config::profiles().await;
let is_current = profiles.latest_arc().current.as_deref() == Some(uid);
let is_current = profiles.latest_arc().current.as_ref() == Some(uid);
let should_refresh = is_current || (!profile_persisted && is_mannual_trigger);
if should_refresh {
+10 -22
View File
@@ -137,11 +137,16 @@ 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?;
save_yaml_str(path, &data_str, prefix).await
let yaml_str = match prefix {
Some(prefix) => format!("{prefix}\n\n{data_str}"),
None => data_str,
};
save_yaml_str(path, &yaml_str).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, prefix: Option<&str>) -> Result<()> {
pub async fn save_yaml_str(path: &Path, yaml_str: &str) -> Result<()> {
let (temporary, file) = loop {
let temporary = path.with_extension(format!("tmp-{}-{}", std::process::id(), nanoid!()));
match std::fs::OpenOptions::new()
@@ -167,16 +172,9 @@ pub async fn save_yaml_str(path: &Path, yaml_str: &str, prefix: Option<&str>) ->
let _ = std::fs::remove_file(path);
});
let mut file = tokio::fs::File::from_std(file);
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.write_all(yaml_str.as_bytes())
.await
.with_context(|| format!("failed to write temporary file for \"{}\"", path.display()))?;
file.flush()
.await
.with_context(|| format!("failed to flush temporary file for \"{}\"", path.display()))?;
@@ -222,16 +220,6 @@ 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());
.map(|(_, value)| value.into_owned().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: &str, had_current_profile: bool) {
async fn post_import_updates(uid: &String, had_current_profile: bool) {
handle::Handle::refresh_verge();
handle::Handle::notify_profile_changed(uid);
@@ -131,7 +131,7 @@ async fn post_import_updates(uid: &str, had_current_profile: bool) {
false
} else {
let profiles = Config::profiles().await;
profiles.latest_arc().current.as_deref() == Some(uid)
profiles.latest_arc().current.as_ref() == Some(uid)
};
if should_update_core {
+131 -30
View File
@@ -5,10 +5,24 @@ import { useCallback, useImperativeHandle, useState, type Ref } from 'react'
import { useTranslation } from 'react-i18next'
import { closeConnection } from 'tauri-plugin-mihomo-api'
import { useProfiles } from '@/hooks/use-profiles'
import parseTraffic from '@/utils/parse-traffic'
import {
getConnectionRuleTargets,
type ConnectionRuleKind,
} from './connection-rule'
import {
ConnectionRuleDialog,
type ConnectionRuleTarget,
} from './connection-rule-dialog'
export interface ConnectionDetailRef {
open: (detail: IConnectionsItem, closed: boolean) => void
open: (
detail: IConnectionsItem,
closed: boolean,
preferredKind?: ConnectionRuleKind,
) => void
close: () => void
}
@@ -16,7 +30,12 @@ export function ConnectionDetail({ ref }: { ref?: Ref<ConnectionDetailRef> }) {
const [open, setOpen] = useState(false)
const [detail, setDetail] = useState<IConnectionsItem | null>(null)
const [closed, setClosed] = useState(false)
const [preferredKind, setPreferredKind] =
useState<ConnectionRuleKind>('domain')
const theme = useTheme()
const [ruleTarget, setRuleTarget] = useState<ConnectionRuleTarget | null>(
null,
)
const onClose = useCallback(() => {
setOpen(false)
@@ -25,51 +44,90 @@ export function ConnectionDetail({ ref }: { ref?: Ref<ConnectionDetailRef> }) {
}, [])
useImperativeHandle(ref, () => ({
open: (detail: IConnectionsItem, closed: boolean) => {
open: (
detail: IConnectionsItem,
closed: boolean,
preferredKind = 'domain',
) => {
if (open) return
setOpen(true)
setDetail(detail)
setClosed(closed)
setPreferredKind(preferredKind)
},
close: onClose,
}))
return (
<Snackbar
anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
open={open}
onClose={onClose}
sx={{
'.MuiSnackbarContent-root': {
maxWidth: '520px',
maxHeight: '480px',
overflowY: 'auto',
backgroundColor: theme.palette.background.paper,
color: theme.palette.text.primary,
},
}}
message={
detail ? (
<InnerConnectionDetail
data={detail}
closed={closed}
onClose={onClose}
/>
) : null
}
/>
<>
<Snackbar
anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
open={open}
onClose={onClose}
sx={{
'.MuiSnackbarContent-root': {
width: '520px',
maxWidth: 'calc(100vw - 32px)',
boxSizing: 'border-box',
maxHeight: '480px',
overflowY: 'auto',
backgroundColor: theme.palette.background.paper,
color: theme.palette.text.primary,
},
'.MuiSnackbarContent-message': { width: '100%', minWidth: 0 },
}}
message={
detail ? (
<InnerConnectionDetail
data={detail}
closed={closed}
preferredKind={preferredKind}
onClose={onClose}
onAddRule={(target) => {
setRuleTarget(target)
onClose()
}}
/>
) : null
}
/>
{ruleTarget && (
<ConnectionRuleDialog
target={ruleTarget}
onClose={() => setRuleTarget(null)}
/>
)}
</>
)
}
interface InnerProps {
data: IConnectionsItem
closed: boolean
preferredKind: ConnectionRuleKind
onClose?: () => void
onAddRule: (target: ConnectionRuleTarget) => void
}
const InnerConnectionDetail = ({ data, closed, onClose }: InnerProps) => {
const InnerConnectionDetail = ({
data,
closed,
preferredKind,
onClose,
onAddRule,
}: InnerProps) => {
const { t } = useTranslation()
const { current } = useProfiles()
const { metadata, rulePayload } = data
const targets = getConnectionRuleTargets(metadata)
const canAddRule = Boolean(
current?.uid &&
current.option?.rules &&
(targets.domain ||
targets.process ||
targets.source ||
targets.destination),
)
const theme = useTheme()
const chains = [...data.chains].reverse().join(' / ')
const rule = rulePayload ? `${data.rule}(${rulePayload})` : data.rule
@@ -105,7 +163,7 @@ const InnerConnectionDetail = ({ data, closed, onClose }: InnerProps) => {
{ label: t('connections.components.fields.rule'), value: rule },
{
label: t('connections.components.fields.process'),
value: `${metadata.process}${metadata.processPath ? `(${metadata.processPath})` : ''}`,
value: `${metadata.process ?? ''}${metadata.processPath ? `(${metadata.processPath})` : ''}`,
},
{
label: t('connections.components.fields.time'),
@@ -132,7 +190,14 @@ const InnerConnectionDetail = ({ data, closed, onClose }: InnerProps) => {
const onDelete = useLockFn(async () => closeConnection(data.id))
return (
<Box sx={{ userSelect: 'text', color: theme.palette.text.secondary }}>
<Box
sx={{
width: '100%',
minWidth: 0,
userSelect: 'text',
color: theme.palette.text.secondary,
}}
>
{information.map((each) => (
<div key={each.label}>
<b>{each.label}</b>
@@ -147,8 +212,32 @@ const InnerConnectionDetail = ({ data, closed, onClose }: InnerProps) => {
</div>
))}
{!closed && (
<Box sx={{ textAlign: 'right' }}>
<Box
sx={{
display: 'flex',
justifyContent: 'flex-end',
gap: 1,
flexWrap: 'wrap',
mt: 1,
}}
>
<Button
variant="outlined"
disabled={!canAddRule}
onClick={() => {
if (!current?.uid || !current.option?.rules) return
onAddRule({
metadata: { ...metadata },
profileUid: current.uid,
profileName: current.name || current.uid,
rulesUid: current.option.rules,
preferredKind,
})
}}
>
{t('connections.ruleDialog.entry')}
</Button>
{!closed && (
<Button
variant="contained"
title={t('connections.components.actions.closeConnection')}
@@ -159,6 +248,18 @@ const InnerConnectionDetail = ({ data, closed, onClose }: InnerProps) => {
>
{t('connections.components.actions.closeConnection')}
</Button>
)}
</Box>
{!canAddRule && (
<Box sx={{ mt: 1, typography: 'caption' }}>
{t(
targets.domain ||
targets.process ||
targets.source ||
targets.destination
? 'connections.ruleDialog.noProfile'
: 'connections.ruleDialog.noMetadata',
)}
</Box>
)}
</Box>
@@ -7,11 +7,12 @@ import { closeConnection } from 'tauri-plugin-mihomo-api'
import { RelativeTime } from './connection-relative-time'
import type { ConnectionRowView } from './connection-row-view'
import type { ConnectionRuleKind } from './connection-rule'
interface Props {
row: ConnectionRowView
closed: boolean
onShowDetail: (id: string) => void
onShowDetail: (id: string, preferredKind?: ConnectionRuleKind) => void
}
const tagStyle = {
@@ -86,7 +87,17 @@ export const ConnectionRowItem = memo(
<div style={tagsStyle}>
<span style={tagStyle}>{row.network}</span>
<span style={tagStyle}>{row.type}</span>
{row.process && <span style={tagStyle}>{row.process}</span>}
{row.process && (
<span
style={tagStyle}
onClick={(event) => {
event.stopPropagation()
onShowDetail(row.id, 'process')
}}
>
{row.process}
</span>
)}
{row.chains && <span style={tagStyle}>{row.chains}</span>}
<span style={tagStyle}>
<RelativeTime start={row.time} />
@@ -0,0 +1,525 @@
import {
Alert,
Autocomplete,
Box,
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
FormControlLabel,
MenuItem,
Radio,
RadioGroup,
TextField,
Typography,
} from '@mui/material'
import { useLockFn } from 'ahooks'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
useClashConfigData,
useProxiesData,
} from '@/providers/app-data-context'
import { getProfiles, readProfileFile, saveProfileFile } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
import {
getConnectionIPRule,
getConnectionRuleTargets,
getConnectionRules,
getConnectionRootDomain,
isConnectionRuleDomain,
findConnectionRule,
saveConnectionRule,
type ConnectionRuleKind,
} from './connection-rule'
export interface ConnectionRuleTarget {
metadata: IConnectionsItem['metadata']
profileUid: string
profileName: string
rulesUid: string
preferredKind: ConnectionRuleKind
}
type DomainScope = 'DOMAIN' | 'DOMAIN-SUFFIX' | 'ROOT-DOMAIN'
function getInitialKind(target: ConnectionRuleTarget) {
const targets = getConnectionRuleTargets(target.metadata)
return targets[target.preferredKind]
? target.preferredKind
: ((['domain', 'process', 'source', 'destination'] as const).find(
(kind) => targets[kind],
) ?? 'domain')
}
export function ConnectionRuleDialog({
target,
onClose,
}: {
target: ConnectionRuleTarget
onClose: () => void
}) {
const { t } = useTranslation()
const { proxyView } = useProxiesData()
const { clashConfig } = useClashConfigData()
const targets = getConnectionRuleTargets(target.metadata)
const [rootDomain, setRootDomain] = useState<string>()
const [kind, setKind] = useState<ConnectionRuleKind>(() =>
getInitialKind(target),
)
const [policy, setPolicy] = useState<string | null>(null)
const [scope, setScope] = useState<DomainScope>('DOMAIN')
const [matchingInput, setMatchingInput] = useState(
() => targets[getInitialKind(target)]?.value ?? '',
)
const [rules, setRules] = useState<string[] | null>(null)
const [loadAttempt, setLoadAttempt] = useState(0)
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [error, setError] = useState('')
const selected = targets[kind]
const matchingRoot = kind === 'domain' && scope === 'ROOT-DOMAIN'
const editingDomain = kind === 'domain' && scope === 'DOMAIN-SUFFIX'
const editingIP = kind === 'source' || kind === 'destination'
const matchingValue = matchingRoot
? (rootDomain ?? '')
: editingDomain || editingIP
? matchingInput
: (selected?.value ?? '')
const invalidDomain =
editingDomain &&
!isConnectionRuleDomain(matchingInput, targets.domain?.value ?? '')
const ipRule = editingIP
? getConnectionIPRule(matchingInput, kind === 'source')
: undefined
const invalidIP = editingIP && !ipRule
const invalidValue = invalidDomain || invalidIP
const condition = editingIP
? ipRule
: selected
? {
type:
kind === 'domain' && scope !== 'DOMAIN'
? 'DOMAIN-SUFFIX'
: selected.type,
value: kind === 'domain' ? matchingValue.trim() : selected.value,
}
: undefined
const existing =
rules && condition && !invalidValue
? findConnectionRule(rules, condition)
: undefined
const modifying = Boolean(existing)
const groups = proxyView
? proxyView.groups.length || !proxyView.global
? proxyView.groups
: [proxyView.global]
: []
const policies = [
...new Set(['DIRECT', 'REJECT', ...groups.map((group) => group.name)]),
]
const kindLabels = {
domain: t('connections.ruleDialog.domain'),
process: t('connections.components.fields.process'),
source: t('connections.ruleDialog.sourceIp'),
destination: t('connections.ruleDialog.destinationIp'),
}
const unavailablePolicy = Boolean(policy && !policies.includes(policy))
const blocked = loading || saving || rules === null
useEffect(() => {
let cancelled = false
const ruleTargets = getConnectionRuleTargets(target.metadata)
Promise.all([
readProfileFile(target.rulesUid),
ruleTargets.domain
? getConnectionRootDomain(ruleTargets.domain.value)
: undefined,
])
.then(([content, root]) => {
const loadedRules = getConnectionRules(content)
const initialKind = getInitialKind(target)
const selectedTarget = ruleTargets[initialKind]
const initial = selectedTarget
? (findConnectionRule(loadedRules, selectedTarget) ??
(initialKind === 'domain'
? findConnectionRule(loadedRules, {
...selectedTarget,
type: 'DOMAIN-SUFFIX',
})
: undefined))
: undefined
if (cancelled) return
setRootDomain(root)
setRules(loadedRules)
setPolicy(initial?.policy ?? null)
setScope(initial?.type === 'DOMAIN-SUFFIX' ? 'DOMAIN-SUFFIX' : 'DOMAIN')
})
.catch((err: unknown) => {
if (!cancelled)
setError(err instanceof Error ? err.message : String(err))
})
.finally(() => {
if (!cancelled) setLoading(false)
})
return () => {
cancelled = true
}
}, [target, loadAttempt])
const handleSave = useLockFn(async () => {
if (
blocked ||
!condition ||
invalidValue ||
!policy ||
!policies.includes(policy)
)
return
if (/[\r\n,]/u.test(condition.value) || /[\r\n,]/u.test(policy)) {
setError(t('connections.ruleDialog.unsupportedValue'))
return
}
setSaving(true)
setError('')
try {
const result = await mutate(
async () => {
const checkProfile = async () => {
const profiles = await getProfiles()
const current = profiles.items?.find(
(item) => item.uid === profiles.current,
)
if (
profiles.current !== target.profileUid ||
current?.option?.rules !== target.rulesUid
) {
throw new Error(t('connections.ruleDialog.profileChanged'))
}
}
await checkProfile()
const content = await readProfileFile(target.rulesUid)
const updated = saveConnectionRule(content, condition, policy)
await checkProfile()
return saveProfileFile(target.rulesUid, updated)
},
{ id: `save-profile-file:${target.rulesUid}`, errorNotice: false },
)
if (!result.ok || !result.value) {
setError(t('connections.ruleDialog.applyFailed'))
return
}
showNotice.success('connections.ruleDialog.saved')
onClose()
} catch (err) {
setError(err instanceof Error ? err.message : String(err))
} finally {
setSaving(false)
}
})
return (
<Dialog open onClose={saving ? undefined : onClose} fullWidth maxWidth="sm">
<DialogTitle>
{t(
modifying
? 'connections.ruleDialog.modifyTitle'
: 'connections.ruleDialog.title',
)}
</DialogTitle>
<DialogContent>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: 1 }}>
<TextField
select
fullWidth
size="small"
label={t('connections.ruleDialog.matchBy')}
value={kind}
disabled={blocked}
onChange={(event) => {
const next = event.target.value as ConnectionRuleKind
const nextTarget = targets[next]
const rule =
rules && nextTarget
? (findConnectionRule(rules, nextTarget) ??
(next === 'domain'
? findConnectionRule(rules, {
...nextTarget,
type: 'DOMAIN-SUFFIX',
})
: undefined))
: undefined
setMatchingInput(nextTarget?.value ?? '')
setKind(next)
setPolicy(rule?.policy ?? null)
setScope(
rule?.type === 'DOMAIN-SUFFIX' ? 'DOMAIN-SUFFIX' : 'DOMAIN',
)
}}
>
{(['domain', 'process', 'source', 'destination'] as const).map(
(option) => (
<MenuItem
key={option}
value={option}
disabled={!targets[option]}
>
{kindLabels[option]}
{!targets[option] &&
` · ${t('connections.ruleDialog.unavailable')}`}
</MenuItem>
),
)}
</TextField>
{kind === 'process' ? (
<>
{target.metadata.process?.trim() && (
<TextField
fullWidth
size="small"
label={kindLabels.process}
value={target.metadata.process}
slotProps={{
input: { readOnly: true },
htmlInput: { title: target.metadata.process },
}}
/>
)}
{selected?.type === 'PROCESS-PATH' && (
<TextField
fullWidth
size="small"
label={t('connections.ruleDialog.fullPath')}
value={selected.value}
slotProps={{
input: { readOnly: true },
htmlInput: { title: selected.value },
}}
/>
)}
</>
) : (
<TextField
fullWidth
size="small"
label={
editingDomain || matchingRoot
? t('connections.ruleDialog.matchingDomain')
: kindLabels[kind]
}
value={matchingValue}
disabled={(editingDomain || editingIP) && blocked}
onChange={(event) => {
const value = event.target.value
setMatchingInput(value)
const nextCondition = editingIP
? getConnectionIPRule(value, kind === 'source')
: isConnectionRuleDomain(value, targets.domain?.value ?? '')
? { type: 'DOMAIN-SUFFIX', value: value.trim() }
: undefined
const match =
rules && nextCondition
? findConnectionRule(rules, nextCondition)
: undefined
if (match) setPolicy(match.policy)
}}
error={invalidValue}
helperText={
editingDomain || matchingRoot ? (
<>
{t('connections.ruleDialog.connectionHost', {
host: targets.domain?.value,
})}
{invalidDomain && (
<>
<br />
{t('connections.ruleDialog.invalidDomain')}
</>
)}
</>
) : invalidIP ? (
t('connections.ruleDialog.invalidIp')
) : undefined
}
slotProps={{
input: { readOnly: !editingDomain && !editingIP },
htmlInput: {
title: condition?.value,
},
}}
/>
)}
</Box>
{kind === 'domain' && (
<RadioGroup
row
aria-label={t('connections.ruleDialog.domainScope')}
value={scope}
onChange={(_, value) => {
const nextScope = value as DomainScope
setScope(nextScope)
setMatchingInput(targets.domain?.value ?? '')
const match =
rules && targets.domain
? findConnectionRule(rules, {
type: nextScope === 'DOMAIN' ? 'DOMAIN' : 'DOMAIN-SUFFIX',
value:
nextScope === 'ROOT-DOMAIN'
? (rootDomain ?? '')
: targets.domain.value,
})
: undefined
setPolicy(match?.policy ?? null)
}}
sx={{ mt: 0.5 }}
>
<FormControlLabel
value="DOMAIN"
control={<Radio size="small" />}
disabled={blocked}
label={t('connections.ruleDialog.exactDomain')}
/>
<FormControlLabel
value="DOMAIN-SUFFIX"
control={<Radio size="small" />}
disabled={blocked}
label={t('connections.ruleDialog.allSubdomains')}
/>
{rootDomain &&
rootDomain.toLowerCase() !==
targets.domain?.value.toLowerCase() && (
<FormControlLabel
value="ROOT-DOMAIN"
control={<Radio size="small" />}
disabled={blocked}
label={t('connections.ruleDialog.rootDomain', {
domain: rootDomain,
})}
/>
)}
</RadioGroup>
)}
{(kind === 'source' || kind === 'destination') && (
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
{t(
kind === 'source'
? 'connections.ruleDialog.sourceHint'
: 'connections.ruleDialog.destinationHint',
)}
</Typography>
)}
{kind === 'process' && (
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
{selected?.type === 'PROCESS-PATH'
? t('connections.ruleDialog.processPathHint')
: t('connections.ruleDialog.processNameHint')}
</Typography>
)}
<Autocomplete
size="small"
options={
unavailablePolicy && policy ? [policy, ...policies] : policies
}
getOptionLabel={(value) =>
value === 'DIRECT'
? t('proxies.components.enums.policies.DIRECT')
: value === 'REJECT'
? t('proxies.components.enums.policies.REJECT')
: value
}
getOptionDisabled={(value) => !policies.includes(value)}
value={policy}
onChange={(_, value) => setPolicy(value)}
disabled={blocked}
loading={loading}
renderInput={(params) => (
<TextField
{...params}
label={t('rules.modals.editor.form.labels.proxyPolicy')}
margin="normal"
error={unavailablePolicy}
helperText={
unavailablePolicy
? t('connections.ruleDialog.policyUnavailable')
: undefined
}
/>
)}
/>
{clashConfig && clashConfig.mode !== 'rule' && (
<Alert severity="info" sx={{ mt: 2 }}>
{t('connections.ruleDialog.ruleModeHint')}
</Alert>
)}
{error && (
<Box sx={{ mt: 2 }}>
<Alert severity="error">
{error}
{rules === null && (
<Button
onClick={() => {
setLoading(true)
setError('')
setLoadAttempt((attempt) => attempt + 1)
}}
>
{t('shared.actions.retry')}
</Button>
)}
</Alert>
</Box>
)}
<Typography
variant="caption"
color="text.secondary"
sx={{ display: 'block', mt: 2, overflowWrap: 'anywhere' }}
>
{t(
modifying
? 'connections.ruleDialog.editDestination'
: 'connections.ruleDialog.destination',
{
name: target.profileName,
},
)}
</Typography>
<Typography
variant="caption"
color="text.secondary"
sx={{ display: 'block' }}
>
{t('connections.ruleDialog.newConnections')}
</Typography>
</DialogContent>
<DialogActions>
<Button disabled={saving} onClick={onClose}>
{t('shared.actions.cancel')}
</Button>
<Button
variant="contained"
loading={saving}
disabled={
blocked ||
!condition ||
invalidValue ||
!policy ||
!policies.includes(policy)
}
onClick={handleSave}
>
{t(
modifying
? 'connections.ruleDialog.saveAndApply'
: 'connections.ruleDialog.addAndApply',
)}
</Button>
</DialogActions>
</Dialog>
)
}
@@ -0,0 +1,163 @@
import { dump, loadAll } from 'js-yaml'
import isFQDN from 'validator/es/lib/isFQDN'
import isIP from 'validator/es/lib/isIP'
import isIPRange from 'validator/es/lib/isIPRange'
export type ConnectionRuleKind = 'domain' | 'process' | 'source' | 'destination'
function getAddressRule(address: string | undefined, source: boolean) {
const ip = address?.trim()
if (!ip || !isIP(ip)) return undefined
return getConnectionIPRule(`${ip}/${isIP(ip, 4) ? 32 : 128}`, source)
}
export function getConnectionIPRule(value: string, source: boolean) {
const cidr = value.trim()
if (cidr.includes('%') || !isIPRange(cidr)) return undefined
const ipv4 = isIP(cidr.split('/')[0], 4)
return {
type: source ? 'SRC-IP-CIDR' : ipv4 ? 'IP-CIDR' : 'IP-CIDR6',
value: cidr,
}
}
export function getConnectionRuleTargets(
metadata: Pick<
IConnectionsItem['metadata'],
| 'host'
| 'process'
| 'processPath'
| 'sourceIP'
| 'destinationIP'
| 'remoteDestination'
>,
) {
const host = metadata.host?.trim() ?? ''
const path = metadata.processPath
const name = metadata.process
const domain =
host && !isIP(host) && isFQDN(host, { require_tld: false })
? { type: 'DOMAIN', value: host }
: undefined
const process = path?.trim()
? { type: 'PROCESS-PATH', value: path }
: name?.trim()
? { type: 'PROCESS-NAME', value: name }
: undefined
const source = getAddressRule(metadata.sourceIP, true)
const destination =
getAddressRule(metadata.destinationIP, false) ??
getAddressRule(metadata.remoteDestination, false)
return { domain, process, source, destination }
}
export function isConnectionRuleDomain(value: string, host: string) {
const domain = value.trim()
if (!domain || isIP(domain) || !isFQDN(domain, { require_tld: false }))
return false
const normalized = domain.toLowerCase()
const current = host.toLowerCase()
return (
normalized === current ||
(domain.split('.').length >= 2 && current.endsWith(`.${normalized}`))
)
}
export async function getConnectionRootDomain(host: string) {
const { parse } = await import('tldts')
const { domain, isIcann, isPrivate } = parse(host, {
allowPrivateDomains: true,
})
return domain && (isIcann || isPrivate) ? domain : undefined
}
function parseRuleExtension(content: string) {
const documents = loadAll(content)
if (documents.length > 1) {
throw new Error('The rule extension must contain a single YAML document.')
}
const parsed = documents[0]
if (
parsed !== undefined &&
parsed !== null &&
(typeof parsed !== 'object' ||
Array.isArray(parsed) ||
Object.getPrototypeOf(parsed) !== Object.prototype)
) {
throw new Error('The rule extension must be a YAML mapping.')
}
const config = (parsed ?? {}) as Record<string, unknown>
for (const key of ['prepend', 'append', 'delete']) {
const sequence = config[key]
if (
sequence != null &&
(!Array.isArray(sequence) ||
sequence.some((item) => typeof item !== 'string'))
) {
throw new Error('The rule extension contains an invalid rule list.')
}
}
return config
}
interface RuleCondition {
type: string
value: string
}
function matchesConnectionRule(raw: string, target: RuleCondition) {
const parts = raw.split(',').map((part) => part.trim())
const hasNoResolve =
(target.type === 'IP-CIDR' || target.type === 'IP-CIDR6') &&
parts.length === 4 &&
parts[3] === 'no-resolve'
if (parts.length !== 3 && !hasNoResolve) return false
if (target.type === 'DOMAIN' || target.type === 'DOMAIN-SUFFIX') {
return (
parts[0] === target.type &&
parts[1].toLowerCase() === target.value.toLowerCase()
)
}
return parts[0] === target.type && parts[1] === target.value
}
export function getConnectionRules(content: string): string[] {
const config = parseRuleExtension(content)
return [
...((config.prepend ?? []) as string[]),
...((config.append ?? []) as string[]),
]
}
export function findConnectionRule(rules: string[], target: RuleCondition) {
for (const raw of rules) {
if (matchesConnectionRule(raw, target)) {
const [type, , policy] = raw.split(',').map((part) => part.trim())
return { type, policy }
}
}
return undefined
}
export function saveConnectionRule(
content: string,
target: RuleCondition,
policy: string,
): string {
const config = parseRuleExtension(content)
const rule = `${target.type},${target.value},${policy}`
let replaced = false
for (const key of ['prepend', 'append']) {
if (!Array.isArray(config[key])) continue
config[key] = (config[key] as string[]).flatMap((raw) => {
if (!matchesConnectionRule(raw, target)) return [raw]
if (replaced) return []
replaced = true
return [raw.split(',').length === 4 ? `${rule},no-resolve` : rule]
})
}
if (!replaced) {
config.prepend = [rule, ...((config.prepend ?? []) as string[])]
}
return dump(config, { forceQuotes: true })
}
+22 -4
View File
@@ -29,6 +29,7 @@ import {
getConnectionStartTime,
getConnectionTypeLabel,
} from './connection-row-view'
import type { ConnectionRuleKind } from './connection-rule'
const ROW_HEIGHT = 40
const RESIZE_HANDLE_WIDTH = 6
@@ -247,7 +248,7 @@ const renderCell = (
interface RowComponentProps {
row: IConnectionsItem
columns: DisplayColumn[]
onShowDetail: (id: string) => void
onShowDetail: (id: string, preferredKind?: ConnectionRuleKind) => void
getSnapshot: (row: IConnectionsItem) => TableRowSnapshot
borderColor: string
virtualTop: number
@@ -263,7 +264,22 @@ const RowComponent = memo(
virtualTop,
}: RowComponentProps) {
const handleClick = useCallback(
() => onShowDetail(row.id),
(event: ReactMouseEvent<HTMLDivElement>) => {
const field =
event.target instanceof Element
? event.target.closest<HTMLElement>('[data-connection-field]')
?.dataset.connectionField
: undefined
const preferredKind =
field === 'process'
? 'process'
: field === 'source'
? 'source'
: field === 'remoteDestination'
? 'destination'
: 'domain'
onShowDetail(row.id, preferredKind)
},
[onShowDetail, row.id],
)
const snapshot = getSnapshot(row)
@@ -285,6 +301,7 @@ const RowComponent = memo(
{columns.map((column) => (
<div
key={column.field}
data-connection-field={column.field}
style={{
boxSizing: 'border-box',
flex: `0 0 ${column.size}px`,
@@ -318,7 +335,7 @@ const RowComponent = memo(
interface Props {
connections: IConnectionsItem[]
onShowDetail: (id: string) => void
onShowDetail: (id: string, preferredKind?: ConnectionRuleKind) => void
columnManagerOpen: boolean
onCloseColumnManager: () => void
}
@@ -333,7 +350,8 @@ export const ConnectionTable = (props: Props) => {
const onShowDetailRef = useRef(rawOnShowDetail)
onShowDetailRef.current = rawOnShowDetail
const onShowDetail = useCallback(
(id: string) => onShowDetailRef.current(id),
(id: string, preferredKind?: ConnectionRuleKind) =>
onShowDetailRef.current(id, preferredKind),
[],
)
const { t } = useTranslation()
+36
View File
@@ -30,5 +30,41 @@
"title": "الأعمدة",
"dragHandle": "Drag handle"
}
},
"ruleDialog": {
"title": "Add rule…",
"matchBy": "Match by",
"domain": "Domain",
"unavailable": "Not available",
"destination": "Add to the prepend rules of “{{name}}”.",
"newConnections": "New connections will match the updated configuration.",
"processPathHint": "Matches all destinations accessed by processes at this path.",
"processNameHint": "Matches all destinations accessed by processes with this name.",
"ruleModeHint": "Rule-based routing takes effect in Rule mode.",
"addAndApply": "Add and apply",
"profileChanged": "The active profile changed. Close this dialog and add the rule again.",
"applyFailed": "The rule could not be applied. Your selection has been kept.",
"unsupportedValue": "This value contains characters that cannot be used in a quick rule.",
"saved": "Rule saved and configuration applied.",
"noMetadata": "This connection has no domain, process or IP information for configuring a rule.",
"noProfile": "No active profile with an editable rule extension is available.",
"entry": "Configure rule…",
"modifyTitle": "Modify rule",
"domainScope": "Domain scope",
"exactDomain": "Only this domain",
"allSubdomains": "This domain and all its subdomains",
"rootDomain": "النطاق الرئيسي وجميع نطاقاته الفرعية ({{domain}})",
"policyUnavailable": "This policy is no longer available. Choose another policy.",
"editDestination": "Update the existing rule in “{{name}}”, keeping its position.",
"saveAndApply": "Save and apply",
"sourceIp": "Source IP",
"destinationIp": "Destination IP",
"sourceHint": "Matches all requests from this IP or subnet, including requests from other applications. No port filtering.",
"destinationHint": "Matches this destination IP or subnet across all domains. No port filtering.",
"fullPath": "Full path",
"connectionHost": "Current connection domain: {{host}}",
"invalidDomain": "Enter the current domain or a parent domain with at least two labels.",
"matchingDomain": "Matching domain",
"invalidIp": "Enter a valid IP/prefix length: 0–32 for IPv4 or 0–128 for IPv6."
}
}
+36
View File
@@ -30,5 +30,41 @@
"title": "Spalten",
"dragHandle": "Ziehpunkt"
}
},
"ruleDialog": {
"title": "Add rule…",
"matchBy": "Match by",
"domain": "Domain",
"unavailable": "Not available",
"destination": "Add to the prepend rules of “{{name}}”.",
"newConnections": "New connections will match the updated configuration.",
"processPathHint": "Matches all destinations accessed by processes at this path.",
"processNameHint": "Matches all destinations accessed by processes with this name.",
"ruleModeHint": "Rule-based routing takes effect in Rule mode.",
"addAndApply": "Add and apply",
"profileChanged": "The active profile changed. Close this dialog and add the rule again.",
"applyFailed": "The rule could not be applied. Your selection has been kept.",
"unsupportedValue": "This value contains characters that cannot be used in a quick rule.",
"saved": "Rule saved and configuration applied.",
"noMetadata": "This connection has no domain, process or IP information for configuring a rule.",
"noProfile": "No active profile with an editable rule extension is available.",
"entry": "Configure rule…",
"modifyTitle": "Modify rule",
"domainScope": "Domain scope",
"exactDomain": "Only this domain",
"allSubdomains": "This domain and all its subdomains",
"rootDomain": "Hauptdomain und alle Subdomains ({{domain}})",
"policyUnavailable": "This policy is no longer available. Choose another policy.",
"editDestination": "Update the existing rule in “{{name}}”, keeping its position.",
"saveAndApply": "Save and apply",
"sourceIp": "Source IP",
"destinationIp": "Destination IP",
"sourceHint": "Matches all requests from this IP or subnet, including requests from other applications. No port filtering.",
"destinationHint": "Matches this destination IP or subnet across all domains. No port filtering.",
"fullPath": "Full path",
"connectionHost": "Current connection domain: {{host}}",
"invalidDomain": "Enter the current domain or a parent domain with at least two labels.",
"matchingDomain": "Matching domain",
"invalidIp": "Enter a valid IP/prefix length: 0–32 for IPv4 or 0–128 for IPv6."
}
}
+36
View File
@@ -30,5 +30,41 @@
"title": "Columns",
"dragHandle": "Drag handle"
}
},
"ruleDialog": {
"title": "Add rule…",
"matchBy": "Match by",
"domain": "Domain",
"unavailable": "Not available",
"destination": "Add to the prepend rules of “{{name}}”.",
"newConnections": "New connections will match the updated configuration.",
"processPathHint": "Matches all destinations accessed by processes at this path.",
"processNameHint": "Matches all destinations accessed by processes with this name.",
"ruleModeHint": "Rule-based routing takes effect in Rule mode.",
"addAndApply": "Add and apply",
"profileChanged": "The active profile changed. Close this dialog and add the rule again.",
"applyFailed": "The rule could not be applied. Your selection has been kept.",
"unsupportedValue": "This value contains characters that cannot be used in a quick rule.",
"saved": "Rule saved and configuration applied.",
"noMetadata": "This connection has no domain, process or IP information for configuring a rule.",
"noProfile": "No active profile with an editable rule extension is available.",
"entry": "Configure rule…",
"modifyTitle": "Modify rule",
"domainScope": "Domain scope",
"exactDomain": "Only this domain",
"allSubdomains": "This domain and all its subdomains",
"rootDomain": "Root domain and all its subdomains ({{domain}})",
"policyUnavailable": "This policy is no longer available. Choose another policy.",
"editDestination": "Update the existing rule in “{{name}}”, keeping its position.",
"saveAndApply": "Save and apply",
"sourceIp": "Source IP",
"destinationIp": "Destination IP",
"sourceHint": "Matches all requests from this IP or subnet, including requests from other applications. No port filtering.",
"destinationHint": "Matches this destination IP or subnet across all domains. No port filtering.",
"fullPath": "Full path",
"connectionHost": "Current connection domain: {{host}}",
"invalidDomain": "Enter the current domain or a parent domain with at least two labels.",
"matchingDomain": "Matching domain",
"invalidIp": "Enter a valid IP/prefix length: 0–32 for IPv4 or 0–128 for IPv6."
}
}
+36
View File
@@ -30,5 +30,41 @@
"title": "Columnas",
"dragHandle": "Drag handle"
}
},
"ruleDialog": {
"title": "Add rule…",
"matchBy": "Match by",
"domain": "Domain",
"unavailable": "Not available",
"destination": "Add to the prepend rules of “{{name}}”.",
"newConnections": "New connections will match the updated configuration.",
"processPathHint": "Matches all destinations accessed by processes at this path.",
"processNameHint": "Matches all destinations accessed by processes with this name.",
"ruleModeHint": "Rule-based routing takes effect in Rule mode.",
"addAndApply": "Add and apply",
"profileChanged": "The active profile changed. Close this dialog and add the rule again.",
"applyFailed": "The rule could not be applied. Your selection has been kept.",
"unsupportedValue": "This value contains characters that cannot be used in a quick rule.",
"saved": "Rule saved and configuration applied.",
"noMetadata": "This connection has no domain, process or IP information for configuring a rule.",
"noProfile": "No active profile with an editable rule extension is available.",
"entry": "Configure rule…",
"modifyTitle": "Modify rule",
"domainScope": "Domain scope",
"exactDomain": "Only this domain",
"allSubdomains": "This domain and all its subdomains",
"rootDomain": "Dominio principal y todos sus subdominios ({{domain}})",
"policyUnavailable": "This policy is no longer available. Choose another policy.",
"editDestination": "Update the existing rule in “{{name}}”, keeping its position.",
"saveAndApply": "Save and apply",
"sourceIp": "Source IP",
"destinationIp": "Destination IP",
"sourceHint": "Matches all requests from this IP or subnet, including requests from other applications. No port filtering.",
"destinationHint": "Matches this destination IP or subnet across all domains. No port filtering.",
"fullPath": "Full path",
"connectionHost": "Current connection domain: {{host}}",
"invalidDomain": "Enter the current domain or a parent domain with at least two labels.",
"matchingDomain": "Matching domain",
"invalidIp": "Enter a valid IP/prefix length: 0–32 for IPv4 or 0–128 for IPv6."
}
}
+36
View File
@@ -30,5 +30,41 @@
"title": "ستون‌ها",
"dragHandle": "Drag handle"
}
},
"ruleDialog": {
"title": "Add rule…",
"matchBy": "Match by",
"domain": "Domain",
"unavailable": "Not available",
"destination": "Add to the prepend rules of “{{name}}”.",
"newConnections": "New connections will match the updated configuration.",
"processPathHint": "Matches all destinations accessed by processes at this path.",
"processNameHint": "Matches all destinations accessed by processes with this name.",
"ruleModeHint": "Rule-based routing takes effect in Rule mode.",
"addAndApply": "Add and apply",
"profileChanged": "The active profile changed. Close this dialog and add the rule again.",
"applyFailed": "The rule could not be applied. Your selection has been kept.",
"unsupportedValue": "This value contains characters that cannot be used in a quick rule.",
"saved": "Rule saved and configuration applied.",
"noMetadata": "This connection has no domain, process or IP information for configuring a rule.",
"noProfile": "No active profile with an editable rule extension is available.",
"entry": "Configure rule…",
"modifyTitle": "Modify rule",
"domainScope": "Domain scope",
"exactDomain": "Only this domain",
"allSubdomains": "This domain and all its subdomains",
"rootDomain": "دامنهٔ اصلی و همهٔ زیردامنه‌های آن ({{domain}})",
"policyUnavailable": "This policy is no longer available. Choose another policy.",
"editDestination": "Update the existing rule in “{{name}}”, keeping its position.",
"saveAndApply": "Save and apply",
"sourceIp": "Source IP",
"destinationIp": "Destination IP",
"sourceHint": "Matches all requests from this IP or subnet, including requests from other applications. No port filtering.",
"destinationHint": "Matches this destination IP or subnet across all domains. No port filtering.",
"fullPath": "Full path",
"connectionHost": "Current connection domain: {{host}}",
"invalidDomain": "Enter the current domain or a parent domain with at least two labels.",
"matchingDomain": "Matching domain",
"invalidIp": "Enter a valid IP/prefix length: 0–32 for IPv4 or 0–128 for IPv6."
}
}
+36
View File
@@ -30,5 +30,41 @@
"title": "Kolom",
"dragHandle": "Drag handle"
}
},
"ruleDialog": {
"title": "Add rule…",
"matchBy": "Match by",
"domain": "Domain",
"unavailable": "Not available",
"destination": "Add to the prepend rules of “{{name}}”.",
"newConnections": "New connections will match the updated configuration.",
"processPathHint": "Matches all destinations accessed by processes at this path.",
"processNameHint": "Matches all destinations accessed by processes with this name.",
"ruleModeHint": "Rule-based routing takes effect in Rule mode.",
"addAndApply": "Add and apply",
"profileChanged": "The active profile changed. Close this dialog and add the rule again.",
"applyFailed": "The rule could not be applied. Your selection has been kept.",
"unsupportedValue": "This value contains characters that cannot be used in a quick rule.",
"saved": "Rule saved and configuration applied.",
"noMetadata": "This connection has no domain, process or IP information for configuring a rule.",
"noProfile": "No active profile with an editable rule extension is available.",
"entry": "Configure rule…",
"modifyTitle": "Modify rule",
"domainScope": "Domain scope",
"exactDomain": "Only this domain",
"allSubdomains": "This domain and all its subdomains",
"rootDomain": "Domain utama dan semua subdomainnya ({{domain}})",
"policyUnavailable": "This policy is no longer available. Choose another policy.",
"editDestination": "Update the existing rule in “{{name}}”, keeping its position.",
"saveAndApply": "Save and apply",
"sourceIp": "Source IP",
"destinationIp": "Destination IP",
"sourceHint": "Matches all requests from this IP or subnet, including requests from other applications. No port filtering.",
"destinationHint": "Matches this destination IP or subnet across all domains. No port filtering.",
"fullPath": "Full path",
"connectionHost": "Current connection domain: {{host}}",
"invalidDomain": "Enter the current domain or a parent domain with at least two labels.",
"matchingDomain": "Matching domain",
"invalidIp": "Enter a valid IP/prefix length: 0–32 for IPv4 or 0–128 for IPv6."
}
}
+36
View File
@@ -30,5 +30,41 @@
"title": "列",
"dragHandle": "Drag handle"
}
},
"ruleDialog": {
"title": "Add rule…",
"matchBy": "Match by",
"domain": "Domain",
"unavailable": "Not available",
"destination": "Add to the prepend rules of “{{name}}”.",
"newConnections": "New connections will match the updated configuration.",
"processPathHint": "Matches all destinations accessed by processes at this path.",
"processNameHint": "Matches all destinations accessed by processes with this name.",
"ruleModeHint": "Rule-based routing takes effect in Rule mode.",
"addAndApply": "Add and apply",
"profileChanged": "The active profile changed. Close this dialog and add the rule again.",
"applyFailed": "The rule could not be applied. Your selection has been kept.",
"unsupportedValue": "This value contains characters that cannot be used in a quick rule.",
"saved": "Rule saved and configuration applied.",
"noMetadata": "This connection has no domain, process or IP information for configuring a rule.",
"noProfile": "No active profile with an editable rule extension is available.",
"entry": "Configure rule…",
"modifyTitle": "Modify rule",
"domainScope": "Domain scope",
"exactDomain": "Only this domain",
"allSubdomains": "This domain and all its subdomains",
"rootDomain": "メインドメインとすべてのサブドメイン({{domain}})",
"policyUnavailable": "This policy is no longer available. Choose another policy.",
"editDestination": "Update the existing rule in “{{name}}”, keeping its position.",
"saveAndApply": "Save and apply",
"sourceIp": "Source IP",
"destinationIp": "Destination IP",
"sourceHint": "Matches all requests from this IP or subnet, including requests from other applications. No port filtering.",
"destinationHint": "Matches this destination IP or subnet across all domains. No port filtering.",
"fullPath": "Full path",
"connectionHost": "Current connection domain: {{host}}",
"invalidDomain": "Enter the current domain or a parent domain with at least two labels.",
"matchingDomain": "Matching domain",
"invalidIp": "Enter a valid IP/prefix length: 0–32 for IPv4 or 0–128 for IPv6."
}
}
+36
View File
@@ -30,5 +30,41 @@
"title": "열",
"dragHandle": "Drag handle"
}
},
"ruleDialog": {
"title": "Add rule…",
"matchBy": "Match by",
"domain": "Domain",
"unavailable": "Not available",
"destination": "Add to the prepend rules of “{{name}}”.",
"newConnections": "New connections will match the updated configuration.",
"processPathHint": "Matches all destinations accessed by processes at this path.",
"processNameHint": "Matches all destinations accessed by processes with this name.",
"ruleModeHint": "Rule-based routing takes effect in Rule mode.",
"addAndApply": "Add and apply",
"profileChanged": "The active profile changed. Close this dialog and add the rule again.",
"applyFailed": "The rule could not be applied. Your selection has been kept.",
"unsupportedValue": "This value contains characters that cannot be used in a quick rule.",
"saved": "Rule saved and configuration applied.",
"noMetadata": "This connection has no domain, process or IP information for configuring a rule.",
"noProfile": "No active profile with an editable rule extension is available.",
"entry": "Configure rule…",
"modifyTitle": "Modify rule",
"domainScope": "Domain scope",
"exactDomain": "Only this domain",
"allSubdomains": "This domain and all its subdomains",
"rootDomain": "기본 도메인 및 모든 하위 도메인 ({{domain}})",
"policyUnavailable": "This policy is no longer available. Choose another policy.",
"editDestination": "Update the existing rule in “{{name}}”, keeping its position.",
"saveAndApply": "Save and apply",
"sourceIp": "Source IP",
"destinationIp": "Destination IP",
"sourceHint": "Matches all requests from this IP or subnet, including requests from other applications. No port filtering.",
"destinationHint": "Matches this destination IP or subnet across all domains. No port filtering.",
"fullPath": "Full path",
"connectionHost": "Current connection domain: {{host}}",
"invalidDomain": "Enter the current domain or a parent domain with at least two labels.",
"matchingDomain": "Matching domain",
"invalidIp": "Enter a valid IP/prefix length: 0–32 for IPv4 or 0–128 for IPv6."
}
}
+36
View File
@@ -30,5 +30,41 @@
"title": "Colunas",
"dragHandle": "Alça de arrastar"
}
},
"ruleDialog": {
"title": "Add rule…",
"matchBy": "Match by",
"domain": "Domain",
"unavailable": "Not available",
"destination": "Add to the prepend rules of “{{name}}”.",
"newConnections": "New connections will match the updated configuration.",
"processPathHint": "Matches all destinations accessed by processes at this path.",
"processNameHint": "Matches all destinations accessed by processes with this name.",
"ruleModeHint": "Rule-based routing takes effect in Rule mode.",
"addAndApply": "Add and apply",
"profileChanged": "The active profile changed. Close this dialog and add the rule again.",
"applyFailed": "The rule could not be applied. Your selection has been kept.",
"unsupportedValue": "This value contains characters that cannot be used in a quick rule.",
"saved": "Rule saved and configuration applied.",
"noMetadata": "This connection has no domain, process or IP information for configuring a rule.",
"noProfile": "No active profile with an editable rule extension is available.",
"entry": "Configure rule…",
"modifyTitle": "Modify rule",
"domainScope": "Domain scope",
"exactDomain": "Only this domain",
"allSubdomains": "This domain and all its subdomains",
"rootDomain": "Domínio principal e todos os seus subdomínios ({{domain}})",
"policyUnavailable": "This policy is no longer available. Choose another policy.",
"editDestination": "Update the existing rule in “{{name}}”, keeping its position.",
"saveAndApply": "Save and apply",
"sourceIp": "Source IP",
"destinationIp": "Destination IP",
"sourceHint": "Matches all requests from this IP or subnet, including requests from other applications. No port filtering.",
"destinationHint": "Matches this destination IP or subnet across all domains. No port filtering.",
"fullPath": "Full path",
"connectionHost": "Current connection domain: {{host}}",
"invalidDomain": "Enter the current domain or a parent domain with at least two labels.",
"matchingDomain": "Matching domain",
"invalidIp": "Enter a valid IP/prefix length: 0–32 for IPv4 or 0–128 for IPv6."
}
}
+36
View File
@@ -30,5 +30,41 @@
"title": "Столбцы",
"dragHandle": "Маркер перетаскивания"
}
},
"ruleDialog": {
"title": "Add rule…",
"matchBy": "Match by",
"domain": "Domain",
"unavailable": "Not available",
"destination": "Add to the prepend rules of “{{name}}”.",
"newConnections": "New connections will match the updated configuration.",
"processPathHint": "Matches all destinations accessed by processes at this path.",
"processNameHint": "Matches all destinations accessed by processes with this name.",
"ruleModeHint": "Rule-based routing takes effect in Rule mode.",
"addAndApply": "Add and apply",
"profileChanged": "The active profile changed. Close this dialog and add the rule again.",
"applyFailed": "The rule could not be applied. Your selection has been kept.",
"unsupportedValue": "This value contains characters that cannot be used in a quick rule.",
"saved": "Rule saved and configuration applied.",
"noMetadata": "This connection has no domain, process or IP information for configuring a rule.",
"noProfile": "No active profile with an editable rule extension is available.",
"entry": "Configure rule…",
"modifyTitle": "Modify rule",
"domainScope": "Domain scope",
"exactDomain": "Only this domain",
"allSubdomains": "This domain and all its subdomains",
"rootDomain": "Основной домен и все его поддомены ({{domain}})",
"policyUnavailable": "This policy is no longer available. Choose another policy.",
"editDestination": "Update the existing rule in “{{name}}”, keeping its position.",
"saveAndApply": "Save and apply",
"sourceIp": "Source IP",
"destinationIp": "Destination IP",
"sourceHint": "Matches all requests from this IP or subnet, including requests from other applications. No port filtering.",
"destinationHint": "Matches this destination IP or subnet across all domains. No port filtering.",
"fullPath": "Full path",
"connectionHost": "Current connection domain: {{host}}",
"invalidDomain": "Enter the current domain or a parent domain with at least two labels.",
"matchingDomain": "Matching domain",
"invalidIp": "Enter a valid IP/prefix length: 0–32 for IPv4 or 0–128 for IPv6."
}
}
+36
View File
@@ -30,5 +30,41 @@
"title": "Sütunlar",
"dragHandle": "Sürükleme tutamacı"
}
},
"ruleDialog": {
"title": "Add rule…",
"matchBy": "Match by",
"domain": "Domain",
"unavailable": "Not available",
"destination": "Add to the prepend rules of “{{name}}”.",
"newConnections": "New connections will match the updated configuration.",
"processPathHint": "Matches all destinations accessed by processes at this path.",
"processNameHint": "Matches all destinations accessed by processes with this name.",
"ruleModeHint": "Rule-based routing takes effect in Rule mode.",
"addAndApply": "Add and apply",
"profileChanged": "The active profile changed. Close this dialog and add the rule again.",
"applyFailed": "The rule could not be applied. Your selection has been kept.",
"unsupportedValue": "This value contains characters that cannot be used in a quick rule.",
"saved": "Rule saved and configuration applied.",
"noMetadata": "This connection has no domain, process or IP information for configuring a rule.",
"noProfile": "No active profile with an editable rule extension is available.",
"entry": "Configure rule…",
"modifyTitle": "Modify rule",
"domainScope": "Domain scope",
"exactDomain": "Only this domain",
"allSubdomains": "This domain and all its subdomains",
"rootDomain": "Ana alan adı ve tüm alt alan adları ({{domain}})",
"policyUnavailable": "This policy is no longer available. Choose another policy.",
"editDestination": "Update the existing rule in “{{name}}”, keeping its position.",
"saveAndApply": "Save and apply",
"sourceIp": "Source IP",
"destinationIp": "Destination IP",
"sourceHint": "Matches all requests from this IP or subnet, including requests from other applications. No port filtering.",
"destinationHint": "Matches this destination IP or subnet across all domains. No port filtering.",
"fullPath": "Full path",
"connectionHost": "Current connection domain: {{host}}",
"invalidDomain": "Enter the current domain or a parent domain with at least two labels.",
"matchingDomain": "Matching domain",
"invalidIp": "Enter a valid IP/prefix length: 0–32 for IPv4 or 0–128 for IPv6."
}
}
+36
View File
@@ -30,5 +30,41 @@
"title": "Баганалар",
"dragHandle": "Drag handle"
}
},
"ruleDialog": {
"title": "Add rule…",
"matchBy": "Match by",
"domain": "Domain",
"unavailable": "Not available",
"destination": "Add to the prepend rules of “{{name}}”.",
"newConnections": "New connections will match the updated configuration.",
"processPathHint": "Matches all destinations accessed by processes at this path.",
"processNameHint": "Matches all destinations accessed by processes with this name.",
"ruleModeHint": "Rule-based routing takes effect in Rule mode.",
"addAndApply": "Add and apply",
"profileChanged": "The active profile changed. Close this dialog and add the rule again.",
"applyFailed": "The rule could not be applied. Your selection has been kept.",
"unsupportedValue": "This value contains characters that cannot be used in a quick rule.",
"saved": "Rule saved and configuration applied.",
"noMetadata": "This connection has no domain, process or IP information for configuring a rule.",
"noProfile": "No active profile with an editable rule extension is available.",
"entry": "Configure rule…",
"modifyTitle": "Modify rule",
"domainScope": "Domain scope",
"exactDomain": "Only this domain",
"allSubdomains": "This domain and all its subdomains",
"rootDomain": "Төп домен һәм аның барлык субдоменнары ({{domain}})",
"policyUnavailable": "This policy is no longer available. Choose another policy.",
"editDestination": "Update the existing rule in “{{name}}”, keeping its position.",
"saveAndApply": "Save and apply",
"sourceIp": "Source IP",
"destinationIp": "Destination IP",
"sourceHint": "Matches all requests from this IP or subnet, including requests from other applications. No port filtering.",
"destinationHint": "Matches this destination IP or subnet across all domains. No port filtering.",
"fullPath": "Full path",
"connectionHost": "Current connection domain: {{host}}",
"invalidDomain": "Enter the current domain or a parent domain with at least two labels.",
"matchingDomain": "Matching domain",
"invalidIp": "Enter a valid IP/prefix length: 0–32 for IPv4 or 0–128 for IPv6."
}
}
+36
View File
@@ -30,5 +30,41 @@
"title": "列设置",
"dragHandle": "拖拽控件"
}
},
"ruleDialog": {
"title": "添加规则…",
"matchBy": "匹配对象",
"domain": "域名",
"unavailable": "未获取",
"destination": "添加到「{{name}}」的前置规则。",
"newConnections": "新建立的连接将按更新后的配置匹配。",
"processPathHint": "匹配此路径对应进程访问的所有目标。",
"processNameHint": "匹配所有同名进程访问的所有目标。",
"ruleModeHint": "规则分流在规则模式下生效。",
"addAndApply": "添加并应用",
"profileChanged": "当前订阅已切换,请关闭弹窗后重新添加规则。",
"applyFailed": "规则未能应用,已保留当前选择。",
"unsupportedValue": "此内容包含快捷规则不支持的字符。",
"saved": "规则已保存,配置已应用。",
"noMetadata": "此连接没有可用于设置规则的域名、进程或 IP 信息。",
"noProfile": "当前没有可编辑规则扩展的活动订阅。",
"entry": "设置规则…",
"modifyTitle": "修改规则",
"domainScope": "域名匹配范围",
"exactDomain": "仅此域名",
"allSubdomains": "此域名及所有子域名",
"rootDomain": "主域名及所有子域名({{domain}})",
"policyUnavailable": "此策略已不可用,请选择其他策略。",
"editDestination": "修改「{{name}}」中的现有规则,保留排序。",
"saveAndApply": "保存并应用",
"sourceIp": "源 IP",
"destinationIp": "目标 IP",
"sourceHint": "匹配来自此 IP 或网段的所有请求,可能包含其他应用,不限定端口。",
"destinationHint": "匹配访问此目标 IP 或网段的请求,覆盖所有域名,不限定端口。",
"fullPath": "完整路径",
"connectionHost": "当前连接域名:{{host}}",
"invalidDomain": "请输入当前连接域名或其父域名,父域名至少包含两级。",
"matchingDomain": "匹配域名",
"invalidIp": "请输入有效的 IP/前缀长度,IPv4 为 0–32,IPv6 为 0–128。"
}
}
+36
View File
@@ -30,5 +30,41 @@
"title": "欄位設定",
"dragHandle": "拖曳以移動"
}
},
"ruleDialog": {
"title": "Add rule…",
"matchBy": "Match by",
"domain": "Domain",
"unavailable": "Not available",
"destination": "Add to the prepend rules of “{{name}}”.",
"newConnections": "New connections will match the updated configuration.",
"processPathHint": "Matches all destinations accessed by processes at this path.",
"processNameHint": "Matches all destinations accessed by processes with this name.",
"ruleModeHint": "Rule-based routing takes effect in Rule mode.",
"addAndApply": "Add and apply",
"profileChanged": "The active profile changed. Close this dialog and add the rule again.",
"applyFailed": "The rule could not be applied. Your selection has been kept.",
"unsupportedValue": "This value contains characters that cannot be used in a quick rule.",
"saved": "Rule saved and configuration applied.",
"noMetadata": "This connection has no domain, process or IP information for configuring a rule.",
"noProfile": "No active profile with an editable rule extension is available.",
"entry": "Configure rule…",
"modifyTitle": "Modify rule",
"domainScope": "Domain scope",
"exactDomain": "Only this domain",
"allSubdomains": "This domain and all its subdomains",
"rootDomain": "主網域及所有子網域({{domain}})",
"policyUnavailable": "This policy is no longer available. Choose another policy.",
"editDestination": "Update the existing rule in “{{name}}”, keeping its position.",
"saveAndApply": "Save and apply",
"sourceIp": "Source IP",
"destinationIp": "Destination IP",
"sourceHint": "Matches all requests from this IP or subnet, including requests from other applications. No port filtering.",
"destinationHint": "Matches this destination IP or subnet across all domains. No port filtering.",
"fullPath": "Full path",
"connectionHost": "Current connection domain: {{host}}",
"invalidDomain": "Enter the current domain or a parent domain with at least two labels.",
"matchingDomain": "Matching domain",
"invalidIp": "Enter a valid IP/prefix length: 0–32 for IPv4 or 0–128 for IPv6."
}
}
+7 -2
View File
@@ -35,6 +35,7 @@ import {
getConnectionStartTime,
useConnectionRowViews,
} from '@/components/connection/connection-row-view'
import type { ConnectionRuleKind } from '@/components/connection/connection-rule'
import { ConnectionTable } from '@/components/connection/connection-table'
import { useConnectionData } from '@/hooks/use-connection-data'
import { useConnectionSetting } from '@/hooks/use-connection-setting'
@@ -161,10 +162,14 @@ const ConnectionsPage = () => {
)
const showDetailById = useCallback(
(id: string) => {
(id: string, preferredKind: ConnectionRuleKind = 'domain') => {
const connection = filterConn.find((item) => item.id === id)
if (connection) {
detailRef.current?.open(connection, connectionsType === 'closed')
detailRef.current?.open(
connection,
connectionsType === 'closed',
preferredKind,
)
}
},
[connectionsType, filterConn],
+34
View File
@@ -22,6 +22,40 @@ export const translationKeys = [
'connections.components.actions.closeConnection',
'connections.components.columnManager.title',
'connections.components.columnManager.dragHandle',
'connections.ruleDialog.title',
'connections.ruleDialog.matchBy',
'connections.ruleDialog.domain',
'connections.ruleDialog.unavailable',
'connections.ruleDialog.destination',
'connections.ruleDialog.newConnections',
'connections.ruleDialog.processPathHint',
'connections.ruleDialog.processNameHint',
'connections.ruleDialog.ruleModeHint',
'connections.ruleDialog.addAndApply',
'connections.ruleDialog.profileChanged',
'connections.ruleDialog.applyFailed',
'connections.ruleDialog.unsupportedValue',
'connections.ruleDialog.saved',
'connections.ruleDialog.noMetadata',
'connections.ruleDialog.noProfile',
'connections.ruleDialog.entry',
'connections.ruleDialog.modifyTitle',
'connections.ruleDialog.domainScope',
'connections.ruleDialog.exactDomain',
'connections.ruleDialog.allSubdomains',
'connections.ruleDialog.rootDomain',
'connections.ruleDialog.policyUnavailable',
'connections.ruleDialog.editDestination',
'connections.ruleDialog.saveAndApply',
'connections.ruleDialog.sourceIp',
'connections.ruleDialog.destinationIp',
'connections.ruleDialog.sourceHint',
'connections.ruleDialog.destinationHint',
'connections.ruleDialog.fullPath',
'connections.ruleDialog.connectionHost',
'connections.ruleDialog.invalidDomain',
'connections.ruleDialog.matchingDomain',
'connections.ruleDialog.invalidIp',
'home.page.tooltips.lightweightMode',
'home.page.tooltips.manual',
'home.page.tooltips.settings',
+36
View File
@@ -36,6 +36,42 @@ export interface TranslationResources {
page: {
title: string
}
ruleDialog: {
addAndApply: string
allSubdomains: string
applyFailed: string
connectionHost: string
destination: string
destinationHint: string
destinationIp: string
domain: string
domainScope: string
editDestination: string
entry: string
exactDomain: string
fullPath: string
invalidDomain: string
invalidIp: string
matchBy: string
matchingDomain: string
modifyTitle: string
newConnections: string
noMetadata: string
noProfile: string
policyUnavailable: string
processNameHint: string
processPathHint: string
profileChanged: string
rootDomain: string
ruleModeHint: string
saveAndApply: string
saved: string
sourceHint: string
sourceIp: string
title: string
unavailable: string
unsupportedValue: string
}
}
home: {
components: {