mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-02 03:00:05 +08:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
87de9bd5bf |
@@ -5,10 +5,10 @@
|
|||||||
"version": "v9.0.0",
|
"version": "v9.0.0",
|
||||||
"sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3"
|
"sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3"
|
||||||
},
|
},
|
||||||
"github/gh-aw-actions/setup@v1.4.2": {
|
"github/gh-aw-actions/setup@v1.4.4": {
|
||||||
"repo": "github/gh-aw-actions/setup",
|
"repo": "github/gh-aw-actions/setup",
|
||||||
"version": "v1.4.2",
|
"version": "v1.4.4",
|
||||||
"sha": "d7852d91d5d1d13e7848771edab8bd1792a08651"
|
"sha": "6147e7c2fba711fb36ac73c79cba401d1e213c4e"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"containers": {
|
"containers": {
|
||||||
@@ -199,13 +199,13 @@
|
|||||||
},
|
},
|
||||||
"ghcr.io/github/gh-aw-node": {
|
"ghcr.io/github/gh-aw-node": {
|
||||||
"image": "ghcr.io/github/gh-aw-node",
|
"image": "ghcr.io/github/gh-aw-node",
|
||||||
"digest": "sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc",
|
"digest": "sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f",
|
||||||
"pinned_image": "ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc"
|
"pinned_image": "ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f"
|
||||||
},
|
},
|
||||||
"ghcr.io/github/github-mcp-server:v2.2.0": {
|
"ghcr.io/github/github-mcp-server:v2.3.0": {
|
||||||
"image": "ghcr.io/github/github-mcp-server:v2.2.0",
|
"image": "ghcr.io/github/github-mcp-server:v2.3.0",
|
||||||
"digest": "sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174",
|
"digest": "sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6",
|
||||||
"pinned_image": "ghcr.io/github/github-mcp-server:v2.2.0@sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174"
|
"pinned_image": "ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,9 +31,9 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
- name: Install gh-aw extension
|
- name: Install gh-aw extension
|
||||||
uses: github/gh-aw-actions/setup-cli@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2
|
uses: github/gh-aw-actions/setup-cli@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4
|
||||||
with:
|
with:
|
||||||
version: v1.4.2
|
version: v1.4.4
|
||||||
- name: Install Rust Stable
|
- name: Install Rust Stable
|
||||||
uses: dtolnay/rust-toolchain@stable
|
uses: dtolnay/rust-toolchain@stable
|
||||||
with:
|
with:
|
||||||
|
|||||||
+35
-28
@@ -1,6 +1,6 @@
|
|||||||
# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"4ca5835c0c9cd01f3432b873f5a177ca6d3d1dbd6a35939e2058dcb37aa224b4","body_hash":"ca82fafbe18061d7c8bd708dc18e91b9116faf0c921a7fa35be1538d47a2b005","compiler_version":"v1.4.2","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.103"}}
|
# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"4ca5835c0c9cd01f3432b873f5a177ca6d3d1dbd6a35939e2058dcb37aa224b4","body_hash":"ca82fafbe18061d7c8bd708dc18e91b9116faf0c921a7fa35be1538d47a2b005","compiler_version":"v1.4.4","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.103"}}
|
||||||
# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_DEFAULT_OTLP_ENDPOINT","GH_AW_DEFAULT_OTLP_HEADERS","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"3d3c42e5aac5ba805825da76410c181273ba90b1","version":"v7.0.1"},{"repo":"actions/download-artifact","sha":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"github/gh-aw-actions/setup","sha":"d7852d91d5d1d13e7848771edab8bd1792a08651","version":"v1.4.2"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca"},{"image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7"},{"image":"ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.5.16","digest":"sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc","pinned_image":"ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc"},{"image":"ghcr.io/github/github-mcp-server:v2.2.0","digest":"sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174","pinned_image":"ghcr.io/github/github-mcp-server:v2.2.0@sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174"}],"mcp_servers":[{"name":"safeoutputs","tools":["add_comment","add_labels","noop","remove_labels","report_incomplete","report_missing_data","report_missing_tool"]}],"threat_detection":{"mode":"enabled"},"admission":false,"agent_metadata":{"14ba41178a91b10b7de6":{"name":"Agentic Workflows"}}}
|
# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_DEFAULT_OTLP_ENDPOINT","GH_AW_DEFAULT_OTLP_HEADERS","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"3d3c42e5aac5ba805825da76410c181273ba90b1","version":"v7.0.1"},{"repo":"actions/download-artifact","sha":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"github/gh-aw-actions/setup","sha":"6147e7c2fba711fb36ac73c79cba401d1e213c4e","version":"v1.4.4"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca"},{"image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7"},{"image":"ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.5.16","digest":"sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f","pinned_image":"ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f"},{"image":"ghcr.io/github/github-mcp-server:v2.3.0","digest":"sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6","pinned_image":"ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6"}],"mcp_servers":[{"name":"safeoutputs","tools":["add_comment","add_labels","noop","remove_labels","report_incomplete","report_missing_data","report_missing_tool"]}],"threat_detection":{"mode":"enabled"},"admission":false,"agent_metadata":{"14ba41178a91b10b7de6":{"name":"Agentic Workflows"}}}
|
||||||
# This file was automatically generated by gh-aw (v1.4.2). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md
|
# This file was automatically generated by gh-aw (v1.4.4). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md
|
||||||
#
|
#
|
||||||
# ___ _ _
|
# ___ _ _
|
||||||
# / _ \ | | (_)
|
# / _ \ | | (_)
|
||||||
@@ -44,12 +44,12 @@
|
|||||||
# - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
# - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||||
# - actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
# - actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||||
# - actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
# - actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||||
# - github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2
|
# - github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4
|
||||||
#
|
#
|
||||||
# Container images used:
|
# Container images used:
|
||||||
# - ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059
|
# - ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059
|
||||||
# - ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc
|
# - ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f
|
||||||
# - ghcr.io/github/github-mcp-server:v2.2.0@sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174
|
# - ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6
|
||||||
# - ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad
|
# - ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad
|
||||||
# - ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca
|
# - ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca
|
||||||
# - ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7
|
# - ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7
|
||||||
@@ -130,7 +130,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Setup Scripts
|
- name: Setup Scripts
|
||||||
id: setup
|
id: setup
|
||||||
uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2
|
uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4
|
||||||
with:
|
with:
|
||||||
destination: ${{ runner.temp }}/gh-aw/actions
|
destination: ${{ runner.temp }}/gh-aw/actions
|
||||||
job-name: ${{ github.job }}
|
job-name: ${{ github.job }}
|
||||||
@@ -152,7 +152,7 @@ jobs:
|
|||||||
GH_AW_INFO_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'auto' }}
|
GH_AW_INFO_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'auto' }}
|
||||||
GH_AW_INFO_VERSION: "1.0.103"
|
GH_AW_INFO_VERSION: "1.0.103"
|
||||||
GH_AW_INFO_AGENT_VERSION: "1.0.103"
|
GH_AW_INFO_AGENT_VERSION: "1.0.103"
|
||||||
GH_AW_INFO_CLI_VERSION: "v1.4.2"
|
GH_AW_INFO_CLI_VERSION: "v1.4.4"
|
||||||
GH_AW_INFO_WORKFLOW_NAME: "PR AI Slop Review"
|
GH_AW_INFO_WORKFLOW_NAME: "PR AI Slop Review"
|
||||||
GH_AW_INFO_WORKFLOW_ID: ${{ job.workflow_ref }}
|
GH_AW_INFO_WORKFLOW_ID: ${{ job.workflow_ref }}
|
||||||
GH_AW_INFO_WORKFLOW_SHA: ${{ job.workflow_sha }}
|
GH_AW_INFO_WORKFLOW_SHA: ${{ job.workflow_sha }}
|
||||||
@@ -271,7 +271,7 @@ jobs:
|
|||||||
if: steps.daily-ai-credits-workflow-guardrail.outputs.daily_ai_credits_guardrail_status != 'quota_blocked'
|
if: steps.daily-ai-credits-workflow-guardrail.outputs.daily_ai_credits_guardrail_status != 'quota_blocked'
|
||||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||||
env:
|
env:
|
||||||
GH_AW_COMPILED_VERSION: "v1.4.2"
|
GH_AW_COMPILED_VERSION: "v1.4.4"
|
||||||
GH_AW_HAS_SAFE_OUTPUTS: "true"
|
GH_AW_HAS_SAFE_OUTPUTS: "true"
|
||||||
GH_AW_BLOCKED_VERSION_REPORT_AS_ISSUE: "false"
|
GH_AW_BLOCKED_VERSION_REPORT_AS_ISSUE: "false"
|
||||||
GH_AW_WORKFLOW_NAME: "PR AI Slop Review"
|
GH_AW_WORKFLOW_NAME: "PR AI Slop Review"
|
||||||
@@ -558,7 +558,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Setup Scripts
|
- name: Setup Scripts
|
||||||
id: setup
|
id: setup
|
||||||
uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2
|
uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4
|
||||||
with:
|
with:
|
||||||
destination: ${{ runner.temp }}/gh-aw/actions
|
destination: ${{ runner.temp }}/gh-aw/actions
|
||||||
job-name: ${{ github.job }}
|
job-name: ${{ github.job }}
|
||||||
@@ -654,7 +654,7 @@ jobs:
|
|||||||
run: "node <<'NODE'\nconst fs = require('fs');\nconst harnessPath = `${process.env.RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs`;\nconst harness = fs.readFileSync(harnessPath, 'utf8');\nconst quotaBranch = [\n ' if (isQuotaExceeded && (result.retryAfterMs == null || /\\\\bquota exceeded\\\\b/i.test(result.output))) {',\n ' log(`attempt ${attempt + 1}: Copilot quota exceeded — not retrying`);',\n ' return { action: \"stop\" };',\n ' }',\n].join('\\n');\nconst nonBlockingQuotaBranch = [\n ' let quotaErrorMsg = null;',\n ' if (isQuotaExceeded && (result.retryAfterMs == null || /\\\\bquota exceeded\\\\b/i.test(result.output))) {',\n ' log(`attempt ${attempt + 1}: Copilot quota exceeded — not retrying`);',\n ' quotaErrorMsg = { action: \"stop\" };',\n ' }',\n ' if (/\\\\b429\\\\b|Too Many Requests/i.test(result.output)) {',\n ' log(`attempt ${attempt + 1}: Copilot quota unavailable — exiting 0`);',\n ' quotaErrorMsg = { action: \"stop\", exitCode: 0 };',\n ' }',\n ' if (quotaErrorMsg) {',\n ' return quotaErrorMsg;',\n ' }',\n].join('\\n');\n\nif (harness.split(quotaBranch).length !== 2) {\n throw new Error('Unexpected Copilot quota branch; re-audit the gh-aw upgrade');\n}\nfs.writeFileSync(harnessPath, harness.replace(quotaBranch, nonBlockingQuotaBranch));\nNODE"
|
run: "node <<'NODE'\nconst fs = require('fs');\nconst harnessPath = `${process.env.RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs`;\nconst harness = fs.readFileSync(harnessPath, 'utf8');\nconst quotaBranch = [\n ' if (isQuotaExceeded && (result.retryAfterMs == null || /\\\\bquota exceeded\\\\b/i.test(result.output))) {',\n ' log(`attempt ${attempt + 1}: Copilot quota exceeded — not retrying`);',\n ' return { action: \"stop\" };',\n ' }',\n].join('\\n');\nconst nonBlockingQuotaBranch = [\n ' let quotaErrorMsg = null;',\n ' if (isQuotaExceeded && (result.retryAfterMs == null || /\\\\bquota exceeded\\\\b/i.test(result.output))) {',\n ' log(`attempt ${attempt + 1}: Copilot quota exceeded — not retrying`);',\n ' quotaErrorMsg = { action: \"stop\" };',\n ' }',\n ' if (/\\\\b429\\\\b|Too Many Requests/i.test(result.output)) {',\n ' log(`attempt ${attempt + 1}: Copilot quota unavailable — exiting 0`);',\n ' quotaErrorMsg = { action: \"stop\", exitCode: 0 };',\n ' }',\n ' if (quotaErrorMsg) {',\n ' return quotaErrorMsg;',\n ' }',\n].join('\\n');\n\nif (harness.split(quotaBranch).length !== 2) {\n throw new Error('Unexpected Copilot quota branch; re-audit the gh-aw upgrade');\n}\nfs.writeFileSync(harnessPath, harness.replace(quotaBranch, nonBlockingQuotaBranch));\nNODE"
|
||||||
|
|
||||||
- name: Download container images
|
- name: Download container images
|
||||||
run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059 ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc ghcr.io/github/github-mcp-server:v2.2.0@sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174 ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7 ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882
|
run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059 ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6 ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7 ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882
|
||||||
- name: Prepare Safe Outputs Directories
|
- name: Prepare Safe Outputs Directories
|
||||||
run: |
|
run: |
|
||||||
mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs"
|
mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs"
|
||||||
@@ -899,12 +899,12 @@ jobs:
|
|||||||
|
|
||||||
mkdir -p "$HOME/.copilot"
|
mkdir -p "$HOME/.copilot"
|
||||||
GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node)
|
GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node)
|
||||||
cat << GH_AW_MCP_CONFIG_d448207cb151e2cb_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs"
|
cat << GH_AW_MCP_CONFIG_36d6009112b7e687_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs"
|
||||||
{
|
{
|
||||||
"mcpServers": {
|
"mcpServers": {
|
||||||
"safeoutputs": {
|
"safeoutputs": {
|
||||||
"type": "stdio",
|
"type": "stdio",
|
||||||
"container": "ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc",
|
"container": "ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f",
|
||||||
"mounts": ["\${GITHUB_WORKSPACE}:\${GITHUB_WORKSPACE}:rw", "${RUNNER_TEMP}/gh-aw/safeoutputs:${RUNNER_TEMP}/gh-aw/safeoutputs:rw", "/tmp/gh-aw:/tmp/gh-aw:rw"],
|
"mounts": ["\${GITHUB_WORKSPACE}:\${GITHUB_WORKSPACE}:rw", "${RUNNER_TEMP}/gh-aw/safeoutputs:${RUNNER_TEMP}/gh-aw/safeoutputs:rw", "/tmp/gh-aw:/tmp/gh-aw:rw"],
|
||||||
"args": ["-w", "\${GITHUB_WORKSPACE}"],
|
"args": ["-w", "\${GITHUB_WORKSPACE}"],
|
||||||
"entrypoint": "sh",
|
"entrypoint": "sh",
|
||||||
@@ -963,7 +963,7 @@ jobs:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
GH_AW_MCP_CONFIG_d448207cb151e2cb_EOF
|
GH_AW_MCP_CONFIG_36d6009112b7e687_EOF
|
||||||
- name: Mount MCP servers as CLIs
|
- name: Mount MCP servers as CLIs
|
||||||
id: mount-mcp-clis
|
id: mount-mcp-clis
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
@@ -1104,7 +1104,7 @@ jobs:
|
|||||||
GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt
|
GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt
|
||||||
GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }}
|
GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }}
|
||||||
GH_AW_TIMEOUT_MINUTES: ${{ fromJSON(vars.GH_AW_DEFAULT_TIMEOUT_MINUTES || '20') }}
|
GH_AW_TIMEOUT_MINUTES: ${{ fromJSON(vars.GH_AW_DEFAULT_TIMEOUT_MINUTES || '20') }}
|
||||||
GH_AW_VERSION: v1.4.2
|
GH_AW_VERSION: v1.4.4
|
||||||
GH_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN || github.token }}
|
GH_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN || github.token }}
|
||||||
GITHUB_API_URL: ${{ github.api_url }}
|
GITHUB_API_URL: ${{ github.api_url }}
|
||||||
GITHUB_AW: true
|
GITHUB_AW: true
|
||||||
@@ -1417,7 +1417,7 @@ jobs:
|
|||||||
permissions:
|
permissions:
|
||||||
actions: read # Read workflow runs and artifacts for workflow context.
|
actions: read # Read workflow runs and artifacts for workflow context.
|
||||||
id-token: write # Request an OIDC token for authenticated services.
|
id-token: write # Request an OIDC token for authenticated services.
|
||||||
issues: write # Create or update issues and comments.
|
issues: write # Enabled by issue reporting, safe outputs, steering, work queues, reaction cleanup, or explicit job permissions.
|
||||||
pull-requests: write # Create or update pull requests and review comments.
|
pull-requests: write # Create or update pull requests and review comments.
|
||||||
concurrency:
|
concurrency:
|
||||||
group: "gh-aw-conclusion-pr-ai-slop-review-${{ inputs.pr_number }}"
|
group: "gh-aw-conclusion-pr-ai-slop-review-${{ inputs.pr_number }}"
|
||||||
@@ -1437,7 +1437,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Setup Scripts
|
- name: Setup Scripts
|
||||||
id: setup
|
id: setup
|
||||||
uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2
|
uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4
|
||||||
with:
|
with:
|
||||||
destination: ${{ runner.temp }}/gh-aw/actions
|
destination: ${{ runner.temp }}/gh-aw/actions
|
||||||
job-name: ${{ github.job }}
|
job-name: ${{ github.job }}
|
||||||
@@ -1816,7 +1816,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Setup Scripts
|
- name: Setup Scripts
|
||||||
id: setup
|
id: setup
|
||||||
uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2
|
uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4
|
||||||
with:
|
with:
|
||||||
destination: ${{ runner.temp }}/gh-aw/actions
|
destination: ${{ runner.temp }}/gh-aw/actions
|
||||||
job-name: ${{ github.job }}
|
job-name: ${{ github.job }}
|
||||||
@@ -1830,11 +1830,12 @@ jobs:
|
|||||||
GH_AW_INFO_ENGINE_ID: "copilot"
|
GH_AW_INFO_ENGINE_ID: "copilot"
|
||||||
GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }}
|
GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }}
|
||||||
- name: Download activation artifact
|
- name: Download activation artifact
|
||||||
|
id: download-detection-activation
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||||
with:
|
with:
|
||||||
name: activation
|
name: activation
|
||||||
path: /tmp/gh-aw
|
path: ${{ runner.temp }}/gh-aw-detection-activation
|
||||||
- name: Download agent output artifact
|
- name: Download agent output artifact
|
||||||
id: download-agent-output
|
id: download-agent-output
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
@@ -1855,6 +1856,10 @@ jobs:
|
|||||||
- name: Clear agent token usage
|
- name: Clear agent token usage
|
||||||
if: always()
|
if: always()
|
||||||
run: rm -f /tmp/gh-aw/agent_usage.json
|
run: rm -f /tmp/gh-aw/agent_usage.json
|
||||||
|
- name: Restore activation metadata
|
||||||
|
if: always()
|
||||||
|
run: |
|
||||||
|
bash "${RUNNER_TEMP}/gh-aw/actions/restore_detection_activation_metadata.sh" "${RUNNER_TEMP}/gh-aw-detection-activation" "/tmp/gh-aw"
|
||||||
- name: Checkout repository for patch context
|
- name: Checkout repository for patch context
|
||||||
if: needs.agent.outputs.has_patch == 'true'
|
if: needs.agent.outputs.has_patch == 'true'
|
||||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||||
@@ -1903,8 +1908,10 @@ jobs:
|
|||||||
- name: Prepare threat detection files
|
- name: Prepare threat detection files
|
||||||
id: detection_prepare
|
id: detection_prepare
|
||||||
if: always() && steps.detection_guard.outputs.run_detection == 'true'
|
if: always() && steps.detection_guard.outputs.run_detection == 'true'
|
||||||
|
env:
|
||||||
|
ACTIVATION_DOWNLOAD_OUTCOME: ${{ steps.download-detection-activation.outcome }}
|
||||||
run: |
|
run: |
|
||||||
bash "${RUNNER_TEMP}/gh-aw/actions/prepare_threat_detection_files.sh"
|
bash "${RUNNER_TEMP}/gh-aw/actions/prepare_detection_inputs.sh" "${RUNNER_TEMP}/gh-aw-detection-activation" "/tmp/gh-aw"
|
||||||
- name: Install AWF binary
|
- name: Install AWF binary
|
||||||
id: detection_awf_install
|
id: detection_awf_install
|
||||||
run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.29.22 --rootless
|
run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.29.22 --rootless
|
||||||
@@ -1921,7 +1928,7 @@ jobs:
|
|||||||
GH_AW_COPILOT_MIN_VERSION: 1.0.35
|
GH_AW_COPILOT_MIN_VERSION: 1.0.35
|
||||||
- name: Execute threat detection with AWF
|
- name: Execute threat detection with AWF
|
||||||
id: detection_agentic_execution
|
id: detection_agentic_execution
|
||||||
if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_staging_reset.outcome == 'success' && steps.detection_prepare.outcome == 'success' && steps.detection_awf_install.outcome == 'success'
|
if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.detection_staging_reset.outcome == 'success' && steps.detection_awf_install.outcome == 'success'
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
timeout-minutes: 10
|
timeout-minutes: 10
|
||||||
env:
|
env:
|
||||||
@@ -1934,11 +1941,11 @@ jobs:
|
|||||||
GH_AW_LLM_PROVIDER: github
|
GH_AW_LLM_PROVIDER: github
|
||||||
GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_DETECTION_MAX_AI_CREDITS || '400' }}
|
GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_DETECTION_MAX_AI_CREDITS || '400' }}
|
||||||
GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }}
|
GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }}
|
||||||
GH_AW_MODEL_FALLBACK: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'auto' }}
|
GH_AW_MODEL_FALLBACK: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'detection' }}
|
||||||
GH_AW_PHASE: detection
|
GH_AW_PHASE: detection
|
||||||
GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt
|
GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt
|
||||||
GH_AW_TIMEOUT_MINUTES: 10
|
GH_AW_TIMEOUT_MINUTES: 10
|
||||||
GH_AW_VERSION: v1.4.2
|
GH_AW_VERSION: v1.4.4
|
||||||
GITHUB_API_URL: ${{ github.api_url }}
|
GITHUB_API_URL: ${{ github.api_url }}
|
||||||
GITHUB_AW: true
|
GITHUB_AW: true
|
||||||
GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows
|
GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows
|
||||||
@@ -2046,7 +2053,7 @@ jobs:
|
|||||||
await main({ additionalDirectories: ["/tmp/gh-aw/threat-detection/sandbox/firewall"], persistDetectionMasks });
|
await main({ additionalDirectories: ["/tmp/gh-aw/threat-detection/sandbox/firewall"], persistDetectionMasks });
|
||||||
- name: Parse threat detection token usage for step summary
|
- name: Parse threat detection token usage for step summary
|
||||||
id: parse_detection_token_usage
|
id: parse_detection_token_usage
|
||||||
if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.redact_detection_logs.outcome == 'success'
|
if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.redact_detection_logs.outcome == 'success'
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||||
env:
|
env:
|
||||||
@@ -2082,7 +2089,7 @@ jobs:
|
|||||||
const { persistDetectionMasks } = require(path.join(actionsDir, 'detection_mask_state.cjs'));
|
const { persistDetectionMasks } = require(path.join(actionsDir, 'detection_mask_state.cjs'));
|
||||||
await main({ additionalDirectories: ["/tmp/gh-aw/threat-detection/sandbox/firewall"], persistDetectionMasks });
|
await main({ additionalDirectories: ["/tmp/gh-aw/threat-detection/sandbox/firewall"], persistDetectionMasks });
|
||||||
- name: Render detection log
|
- name: Render detection log
|
||||||
if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success'
|
if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success'
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||||
with:
|
with:
|
||||||
@@ -2094,7 +2101,7 @@ jobs:
|
|||||||
const { main } = require(path.join(actionsDir, 'render_detection_log.cjs'));
|
const { main } = require(path.join(actionsDir, 'render_detection_log.cjs'));
|
||||||
await main();
|
await main();
|
||||||
- name: Upload threat detection artifact
|
- name: Upload threat detection artifact
|
||||||
if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success' && steps.detection_staging_reset.outcome == 'success'
|
if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success' && steps.detection_staging_reset.outcome == 'success'
|
||||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||||
with:
|
with:
|
||||||
name: detection
|
name: detection
|
||||||
@@ -2110,7 +2117,7 @@ jobs:
|
|||||||
retention-days: ${{ vars.GH_AW_DEFAULT_ARTIFACT_RETENTION_DAYS || '0' }}
|
retention-days: ${{ vars.GH_AW_DEFAULT_ARTIFACT_RETENTION_DAYS || '0' }}
|
||||||
- name: Conclude threat detection
|
- name: Conclude threat detection
|
||||||
id: detection_conclusion
|
id: detection_conclusion
|
||||||
if: always() && steps.detection_guard.outputs.run_detection == 'false' || (always() && steps.detection_guard.outputs.run_detection == 'true' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success')
|
if: always() && steps.detection_guard.outputs.run_detection == 'false' || (always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success')
|
||||||
env:
|
env:
|
||||||
RUN_DETECTION: ${{ steps.detection_guard.outputs.run_detection }}
|
RUN_DETECTION: ${{ steps.detection_guard.outputs.run_detection }}
|
||||||
DETECTION_AGENTIC_EXECUTION_OUTCOME: ${{ steps.detection_agentic_execution.outcome }}
|
DETECTION_AGENTIC_EXECUTION_OUTCOME: ${{ steps.detection_agentic_execution.outcome }}
|
||||||
@@ -2182,7 +2189,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Setup Scripts
|
- name: Setup Scripts
|
||||||
id: setup
|
id: setup
|
||||||
uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2
|
uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4
|
||||||
with:
|
with:
|
||||||
destination: ${{ runner.temp }}/gh-aw/actions
|
destination: ${{ runner.temp }}/gh-aw/actions
|
||||||
job-name: ${{ github.job }}
|
job-name: ${{ github.job }}
|
||||||
|
|||||||
Generated
+36
-29
@@ -1,6 +1,6 @@
|
|||||||
# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"d6b72464a3766dd7d74aefe4c7dd982ae7ae2db951f8040f978feca9166adb39","body_hash":"deddd98c5fa425a91487fb5f50dc59ac61ae395bdcd4dff6543f1e8e563a7d73","compiler_version":"v1.4.2","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.103"}}
|
# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"d6b72464a3766dd7d74aefe4c7dd982ae7ae2db951f8040f978feca9166adb39","body_hash":"deddd98c5fa425a91487fb5f50dc59ac61ae395bdcd4dff6543f1e8e563a7d73","compiler_version":"v1.4.4","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.103"}}
|
||||||
# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_DEFAULT_OTLP_ENDPOINT","GH_AW_DEFAULT_OTLP_HEADERS","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"3d3c42e5aac5ba805825da76410c181273ba90b1","version":"v7.0.1"},{"repo":"actions/download-artifact","sha":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"github/gh-aw-actions/setup","sha":"d7852d91d5d1d13e7848771edab8bd1792a08651","version":"v1.4.2"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca"},{"image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7"},{"image":"ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.5.16","digest":"sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc","pinned_image":"ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc"},{"image":"ghcr.io/github/github-mcp-server:v2.2.0","digest":"sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174","pinned_image":"ghcr.io/github/github-mcp-server:v2.2.0@sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174"}],"mcp_servers":[{"name":"safeoutputs","tools":["add_comment","noop","report_incomplete","report_missing_data","report_missing_tool"]}],"threat_detection":{"mode":"enabled"},"admission":false,"agent_metadata":{"14ba41178a91b10b7de6":{"name":"Agentic Workflows"}}}
|
# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_DEFAULT_OTLP_ENDPOINT","GH_AW_DEFAULT_OTLP_HEADERS","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"3d3c42e5aac5ba805825da76410c181273ba90b1","version":"v7.0.1"},{"repo":"actions/download-artifact","sha":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"github/gh-aw-actions/setup","sha":"6147e7c2fba711fb36ac73c79cba401d1e213c4e","version":"v1.4.4"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca"},{"image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7"},{"image":"ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.5.16","digest":"sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f","pinned_image":"ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f"},{"image":"ghcr.io/github/github-mcp-server:v2.3.0","digest":"sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6","pinned_image":"ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6"}],"mcp_servers":[{"name":"safeoutputs","tools":["add_comment","noop","report_incomplete","report_missing_data","report_missing_tool"]}],"threat_detection":{"mode":"enabled"},"admission":false,"agent_metadata":{"14ba41178a91b10b7de6":{"name":"Agentic Workflows"}}}
|
||||||
# This file was automatically generated by gh-aw (v1.4.2). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md
|
# This file was automatically generated by gh-aw (v1.4.4). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md
|
||||||
#
|
#
|
||||||
# ___ _ _
|
# ___ _ _
|
||||||
# / _ \ | | (_)
|
# / _ \ | | (_)
|
||||||
@@ -43,12 +43,12 @@
|
|||||||
# - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
# - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||||
# - actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
# - actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||||
# - actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
# - actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||||
# - github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2
|
# - github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4
|
||||||
#
|
#
|
||||||
# Container images used:
|
# Container images used:
|
||||||
# - ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059
|
# - ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059
|
||||||
# - ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc
|
# - ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f
|
||||||
# - ghcr.io/github/github-mcp-server:v2.2.0@sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174
|
# - ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6
|
||||||
# - ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad
|
# - ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad
|
||||||
# - ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca
|
# - ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca
|
||||||
# - ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7
|
# - ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7
|
||||||
@@ -141,7 +141,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Setup Scripts
|
- name: Setup Scripts
|
||||||
id: setup
|
id: setup
|
||||||
uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2
|
uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4
|
||||||
with:
|
with:
|
||||||
destination: ${{ runner.temp }}/gh-aw/actions
|
destination: ${{ runner.temp }}/gh-aw/actions
|
||||||
job-name: ${{ github.job }}
|
job-name: ${{ github.job }}
|
||||||
@@ -165,7 +165,7 @@ jobs:
|
|||||||
GH_AW_INFO_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'auto' }}
|
GH_AW_INFO_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'auto' }}
|
||||||
GH_AW_INFO_VERSION: "1.0.103"
|
GH_AW_INFO_VERSION: "1.0.103"
|
||||||
GH_AW_INFO_AGENT_VERSION: "1.0.103"
|
GH_AW_INFO_AGENT_VERSION: "1.0.103"
|
||||||
GH_AW_INFO_CLI_VERSION: "v1.4.2"
|
GH_AW_INFO_CLI_VERSION: "v1.4.4"
|
||||||
GH_AW_INFO_WORKFLOW_NAME: "Verify Review Fixes"
|
GH_AW_INFO_WORKFLOW_NAME: "Verify Review Fixes"
|
||||||
GH_AW_INFO_WORKFLOW_ID: ${{ job.workflow_ref }}
|
GH_AW_INFO_WORKFLOW_ID: ${{ job.workflow_ref }}
|
||||||
GH_AW_INFO_WORKFLOW_SHA: ${{ job.workflow_sha }}
|
GH_AW_INFO_WORKFLOW_SHA: ${{ job.workflow_sha }}
|
||||||
@@ -284,7 +284,7 @@ jobs:
|
|||||||
if: steps.daily-ai-credits-workflow-guardrail.outputs.daily_ai_credits_guardrail_status != 'quota_blocked'
|
if: steps.daily-ai-credits-workflow-guardrail.outputs.daily_ai_credits_guardrail_status != 'quota_blocked'
|
||||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||||
env:
|
env:
|
||||||
GH_AW_COMPILED_VERSION: "v1.4.2"
|
GH_AW_COMPILED_VERSION: "v1.4.4"
|
||||||
GH_AW_HAS_SAFE_OUTPUTS: "true"
|
GH_AW_HAS_SAFE_OUTPUTS: "true"
|
||||||
GH_AW_BLOCKED_VERSION_REPORT_AS_ISSUE: "false"
|
GH_AW_BLOCKED_VERSION_REPORT_AS_ISSUE: "false"
|
||||||
GH_AW_WORKFLOW_NAME: "Verify Review Fixes"
|
GH_AW_WORKFLOW_NAME: "Verify Review Fixes"
|
||||||
@@ -596,7 +596,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Setup Scripts
|
- name: Setup Scripts
|
||||||
id: setup
|
id: setup
|
||||||
uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2
|
uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4
|
||||||
with:
|
with:
|
||||||
destination: ${{ runner.temp }}/gh-aw/actions
|
destination: ${{ runner.temp }}/gh-aw/actions
|
||||||
job-name: ${{ github.job }}
|
job-name: ${{ github.job }}
|
||||||
@@ -693,7 +693,7 @@ jobs:
|
|||||||
GH_AW_SKILL_DIR: ".github/skills"
|
GH_AW_SKILL_DIR: ".github/skills"
|
||||||
run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh"
|
run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh"
|
||||||
- name: Download container images
|
- name: Download container images
|
||||||
run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059 ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc ghcr.io/github/github-mcp-server:v2.2.0@sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174 ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7 ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882
|
run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059 ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6 ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7 ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882
|
||||||
- name: Prepare Safe Outputs Directories
|
- name: Prepare Safe Outputs Directories
|
||||||
run: |
|
run: |
|
||||||
mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs"
|
mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs"
|
||||||
@@ -902,12 +902,12 @@ jobs:
|
|||||||
|
|
||||||
mkdir -p "$HOME/.copilot"
|
mkdir -p "$HOME/.copilot"
|
||||||
GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node)
|
GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node)
|
||||||
cat << GH_AW_MCP_CONFIG_e9f853f8279889ed_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs"
|
cat << GH_AW_MCP_CONFIG_060492a5ed2a5139_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs"
|
||||||
{
|
{
|
||||||
"mcpServers": {
|
"mcpServers": {
|
||||||
"safeoutputs": {
|
"safeoutputs": {
|
||||||
"type": "stdio",
|
"type": "stdio",
|
||||||
"container": "ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc",
|
"container": "ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f",
|
||||||
"mounts": ["\${GITHUB_WORKSPACE}:\${GITHUB_WORKSPACE}:rw", "${RUNNER_TEMP}/gh-aw/safeoutputs:${RUNNER_TEMP}/gh-aw/safeoutputs:rw", "/tmp/gh-aw:/tmp/gh-aw:rw"],
|
"mounts": ["\${GITHUB_WORKSPACE}:\${GITHUB_WORKSPACE}:rw", "${RUNNER_TEMP}/gh-aw/safeoutputs:${RUNNER_TEMP}/gh-aw/safeoutputs:rw", "/tmp/gh-aw:/tmp/gh-aw:rw"],
|
||||||
"args": ["-w", "\${GITHUB_WORKSPACE}"],
|
"args": ["-w", "\${GITHUB_WORKSPACE}"],
|
||||||
"entrypoint": "sh",
|
"entrypoint": "sh",
|
||||||
@@ -965,7 +965,7 @@ jobs:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
GH_AW_MCP_CONFIG_e9f853f8279889ed_EOF
|
GH_AW_MCP_CONFIG_060492a5ed2a5139_EOF
|
||||||
- name: Mount MCP servers as CLIs
|
- name: Mount MCP servers as CLIs
|
||||||
id: mount-mcp-clis
|
id: mount-mcp-clis
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
@@ -1105,7 +1105,7 @@ jobs:
|
|||||||
GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt
|
GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt
|
||||||
GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }}
|
GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }}
|
||||||
GH_AW_TIMEOUT_MINUTES: ${{ fromJSON(vars.GH_AW_DEFAULT_TIMEOUT_MINUTES || '20') }}
|
GH_AW_TIMEOUT_MINUTES: ${{ fromJSON(vars.GH_AW_DEFAULT_TIMEOUT_MINUTES || '20') }}
|
||||||
GH_AW_VERSION: v1.4.2
|
GH_AW_VERSION: v1.4.4
|
||||||
GH_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN || github.token }}
|
GH_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN || github.token }}
|
||||||
GITHUB_API_URL: ${{ github.api_url }}
|
GITHUB_API_URL: ${{ github.api_url }}
|
||||||
GITHUB_AW: true
|
GITHUB_AW: true
|
||||||
@@ -1419,7 +1419,7 @@ jobs:
|
|||||||
permissions:
|
permissions:
|
||||||
actions: read # Read workflow runs and artifacts for workflow context.
|
actions: read # Read workflow runs and artifacts for workflow context.
|
||||||
id-token: write # Request an OIDC token for authenticated services.
|
id-token: write # Request an OIDC token for authenticated services.
|
||||||
issues: write # Create or update issues and comments.
|
issues: write # Enabled by issue reporting, safe outputs, steering, work queues, reaction cleanup, or explicit job permissions.
|
||||||
pull-requests: write # Create or update pull requests and review comments.
|
pull-requests: write # Create or update pull requests and review comments.
|
||||||
concurrency:
|
concurrency:
|
||||||
group: "gh-aw-conclusion-pr-verify-fix-${{ github.event.issue.number || inputs.pr_number || github.run_id }}"
|
group: "gh-aw-conclusion-pr-verify-fix-${{ github.event.issue.number || inputs.pr_number || github.run_id }}"
|
||||||
@@ -1439,7 +1439,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Setup Scripts
|
- name: Setup Scripts
|
||||||
id: setup
|
id: setup
|
||||||
uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2
|
uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4
|
||||||
with:
|
with:
|
||||||
destination: ${{ runner.temp }}/gh-aw/actions
|
destination: ${{ runner.temp }}/gh-aw/actions
|
||||||
job-name: ${{ github.job }}
|
job-name: ${{ github.job }}
|
||||||
@@ -1818,7 +1818,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Setup Scripts
|
- name: Setup Scripts
|
||||||
id: setup
|
id: setup
|
||||||
uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2
|
uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4
|
||||||
with:
|
with:
|
||||||
destination: ${{ runner.temp }}/gh-aw/actions
|
destination: ${{ runner.temp }}/gh-aw/actions
|
||||||
job-name: ${{ github.job }}
|
job-name: ${{ github.job }}
|
||||||
@@ -1832,11 +1832,12 @@ jobs:
|
|||||||
GH_AW_INFO_ENGINE_ID: "copilot"
|
GH_AW_INFO_ENGINE_ID: "copilot"
|
||||||
GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }}
|
GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }}
|
||||||
- name: Download activation artifact
|
- name: Download activation artifact
|
||||||
|
id: download-detection-activation
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||||
with:
|
with:
|
||||||
name: activation
|
name: activation
|
||||||
path: /tmp/gh-aw
|
path: ${{ runner.temp }}/gh-aw-detection-activation
|
||||||
- name: Download agent output artifact
|
- name: Download agent output artifact
|
||||||
id: download-agent-output
|
id: download-agent-output
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
@@ -1857,6 +1858,10 @@ jobs:
|
|||||||
- name: Clear agent token usage
|
- name: Clear agent token usage
|
||||||
if: always()
|
if: always()
|
||||||
run: rm -f /tmp/gh-aw/agent_usage.json
|
run: rm -f /tmp/gh-aw/agent_usage.json
|
||||||
|
- name: Restore activation metadata
|
||||||
|
if: always()
|
||||||
|
run: |
|
||||||
|
bash "${RUNNER_TEMP}/gh-aw/actions/restore_detection_activation_metadata.sh" "${RUNNER_TEMP}/gh-aw-detection-activation" "/tmp/gh-aw"
|
||||||
- name: Checkout repository for patch context
|
- name: Checkout repository for patch context
|
||||||
if: needs.agent.outputs.has_patch == 'true'
|
if: needs.agent.outputs.has_patch == 'true'
|
||||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||||
@@ -1905,8 +1910,10 @@ jobs:
|
|||||||
- name: Prepare threat detection files
|
- name: Prepare threat detection files
|
||||||
id: detection_prepare
|
id: detection_prepare
|
||||||
if: always() && steps.detection_guard.outputs.run_detection == 'true'
|
if: always() && steps.detection_guard.outputs.run_detection == 'true'
|
||||||
|
env:
|
||||||
|
ACTIVATION_DOWNLOAD_OUTCOME: ${{ steps.download-detection-activation.outcome }}
|
||||||
run: |
|
run: |
|
||||||
bash "${RUNNER_TEMP}/gh-aw/actions/prepare_threat_detection_files.sh"
|
bash "${RUNNER_TEMP}/gh-aw/actions/prepare_detection_inputs.sh" "${RUNNER_TEMP}/gh-aw-detection-activation" "/tmp/gh-aw"
|
||||||
- name: Install AWF binary
|
- name: Install AWF binary
|
||||||
id: detection_awf_install
|
id: detection_awf_install
|
||||||
run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.29.22 --rootless
|
run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.29.22 --rootless
|
||||||
@@ -1923,7 +1930,7 @@ jobs:
|
|||||||
GH_AW_COPILOT_MIN_VERSION: 1.0.35
|
GH_AW_COPILOT_MIN_VERSION: 1.0.35
|
||||||
- name: Execute threat detection with AWF
|
- name: Execute threat detection with AWF
|
||||||
id: detection_agentic_execution
|
id: detection_agentic_execution
|
||||||
if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_staging_reset.outcome == 'success' && steps.detection_prepare.outcome == 'success' && steps.detection_awf_install.outcome == 'success'
|
if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.detection_staging_reset.outcome == 'success' && steps.detection_awf_install.outcome == 'success'
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
timeout-minutes: 10
|
timeout-minutes: 10
|
||||||
env:
|
env:
|
||||||
@@ -1936,11 +1943,11 @@ jobs:
|
|||||||
GH_AW_LLM_PROVIDER: github
|
GH_AW_LLM_PROVIDER: github
|
||||||
GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_DETECTION_MAX_AI_CREDITS || '400' }}
|
GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_DETECTION_MAX_AI_CREDITS || '400' }}
|
||||||
GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }}
|
GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }}
|
||||||
GH_AW_MODEL_FALLBACK: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'auto' }}
|
GH_AW_MODEL_FALLBACK: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'detection' }}
|
||||||
GH_AW_PHASE: detection
|
GH_AW_PHASE: detection
|
||||||
GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt
|
GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt
|
||||||
GH_AW_TIMEOUT_MINUTES: 10
|
GH_AW_TIMEOUT_MINUTES: 10
|
||||||
GH_AW_VERSION: v1.4.2
|
GH_AW_VERSION: v1.4.4
|
||||||
GITHUB_API_URL: ${{ github.api_url }}
|
GITHUB_API_URL: ${{ github.api_url }}
|
||||||
GITHUB_AW: true
|
GITHUB_AW: true
|
||||||
GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows
|
GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows
|
||||||
@@ -2048,7 +2055,7 @@ jobs:
|
|||||||
await main({ additionalDirectories: ["/tmp/gh-aw/threat-detection/sandbox/firewall"], persistDetectionMasks });
|
await main({ additionalDirectories: ["/tmp/gh-aw/threat-detection/sandbox/firewall"], persistDetectionMasks });
|
||||||
- name: Parse threat detection token usage for step summary
|
- name: Parse threat detection token usage for step summary
|
||||||
id: parse_detection_token_usage
|
id: parse_detection_token_usage
|
||||||
if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.redact_detection_logs.outcome == 'success'
|
if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.redact_detection_logs.outcome == 'success'
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||||
env:
|
env:
|
||||||
@@ -2084,7 +2091,7 @@ jobs:
|
|||||||
const { persistDetectionMasks } = require(path.join(actionsDir, 'detection_mask_state.cjs'));
|
const { persistDetectionMasks } = require(path.join(actionsDir, 'detection_mask_state.cjs'));
|
||||||
await main({ additionalDirectories: ["/tmp/gh-aw/threat-detection/sandbox/firewall"], persistDetectionMasks });
|
await main({ additionalDirectories: ["/tmp/gh-aw/threat-detection/sandbox/firewall"], persistDetectionMasks });
|
||||||
- name: Render detection log
|
- name: Render detection log
|
||||||
if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success'
|
if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success'
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||||
with:
|
with:
|
||||||
@@ -2096,7 +2103,7 @@ jobs:
|
|||||||
const { main } = require(path.join(actionsDir, 'render_detection_log.cjs'));
|
const { main } = require(path.join(actionsDir, 'render_detection_log.cjs'));
|
||||||
await main();
|
await main();
|
||||||
- name: Upload threat detection artifact
|
- name: Upload threat detection artifact
|
||||||
if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success' && steps.detection_staging_reset.outcome == 'success'
|
if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success' && steps.detection_staging_reset.outcome == 'success'
|
||||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||||
with:
|
with:
|
||||||
name: detection
|
name: detection
|
||||||
@@ -2112,7 +2119,7 @@ jobs:
|
|||||||
retention-days: ${{ vars.GH_AW_DEFAULT_ARTIFACT_RETENTION_DAYS || '0' }}
|
retention-days: ${{ vars.GH_AW_DEFAULT_ARTIFACT_RETENTION_DAYS || '0' }}
|
||||||
- name: Conclude threat detection
|
- name: Conclude threat detection
|
||||||
id: detection_conclusion
|
id: detection_conclusion
|
||||||
if: always() && steps.detection_guard.outputs.run_detection == 'false' || (always() && steps.detection_guard.outputs.run_detection == 'true' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success')
|
if: always() && steps.detection_guard.outputs.run_detection == 'false' || (always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success')
|
||||||
env:
|
env:
|
||||||
RUN_DETECTION: ${{ steps.detection_guard.outputs.run_detection }}
|
RUN_DETECTION: ${{ steps.detection_guard.outputs.run_detection }}
|
||||||
DETECTION_AGENTIC_EXECUTION_OUTCOME: ${{ steps.detection_agentic_execution.outcome }}
|
DETECTION_AGENTIC_EXECUTION_OUTCOME: ${{ steps.detection_agentic_execution.outcome }}
|
||||||
@@ -2145,7 +2152,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Setup Scripts
|
- name: Setup Scripts
|
||||||
id: setup
|
id: setup
|
||||||
uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2
|
uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4
|
||||||
with:
|
with:
|
||||||
destination: ${{ runner.temp }}/gh-aw/actions
|
destination: ${{ runner.temp }}/gh-aw/actions
|
||||||
job-name: ${{ github.job }}
|
job-name: ${{ github.job }}
|
||||||
@@ -2240,7 +2247,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Setup Scripts
|
- name: Setup Scripts
|
||||||
id: setup
|
id: setup
|
||||||
uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2
|
uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4
|
||||||
with:
|
with:
|
||||||
destination: ${{ runner.temp }}/gh-aw/actions
|
destination: ${{ runner.temp }}/gh-aw/actions
|
||||||
job-name: ${{ github.job }}
|
job-name: ${{ github.job }}
|
||||||
|
|||||||
+35
-28
@@ -1,6 +1,6 @@
|
|||||||
# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"e44852fbf56eab99e67b3f6a306f75195603ece6ed130e55652a2467efed1415","body_hash":"7835f25016082d56592b67f4d2bf5b839eb02a6fa8f03d65699ed6bae979c5ad","compiler_version":"v1.4.2","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.103"}}
|
# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"e44852fbf56eab99e67b3f6a306f75195603ece6ed130e55652a2467efed1415","body_hash":"7835f25016082d56592b67f4d2bf5b839eb02a6fa8f03d65699ed6bae979c5ad","compiler_version":"v1.4.4","strict":true,"agent_id":"copilot","engine_versions":{"copilot":"1.0.103"}}
|
||||||
# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_DEFAULT_OTLP_ENDPOINT","GH_AW_DEFAULT_OTLP_HEADERS","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"3d3c42e5aac5ba805825da76410c181273ba90b1","version":"v7.0.1"},{"repo":"actions/download-artifact","sha":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"github/gh-aw-actions/setup","sha":"d7852d91d5d1d13e7848771edab8bd1792a08651","version":"v1.4.2"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca"},{"image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7"},{"image":"ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.5.16","digest":"sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc","pinned_image":"ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc"},{"image":"ghcr.io/github/github-mcp-server:v2.2.0","digest":"sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174","pinned_image":"ghcr.io/github/github-mcp-server:v2.2.0@sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174"}],"mcp_servers":[{"name":"safeoutputs","tools":["add_comment","noop","report_incomplete","report_missing_data","report_missing_tool"]}],"threat_detection":{"mode":"enabled"},"admission":false,"agent_metadata":{"14ba41178a91b10b7de6":{"name":"Agentic Workflows"}}}
|
# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_DEFAULT_OTLP_ENDPOINT","GH_AW_DEFAULT_OTLP_HEADERS","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"3d3c42e5aac5ba805825da76410c181273ba90b1","version":"v7.0.1"},{"repo":"actions/download-artifact","sha":"9000827ccba6bdab643e8b6fd33ac0654aef8333","version":"v8.0.2"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"949feb2413d6458794dcd2491c4babbbce0c15c1","version":"v7.1.0"},{"repo":"actions/upload-artifact","sha":"cf430e030ddbb5b0abf93d22962f4752f3646cd9","version":"v7.0.2"},{"repo":"github/gh-aw-actions/setup","sha":"6147e7c2fba711fb36ac73c79cba401d1e213c4e","version":"v1.4.4"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca"},{"image":"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7"},{"image":"ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.5.16","digest":"sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f","pinned_image":"ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f"},{"image":"ghcr.io/github/github-mcp-server:v2.3.0","digest":"sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6","pinned_image":"ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6"}],"mcp_servers":[{"name":"safeoutputs","tools":["add_comment","noop","report_incomplete","report_missing_data","report_missing_tool"]}],"threat_detection":{"mode":"enabled"},"admission":false,"agent_metadata":{"14ba41178a91b10b7de6":{"name":"Agentic Workflows"}}}
|
||||||
# This file was automatically generated by gh-aw (v1.4.2). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md
|
# This file was automatically generated by gh-aw (v1.4.4). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md
|
||||||
#
|
#
|
||||||
# ___ _ _
|
# ___ _ _
|
||||||
# / _ \ | | (_)
|
# / _ \ | | (_)
|
||||||
@@ -43,12 +43,12 @@
|
|||||||
# - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
# - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||||
# - actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
# - actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||||
# - actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
# - actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||||
# - github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2
|
# - github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4
|
||||||
#
|
#
|
||||||
# Container images used:
|
# Container images used:
|
||||||
# - ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059
|
# - ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059
|
||||||
# - ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc
|
# - ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f
|
||||||
# - ghcr.io/github/github-mcp-server:v2.2.0@sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174
|
# - ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6
|
||||||
# - ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad
|
# - ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad
|
||||||
# - ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca
|
# - ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca
|
||||||
# - ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7
|
# - ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7
|
||||||
@@ -133,7 +133,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Setup Scripts
|
- name: Setup Scripts
|
||||||
id: setup
|
id: setup
|
||||||
uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2
|
uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4
|
||||||
with:
|
with:
|
||||||
destination: ${{ runner.temp }}/gh-aw/actions
|
destination: ${{ runner.temp }}/gh-aw/actions
|
||||||
job-name: ${{ github.job }}
|
job-name: ${{ github.job }}
|
||||||
@@ -155,7 +155,7 @@ jobs:
|
|||||||
GH_AW_INFO_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'auto' }}
|
GH_AW_INFO_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'auto' }}
|
||||||
GH_AW_INFO_VERSION: "1.0.103"
|
GH_AW_INFO_VERSION: "1.0.103"
|
||||||
GH_AW_INFO_AGENT_VERSION: "1.0.103"
|
GH_AW_INFO_AGENT_VERSION: "1.0.103"
|
||||||
GH_AW_INFO_CLI_VERSION: "v1.4.2"
|
GH_AW_INFO_CLI_VERSION: "v1.4.4"
|
||||||
GH_AW_INFO_WORKFLOW_NAME: "Renovate Minor Upgrade Analysis"
|
GH_AW_INFO_WORKFLOW_NAME: "Renovate Minor Upgrade Analysis"
|
||||||
GH_AW_INFO_WORKFLOW_ID: ${{ job.workflow_ref }}
|
GH_AW_INFO_WORKFLOW_ID: ${{ job.workflow_ref }}
|
||||||
GH_AW_INFO_WORKFLOW_SHA: ${{ job.workflow_sha }}
|
GH_AW_INFO_WORKFLOW_SHA: ${{ job.workflow_sha }}
|
||||||
@@ -274,7 +274,7 @@ jobs:
|
|||||||
if: steps.daily-ai-credits-workflow-guardrail.outputs.daily_ai_credits_guardrail_status != 'quota_blocked'
|
if: steps.daily-ai-credits-workflow-guardrail.outputs.daily_ai_credits_guardrail_status != 'quota_blocked'
|
||||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||||
env:
|
env:
|
||||||
GH_AW_COMPILED_VERSION: "v1.4.2"
|
GH_AW_COMPILED_VERSION: "v1.4.4"
|
||||||
GH_AW_HAS_SAFE_OUTPUTS: "true"
|
GH_AW_HAS_SAFE_OUTPUTS: "true"
|
||||||
GH_AW_BLOCKED_VERSION_REPORT_AS_ISSUE: "false"
|
GH_AW_BLOCKED_VERSION_REPORT_AS_ISSUE: "false"
|
||||||
GH_AW_WORKFLOW_NAME: "Renovate Minor Upgrade Analysis"
|
GH_AW_WORKFLOW_NAME: "Renovate Minor Upgrade Analysis"
|
||||||
@@ -562,7 +562,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Setup Scripts
|
- name: Setup Scripts
|
||||||
id: setup
|
id: setup
|
||||||
uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2
|
uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4
|
||||||
with:
|
with:
|
||||||
destination: ${{ runner.temp }}/gh-aw/actions
|
destination: ${{ runner.temp }}/gh-aw/actions
|
||||||
job-name: ${{ github.job }}
|
job-name: ${{ github.job }}
|
||||||
@@ -674,7 +674,7 @@ jobs:
|
|||||||
GH_AW_SKILL_DIR: ".github/skills"
|
GH_AW_SKILL_DIR: ".github/skills"
|
||||||
run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh"
|
run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh"
|
||||||
- name: Download container images
|
- name: Download container images
|
||||||
run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059 ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc ghcr.io/github/github-mcp-server:v2.2.0@sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174 ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7 ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882
|
run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059 ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6 ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7 ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882
|
||||||
- name: Prepare Safe Outputs Directories
|
- name: Prepare Safe Outputs Directories
|
||||||
run: |
|
run: |
|
||||||
mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs"
|
mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs"
|
||||||
@@ -885,12 +885,12 @@ jobs:
|
|||||||
|
|
||||||
mkdir -p "$HOME/.copilot"
|
mkdir -p "$HOME/.copilot"
|
||||||
GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node)
|
GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node)
|
||||||
cat << GH_AW_MCP_CONFIG_d448207cb151e2cb_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs"
|
cat << GH_AW_MCP_CONFIG_36d6009112b7e687_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs"
|
||||||
{
|
{
|
||||||
"mcpServers": {
|
"mcpServers": {
|
||||||
"safeoutputs": {
|
"safeoutputs": {
|
||||||
"type": "stdio",
|
"type": "stdio",
|
||||||
"container": "ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc",
|
"container": "ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f",
|
||||||
"mounts": ["\${GITHUB_WORKSPACE}:\${GITHUB_WORKSPACE}:rw", "${RUNNER_TEMP}/gh-aw/safeoutputs:${RUNNER_TEMP}/gh-aw/safeoutputs:rw", "/tmp/gh-aw:/tmp/gh-aw:rw"],
|
"mounts": ["\${GITHUB_WORKSPACE}:\${GITHUB_WORKSPACE}:rw", "${RUNNER_TEMP}/gh-aw/safeoutputs:${RUNNER_TEMP}/gh-aw/safeoutputs:rw", "/tmp/gh-aw:/tmp/gh-aw:rw"],
|
||||||
"args": ["-w", "\${GITHUB_WORKSPACE}"],
|
"args": ["-w", "\${GITHUB_WORKSPACE}"],
|
||||||
"entrypoint": "sh",
|
"entrypoint": "sh",
|
||||||
@@ -949,7 +949,7 @@ jobs:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
GH_AW_MCP_CONFIG_d448207cb151e2cb_EOF
|
GH_AW_MCP_CONFIG_36d6009112b7e687_EOF
|
||||||
- name: Mount MCP servers as CLIs
|
- name: Mount MCP servers as CLIs
|
||||||
id: mount-mcp-clis
|
id: mount-mcp-clis
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
@@ -1094,7 +1094,7 @@ jobs:
|
|||||||
GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt
|
GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt
|
||||||
GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }}
|
GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }}
|
||||||
GH_AW_TIMEOUT_MINUTES: ${{ fromJSON(vars.GH_AW_DEFAULT_TIMEOUT_MINUTES || '20') }}
|
GH_AW_TIMEOUT_MINUTES: ${{ fromJSON(vars.GH_AW_DEFAULT_TIMEOUT_MINUTES || '20') }}
|
||||||
GH_AW_VERSION: v1.4.2
|
GH_AW_VERSION: v1.4.4
|
||||||
GH_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN || github.token }}
|
GH_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN || github.token }}
|
||||||
GITHUB_API_URL: ${{ github.api_url }}
|
GITHUB_API_URL: ${{ github.api_url }}
|
||||||
GITHUB_AW: true
|
GITHUB_AW: true
|
||||||
@@ -1413,7 +1413,7 @@ jobs:
|
|||||||
permissions:
|
permissions:
|
||||||
actions: read # Read workflow runs and artifacts for workflow context.
|
actions: read # Read workflow runs and artifacts for workflow context.
|
||||||
id-token: write # Request an OIDC token for authenticated services.
|
id-token: write # Request an OIDC token for authenticated services.
|
||||||
issues: write # Create or update issues and comments.
|
issues: write # Enabled by issue reporting, safe outputs, steering, work queues, reaction cleanup, or explicit job permissions.
|
||||||
pull-requests: write # Create or update pull requests and review comments.
|
pull-requests: write # Create or update pull requests and review comments.
|
||||||
concurrency:
|
concurrency:
|
||||||
group: "gh-aw-conclusion-renovate-minor-review-${{ inputs.pr_number }}"
|
group: "gh-aw-conclusion-renovate-minor-review-${{ inputs.pr_number }}"
|
||||||
@@ -1433,7 +1433,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Setup Scripts
|
- name: Setup Scripts
|
||||||
id: setup
|
id: setup
|
||||||
uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2
|
uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4
|
||||||
with:
|
with:
|
||||||
destination: ${{ runner.temp }}/gh-aw/actions
|
destination: ${{ runner.temp }}/gh-aw/actions
|
||||||
job-name: ${{ github.job }}
|
job-name: ${{ github.job }}
|
||||||
@@ -1812,7 +1812,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Setup Scripts
|
- name: Setup Scripts
|
||||||
id: setup
|
id: setup
|
||||||
uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2
|
uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4
|
||||||
with:
|
with:
|
||||||
destination: ${{ runner.temp }}/gh-aw/actions
|
destination: ${{ runner.temp }}/gh-aw/actions
|
||||||
job-name: ${{ github.job }}
|
job-name: ${{ github.job }}
|
||||||
@@ -1826,11 +1826,12 @@ jobs:
|
|||||||
GH_AW_INFO_ENGINE_ID: "copilot"
|
GH_AW_INFO_ENGINE_ID: "copilot"
|
||||||
GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }}
|
GH_AW_SETUP_AW_CONTEXT: ${{ inputs.aw_context }}
|
||||||
- name: Download activation artifact
|
- name: Download activation artifact
|
||||||
|
id: download-detection-activation
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||||
with:
|
with:
|
||||||
name: activation
|
name: activation
|
||||||
path: /tmp/gh-aw
|
path: ${{ runner.temp }}/gh-aw-detection-activation
|
||||||
- name: Download agent output artifact
|
- name: Download agent output artifact
|
||||||
id: download-agent-output
|
id: download-agent-output
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
@@ -1851,6 +1852,10 @@ jobs:
|
|||||||
- name: Clear agent token usage
|
- name: Clear agent token usage
|
||||||
if: always()
|
if: always()
|
||||||
run: rm -f /tmp/gh-aw/agent_usage.json
|
run: rm -f /tmp/gh-aw/agent_usage.json
|
||||||
|
- name: Restore activation metadata
|
||||||
|
if: always()
|
||||||
|
run: |
|
||||||
|
bash "${RUNNER_TEMP}/gh-aw/actions/restore_detection_activation_metadata.sh" "${RUNNER_TEMP}/gh-aw-detection-activation" "/tmp/gh-aw"
|
||||||
- name: Checkout repository for patch context
|
- name: Checkout repository for patch context
|
||||||
if: needs.agent.outputs.has_patch == 'true'
|
if: needs.agent.outputs.has_patch == 'true'
|
||||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||||
@@ -1899,8 +1904,10 @@ jobs:
|
|||||||
- name: Prepare threat detection files
|
- name: Prepare threat detection files
|
||||||
id: detection_prepare
|
id: detection_prepare
|
||||||
if: always() && steps.detection_guard.outputs.run_detection == 'true'
|
if: always() && steps.detection_guard.outputs.run_detection == 'true'
|
||||||
|
env:
|
||||||
|
ACTIVATION_DOWNLOAD_OUTCOME: ${{ steps.download-detection-activation.outcome }}
|
||||||
run: |
|
run: |
|
||||||
bash "${RUNNER_TEMP}/gh-aw/actions/prepare_threat_detection_files.sh"
|
bash "${RUNNER_TEMP}/gh-aw/actions/prepare_detection_inputs.sh" "${RUNNER_TEMP}/gh-aw-detection-activation" "/tmp/gh-aw"
|
||||||
- name: Install AWF binary
|
- name: Install AWF binary
|
||||||
id: detection_awf_install
|
id: detection_awf_install
|
||||||
run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.29.22 --rootless
|
run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.29.22 --rootless
|
||||||
@@ -1917,7 +1924,7 @@ jobs:
|
|||||||
GH_AW_COPILOT_MIN_VERSION: 1.0.35
|
GH_AW_COPILOT_MIN_VERSION: 1.0.35
|
||||||
- name: Execute threat detection with AWF
|
- name: Execute threat detection with AWF
|
||||||
id: detection_agentic_execution
|
id: detection_agentic_execution
|
||||||
if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_staging_reset.outcome == 'success' && steps.detection_prepare.outcome == 'success' && steps.detection_awf_install.outcome == 'success'
|
if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.detection_staging_reset.outcome == 'success' && steps.detection_awf_install.outcome == 'success'
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
timeout-minutes: 10
|
timeout-minutes: 10
|
||||||
env:
|
env:
|
||||||
@@ -1930,11 +1937,11 @@ jobs:
|
|||||||
GH_AW_LLM_PROVIDER: github
|
GH_AW_LLM_PROVIDER: github
|
||||||
GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_DETECTION_MAX_AI_CREDITS || '400' }}
|
GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_DETECTION_MAX_AI_CREDITS || '400' }}
|
||||||
GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }}
|
GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }}
|
||||||
GH_AW_MODEL_FALLBACK: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'auto' }}
|
GH_AW_MODEL_FALLBACK: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'detection' }}
|
||||||
GH_AW_PHASE: detection
|
GH_AW_PHASE: detection
|
||||||
GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt
|
GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt
|
||||||
GH_AW_TIMEOUT_MINUTES: 10
|
GH_AW_TIMEOUT_MINUTES: 10
|
||||||
GH_AW_VERSION: v1.4.2
|
GH_AW_VERSION: v1.4.4
|
||||||
GITHUB_API_URL: ${{ github.api_url }}
|
GITHUB_API_URL: ${{ github.api_url }}
|
||||||
GITHUB_AW: true
|
GITHUB_AW: true
|
||||||
GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows
|
GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows
|
||||||
@@ -2042,7 +2049,7 @@ jobs:
|
|||||||
await main({ additionalDirectories: ["/tmp/gh-aw/threat-detection/sandbox/firewall"], persistDetectionMasks });
|
await main({ additionalDirectories: ["/tmp/gh-aw/threat-detection/sandbox/firewall"], persistDetectionMasks });
|
||||||
- name: Parse threat detection token usage for step summary
|
- name: Parse threat detection token usage for step summary
|
||||||
id: parse_detection_token_usage
|
id: parse_detection_token_usage
|
||||||
if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.redact_detection_logs.outcome == 'success'
|
if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.redact_detection_logs.outcome == 'success'
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||||
env:
|
env:
|
||||||
@@ -2078,7 +2085,7 @@ jobs:
|
|||||||
const { persistDetectionMasks } = require(path.join(actionsDir, 'detection_mask_state.cjs'));
|
const { persistDetectionMasks } = require(path.join(actionsDir, 'detection_mask_state.cjs'));
|
||||||
await main({ additionalDirectories: ["/tmp/gh-aw/threat-detection/sandbox/firewall"], persistDetectionMasks });
|
await main({ additionalDirectories: ["/tmp/gh-aw/threat-detection/sandbox/firewall"], persistDetectionMasks });
|
||||||
- name: Render detection log
|
- name: Render detection log
|
||||||
if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success'
|
if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success'
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||||
with:
|
with:
|
||||||
@@ -2090,7 +2097,7 @@ jobs:
|
|||||||
const { main } = require(path.join(actionsDir, 'render_detection_log.cjs'));
|
const { main } = require(path.join(actionsDir, 'render_detection_log.cjs'));
|
||||||
await main();
|
await main();
|
||||||
- name: Upload threat detection artifact
|
- name: Upload threat detection artifact
|
||||||
if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success' && steps.detection_staging_reset.outcome == 'success'
|
if: always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success' && steps.detection_staging_reset.outcome == 'success'
|
||||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||||
with:
|
with:
|
||||||
name: detection
|
name: detection
|
||||||
@@ -2106,7 +2113,7 @@ jobs:
|
|||||||
retention-days: ${{ vars.GH_AW_DEFAULT_ARTIFACT_RETENTION_DAYS || '0' }}
|
retention-days: ${{ vars.GH_AW_DEFAULT_ARTIFACT_RETENTION_DAYS || '0' }}
|
||||||
- name: Conclude threat detection
|
- name: Conclude threat detection
|
||||||
id: detection_conclusion
|
id: detection_conclusion
|
||||||
if: always() && steps.detection_guard.outputs.run_detection == 'false' || (always() && steps.detection_guard.outputs.run_detection == 'true' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success')
|
if: always() && steps.detection_guard.outputs.run_detection == 'false' || (always() && steps.detection_guard.outputs.run_detection == 'true' && steps.detection_prepare.outcome == 'success' && steps.redact_detection_logs.outcome == 'success' && steps.redact_detection_artifacts.outcome == 'success')
|
||||||
env:
|
env:
|
||||||
RUN_DETECTION: ${{ steps.detection_guard.outputs.run_detection }}
|
RUN_DETECTION: ${{ steps.detection_guard.outputs.run_detection }}
|
||||||
DETECTION_AGENTIC_EXECUTION_OUTCOME: ${{ steps.detection_agentic_execution.outcome }}
|
DETECTION_AGENTIC_EXECUTION_OUTCOME: ${{ steps.detection_agentic_execution.outcome }}
|
||||||
@@ -2178,7 +2185,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Setup Scripts
|
- name: Setup Scripts
|
||||||
id: setup
|
id: setup
|
||||||
uses: github/gh-aw-actions/setup@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2
|
uses: github/gh-aw-actions/setup@6147e7c2fba711fb36ac73c79cba401d1e213c4e # v1.4.4
|
||||||
with:
|
with:
|
||||||
destination: ${{ runner.temp }}/gh-aw/actions
|
destination: ${{ runner.temp }}/gh-aw/actions
|
||||||
job-name: ${{ github.job }}
|
job-name: ${{ github.job }}
|
||||||
|
|||||||
@@ -60,10 +60,6 @@ the ownership evidence the AI-slop review evaluates (see
|
|||||||
|
|
||||||
- For development and bug fixes, follow the
|
- For development and bug fixes, follow the
|
||||||
[development workflow](CONTRIBUTING.md#development-workflow).
|
[development workflow](CONTRIBUTING.md#development-workflow).
|
||||||
- For Rust backend changes that affect capability ownership or dependency
|
|
||||||
boundaries, follow [Workspace Crate Architecture](crates/AGENTS.md).
|
|
||||||
For Tauri commands and desktop integration, also follow
|
|
||||||
[Backend Architecture Guardrails](src-tauri/AGENTS.md).
|
|
||||||
- For code review and verification of review fixes, follow [REVIEW.md](REVIEW.md).
|
- For code review and verification of review fixes, follow [REVIEW.md](REVIEW.md).
|
||||||
Review is read-only unless changes are authorized; findings do not expand
|
Review is read-only unless changes are authorized; findings do not expand
|
||||||
that authorization to unrelated fixes, commits, pushes, or GitHub updates.
|
that authorization to unrelated fixes, commits, pushes, or GitHub updates.
|
||||||
|
|||||||
Generated
+3
-90
@@ -1089,21 +1089,15 @@ dependencies = [
|
|||||||
"async-trait",
|
"async-trait",
|
||||||
"backon",
|
"backon",
|
||||||
"base64 0.23.1",
|
"base64 0.23.1",
|
||||||
|
"boa_engine",
|
||||||
"bytes",
|
"bytes",
|
||||||
"chrono",
|
"chrono",
|
||||||
"clash-verge-backup-archive",
|
|
||||||
"clash-verge-config-render",
|
|
||||||
"clash-verge-draft",
|
"clash-verge-draft",
|
||||||
"clash-verge-i18n",
|
"clash-verge-i18n",
|
||||||
"clash-verge-limiter",
|
"clash-verge-limiter",
|
||||||
"clash-verge-logging",
|
"clash-verge-logging",
|
||||||
"clash-verge-media-unlock",
|
"clash-verge-media-unlock",
|
||||||
"clash-verge-profile",
|
|
||||||
"clash-verge-profile-script",
|
|
||||||
"clash-verge-proxy-view",
|
|
||||||
"clash-verge-runtime-bundle",
|
|
||||||
"clash-verge-signal",
|
"clash-verge-signal",
|
||||||
"clash-verge-subscription",
|
|
||||||
"clash-verge-task",
|
"clash-verge-task",
|
||||||
"clash_verge_service_ipc",
|
"clash_verge_service_ipc",
|
||||||
"dark-light",
|
"dark-light",
|
||||||
@@ -1172,34 +1166,13 @@ dependencies = [
|
|||||||
"zip",
|
"zip",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "clash-verge-backup-archive"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"thiserror 2.0.20",
|
|
||||||
"zip",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "clash-verge-config-render"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"clash-verge-logging",
|
|
||||||
"log",
|
|
||||||
"serde",
|
|
||||||
"serde_json",
|
|
||||||
"serde_yaml_ng",
|
|
||||||
"tokio",
|
|
||||||
"tristr",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "clash-verge-draft"
|
name = "clash-verge-draft"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"anyhow",
|
||||||
"criterion",
|
"criterion",
|
||||||
"parking_lot 0.13.0",
|
"parking_lot 0.13.0",
|
||||||
"thiserror 2.0.20",
|
|
||||||
"tokio",
|
"tokio",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -1219,10 +1192,10 @@ version = "0.1.0"
|
|||||||
name = "clash-verge-logging"
|
name = "clash-verge-logging"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"anyhow",
|
||||||
"flexi_logger",
|
"flexi_logger",
|
||||||
"log",
|
"log",
|
||||||
"parking_lot 0.13.0",
|
"parking_lot 0.13.0",
|
||||||
"thiserror 2.0.20",
|
|
||||||
"tracing-estuary",
|
"tracing-estuary",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -1241,55 +1214,6 @@ dependencies = [
|
|||||||
"tokio",
|
"tokio",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "clash-verge-profile"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"serde",
|
|
||||||
"serde_json",
|
|
||||||
"serde_yaml_ng",
|
|
||||||
"specta",
|
|
||||||
"thiserror 2.0.20",
|
|
||||||
"tristr",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "clash-verge-profile-script"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"boa_engine",
|
|
||||||
"clash-verge-logging",
|
|
||||||
"log",
|
|
||||||
"parking_lot 0.13.0",
|
|
||||||
"serde_json",
|
|
||||||
"serde_yaml_ng",
|
|
||||||
"tokio",
|
|
||||||
"tristr",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "clash-verge-proxy-view"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"serde",
|
|
||||||
"specta",
|
|
||||||
"tristr",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "clash-verge-runtime-bundle"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"clash-verge-logging",
|
|
||||||
"hex",
|
|
||||||
"log",
|
|
||||||
"serde_yaml_ng",
|
|
||||||
"sha2 0.11.2",
|
|
||||||
"thiserror 2.0.20",
|
|
||||||
"tokio",
|
|
||||||
"tristr",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "clash-verge-signal"
|
name = "clash-verge-signal"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
@@ -1299,17 +1223,6 @@ dependencies = [
|
|||||||
"tokio",
|
"tokio",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "clash-verge-subscription"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"http",
|
|
||||||
"percent-encoding",
|
|
||||||
"serde_yaml_ng",
|
|
||||||
"thiserror 2.0.20",
|
|
||||||
"url",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "clash-verge-task"
|
name = "clash-verge-task"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
|
|||||||
+2
-20
@@ -9,13 +9,6 @@ members = [
|
|||||||
"crates/tauri-plugin-clash-verge-sysinfo",
|
"crates/tauri-plugin-clash-verge-sysinfo",
|
||||||
"crates/clash-verge-i18n",
|
"crates/clash-verge-i18n",
|
||||||
"crates/clash-verge-limiter",
|
"crates/clash-verge-limiter",
|
||||||
"crates/clash-verge-subscription",
|
|
||||||
"crates/clash-verge-runtime-bundle",
|
|
||||||
"crates/clash-verge-config-render",
|
|
||||||
"crates/clash-verge-profile-script",
|
|
||||||
"crates/clash-verge-proxy-view",
|
|
||||||
"crates/clash-verge-profile",
|
|
||||||
"crates/clash-verge-backup-archive",
|
|
||||||
]
|
]
|
||||||
resolver = "2"
|
resolver = "2"
|
||||||
|
|
||||||
@@ -59,8 +52,6 @@ split-debuginfo = "unpacked"
|
|||||||
muda = { git = "https://github.com/wonfen/muda.git", rev = "547de49352791653fbdfa785f20f3c7ece8468e2" }
|
muda = { git = "https://github.com/wonfen/muda.git", rev = "547de49352791653fbdfa785f20f3c7ece8468e2" }
|
||||||
|
|
||||||
[workspace.dependencies]
|
[workspace.dependencies]
|
||||||
clash-verge-config-render = { path = "crates/clash-verge-config-render" }
|
|
||||||
clash-verge-profile-script = { path = "crates/clash-verge-profile-script" }
|
|
||||||
clash-verge-draft = { path = "crates/clash-verge-draft" }
|
clash-verge-draft = { path = "crates/clash-verge-draft" }
|
||||||
clash-verge-task = { path = "crates/clash-verge-task" }
|
clash-verge-task = { path = "crates/clash-verge-task" }
|
||||||
clash-verge-media-unlock = { path = "crates/clash-verge-media-unlock" }
|
clash-verge-media-unlock = { path = "crates/clash-verge-media-unlock" }
|
||||||
@@ -68,12 +59,6 @@ clash-verge-logging = { path = "crates/clash-verge-logging" }
|
|||||||
clash-verge-signal = { path = "crates/clash-verge-signal" }
|
clash-verge-signal = { path = "crates/clash-verge-signal" }
|
||||||
clash-verge-i18n = { path = "crates/clash-verge-i18n" }
|
clash-verge-i18n = { path = "crates/clash-verge-i18n" }
|
||||||
clash-verge-limiter = { path = "crates/clash-verge-limiter" }
|
clash-verge-limiter = { path = "crates/clash-verge-limiter" }
|
||||||
clash-verge-subscription = { path = "crates/clash-verge-subscription" }
|
|
||||||
clash-verge-runtime-bundle = { path = "crates/clash-verge-runtime-bundle" }
|
|
||||||
clash-verge-proxy-view = { path = "crates/clash-verge-proxy-view" }
|
|
||||||
clash-verge-profile = { path = "crates/clash-verge-profile" }
|
|
||||||
clash-verge-backup-archive = { path = "crates/clash-verge-backup-archive" }
|
|
||||||
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", branch = "main", version = "2.8.2", default-features = false }
|
|
||||||
tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", branch = "main" }
|
tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", branch = "main" }
|
||||||
tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" }
|
tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" }
|
||||||
tracing = "0.1.44"
|
tracing = "0.1.44"
|
||||||
@@ -82,9 +67,6 @@ tauri = { version = "2.12.7" }
|
|||||||
tauri-plugin-clipboard-manager = "2.5.0"
|
tauri-plugin-clipboard-manager = "2.5.0"
|
||||||
parking_lot = "0.13.0"
|
parking_lot = "0.13.0"
|
||||||
anyhow = "1.0.105"
|
anyhow = "1.0.105"
|
||||||
thiserror = "2.0.20"
|
|
||||||
zip = "9.9.0"
|
|
||||||
boa_engine = "0.22.0"
|
|
||||||
futures = "0.3.34"
|
futures = "0.3.34"
|
||||||
chrono = "0.4.45"
|
chrono = "0.4.45"
|
||||||
criterion = { version = "0.8.2", features = ["async_tokio"] }
|
criterion = { version = "0.8.2", features = ["async_tokio"] }
|
||||||
@@ -109,8 +91,6 @@ serde = { version = "1.0.229" }
|
|||||||
tristr = { git = "https://github.com/Tunglies/tristr", rev = "d849e5cff47a570849c2e1bada0a2b6481cf3378", default-features = false, features = ["serde", "specta"] }
|
tristr = { git = "https://github.com/Tunglies/tristr", rev = "d849e5cff47a570849c2e1bada0a2b6481cf3378", default-features = false, features = ["serde", "specta"] }
|
||||||
serde_json = { version = "1.0.154" }
|
serde_json = { version = "1.0.154" }
|
||||||
serde_yaml_ng = { version = "0.10.0" }
|
serde_yaml_ng = { version = "0.10.0" }
|
||||||
sha2 = "0.11.2"
|
|
||||||
specta = "=2.0.0-rc.26"
|
|
||||||
socket2 = "0.6.5"
|
socket2 = "0.6.5"
|
||||||
|
|
||||||
# *** For Windows platform only ***
|
# *** For Windows platform only ***
|
||||||
@@ -144,6 +124,7 @@ copy_iterator = "deny"
|
|||||||
correctness = { level = "deny", priority = -1 }
|
correctness = { level = "deny", priority = -1 }
|
||||||
dbg_macro = "warn"
|
dbg_macro = "warn"
|
||||||
equatable_if_let = "deny"
|
equatable_if_let = "deny"
|
||||||
|
expect_used = "warn"
|
||||||
expl_impl_clone_on_copy = "deny"
|
expl_impl_clone_on_copy = "deny"
|
||||||
future_not_send = "deny"
|
future_not_send = "deny"
|
||||||
iter_on_empty_collections = "deny"
|
iter_on_empty_collections = "deny"
|
||||||
@@ -182,6 +163,7 @@ unnecessary_self_imports = "deny"
|
|||||||
unnecessary_wraps = "deny"
|
unnecessary_wraps = "deny"
|
||||||
unused_async = "deny"
|
unused_async = "deny"
|
||||||
unused_trait_names = "deny"
|
unused_trait_names = "deny"
|
||||||
|
unwrap_used = "warn"
|
||||||
use_self = "deny"
|
use_self = "deny"
|
||||||
useless_let_if_seq = "deny"
|
useless_let_if_seq = "deny"
|
||||||
wildcard_imports = "deny"
|
wildcard_imports = "deny"
|
||||||
|
|||||||
@@ -33,7 +33,6 @@
|
|||||||
- 修复检测更新后又发布新版时,应用内更新失败
|
- 修复检测更新后又发布新版时,应用内更新失败
|
||||||
- 修复关闭「自动检查更新」后,手动检查更新时弹窗空白
|
- 修复关闭「自动检查更新」后,手动检查更新时弹窗空白
|
||||||
- 修复订阅响应过大导致内存占用过高,限制单次下载为 4 MiB
|
- 修复订阅响应过大导致内存占用过高,限制单次下载为 4 MiB
|
||||||
- 修复服务端文件名无效时导入的订阅名称为空
|
|
||||||
- 修复全局模式默认停在 `DIRECT` 或 `REJECT` 导致流量未经代理,现自动切换到第一个策略组
|
- 修复全局模式默认停在 `DIRECT` 或 `REJECT` 导致流量未经代理,现自动切换到第一个策略组
|
||||||
- 修复订阅中未加引号的 REALITY `short-id`(如 `1234e123`)被误读为数字,导致订阅无法启用
|
- 修复订阅中未加引号的 REALITY `short-id`(如 `1234e123`)被误读为数字,导致订阅无法启用
|
||||||
- 修复订阅中唯一的代理组名为 `GLOBAL` 或没有代理组时,规则模式下代理页面显示「未获取到代理信息」
|
- 修复订阅中唯一的代理组名为 `GLOBAL` 或没有代理组时,规则模式下代理页面显示「未获取到代理信息」
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
# Clippy loads a single configuration file, so repeat the workspace defaults.
|
|
||||||
avoid-breaking-exported-api = true
|
|
||||||
allow-unwrap-in-tests = true
|
|
||||||
cognitive-complexity-threshold = 25
|
|
||||||
excessive-nesting-threshold = 5
|
|
||||||
+9
-46
@@ -2,34 +2,19 @@
|
|||||||
|
|
||||||
## Choose the boundary
|
## Choose the boundary
|
||||||
|
|
||||||
- Apply Functional Core, Imperative Shell and Ports and Adapters. Keep domain
|
|
||||||
types, invariants, parsing, validation, and deterministic transitions
|
|
||||||
independent of Tauri, concrete OS APIs, and implicit application state.
|
|
||||||
- Keep use cases, async coordination, cancellation, and timeouts in
|
|
||||||
framework-independent application modules. Pass dependencies explicitly.
|
|
||||||
Define ports where an external effect needs a contract. Adapters implement
|
|
||||||
the contracts owned by their consumers. Keep filesystem, network, IPC, process,
|
|
||||||
and OS-specific operations in their adapters.
|
|
||||||
- Extract a capability whose invariants can be owned behind a small API. Before
|
- Extract a capability whose invariants can be owned behind a small API. Before
|
||||||
creating a crate, identify its owner, what callers supply, and what can be
|
creating a crate, identify its owner, what callers supply, and what can be
|
||||||
verified through the crate API. Extract a crate when it provides a useful
|
verified through the crate API. Keep a module when the proposed boundary only
|
||||||
dependency, portability, testing, or ownership boundary. Keep a module when
|
relocates implementation or introduces a pass-through API.
|
||||||
the proposed boundary only relocates implementation or introduces a
|
- Keep the dependency direction from the app to the crate. Resolve app paths,
|
||||||
pass-through API.
|
read product settings, start app-owned tasks, and publish UI events in the app.
|
||||||
- Keep capability crates independent by default. Compose peer capabilities in
|
Pass the values, resources, or callbacks the crate needs. For example,
|
||||||
the application and pass inputs or callbacks through the consumer's API.
|
|
||||||
Depend on another workspace crate for foundational mechanisms such as logging
|
|
||||||
and task primitives, or for a shared domain contract required to enforce the
|
|
||||||
same invariant. Keep tightly coupled rules together when separating them
|
|
||||||
would duplicate that contract or split its ownership.
|
|
||||||
- Keep dependencies pointing toward domain and application contracts. Resolve
|
|
||||||
app paths and read current settings at the application boundary. Pass in the
|
|
||||||
required values, resources, or callbacks. For example,
|
|
||||||
[logging](clash-verge-logging/src/lib.rs) owns its pipeline and writers while the
|
[logging](clash-verge-logging/src/lib.rs) owns its pipeline and writers while the
|
||||||
app supplies directories and limits through `LoggerConfig`.
|
app supplies directories and limits through `LoggerConfig`.
|
||||||
- Run framework-independent tests without starting the desktop app. A platform
|
- Keep framework and platform dependencies scoped to the capability that needs
|
||||||
adapter can own runtime startup when its resource lifetime requires it, as
|
them. Runtime-independent logic should be runnable without the desktop app.
|
||||||
[signal](clash-verge-signal/src/lib.rs) does for Linux shutdown.
|
A platform adapter can own runtime startup when its resource lifetime requires
|
||||||
|
it, as [signal](clash-verge-signal/src/lib.rs) does for Linux shutdown.
|
||||||
|
|
||||||
## Design the API
|
## Design the API
|
||||||
|
|
||||||
@@ -46,14 +31,6 @@
|
|||||||
workspace lints. Reuse workspace dependencies where available and declare
|
workspace lints. Reuse workspace dependencies where available and declare
|
||||||
only the features the crate needs.
|
only the features the crate needs.
|
||||||
|
|
||||||
## Handle fallible input
|
|
||||||
|
|
||||||
- Define crate-owned error types with `thiserror` in a dedicated `error` module.
|
|
||||||
Re-export public errors through their established import paths.
|
|
||||||
- Crates may use `unwrap()` or `expect()` for internal invariants. Propagate
|
|
||||||
errors from required external data and use defaults only when the input
|
|
||||||
contract gives the default a meaning.
|
|
||||||
|
|
||||||
## Own background work
|
## Own background work
|
||||||
|
|
||||||
- Give ordered start, replacement, and cleanup to one task owner. Reuse
|
- Give ordered start, replacement, and cleanup to one task owner. Reuse
|
||||||
@@ -66,20 +43,6 @@
|
|||||||
transaction boundaries and keep the reply path free of locks held by the
|
transaction boundaries and keep the reply path free of locks held by the
|
||||||
waiting caller. Cancel only at safe boundaries and own issued effects through
|
waiting caller. Cancel only at safe boundaries and own issued effects through
|
||||||
completion or explicit reconciliation.
|
completion or explicit reconciliation.
|
||||||
- Distinguish requested effects from completed effects in typed outcomes.
|
|
||||||
Define how failures, cancellation, and timeouts affect publication, retry,
|
|
||||||
rollback, or reconciliation.
|
|
||||||
|
|
||||||
## Validate new crates
|
|
||||||
|
|
||||||
- Fuzz the public boundary before tuning. Exercise malformed input, fallback
|
|
||||||
behavior, and failures that can affect user data. Preserve the corpus and
|
|
||||||
record the baseline revision and dependency resolution.
|
|
||||||
- Try at least one targeted performance improvement. Compare the baseline and
|
|
||||||
candidate on the same workload and build settings. Record stable gains, flat
|
|
||||||
cases, and regressions, and justify which changes to keep.
|
|
||||||
- Fuzz the final candidate again. Use the baseline corpus and compare outputs,
|
|
||||||
diagnostics, and errors with the baseline where behavior should be preserved.
|
|
||||||
|
|
||||||
Verify the extracted contract through its public API when practical. Use
|
Verify the extracted contract through its public API when practical. Use
|
||||||
`cargo test -p <crate>` for focused tests and keep native behavior checks at the
|
`cargo test -p <crate>` for focused tests and keep native behavior checks at the
|
||||||
|
|||||||
@@ -1,11 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "clash-verge-backup-archive"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
thiserror = { workspace = true }
|
|
||||||
zip = { workspace = true }
|
|
||||||
|
|
||||||
[lints]
|
|
||||||
workspace = true
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
#[derive(Debug, thiserror::Error)]
|
|
||||||
pub enum ArchiveError {
|
|
||||||
#[error(transparent)]
|
|
||||||
Zip(#[from] zip::result::ZipError),
|
|
||||||
#[error(transparent)]
|
|
||||||
Io(#[from] std::io::Error),
|
|
||||||
#[error("backup contains a symbolic link")]
|
|
||||||
Symlink,
|
|
||||||
#[error("backup contains an invalid path")]
|
|
||||||
InvalidPath,
|
|
||||||
#[error("archive contains profile recovery data")]
|
|
||||||
ReservedEntry,
|
|
||||||
}
|
|
||||||
@@ -1,104 +0,0 @@
|
|||||||
mod error;
|
|
||||||
|
|
||||||
pub use error::ArchiveError;
|
|
||||||
|
|
||||||
use std::{
|
|
||||||
io::{self, Read, Seek, Write},
|
|
||||||
path::{Component, Path},
|
|
||||||
};
|
|
||||||
use zip::{CompressionMethod, ZipArchive, ZipWriter, write::SimpleFileOptions};
|
|
||||||
|
|
||||||
pub struct BackupWriter<W: Write + Seek> {
|
|
||||||
zip: ZipWriter<W>,
|
|
||||||
options: SimpleFileOptions,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<W: Write + Seek> BackupWriter<W> {
|
|
||||||
pub fn new(target: W) -> Result<Self, ArchiveError> {
|
|
||||||
let mut zip = ZipWriter::new(target);
|
|
||||||
zip.add_directory("profiles/", SimpleFileOptions::default())?;
|
|
||||||
let options = SimpleFileOptions::default().compression_method(CompressionMethod::Stored);
|
|
||||||
Ok(Self { zip, options })
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn start_profile<'a>(&'a mut self, filename: &str) -> Result<impl Write + use<'a, W>, ArchiveError> {
|
|
||||||
self.start_file(&format!("profiles/{filename}"))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn start_file<'a>(&'a mut self, name: &str) -> Result<impl Write + use<'a, W>, ArchiveError> {
|
|
||||||
self.zip.start_file_with_options(self.options.name(name.as_bytes()))?;
|
|
||||||
Ok(&mut self.zip)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn finish(self) -> Result<W, ArchiveError> {
|
|
||||||
Ok(self.zip.finish()?)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct ValidatedBackup<R: Read + Seek> {
|
|
||||||
zip: ZipArchive<R>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<R: Read + Seek> ValidatedBackup<R> {
|
|
||||||
pub fn open(source: R, reserved_names: &[&str]) -> Result<Self, ArchiveError> {
|
|
||||||
let mut zip = ZipArchive::new(source)?;
|
|
||||||
for index in 0..zip.len() {
|
|
||||||
let mut entry = zip.by_index(index)?;
|
|
||||||
if entry.is_symlink() {
|
|
||||||
return Err(ArchiveError::Symlink);
|
|
||||||
}
|
|
||||||
let path = entry.enclosed_name().ok_or(ArchiveError::InvalidPath)?;
|
|
||||||
for component in path.components() {
|
|
||||||
let Component::Normal(name) = component else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let name = name.to_string_lossy();
|
|
||||||
if reserved_names
|
|
||||||
.iter()
|
|
||||||
.any(|reserved| name.eq_ignore_ascii_case(reserved))
|
|
||||||
{
|
|
||||||
return Err(ArchiveError::ReservedEntry);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
io::copy(&mut entry, &mut io::sink())?;
|
|
||||||
}
|
|
||||||
Ok(Self { zip })
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn extract_to(mut self, destination: &Path) -> Result<(), ArchiveError> {
|
|
||||||
self.zip.extract(destination)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use std::io::Cursor;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn writes_and_validates_the_backup_layout() -> Result<(), ArchiveError> {
|
|
||||||
let mut writer = BackupWriter::new(Cursor::new(Vec::new()))?;
|
|
||||||
writer.start_profile("example.yaml")?.write_all(b"proxies: []\n")?;
|
|
||||||
writer.start_file("profiles.yaml")?.write_all(b"items: []\n")?;
|
|
||||||
let source = writer.finish()?;
|
|
||||||
|
|
||||||
let mut zip = ZipArchive::new(source.clone())?;
|
|
||||||
assert_eq!(zip.len(), 3);
|
|
||||||
assert_eq!(zip.by_index(0)?.name()?, "profiles/");
|
|
||||||
let profile_time = {
|
|
||||||
let mut entry = zip.by_index(1)?;
|
|
||||||
assert_eq!(entry.name()?, "profiles/example.yaml");
|
|
||||||
assert_eq!(entry.compression(), CompressionMethod::Stored);
|
|
||||||
let mut contents = Vec::new();
|
|
||||||
entry.read_to_end(&mut contents)?;
|
|
||||||
assert_eq!(contents, b"proxies: []\n");
|
|
||||||
entry.last_modified()
|
|
||||||
};
|
|
||||||
let index = zip.by_index(2)?;
|
|
||||||
assert_eq!(index.name()?, "profiles.yaml");
|
|
||||||
assert_eq!(index.last_modified(), profile_time);
|
|
||||||
ValidatedBackup::open(source, &[".profile-refresh", ".profile-refresh.lock"])?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "clash-verge-config-render"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
clash-verge-logging = { workspace = true }
|
|
||||||
log = { workspace = true }
|
|
||||||
serde = { workspace = true, features = ["derive"] }
|
|
||||||
serde_json = { workspace = true }
|
|
||||||
serde_yaml_ng = { workspace = true }
|
|
||||||
tristr = { workspace = true }
|
|
||||||
|
|
||||||
[dev-dependencies]
|
|
||||||
tokio = { workspace = true }
|
|
||||||
|
|
||||||
[lints]
|
|
||||||
workspace = true
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,81 +0,0 @@
|
|||||||
use super::{ResultLog, ScriptOutcome, field::use_lowercase};
|
|
||||||
use serde_yaml_ng::Mapping;
|
|
||||||
use tristr::alias::String;
|
|
||||||
|
|
||||||
type ScriptResult = (Mapping, Vec<String>, ResultLog);
|
|
||||||
|
|
||||||
/// Never fails: exceptions are logged and the input config is returned unchanged.
|
|
||||||
pub(super) async fn use_script<Fut: Future<Output = ScriptOutcome> + Send>(
|
|
||||||
script: String,
|
|
||||||
config: Mapping,
|
|
||||||
name: String,
|
|
||||||
execute: impl FnOnce(String, serde_json::Value, String) -> Fut + Send,
|
|
||||||
) -> ScriptResult {
|
|
||||||
// The template is identity-plus-lowercasing; skip the Boa round-trip.
|
|
||||||
if script == super::ITEM_SCRIPT {
|
|
||||||
return (use_lowercase(config), vec![], vec![]);
|
|
||||||
}
|
|
||||||
|
|
||||||
let json = match serde_json::to_value(&config) {
|
|
||||||
Ok(mut json) => {
|
|
||||||
if let Some(map) = json.as_object_mut() {
|
|
||||||
let mut lowered = serde_json::Map::with_capacity(map.len());
|
|
||||||
for (key, value) in std::mem::take(map) {
|
|
||||||
let mut key = key;
|
|
||||||
key.make_ascii_lowercase();
|
|
||||||
lowered.insert(key, value);
|
|
||||||
}
|
|
||||||
*map = lowered;
|
|
||||||
}
|
|
||||||
json
|
|
||||||
}
|
|
||||||
Err(err) => return (config, vec![], vec![("exception".into(), err.to_string().into())]),
|
|
||||||
};
|
|
||||||
|
|
||||||
let (outcome, mut logs) = execute(script, json, name).await;
|
|
||||||
match outcome {
|
|
||||||
Ok(result) => {
|
|
||||||
let result = use_lowercase(result);
|
|
||||||
// Compared against the config as handed in, not the lowercased copy the script saw.
|
|
||||||
let changed_keys = result
|
|
||||||
.iter()
|
|
||||||
.filter(|(key, value)| config.get(key) != Some(value))
|
|
||||||
.filter_map(|(key, _)| {
|
|
||||||
let mut key: String = key.as_str()?.into();
|
|
||||||
key.make_ascii_lowercase();
|
|
||||||
Some(key)
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
(result, changed_keys, logs)
|
|
||||||
}
|
|
||||||
Err(reason) => {
|
|
||||||
logs.push(("exception".into(), reason.into()));
|
|
||||||
(config, vec![], logs)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use std::future::ready;
|
|
||||||
|
|
||||||
use super::{Mapping, use_script};
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn default_template_skips_the_executor() {
|
|
||||||
let mut called = false;
|
|
||||||
let mut config = Mapping::new();
|
|
||||||
config.insert("MiXeD".into(), true.into());
|
|
||||||
let (config, changed_keys, logs) =
|
|
||||||
use_script(crate::ITEM_SCRIPT.into(), config, "profile".into(), |_, _, _| {
|
|
||||||
called = true;
|
|
||||||
ready((Ok(Mapping::new()), vec![]))
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
|
|
||||||
assert!(!called);
|
|
||||||
assert_eq!(config["mixed"], serde_yaml_ng::Value::Bool(true));
|
|
||||||
assert!(changed_keys.is_empty());
|
|
||||||
assert!(logs.is_empty());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -10,7 +10,7 @@ harness = false
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
parking_lot = { workspace = true }
|
parking_lot = { workspace = true }
|
||||||
thiserror = { workspace = true }
|
anyhow = { workspace = true }
|
||||||
tokio = { workspace = true }
|
tokio = { workspace = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ use criterion::{Criterion, criterion_group, criterion_main};
|
|||||||
use std::hint::black_box;
|
use std::hint::black_box;
|
||||||
use tokio::runtime::Runtime;
|
use tokio::runtime::Runtime;
|
||||||
|
|
||||||
use clash_verge_draft::{Draft, DraftConflict};
|
use clash_verge_draft::Draft;
|
||||||
|
|
||||||
#[derive(Default, Clone, Debug)]
|
#[derive(Default, Clone, Debug)]
|
||||||
struct IVerge {
|
struct IVerge {
|
||||||
@@ -99,8 +99,8 @@ pub fn bench_draft(c: &mut Criterion) {
|
|||||||
group.bench_function("with_data_modify_async", |b| {
|
group.bench_function("with_data_modify_async", |b| {
|
||||||
b.to_async(&rt).iter(|| async {
|
b.to_async(&rt).iter(|| async {
|
||||||
let draft = black_box(make_draft());
|
let draft = black_box(make_draft());
|
||||||
let _: Result<(), DraftConflict> = draft
|
let _: Result<(), anyhow::Error> = draft
|
||||||
.with_data_modify(|mut box_data| async move {
|
.with_data_modify::<_, _, _>(|mut box_data| async move {
|
||||||
box_data.enable_auto_launch = Some(!box_data.enable_auto_launch.unwrap_or(false));
|
box_data.enable_auto_launch = Some(!box_data.enable_auto_launch.unwrap_or(false));
|
||||||
Ok((box_data, ()))
|
Ok((box_data, ()))
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,12 +0,0 @@
|
|||||||
/// Committed data changed before an asynchronous edit could publish.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
|
||||||
#[error("Optimistic lock failed: Committed data has changed during async operation")]
|
|
||||||
pub struct DraftConflict;
|
|
||||||
|
|
||||||
/// Another transaction is already staging a change to one of the layers asked for.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
|
||||||
#[error("configuration layer {layer} is being changed elsewhere")]
|
|
||||||
pub struct DraftBusy {
|
|
||||||
/// The layer that was already claimed.
|
|
||||||
pub layer: &'static str,
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,3 @@
|
|||||||
mod error;
|
|
||||||
|
|
||||||
pub use error::{DraftBusy, DraftConflict};
|
|
||||||
|
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::sync::atomic::{
|
use std::sync::atomic::{
|
||||||
@@ -95,16 +91,14 @@ impl<T: Clone> Draft<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Optimistically replaces committed data after an asynchronous edit.
|
/// Optimistically replaces committed data after an asynchronous edit.
|
||||||
/// The caller's error type carries both edit failures and publication conflicts.
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub async fn with_data_modify<F, Fut, R, E>(&self, f: F) -> Result<R, E>
|
pub async fn with_data_modify<F, Fut, R>(&self, f: F) -> Result<R, anyhow::Error>
|
||||||
where
|
where
|
||||||
T: Send + Sync + 'static,
|
T: Send + Sync + 'static,
|
||||||
F: FnOnce(T) -> Fut + Send,
|
F: FnOnce(T) -> Fut + Send,
|
||||||
Fut: std::future::Future<Output = Result<(T, R), E>> + Send,
|
Fut: std::future::Future<Output = Result<(T, R), anyhow::Error>> + Send,
|
||||||
E: From<DraftConflict>,
|
|
||||||
{
|
{
|
||||||
let permit = self.acquire_data_modify_permit().await;
|
let _permit = self.acquire_data_modify_permit().await;
|
||||||
let (local, original_arc) = {
|
let (local, original_arc) = {
|
||||||
let guard = self.inner.data.lock();
|
let guard = self.inner.data.lock();
|
||||||
let arc = Arc::clone(&guard.0);
|
let arc = Arc::clone(&guard.0);
|
||||||
@@ -114,9 +108,9 @@ impl<T: Clone> Draft<T> {
|
|||||||
let (new_local, res) = f(local).await?;
|
let (new_local, res) = f(local).await?;
|
||||||
let mut guard = self.inner.data.lock();
|
let mut guard = self.inner.data.lock();
|
||||||
if !Arc::ptr_eq(&guard.0, &original_arc) {
|
if !Arc::ptr_eq(&guard.0, &original_arc) {
|
||||||
drop(guard);
|
return Err(anyhow::anyhow!(
|
||||||
drop(permit);
|
"Optimistic lock failed: Committed data has changed during async operation"
|
||||||
return Err(DraftConflict.into());
|
));
|
||||||
}
|
}
|
||||||
guard.0 = Arc::new(Box::new(new_local));
|
guard.0 = Arc::new(Box::new(new_local));
|
||||||
drop(guard);
|
drop(guard);
|
||||||
@@ -197,6 +191,25 @@ impl<T: Clone + Send + Sync> DraftLayer for Draft<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Another transaction is already staging a change to one of the layers asked for.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct DraftBusy {
|
||||||
|
/// The layer that was already claimed.
|
||||||
|
pub layer: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for DraftBusy {
|
||||||
|
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
write!(
|
||||||
|
formatter,
|
||||||
|
"configuration layer {} is being changed elsewhere",
|
||||||
|
self.layer
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for DraftBusy {}
|
||||||
|
|
||||||
/// Exclusively claims several draft layers and rolls them all back unless committed.
|
/// Exclusively claims several draft layers and rolls them all back unless committed.
|
||||||
///
|
///
|
||||||
/// A layer has one draft slot, so concurrent transactions cannot be isolated and are rejected.
|
/// A layer has one draft slot, so concurrent transactions cannot be isolated and are rejected.
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use clash_verge_draft::{Draft, DraftBusy, DraftConflict, DraftTransaction};
|
use clash_verge_draft::{Draft, DraftTransaction};
|
||||||
use tokio::sync::Notify;
|
use tokio::sync::Notify;
|
||||||
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq)]
|
#[derive(Clone, Debug, Default, PartialEq)]
|
||||||
@@ -28,19 +28,14 @@ fn edits_can_be_committed_or_discarded() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn async_updates_are_serialized() -> Result<(), Box<dyn std::error::Error>> {
|
async fn async_updates_are_serialized() -> anyhow::Result<()> {
|
||||||
let draft = Arc::new(Draft::new(0_u8));
|
let draft = Arc::new(Draft::new(0_u8));
|
||||||
let mut updates = Vec::new();
|
let mut updates = Vec::new();
|
||||||
|
|
||||||
for _ in 0..16 {
|
for _ in 0..16 {
|
||||||
let draft = Arc::clone(&draft);
|
let draft = Arc::clone(&draft);
|
||||||
updates.push(tokio::spawn(async move {
|
updates.push(tokio::spawn(async move {
|
||||||
draft
|
draft.with_data_modify(|value| async move { Ok((value + 1, ())) }).await
|
||||||
.with_data_modify(|value| async move {
|
|
||||||
tokio::task::yield_now().await;
|
|
||||||
Ok::<_, DraftConflict>((value + 1, ()))
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
for update in updates {
|
for update in updates {
|
||||||
@@ -52,7 +47,7 @@ async fn async_updates_are_serialized() -> Result<(), Box<dyn std::error::Error>
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn async_update_rejects_a_changed_committed_value() -> Result<(), Box<dyn std::error::Error>> {
|
async fn async_update_rejects_a_changed_committed_value() -> anyhow::Result<()> {
|
||||||
let draft = Arc::new(Draft::new(Config::default()));
|
let draft = Arc::new(Draft::new(Config::default()));
|
||||||
let started = Arc::new(Notify::new());
|
let started = Arc::new(Notify::new());
|
||||||
let finish = Arc::new(Notify::new());
|
let finish = Arc::new(Notify::new());
|
||||||
@@ -66,7 +61,7 @@ async fn async_update_rejects_a_changed_committed_value() -> Result<(), Box<dyn
|
|||||||
started.notify_one();
|
started.notify_one();
|
||||||
finish.notified().await;
|
finish.notified().await;
|
||||||
config.enabled = true;
|
config.enabled = true;
|
||||||
Ok::<_, DraftConflict>((config, ()))
|
Ok((config, ()))
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
})
|
})
|
||||||
@@ -77,14 +72,14 @@ async fn async_update_rejects_a_changed_committed_value() -> Result<(), Box<dyn
|
|||||||
draft.apply();
|
draft.apply();
|
||||||
finish.notify_one();
|
finish.notify_one();
|
||||||
|
|
||||||
assert_eq!(update.await?, Err(DraftConflict));
|
assert!(update.await?.is_err());
|
||||||
assert!(!draft.data_arc().enabled);
|
assert!(!draft.data_arc().enabled);
|
||||||
assert_eq!(draft.data_arc().port, 7897);
|
assert_eq!(draft.data_arc().port, 7897);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn transaction_commits_every_layer() -> Result<(), DraftBusy> {
|
fn transaction_commits_every_layer() -> anyhow::Result<()> {
|
||||||
let first = Draft::new(1_u8);
|
let first = Draft::new(1_u8);
|
||||||
let second = Draft::new(String::from("a"));
|
let second = Draft::new(String::from("a"));
|
||||||
let transaction = DraftTransaction::begin(vec![&first, &second])?;
|
let transaction = DraftTransaction::begin(vec![&first, &second])?;
|
||||||
@@ -99,7 +94,7 @@ fn transaction_commits_every_layer() -> Result<(), DraftBusy> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn dropped_transaction_rolls_every_layer_back() -> Result<(), DraftBusy> {
|
fn dropped_transaction_rolls_every_layer_back() -> anyhow::Result<()> {
|
||||||
let first = Draft::new(1_u8);
|
let first = Draft::new(1_u8);
|
||||||
let second = Draft::new(String::from("a"));
|
let second = Draft::new(String::from("a"));
|
||||||
|
|
||||||
@@ -115,7 +110,7 @@ fn dropped_transaction_rolls_every_layer_back() -> Result<(), DraftBusy> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn transaction_claims_are_exclusive_and_release_partial_claims() -> Result<(), DraftBusy> {
|
fn transaction_claims_are_exclusive_and_release_partial_claims() -> anyhow::Result<()> {
|
||||||
let first = Draft::new(1_u8);
|
let first = Draft::new(1_u8);
|
||||||
let second = Draft::new(2_u8);
|
let second = Draft::new(2_u8);
|
||||||
let held = DraftTransaction::begin(vec![&second])?;
|
let held = DraftTransaction::begin(vec![&second])?;
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ edition = "2024"
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
log = { workspace = true }
|
log = { workspace = true }
|
||||||
parking_lot = { workspace = true }
|
parking_lot = { workspace = true }
|
||||||
thiserror = { workspace = true }
|
anyhow = { workspace = true }
|
||||||
flexi_logger = { workspace = true }
|
flexi_logger = { workspace = true }
|
||||||
tracing-estuary = { workspace = true }
|
tracing-estuary = { workspace = true }
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +0,0 @@
|
|||||||
#[derive(Debug, thiserror::Error)]
|
|
||||||
pub enum LoggerError {
|
|
||||||
#[error(transparent)]
|
|
||||||
Pipeline(Box<dyn std::error::Error + Send + Sync>),
|
|
||||||
#[error(transparent)]
|
|
||||||
Sidecar(#[from] flexi_logger::FlexiLoggerError),
|
|
||||||
#[error("failed to get tracing pipeline, make sure it init")]
|
|
||||||
PipelineUnavailable,
|
|
||||||
#[error("failed to reset log writer: {0}")]
|
|
||||||
ResetWriter(String),
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,3 @@
|
|||||||
mod error;
|
|
||||||
|
|
||||||
pub use error::LoggerError;
|
|
||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
collections::VecDeque,
|
collections::VecDeque,
|
||||||
fmt,
|
fmt,
|
||||||
@@ -14,6 +10,7 @@ use std::{
|
|||||||
time::Duration,
|
time::Duration,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
use anyhow::{Result, bail};
|
||||||
use flexi_logger::{
|
use flexi_logger::{
|
||||||
Cleanup, Criterion, DeferredNow, FileSpec, Naming,
|
Cleanup, Criterion, DeferredNow, FileSpec, Naming,
|
||||||
writers::{FileLogWriter, FileLogWriterBuilder, LogWriter as _},
|
writers::{FileLogWriter, FileLogWriterBuilder, LogWriter as _},
|
||||||
@@ -180,7 +177,7 @@ impl Logger {
|
|||||||
|
|
||||||
/// Installs the global tracing pipeline. `RUST_LOG` (parsed as a bare
|
/// Installs the global tracing pipeline. `RUST_LOG` (parsed as a bare
|
||||||
/// level) overrides the configured level.
|
/// level) overrides the configured level.
|
||||||
pub fn init(&self, cfg: &LoggerConfig) -> Result<(), LoggerError> {
|
pub fn init(&self, cfg: &LoggerConfig) -> Result<()> {
|
||||||
let log_level = std::env::var("RUST_LOG")
|
let log_level = std::env::var("RUST_LOG")
|
||||||
.ok()
|
.ok()
|
||||||
.and_then(|v| LevelFilter::from_str(v.trim()).ok())
|
.and_then(|v| LevelFilter::from_str(v.trim()).ok())
|
||||||
@@ -189,15 +186,14 @@ impl Logger {
|
|||||||
let pipeline = tracing_estuary::PipelineBuilder::new()
|
let pipeline = tracing_estuary::PipelineBuilder::new()
|
||||||
.default_level(log_level)
|
.default_level(log_level)
|
||||||
.file_writer(self.generate_file_log_writer())
|
.file_writer(self.generate_file_log_writer())
|
||||||
.init()
|
.init()?;
|
||||||
.map_err(|error| LoggerError::Pipeline(error.into_boxed_dyn_error()))?;
|
|
||||||
self.pipeline.set(pipeline).ok();
|
self.pipeline.set(pipeline).ok();
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Installs the sidecar file writer and the panic hook. Safe to call when
|
/// Installs the sidecar file writer and the panic hook. Safe to call when
|
||||||
/// the pipeline is owned elsewhere (e.g. a devtools-provided subscriber).
|
/// the pipeline is owned elsewhere (e.g. a devtools-provided subscriber).
|
||||||
pub fn init_sidecar(&self, cfg: &LoggerConfig) -> Result<(), LoggerError> {
|
pub fn init_sidecar(&self, cfg: &LoggerConfig) -> Result<()> {
|
||||||
self.store_config(cfg);
|
self.store_config(cfg);
|
||||||
self.ensure_sidecar_writer(self.generate_sidecar_builder())?;
|
self.ensure_sidecar_writer(self.generate_sidecar_builder())?;
|
||||||
|
|
||||||
@@ -249,7 +245,7 @@ impl Logger {
|
|||||||
/// Ensures the sidecar writer exists and points at `builder`'s config:
|
/// Ensures the sidecar writer exists and points at `builder`'s config:
|
||||||
/// built once, then reset in place — flexi's flusher thread cannot be
|
/// built once, then reset in place — flexi's flusher thread cannot be
|
||||||
/// stopped, so every dropped writer would leak a thread and an fd.
|
/// stopped, so every dropped writer would leak a thread and an fd.
|
||||||
fn ensure_sidecar_writer(&self, builder: FileLogWriterBuilder) -> Result<(), LoggerError> {
|
fn ensure_sidecar_writer(&self, builder: FileLogWriterBuilder) -> Result<()> {
|
||||||
let sidecar = self.sidecar_file_writer.write();
|
let sidecar = self.sidecar_file_writer.write();
|
||||||
match sidecar.as_ref() {
|
match sidecar.as_ref() {
|
||||||
Some(writer) => {
|
Some(writer) => {
|
||||||
@@ -300,29 +296,27 @@ impl Logger {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// only update app log level
|
/// only update app log level
|
||||||
pub fn update_log_level(&self, level: LevelFilter) -> Result<(), LoggerError> {
|
pub fn update_log_level(&self, level: LevelFilter) -> Result<()> {
|
||||||
if let Some(pipeline) = self.pipeline.get() {
|
if let Some(pipeline) = self.pipeline.get() {
|
||||||
pipeline
|
pipeline.filter.set_default_level(level)?;
|
||||||
.filter
|
|
||||||
.set_default_level(level)
|
|
||||||
.map_err(|error| LoggerError::Pipeline(error.into_boxed_dyn_error()))?;
|
|
||||||
} else {
|
} else {
|
||||||
return Err(LoggerError::PipelineUnavailable);
|
bail!("failed to get tracing pipeline, make sure it init");
|
||||||
};
|
};
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Rebuilds both file writers with the new limits.
|
/// Rebuilds both file writers with the new limits.
|
||||||
pub fn update_log_config(&self, log_max_size: u64, log_max_count: usize) -> Result<(), LoggerError> {
|
pub fn update_log_config(&self, log_max_size: u64, log_max_count: usize) -> Result<()> {
|
||||||
self.log_max_size.store(log_max_size, Ordering::SeqCst);
|
self.log_max_size.store(log_max_size, Ordering::SeqCst);
|
||||||
self.log_max_count.store(log_max_count, Ordering::SeqCst);
|
self.log_max_count.store(log_max_count, Ordering::SeqCst);
|
||||||
if let Some(pipeline) = self.pipeline.get() {
|
if let Some(pipeline) = self.pipeline.get() {
|
||||||
let log_file_writer = self.generate_file_log_writer();
|
let log_file_writer = self.generate_file_log_writer();
|
||||||
if let Some(sink) = pipeline.sink.as_ref() {
|
if let Some(sink) = pipeline.sink.as_ref() {
|
||||||
sink.reset(log_file_writer).map_err(LoggerError::ResetWriter)?;
|
sink.reset(log_file_writer)
|
||||||
|
.map_err(|error| anyhow::anyhow!("failed to reset log writer: {error}"))?;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
return Err(LoggerError::PipelineUnavailable);
|
bail!("failed to get tracing pipeline, make sure it init");
|
||||||
};
|
};
|
||||||
self.ensure_sidecar_writer(self.generate_sidecar_builder())?;
|
self.ensure_sidecar_writer(self.generate_sidecar_builder())?;
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -1,17 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "clash-verge-profile-script"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
boa_engine = { workspace = true }
|
|
||||||
clash-verge-logging = { workspace = true }
|
|
||||||
log = { workspace = true }
|
|
||||||
parking_lot = { workspace = true }
|
|
||||||
serde_json = { workspace = true }
|
|
||||||
serde_yaml_ng = { workspace = true }
|
|
||||||
tokio = { workspace = true }
|
|
||||||
tristr = { workspace = true }
|
|
||||||
|
|
||||||
[lints]
|
|
||||||
workspace = true
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "clash-verge-profile"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
serde = { workspace = true, features = ["derive"] }
|
|
||||||
specta = { workspace = true, features = ["derive"] }
|
|
||||||
thiserror = { workspace = true }
|
|
||||||
tristr = { workspace = true }
|
|
||||||
|
|
||||||
[dev-dependencies]
|
|
||||||
serde_json = { workspace = true }
|
|
||||||
serde_yaml_ng = { workspace = true }
|
|
||||||
|
|
||||||
[lints]
|
|
||||||
workspace = true
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
#[derive(Debug, thiserror::Error)]
|
|
||||||
#[error("failed to get the profile item \"uid:{uid}\"")]
|
|
||||||
pub struct ProfileNotFound {
|
|
||||||
pub(super) uid: String,
|
|
||||||
}
|
|
||||||
@@ -1,410 +0,0 @@
|
|||||||
mod error;
|
|
||||||
pub mod selected_nodes;
|
|
||||||
mod subscription_schedule;
|
|
||||||
|
|
||||||
pub use error::ProfileNotFound;
|
|
||||||
pub use subscription_schedule::SubscriptionSchedule;
|
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use tristr::alias::String;
|
|
||||||
|
|
||||||
macro_rules! patch_opt_field {
|
|
||||||
($lv:expr, $rv:expr, $key:tt) => {
|
|
||||||
if ($rv.$key).is_some() {
|
|
||||||
$lv.$key = $rv.$key.clone();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize, Default, specta::Type)]
|
|
||||||
#[serde(default)]
|
|
||||||
pub struct PrfItem {
|
|
||||||
pub uid: Option<String>,
|
|
||||||
|
|
||||||
/// enum value: remote | local | script | merge
|
|
||||||
#[serde(rename = "type")]
|
|
||||||
pub itype: Option<String>,
|
|
||||||
pub name: Option<String>,
|
|
||||||
pub file: Option<String>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub desc: Option<String>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub url: Option<String>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub selected: Option<Vec<PrfSelected>>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub extra: Option<PrfExtra>,
|
|
||||||
pub updated: Option<usize>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub option: Option<PrfOption>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub home: Option<String>,
|
|
||||||
#[serde(skip)]
|
|
||||||
pub file_data: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)]
|
|
||||||
#[serde(default)]
|
|
||||||
pub struct PrfSelected {
|
|
||||||
pub name: Option<String>,
|
|
||||||
pub now: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default, Debug, Clone, Copy, Deserialize, Serialize, specta::Type)]
|
|
||||||
pub struct PrfExtra {
|
|
||||||
pub upload: u64,
|
|
||||||
pub download: u64,
|
|
||||||
pub total: u64,
|
|
||||||
pub expire: u64,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)]
|
|
||||||
#[serde(default)]
|
|
||||||
pub struct PrfOption {
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub user_agent: Option<String>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub with_proxy: Option<bool>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub self_proxy: Option<bool>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub update_interval: Option<u64>,
|
|
||||||
/// HTTP request timeout in seconds
|
|
||||||
/// default is 60 seconds
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub timeout_seconds: Option<u64>,
|
|
||||||
/// default is `false`
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub danger_accept_invalid_certs: Option<bool>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub allow_auto_update: Option<bool>,
|
|
||||||
pub merge: Option<String>,
|
|
||||||
pub script: Option<String>,
|
|
||||||
pub rules: Option<String>,
|
|
||||||
pub proxies: Option<String>,
|
|
||||||
pub groups: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PrfOption {
|
|
||||||
pub fn merge(one: Option<&Self>, other: Option<&Self>) -> Option<Self> {
|
|
||||||
match (one, other) {
|
|
||||||
(Some(a_ref), Some(b_ref)) => {
|
|
||||||
let mut result = a_ref.clone();
|
|
||||||
patch_opt_field!(result, b_ref, user_agent);
|
|
||||||
patch_opt_field!(result, b_ref, with_proxy);
|
|
||||||
patch_opt_field!(result, b_ref, self_proxy);
|
|
||||||
patch_opt_field!(result, b_ref, danger_accept_invalid_certs);
|
|
||||||
patch_opt_field!(result, b_ref, allow_auto_update);
|
|
||||||
patch_opt_field!(result, b_ref, update_interval);
|
|
||||||
patch_opt_field!(result, b_ref, merge);
|
|
||||||
patch_opt_field!(result, b_ref, script);
|
|
||||||
patch_opt_field!(result, b_ref, rules);
|
|
||||||
patch_opt_field!(result, b_ref, proxies);
|
|
||||||
patch_opt_field!(result, b_ref, groups);
|
|
||||||
patch_opt_field!(result, b_ref, timeout_seconds);
|
|
||||||
Some(result)
|
|
||||||
}
|
|
||||||
(Some(a_ref), None) => Some(a_ref.clone()),
|
|
||||||
(None, Some(b_ref)) => Some(b_ref.clone()),
|
|
||||||
(None, None) => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
macro_rules! current_field {
|
|
||||||
($name:ident, $field:ident) => {
|
|
||||||
pub fn $name(&self) -> Option<&String> {
|
|
||||||
self.option.as_ref().and_then(|o| o.$field.as_ref())
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PrfItem {
|
|
||||||
current_field!(current_merge, merge);
|
|
||||||
current_field!(current_script, script);
|
|
||||||
current_field!(current_rules, rules);
|
|
||||||
current_field!(current_proxies, proxies);
|
|
||||||
current_field!(current_groups, groups);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Define the `profiles.yaml` schema
|
|
||||||
#[derive(Default, Debug, Clone, Deserialize, Serialize, specta::Type)]
|
|
||||||
#[serde(default)]
|
|
||||||
pub struct IProfiles {
|
|
||||||
pub current: Option<String>,
|
|
||||||
pub items: Option<Vec<PrfItem>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct IProfilePreview<'a> {
|
|
||||||
pub uid: &'a String,
|
|
||||||
pub name: &'a String,
|
|
||||||
pub is_current: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct ProfileDeletePlan {
|
|
||||||
pub deleting_current: bool,
|
|
||||||
pub files: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl IProfiles {
|
|
||||||
pub fn patch_current(&mut self, current: Option<&String>) {
|
|
||||||
let items = self.items.get_or_insert_with(Vec::new);
|
|
||||||
if let Some(current) = current
|
|
||||||
&& items.iter().any(|item| item.uid.as_ref() == Some(current))
|
|
||||||
{
|
|
||||||
self.current = Some(current.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_item(&self, uid: impl AsRef<str>) -> Result<&PrfItem, ProfileNotFound> {
|
|
||||||
let uid_str = uid.as_ref();
|
|
||||||
|
|
||||||
if let Some(items) = self.items.as_ref() {
|
|
||||||
for each in items.iter() {
|
|
||||||
if let Some(uid_val) = &each.uid
|
|
||||||
&& uid_val.as_str() == uid_str
|
|
||||||
{
|
|
||||||
return Ok(each);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Err(ProfileNotFound {
|
|
||||||
uid: uid_str.to_owned(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Inserts a prepared entry after any required body write.
|
|
||||||
pub fn append_item(&mut self, item: &PrfItem) {
|
|
||||||
if self.current.is_none() && matches!(item.itype.as_deref(), Some("remote" | "local")) {
|
|
||||||
self.current = item.uid.clone();
|
|
||||||
}
|
|
||||||
|
|
||||||
self.items.get_or_insert_with(Vec::new).push(item.clone());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns true if both IDs were found, including when the item stayed at its old position.
|
|
||||||
pub fn reorder(&mut self, active_id: &str, over_id: &str) -> bool {
|
|
||||||
let Some(items) = self.items.as_mut() else {
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
let old_index = items.iter().rposition(|item| item.uid.as_deref() == Some(active_id));
|
|
||||||
let new_index = items.iter().rposition(|item| item.uid.as_deref() == Some(over_id));
|
|
||||||
let (Some(old_idx), Some(new_idx)) = (old_index, new_index) else {
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
let item = items.remove(old_idx);
|
|
||||||
items.insert(new_idx, item);
|
|
||||||
true
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn plan_delete_item(&mut self, uid: &str) -> Result<ProfileDeletePlan, ProfileNotFound> {
|
|
||||||
let deleting_current = self.current.as_deref().is_none_or(|current| current == uid);
|
|
||||||
let delete_uids = self.get_item(uid)?.option.as_ref().map_or_else(Vec::new, |op| {
|
|
||||||
[
|
|
||||||
op.merge.clone(),
|
|
||||||
op.script.clone(),
|
|
||||||
op.rules.clone(),
|
|
||||||
op.proxies.clone(),
|
|
||||||
op.groups.clone(),
|
|
||||||
]
|
|
||||||
.into_iter()
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
});
|
|
||||||
let mut items = self.items.take().unwrap_or_default();
|
|
||||||
let mut files = Vec::new();
|
|
||||||
|
|
||||||
if let Some(file) = take_item_file_by_uid(&mut items, Some(uid)) {
|
|
||||||
files.push(file);
|
|
||||||
}
|
|
||||||
|
|
||||||
for delete_uid in delete_uids {
|
|
||||||
if let Some(file) = take_item_file_by_uid(&mut items, delete_uid.as_deref()) {
|
|
||||||
files.push(file);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if deleting_current {
|
|
||||||
self.current = None;
|
|
||||||
for item in items.iter() {
|
|
||||||
if matches!(item.itype.as_deref(), Some("remote" | "local")) {
|
|
||||||
self.current = item.uid.clone();
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
self.items = Some(items);
|
|
||||||
Ok(ProfileDeletePlan {
|
|
||||||
deleting_current,
|
|
||||||
files,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn profiles_preview(&self) -> Option<Vec<IProfilePreview<'_>>> {
|
|
||||||
self.items.as_ref().map(|items| {
|
|
||||||
items
|
|
||||||
.iter()
|
|
||||||
.filter_map(|e| {
|
|
||||||
if let (Some(uid), Some(name)) = (e.uid.as_ref(), e.name.as_ref()) {
|
|
||||||
let is_current = self.current.as_ref() == Some(uid);
|
|
||||||
let preview = IProfilePreview { uid, name, is_current };
|
|
||||||
Some(preview)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn take_item_file_by_uid(items: &mut Vec<PrfItem>, target_uid: Option<&str>) -> Option<String> {
|
|
||||||
let index = items.iter().position(|item| item.uid.as_deref() == target_uid)?;
|
|
||||||
items.remove(index).file
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn old_index_preserves_missing_and_explicit_values() -> Result<(), Box<dyn std::error::Error>> {
|
|
||||||
let mut profiles: IProfiles = serde_yaml_ng::from_str(
|
|
||||||
r#"
|
|
||||||
current: first
|
|
||||||
items:
|
|
||||||
- uid: first
|
|
||||||
type: remote
|
|
||||||
option: {allow_auto_update: false, update_interval: 0, merge: ""}
|
|
||||||
file_data: ignored
|
|
||||||
- uid: second
|
|
||||||
name: ""
|
|
||||||
"#,
|
|
||||||
)?;
|
|
||||||
let first = profiles.get_item("first")?;
|
|
||||||
assert!(first.file_data.is_none());
|
|
||||||
assert_eq!(first.current_merge().map(String::as_str), Some(""));
|
|
||||||
assert!(first.current_script().is_none());
|
|
||||||
if let Some(items) = profiles.items.as_mut() {
|
|
||||||
items[0].file_data = Some("in memory".into());
|
|
||||||
}
|
|
||||||
assert_eq!(
|
|
||||||
serde_json::to_value(&profiles)?,
|
|
||||||
serde_json::json!({
|
|
||||||
"current": "first",
|
|
||||||
"items": [
|
|
||||||
{"uid": "first", "type": "remote", "name": null, "file": null, "updated": null,
|
|
||||||
"option": {"allow_auto_update": false, "update_interval": 0, "merge": "",
|
|
||||||
"script": null, "rules": null, "proxies": null, "groups": null}},
|
|
||||||
{"uid": "second", "type": null, "name": "", "file": null, "updated": null}
|
|
||||||
]
|
|
||||||
})
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
serde_json::to_value(serde_yaml_ng::from_str::<IProfiles>("{}")?)?,
|
|
||||||
serde_json::json!({"current": null, "items": null})
|
|
||||||
);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn merge_overrides_only_explicit_values() {
|
|
||||||
let base = PrfOption {
|
|
||||||
user_agent: Some("original".into()),
|
|
||||||
allow_auto_update: Some(true),
|
|
||||||
update_interval: Some(60),
|
|
||||||
merge: Some("original-merge".into()),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
let overrides = PrfOption {
|
|
||||||
user_agent: Some("".into()),
|
|
||||||
allow_auto_update: Some(false),
|
|
||||||
update_interval: Some(0),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
let expected = PrfOption {
|
|
||||||
merge: base.merge.clone(),
|
|
||||||
..overrides.clone()
|
|
||||||
};
|
|
||||||
assert_eq!(PrfOption::merge(Some(&base), Some(&overrides)), Some(expected));
|
|
||||||
assert_eq!(PrfOption::merge(None, None), None);
|
|
||||||
assert_eq!(
|
|
||||||
PrfOption::merge(None, Some(&PrfOption::default())),
|
|
||||||
Some(PrfOption::default())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn lookup_preview_and_reorder_preserve_duplicate_uid_rules() -> Result<(), Box<dyn std::error::Error>> {
|
|
||||||
let mut profiles: IProfiles = serde_yaml_ng::from_str(
|
|
||||||
r#"
|
|
||||||
current: duplicate
|
|
||||||
items:
|
|
||||||
- {uid: duplicate, name: first}
|
|
||||||
- {uid: duplicate, name: last}
|
|
||||||
- {uid: target, name: ""}
|
|
||||||
- {name: no UID}
|
|
||||||
"#,
|
|
||||||
)?;
|
|
||||||
assert_eq!(profiles.get_item("duplicate")?.name.as_deref(), Some("first"));
|
|
||||||
assert!(!profiles.reorder("missing", "target"));
|
|
||||||
assert!(!profiles.reorder("duplicate", "missing"));
|
|
||||||
assert!(profiles.reorder("duplicate", "duplicate"));
|
|
||||||
assert!(profiles.reorder("duplicate", "target"));
|
|
||||||
let preview = profiles.profiles_preview().unwrap_or_default();
|
|
||||||
let names: Vec<_> = preview
|
|
||||||
.iter()
|
|
||||||
.map(|item| (item.name.as_str(), item.is_current))
|
|
||||||
.collect();
|
|
||||||
assert_eq!(names, [("first", true), ("", false), ("last", true)]);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn current_patch_initializes_missing_items_and_only_selects_an_existing_uid() {
|
|
||||||
let mut profiles = IProfiles::default();
|
|
||||||
profiles.patch_current(None);
|
|
||||||
assert!(matches!(&profiles.items, Some(items) if items.is_empty()));
|
|
||||||
assert!(profiles.current.is_none());
|
|
||||||
profiles.append_item(&PrfItem {
|
|
||||||
uid: Some("script".into()),
|
|
||||||
itype: Some("script".into()),
|
|
||||||
..Default::default()
|
|
||||||
});
|
|
||||||
assert!(profiles.current.is_none());
|
|
||||||
profiles.append_item(&PrfItem {
|
|
||||||
uid: Some("local".into()),
|
|
||||||
itype: Some("local".into()),
|
|
||||||
..Default::default()
|
|
||||||
});
|
|
||||||
assert_eq!(profiles.current.as_deref(), Some("local"));
|
|
||||||
profiles.patch_current(None);
|
|
||||||
profiles.patch_current(Some(&String::from("missing")));
|
|
||||||
assert_eq!(profiles.current.as_deref(), Some("local"));
|
|
||||||
profiles.patch_current(Some(&String::from("script")));
|
|
||||||
assert_eq!(profiles.current.as_deref(), Some("script"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn delete_plan_preserves_file_order_and_legacy_missing_uid_matching() -> Result<(), Box<dyn std::error::Error>> {
|
|
||||||
let mut profiles: IProfiles = serde_yaml_ng::from_str(
|
|
||||||
r"
|
|
||||||
items:
|
|
||||||
- {uid: active, type: remote, file: first.yaml, option: {merge: owned}}
|
|
||||||
- {uid: owned, type: merge, file: owned.yaml}
|
|
||||||
- {type: script, file: missing-uid.js}
|
|
||||||
- {uid: next, type: local, file: next.yaml}
|
|
||||||
",
|
|
||||||
)?;
|
|
||||||
let plan = profiles.plan_delete_item("active")?;
|
|
||||||
assert!(plan.deleting_current);
|
|
||||||
assert_eq!(
|
|
||||||
plan.files,
|
|
||||||
["first.yaml", "owned.yaml", "missing-uid.js"].map(String::from)
|
|
||||||
);
|
|
||||||
assert_eq!(profiles.current.as_deref(), Some("next"));
|
|
||||||
assert!(profiles.get_item("owned").is_err());
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,147 +0,0 @@
|
|||||||
use super::PrfSelected;
|
|
||||||
use std::collections::HashSet;
|
|
||||||
use tristr::alias::String;
|
|
||||||
|
|
||||||
pub struct SelectedGroup<'a> {
|
|
||||||
pub members: Option<&'a [std::string::String]>,
|
|
||||||
pub current: Option<&'a str>,
|
|
||||||
pub selectable: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, PartialEq, Eq)]
|
|
||||||
pub struct SelectedNodesPlan {
|
|
||||||
pub selected: Vec<PrfSelected>,
|
|
||||||
pub activations: Vec<(String, String)>,
|
|
||||||
pub repaired_count: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn node_is_available(available_nodes: &[std::string::String], node: &str) -> bool {
|
|
||||||
available_nodes.iter().any(|available| available == node)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn selected_nodes_need_confirmation<'a, Snapshot>(
|
|
||||||
selected: &[PrfSelected],
|
|
||||||
snapshot: &'a Snapshot,
|
|
||||||
lookup: impl Fn(&'a Snapshot, &str) -> Option<SelectedGroup<'a>>,
|
|
||||||
) -> bool {
|
|
||||||
selected.iter().any(|selected_item| {
|
|
||||||
let (Some(group_name), Some(node)) = (&selected_item.name, &selected_item.now) else {
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
let Some(group) = lookup(snapshot, group_name) else {
|
|
||||||
return true;
|
|
||||||
};
|
|
||||||
let Some(available_nodes) = group.members.filter(|nodes| !nodes.is_empty()) else {
|
|
||||||
return true;
|
|
||||||
};
|
|
||||||
!node_is_available(available_nodes, node)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn reconcile_selected_nodes<'a, Snapshot>(
|
|
||||||
selected: &[PrfSelected],
|
|
||||||
previous: Option<&'a Snapshot>,
|
|
||||||
current: &'a Snapshot,
|
|
||||||
lookup: impl Fn(&'a Snapshot, &str) -> Option<SelectedGroup<'a>>,
|
|
||||||
) -> SelectedNodesPlan {
|
|
||||||
let mut plan = SelectedNodesPlan {
|
|
||||||
selected: Vec::with_capacity(selected.len()),
|
|
||||||
activations: Vec::new(),
|
|
||||||
repaired_count: 0,
|
|
||||||
};
|
|
||||||
let mut seen_groups = HashSet::new();
|
|
||||||
let mut unique_selected = selected
|
|
||||||
.iter()
|
|
||||||
.rev()
|
|
||||||
.filter(|item| item.name.as_deref().is_some_and(|name| seen_groups.insert(name)))
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
unique_selected.reverse();
|
|
||||||
plan.repaired_count += selected.len() - unique_selected.len();
|
|
||||||
|
|
||||||
for selected_item in unique_selected {
|
|
||||||
let (Some(group_name), Some(node)) = (&selected_item.name, &selected_item.now) else {
|
|
||||||
plan.repaired_count += 1;
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let Some(group) = lookup(current, group_name) else {
|
|
||||||
if previous.is_some_and(|snapshot| lookup(snapshot, group_name).is_none()) {
|
|
||||||
plan.repaired_count += 1;
|
|
||||||
} else {
|
|
||||||
plan.selected.push(selected_item.clone());
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let Some(available_nodes) = group.members.filter(|nodes| !nodes.is_empty()) else {
|
|
||||||
// Provider-backed groups can be temporarily incomplete immediately after a reload.
|
|
||||||
plan.selected.push(selected_item.clone());
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
if !group.selectable {
|
|
||||||
let preferred_node = group
|
|
||||||
.current
|
|
||||||
.filter(|current| node_is_available(available_nodes, current))
|
|
||||||
.or_else(|| node_is_available(available_nodes, node).then_some(node.as_str()));
|
|
||||||
let Some(preferred_node) = preferred_node else {
|
|
||||||
plan.repaired_count += 1;
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
plan.repaired_count += usize::from(preferred_node != node.as_str());
|
|
||||||
plan.selected.push(PrfSelected {
|
|
||||||
name: Some(group_name.clone()),
|
|
||||||
now: Some(preferred_node.into()),
|
|
||||||
});
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if node_is_available(available_nodes, node) {
|
|
||||||
plan.selected.push(selected_item.clone());
|
|
||||||
if group.current != Some(node.as_str()) {
|
|
||||||
plan.activations.push((group_name.clone(), node.clone()));
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
let missing_was_confirmed = previous
|
|
||||||
.and_then(|snapshot| lookup(snapshot, group_name))
|
|
||||||
.and_then(|group| group.members)
|
|
||||||
.filter(|nodes| !nodes.is_empty())
|
|
||||||
.is_some_and(|nodes| !node_is_available(nodes, node));
|
|
||||||
if !missing_was_confirmed {
|
|
||||||
plan.selected.push(selected_item.clone());
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
plan.repaired_count += 1;
|
|
||||||
if let Some(current_node) = group
|
|
||||||
.current
|
|
||||||
.filter(|current| node_is_available(available_nodes, current))
|
|
||||||
{
|
|
||||||
plan.selected.push(PrfSelected {
|
|
||||||
name: Some(group_name.clone()),
|
|
||||||
now: Some(current_node.into()),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
plan
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns recorded selections whose groups have not reached the requested node.
|
|
||||||
pub fn unsettled_selections<'a, Snapshot>(
|
|
||||||
selected: &[PrfSelected],
|
|
||||||
snapshot: &'a Snapshot,
|
|
||||||
lookup: impl Fn(&'a Snapshot, &str) -> Option<SelectedGroup<'a>>,
|
|
||||||
) -> Vec<String> {
|
|
||||||
selected
|
|
||||||
.iter()
|
|
||||||
.filter_map(|item| {
|
|
||||||
let (Some(group_name), Some(node)) = (&item.name, &item.now) else {
|
|
||||||
return None;
|
|
||||||
};
|
|
||||||
match lookup(snapshot, group_name) {
|
|
||||||
Some(group) if group.current == Some(node.as_str()) => None,
|
|
||||||
_ => Some(group_name.clone()),
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
use super::PrfItem;
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
/// Scheduling policy for a Profile, independent of the task queue and clock.
|
|
||||||
#[derive(Debug, PartialEq, Eq)]
|
|
||||||
pub struct SubscriptionSchedule {
|
|
||||||
pub interval_minutes: u64,
|
|
||||||
pub first_delay: Duration,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl SubscriptionSchedule {
|
|
||||||
pub fn for_profile(item: &PrfItem, initializing: bool, now: i64) -> Option<Self> {
|
|
||||||
let option = item.option.as_ref()?;
|
|
||||||
let interval = option.update_interval.filter(|interval| *interval > 0)?;
|
|
||||||
if !option.allow_auto_update.unwrap_or(true) {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut schedule = Self::new(interval, item.updated, now);
|
|
||||||
// Startup historically treats an explicit zero timestamp as overdue.
|
|
||||||
if initializing && item.updated == Some(0) {
|
|
||||||
schedule.first_delay = Duration::ZERO;
|
|
||||||
}
|
|
||||||
Some(schedule)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn new(interval_minutes: u64, updated: Option<usize>, now: i64) -> Self {
|
|
||||||
let full = Self::interval_duration(interval_minutes);
|
|
||||||
let elapsed = updated
|
|
||||||
.filter(|updated| *updated > 0)
|
|
||||||
.map_or(0, |updated| now.saturating_sub(updated as i64).max(0) as u64);
|
|
||||||
|
|
||||||
Self {
|
|
||||||
interval_minutes,
|
|
||||||
first_delay: full.saturating_sub(Duration::from_secs(elapsed)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub const fn interval_duration(interval_minutes: u64) -> Duration {
|
|
||||||
Duration::from_secs(interval_minutes.saturating_mul(60))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The UI deadline is based on the last saved update. The queue can delay retries further.
|
|
||||||
pub fn reported_deadline(interval_minutes: u64, updated: Option<usize>) -> Option<i64> {
|
|
||||||
let updated = i64::try_from(updated.filter(|updated| *updated > 0)?).ok()?;
|
|
||||||
let interval = i64::try_from(interval_minutes).ok()?.checked_mul(60)?;
|
|
||||||
updated.checked_add(interval)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "clash-verge-proxy-view"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
serde = { workspace = true, features = ["derive"] }
|
|
||||||
specta = { workspace = true, features = ["derive"] }
|
|
||||||
tristr = { workspace = true }
|
|
||||||
|
|
||||||
[lints]
|
|
||||||
workspace = true
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "clash-verge-runtime-bundle"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
thiserror = { workspace = true }
|
|
||||||
clash-verge-logging = { workspace = true }
|
|
||||||
hex = "0.4.3"
|
|
||||||
log = { workspace = true }
|
|
||||||
serde_yaml_ng = { workspace = true }
|
|
||||||
sha2 = { workspace = true }
|
|
||||||
tristr = { workspace = true }
|
|
||||||
tokio = { workspace = true, features = ["fs"] }
|
|
||||||
|
|
||||||
[lints]
|
|
||||||
workspace = true
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
#[derive(Debug, thiserror::Error)]
|
|
||||||
pub enum RuntimeBundleError {
|
|
||||||
#[error(transparent)]
|
|
||||||
Io(#[from] std::io::Error),
|
|
||||||
#[error("failed to read runtime config {path:?}")]
|
|
||||||
ReadConfig {
|
|
||||||
path: PathBuf,
|
|
||||||
#[source]
|
|
||||||
source: std::io::Error,
|
|
||||||
},
|
|
||||||
#[error("failed to parse runtime config {path:?}")]
|
|
||||||
ParseConfig {
|
|
||||||
path: PathBuf,
|
|
||||||
#[source]
|
|
||||||
source: serde_yaml_ng::Error,
|
|
||||||
},
|
|
||||||
#[error("runtime config has no parent directory")]
|
|
||||||
MissingConfigDirectory,
|
|
||||||
#[error("runtime provider destination {0:?} is declared for two different sources")]
|
|
||||||
DifferentSources(String),
|
|
||||||
#[error("runtime provider destination {0:?} is claimed more than once")]
|
|
||||||
DuplicateDestination(String),
|
|
||||||
#[error("local runtime provider is unavailable: {path:?}")]
|
|
||||||
LocalProviderUnavailable {
|
|
||||||
path: PathBuf,
|
|
||||||
#[source]
|
|
||||||
source: std::io::Error,
|
|
||||||
},
|
|
||||||
#[error("local runtime provider is outside the config root: {0:?}")]
|
|
||||||
LocalProviderOutsideRoot(PathBuf),
|
|
||||||
#[error("runtime provider destination traverses outside the runtime")]
|
|
||||||
DestinationOutsideRuntime,
|
|
||||||
#[error("runtime provider path has no existing ancestor: {0:?}")]
|
|
||||||
MissingAncestor(PathBuf),
|
|
||||||
#[error("runtime provider path is outside the config root: {0:?}")]
|
|
||||||
ProviderOutsideRoot(PathBuf),
|
|
||||||
#[error("local runtime provider destination traverses outside the runtime")]
|
|
||||||
LocalDestinationOutsideRuntime,
|
|
||||||
#[error("local runtime provider destination is empty")]
|
|
||||||
EmptyDestination,
|
|
||||||
}
|
|
||||||
@@ -4,7 +4,7 @@ version = "0.1.0"
|
|||||||
edition = "2024"
|
edition = "2024"
|
||||||
rust-version = "1.91"
|
rust-version = "1.91"
|
||||||
|
|
||||||
[target.'cfg(target_os = "linux")'.dependencies]
|
[dependencies]
|
||||||
clash-verge-logging = { workspace = true }
|
clash-verge-logging = { workspace = true }
|
||||||
log = { workspace = true }
|
log = { workspace = true }
|
||||||
tokio = { workspace = true, features = ["signal"] }
|
tokio = { workspace = true, features = ["signal"] }
|
||||||
|
|||||||
@@ -1,14 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "clash-verge-subscription"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
thiserror = { workspace = true }
|
|
||||||
http = "1"
|
|
||||||
percent-encoding = "2.3.2"
|
|
||||||
serde_yaml_ng = { workspace = true }
|
|
||||||
url = "2.5"
|
|
||||||
|
|
||||||
[lints]
|
|
||||||
workspace = true
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
use percent_encoding::percent_decode_str;
|
|
||||||
use std::borrow::Cow;
|
|
||||||
use url::Url;
|
|
||||||
|
|
||||||
pub struct SubscriptionLink<'a> {
|
|
||||||
pub url: Cow<'a, str>,
|
|
||||||
pub name: Option<Cow<'a, str>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn decode_subscription_link(link: &Url) -> Option<SubscriptionLink<'_>> {
|
|
||||||
if !matches!(link.scheme(), "clash" | "clash-verge") {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
// The embedded URL can contain unescaped query separators of its own.
|
|
||||||
let raw_url = link.query()?.split_once("url=")?.1.trim();
|
|
||||||
let name = link.query_pairs().find(|(key, _)| key == "name").map(|(_, name)| name);
|
|
||||||
Some(SubscriptionLink {
|
|
||||||
url: decode_subscription_url(raw_url),
|
|
||||||
name,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn decode_subscription_url(raw_url: &str) -> Cow<'_, str> {
|
|
||||||
let mut candidate = Cow::Borrowed(raw_url);
|
|
||||||
if Url::parse(raw_url).is_ok() {
|
|
||||||
return candidate;
|
|
||||||
}
|
|
||||||
|
|
||||||
for _ in 0..2 {
|
|
||||||
let decoded = percent_decode_str(&candidate).decode_utf8_lossy();
|
|
||||||
if decoded == candidate {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
candidate = Cow::Owned(decoded.into_owned());
|
|
||||||
if Url::parse(&candidate).is_ok() {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
candidate
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn preserves_nested_query_separators_and_decodes_wrapped_links() -> Result<(), url::ParseError> {
|
|
||||||
let plain = Url::parse("clash://install-config?name=Work%20VPN&url=https://example.invalid/sub?a=1&b=2")?;
|
|
||||||
let link = decode_subscription_link(&plain).expect("plain subscription link");
|
|
||||||
assert_eq!(link.name.as_deref(), Some("Work VPN"));
|
|
||||||
assert!(matches!(link.url, Cow::Borrowed("https://example.invalid/sub?a=1&b=2")));
|
|
||||||
|
|
||||||
let encoded = Url::parse("clash-verge://install-config?url=https%253A%252F%252Fexample.invalid%252Fsub")?;
|
|
||||||
let link = decode_subscription_link(&encoded).expect("double-encoded subscription link");
|
|
||||||
assert_eq!(link.url, "https://example.invalid/sub");
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
#[derive(Debug, thiserror::Error)]
|
|
||||||
pub enum SubscriptionError {
|
|
||||||
#[error("the remote profile data is invalid yaml")]
|
|
||||||
InvalidYaml(#[source] serde_yaml_ng::Error),
|
|
||||||
#[error("profile does not contain `proxies` or `proxy-providers`")]
|
|
||||||
MissingProviders,
|
|
||||||
}
|
|
||||||
@@ -1,193 +0,0 @@
|
|||||||
mod deep_link;
|
|
||||||
mod error;
|
|
||||||
|
|
||||||
pub use deep_link::{SubscriptionLink, decode_subscription_link};
|
|
||||||
pub use error::SubscriptionError;
|
|
||||||
|
|
||||||
use http::HeaderMap;
|
|
||||||
use percent_encoding::percent_decode_str;
|
|
||||||
use serde_yaml_ng::Mapping;
|
|
||||||
use url::Url;
|
|
||||||
|
|
||||||
pub struct SubscriptionDocument<'a> {
|
|
||||||
pub body: &'a str,
|
|
||||||
pub filename: Option<String>,
|
|
||||||
pub usage: Option<SubscriptionUsage>,
|
|
||||||
pub update_interval_minutes: Option<u64>,
|
|
||||||
pub home: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct SubscriptionUsage {
|
|
||||||
pub upload: u64,
|
|
||||||
pub download: u64,
|
|
||||||
pub total: u64,
|
|
||||||
pub expire: u64,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn decode_subscription<'a>(
|
|
||||||
url: &Url,
|
|
||||||
headers: &HeaderMap,
|
|
||||||
body: &'a str,
|
|
||||||
) -> Result<SubscriptionDocument<'a>, SubscriptionError> {
|
|
||||||
let body = body.trim_start_matches('\u{feff}');
|
|
||||||
let yaml = serde_yaml_ng::from_str::<Mapping>(body).map_err(SubscriptionError::InvalidYaml)?;
|
|
||||||
|
|
||||||
if !yaml.contains_key("proxies") && !yaml.contains_key("proxy-providers") {
|
|
||||||
return Err(SubscriptionError::MissingProviders);
|
|
||||||
}
|
|
||||||
|
|
||||||
let usage = headers.iter().find_map(|(name, value)| {
|
|
||||||
let prefix = name.as_str().strip_suffix("subscription-userinfo")?;
|
|
||||||
if !prefix.is_empty() && !prefix.ends_with('-') {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
let value = value.to_str().unwrap_or("");
|
|
||||||
Some(SubscriptionUsage {
|
|
||||||
upload: find_field(value, "upload", |field| field.parse().ok()).unwrap_or(0),
|
|
||||||
download: find_field(value, "download", |field| field.parse().ok()).unwrap_or(0),
|
|
||||||
total: find_field(value, "total", |field| field.parse().ok()).unwrap_or(0),
|
|
||||||
expire: find_field(value, "expire", |field| field.parse().ok()).unwrap_or(0),
|
|
||||||
})
|
|
||||||
});
|
|
||||||
let update_interval_minutes = headers.get("profile-update-interval").and_then(|value| {
|
|
||||||
let hours = value.to_str().ok()?.parse::<u64>().ok()?;
|
|
||||||
hours.checked_mul(60)
|
|
||||||
});
|
|
||||||
let home = headers
|
|
||||||
.get("profile-web-page-url")
|
|
||||||
.and_then(|value| value.to_str().ok())
|
|
||||||
.and_then(normalize_profile_home_url);
|
|
||||||
|
|
||||||
Ok(SubscriptionDocument {
|
|
||||||
body,
|
|
||||||
filename: subscription_filename(url, headers),
|
|
||||||
usage,
|
|
||||||
update_interval_minutes,
|
|
||||||
home,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn subscription_filename(url: &Url, headers: &HeaderMap) -> Option<String> {
|
|
||||||
if let Some(value) = headers.get("content-disposition") {
|
|
||||||
let disposition = format!("{value:?}");
|
|
||||||
let disposition = disposition.trim_matches('"');
|
|
||||||
if let Some(encoded) = find_field(disposition, "filename*", Some)
|
|
||||||
&& let Ok(decoded) = percent_decode_str(encoded).decode_utf8()
|
|
||||||
&& let Some(filename) = decoded.split("''").last()
|
|
||||||
&& !filename.trim().is_empty()
|
|
||||||
{
|
|
||||||
return Some(filename.to_owned());
|
|
||||||
}
|
|
||||||
if let Some(filename) = find_field(disposition, "filename", Some).map(|name| name.trim_matches('"'))
|
|
||||||
&& !filename.trim().is_empty()
|
|
||||||
{
|
|
||||||
return Some(filename.to_owned());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let url = url.as_str();
|
|
||||||
let path = url.split_once('?').map_or(url, |(path, _)| path);
|
|
||||||
let filename = path.rsplit_once('/').map_or(path, |(_, filename)| filename);
|
|
||||||
let filename = percent_decode_str(filename).decode_utf8_lossy();
|
|
||||||
if filename.trim().is_empty() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
Some(filename.into_owned())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn normalize_profile_home_url(raw: &str) -> Option<String> {
|
|
||||||
let url = Url::parse(raw.trim()).ok()?;
|
|
||||||
|
|
||||||
if !matches!(url.scheme(), "http" | "https") {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
url.host_str()?;
|
|
||||||
Some(url.as_str().into())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn find_field<'a, T>(target: &'a str, key: &str, mut parse: impl FnMut(&'a str) -> Option<T>) -> Option<T> {
|
|
||||||
target.split(';').map(str::trim).find_map(|s| {
|
|
||||||
let (name, value) = s.split_once('=')?;
|
|
||||||
if name != key {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
parse(value)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use http::HeaderValue;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn decodes_metadata_and_preserves_provider_only_yaml() -> Result<(), Box<dyn std::error::Error>> {
|
|
||||||
let url = Url::parse("https://example.com/fallback.yaml")?;
|
|
||||||
let mut headers = HeaderMap::new();
|
|
||||||
headers.insert(
|
|
||||||
"content-disposition",
|
|
||||||
HeaderValue::from_static("attachment; filename*=UTF-8''My%20Profile.yaml; filename=fallback.yaml"),
|
|
||||||
);
|
|
||||||
headers.insert(
|
|
||||||
"x-amz-meta-subscription-userinfo",
|
|
||||||
HeaderValue::from_static("upload=1; download=2; total=3; expire=4"),
|
|
||||||
);
|
|
||||||
headers.insert("profile-update-interval", HeaderValue::from_static("2"));
|
|
||||||
headers.insert(
|
|
||||||
"profile-web-page-url",
|
|
||||||
HeaderValue::from_static(" https://example.com "),
|
|
||||||
);
|
|
||||||
let yaml = "# keep this comment\nproxy-providers: {}\n";
|
|
||||||
let body = format!("\u{feff}{yaml}");
|
|
||||||
|
|
||||||
let document = decode_subscription(&url, &headers, &body)?;
|
|
||||||
assert_eq!(document.body, yaml);
|
|
||||||
assert_eq!(document.filename.as_deref(), Some("My Profile.yaml"));
|
|
||||||
assert_eq!(document.update_interval_minutes, Some(120));
|
|
||||||
assert_eq!(document.home.as_deref(), Some("https://example.com/"));
|
|
||||||
let usage = document.usage.ok_or("missing subscription usage")?;
|
|
||||||
assert_eq!((usage.upload, usage.download, usage.total, usage.expire), (1, 2, 3, 4));
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn falls_back_when_suggested_filename_is_invalid_or_empty() -> Result<(), Box<dyn std::error::Error>> {
|
|
||||||
let url = Url::parse("https://example.com/url.yaml?token=value")?;
|
|
||||||
let root_url = Url::parse("https://example.com/")?;
|
|
||||||
for (disposition, url, expected) in [
|
|
||||||
(
|
|
||||||
"attachment; filename*=UTF-8''%FF; filename=valid.yaml",
|
|
||||||
&url,
|
|
||||||
Some("valid.yaml"),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"attachment; filename*=UTF-8''; filename=valid.yaml",
|
|
||||||
&url,
|
|
||||||
Some("valid.yaml"),
|
|
||||||
),
|
|
||||||
("attachment; filename*=UTF-8''%FF", &url, Some("url.yaml")),
|
|
||||||
("attachment; filename=", &root_url, None),
|
|
||||||
] {
|
|
||||||
let mut headers = HeaderMap::new();
|
|
||||||
headers.insert("content-disposition", HeaderValue::from_static(disposition));
|
|
||||||
let document = decode_subscription(url, &headers, "proxies: []")?;
|
|
||||||
assert_eq!(document.filename.as_deref(), expected);
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn ignores_overflowing_server_interval() -> Result<(), Box<dyn std::error::Error>> {
|
|
||||||
let url = Url::parse("https://example.com/My%20Profile.yaml?token=value")?;
|
|
||||||
let mut headers = HeaderMap::new();
|
|
||||||
headers.insert("profile-update-interval", HeaderValue::from_str(&u64::MAX.to_string())?);
|
|
||||||
|
|
||||||
let document = decode_subscription(&url, &headers, "proxies: []")?;
|
|
||||||
assert_eq!(document.update_interval_minutes, None);
|
|
||||||
assert_eq!(document.filename.as_deref(), Some("My Profile.yaml"));
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
//! Task drivers and retry primitives with caller-managed runtime and cancellation.
|
//! Single-owner task drivers with caller-managed runtime and cancellation.
|
||||||
|
|
||||||
pub mod countdown;
|
pub mod countdown;
|
||||||
pub mod retry;
|
|
||||||
pub mod scheduled_task;
|
pub mod scheduled_task;
|
||||||
pub mod watch_task;
|
pub mod watch_task;
|
||||||
|
|||||||
+3
-10
@@ -1,17 +1,10 @@
|
|||||||
# Backend Architecture Guardrails
|
# Backend Architecture Guardrails
|
||||||
|
|
||||||
Follow [Workspace Crate Architecture](../crates/AGENTS.md) when changing
|
Use [Workspace Crate Architecture](../crates/AGENTS.md) when extracting backend
|
||||||
backend capability boundaries, reusable orchestration, or background task
|
capabilities or changing background task ownership.
|
||||||
ownership.
|
|
||||||
|
|
||||||
- **Tauri adapter.** Commands validate transport input, delegate to application
|
|
||||||
use cases, and map results and errors to IPC. Tauri wires dependencies and
|
|
||||||
owns desktop lifecycle, window and tray integration, and event delivery.
|
|
||||||
Keep domain validation and reusable orchestration independent of command
|
|
||||||
handlers and framework state.
|
|
||||||
- **Configuration and effects.** `config` owns source configuration, drafts, and
|
- **Configuration and effects.** `config` owns source configuration, drafts, and
|
||||||
persistence coordination. Persistence adapters perform storage and recovery.
|
persistence. The effects layer classifies every Verge patch field, including
|
||||||
The effects layer classifies every Verge patch field, including
|
|
||||||
fields without effects and platform-specific fields, and reconciles requested
|
fields without effects and platform-specific fields, and reconciles requested
|
||||||
state in dependency order. Publish rollbackable state after persistence and
|
state in dependency order. Publish rollbackable state after persistence and
|
||||||
commit. On failure, preserve already applied runtime effects, independently
|
commit. On failure, preserve already applied runtime effects, independently
|
||||||
|
|||||||
+7
-11
@@ -36,13 +36,6 @@ clash-verge-media-unlock = { workspace = true }
|
|||||||
clash-verge-logging = { workspace = true }
|
clash-verge-logging = { workspace = true }
|
||||||
clash-verge-i18n = { workspace = true }
|
clash-verge-i18n = { workspace = true }
|
||||||
clash-verge-limiter = { workspace = true }
|
clash-verge-limiter = { workspace = true }
|
||||||
clash-verge-subscription = { workspace = true }
|
|
||||||
clash-verge-runtime-bundle = { workspace = true }
|
|
||||||
clash-verge-config-render = { workspace = true }
|
|
||||||
clash-verge-profile-script = { workspace = true }
|
|
||||||
clash-verge-proxy-view = { workspace = true }
|
|
||||||
clash-verge-profile = { workspace = true }
|
|
||||||
clash-verge-backup-archive = { workspace = true }
|
|
||||||
tauri-plugin-clash-verge-sysinfo = { workspace = true }
|
tauri-plugin-clash-verge-sysinfo = { workspace = true }
|
||||||
tauri-plugin-clipboard-manager = { workspace = true }
|
tauri-plugin-clipboard-manager = { workspace = true }
|
||||||
tauri = { workspace = true, features = [
|
tauri = { workspace = true, features = [
|
||||||
@@ -69,6 +62,7 @@ dirs = "7.0.0"
|
|||||||
dunce = "1.0.5"
|
dunce = "1.0.5"
|
||||||
nanoid = "0.5"
|
nanoid = "0.5"
|
||||||
chrono = { workspace = true }
|
chrono = { workspace = true }
|
||||||
|
boa_engine = "0.22.0"
|
||||||
http-body-util = "0.1.5"
|
http-body-util = "0.1.5"
|
||||||
percent-encoding = "2.3.2"
|
percent-encoding = "2.3.2"
|
||||||
reqwest = { workspace = true }
|
reqwest = { workspace = true }
|
||||||
@@ -82,12 +76,12 @@ tauri-plugin-dialog = "2.8.4"
|
|||||||
tauri-plugin-fs = "2.7.1"
|
tauri-plugin-fs = "2.7.1"
|
||||||
tauri-plugin-deep-link = "2.6.3"
|
tauri-plugin-deep-link = "2.6.3"
|
||||||
tauri-plugin-window-state = "2.5.0"
|
tauri-plugin-window-state = "2.5.0"
|
||||||
zip = { workspace = true }
|
zip = "9.9.0"
|
||||||
flate2 = "1.1.11"
|
flate2 = "1.1.11"
|
||||||
reqwest_dav = "0.4.0"
|
reqwest_dav = "0.4.0"
|
||||||
aes-gcm = { version = "0.11.1" }
|
aes-gcm = { version = "0.11.1" }
|
||||||
base64 = "0.23.1"
|
base64 = "0.23.1"
|
||||||
sha2 = { workspace = true }
|
sha2 = "0.11.2"
|
||||||
getrandom = "0.4.3"
|
getrandom = "0.4.3"
|
||||||
futures = { workspace = true }
|
futures = { workspace = true }
|
||||||
gethostname = "1.1.0"
|
gethostname = "1.1.0"
|
||||||
@@ -98,7 +92,9 @@ tracing = { workspace = true }
|
|||||||
tauri-plugin-devtools = { version = "2.2.3", optional = true }
|
tauri-plugin-devtools = { version = "2.2.3", optional = true }
|
||||||
tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", rev = "7e4fa8642cf6c394ed88b5a969420d8eab60087f" }
|
tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", rev = "7e4fa8642cf6c394ed88b5a969420d8eab60087f" }
|
||||||
async-trait = "0.1.92"
|
async-trait = "0.1.92"
|
||||||
clash_verge_service_ipc = { workspace = true, features = ["client"] }
|
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", branch = "main", version = "2.8.2", features = [
|
||||||
|
"client",
|
||||||
|
] }
|
||||||
arc-swap = "1.9.5"
|
arc-swap = "1.9.5"
|
||||||
tokio-rustls = "0.26.6"
|
tokio-rustls = "0.26.6"
|
||||||
rustls = { version = "0.23.46", features = ["ring"] }
|
rustls = { version = "0.23.46", features = ["ring"] }
|
||||||
@@ -106,7 +102,7 @@ webpki-roots = "1.0.12"
|
|||||||
dark-light = "3.0.0"
|
dark-light = "3.0.0"
|
||||||
bytes = "1.12.2"
|
bytes = "1.12.2"
|
||||||
tokio-util = { version = "0.7.20", features = ["time"] }
|
tokio-util = { version = "0.7.20", features = ["time"] }
|
||||||
specta = { workspace = true, features = ["derive", "function", "serde_json"] }
|
specta = { version = "=2.0.0-rc.26", features = ["derive", "function", "serde_json"] }
|
||||||
tauri-specta = { version = "=2.0.0-rc.26", features = ["derive", "typescript"] }
|
tauri-specta = { version = "=2.0.0-rc.26", features = ["derive", "typescript"] }
|
||||||
specta-typescript = "=0.0.13"
|
specta-typescript = "=0.0.13"
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
#![deny(clippy::expect_used, clippy::unwrap_used)]
|
|
||||||
|
|
||||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows")
|
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows")
|
||||||
&& std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc")
|
&& std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc")
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
#![deny(clippy::expect_used, clippy::unwrap_used)]
|
|
||||||
|
|
||||||
// Dev-only target: Tauri ships everything under src/bin/ to /usr/bin in deb/rpm
|
// Dev-only target: Tauri ships everything under src/bin/ to /usr/bin in deb/rpm
|
||||||
// bundles (PR #8131), so this generator must stay an example, never a bin.
|
// bundles (PR #8131), so this generator must stay an example, never a bin.
|
||||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
use super::{CmdResult, CommandFailure, WithErrorCode as _, proxy_aware_coded_error, proxy_aware_error};
|
use super::{CmdResult, CommandFailure, WithErrorCode as _, proxy_aware_coded_error, proxy_aware_error};
|
||||||
use crate::core::notify::NoticeStatus;
|
use crate::core::notify::NoticeStatus;
|
||||||
use crate::feat;
|
use crate::feat;
|
||||||
use crate::utils::dirs;
|
use crate::utils::{dirs, yaml_emitter};
|
||||||
use crate::{
|
use crate::{
|
||||||
cmd::StringifyErr as _,
|
cmd::StringifyErr as _,
|
||||||
config::{ClashInfo, Config, mihomo_yaml, profiles::profiles_save_file_safe},
|
config::{ClashInfo, Config, profiles::profiles_save_file_safe},
|
||||||
constants,
|
constants,
|
||||||
core::{
|
core::{
|
||||||
CoreManager, handle,
|
CoreManager, handle,
|
||||||
@@ -132,7 +132,7 @@ pub async fn save_dns_config(dns_config: crate::ipc::YamlMapping) -> CmdResult {
|
|||||||
|
|
||||||
let dns_path = dirs::app_home_dir().stringify_err()?.join(constants::files::DNS_CONFIG);
|
let dns_path = dirs::app_home_dir().stringify_err()?.join(constants::files::DNS_CONFIG);
|
||||||
|
|
||||||
let yaml_str = mihomo_yaml::serialize_for_export(&dns_config.0).stringify_err()?;
|
let yaml_str = yaml_emitter::to_mihomo_config_string(&dns_config.0).stringify_err()?;
|
||||||
fs::write(&dns_path, yaml_str).await.stringify_err()?;
|
fs::write(&dns_path, yaml_str).await.stringify_err()?;
|
||||||
logging!(info, Type::Config, "DNS config saved to {dns_path:?}");
|
logging!(info, Type::Config, "DNS config saved to {dns_path:?}");
|
||||||
|
|
||||||
|
|||||||
@@ -5,13 +5,12 @@ use crate::core::notify::NoticeStatus;
|
|||||||
use crate::utils::window_manager::WindowManager;
|
use crate::utils::window_manager::WindowManager;
|
||||||
use crate::{
|
use crate::{
|
||||||
config::{
|
config::{
|
||||||
Config, IProfiles, PrfItem, PrfOption, build_remote_profile,
|
Config, IProfiles, PrfItem, PrfOption,
|
||||||
profiles::{
|
profiles::{
|
||||||
PROFILE_WRITE_LOCK, cleanup_profile_files, profiles_append_item_safe,
|
PROFILE_WRITE_LOCK, profiles_append_item_with_filedata_safe, profiles_patch_item_safe,
|
||||||
profiles_append_item_with_filedata_safe, profiles_patch_item_safe, profiles_reorder_safe,
|
profiles_reorder_safe, profiles_save_file_safe,
|
||||||
profiles_save_file_safe, save_profiles,
|
|
||||||
},
|
},
|
||||||
read_profile_item_file,
|
profiles_append_item_safe,
|
||||||
},
|
},
|
||||||
core::{CoreManager, handle, timer::Timer, tray::Tray, validate::ValidationOutcome},
|
core::{CoreManager, handle, timer::Timer, tray::Tray, validate::ValidationOutcome},
|
||||||
feat,
|
feat,
|
||||||
@@ -72,7 +71,7 @@ pub async fn enhance_profiles() -> CmdResult<ValidationOutcome> {
|
|||||||
#[tracing::instrument(skip_all, level = "info", fields(url = %help::mask_url(&url), uid = tracing::field::Empty))]
|
#[tracing::instrument(skip_all, level = "info", fields(url = %help::mask_url(&url), uid = tracing::field::Empty))]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub async fn import_profile(url: std::string::String, option: Option<PrfOption>) -> CmdResult {
|
pub async fn import_profile(url: std::string::String, option: Option<PrfOption>) -> CmdResult {
|
||||||
let item = &mut match build_remote_profile(&url, None, None, option.as_ref()).await {
|
let item = &mut match PrfItem::from_url(&url, None, None, option.as_ref()).await {
|
||||||
Ok(it) => it,
|
Ok(it) => it,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
logging!(error, Type::Cmd, "[导入订阅] 下载失败: {e:#}");
|
logging!(error, Type::Cmd, "[导入订阅] 下载失败: {e:#}");
|
||||||
@@ -160,10 +159,9 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
|
|||||||
|
|
||||||
let profiles = Config::profiles().await;
|
let profiles = Config::profiles().await;
|
||||||
let result = profiles
|
let result = profiles
|
||||||
.with_data_modify::<_, _, _, anyhow::Error>(|mut candidate| async move {
|
.with_data_modify(|mut candidate| async move {
|
||||||
let original = candidate.clone();
|
let original = candidate.clone();
|
||||||
let plan = candidate.plan_delete_item(&index)?;
|
let (should_update, plan) = candidate.plan_delete_item(&index)?;
|
||||||
let should_update = plan.deleting_current;
|
|
||||||
let guard = if should_update {
|
let guard = if should_update {
|
||||||
match CoreManager::global()
|
match CoreManager::global()
|
||||||
.update_config_forced_with_profiles(&candidate, &original)
|
.update_config_forced_with_profiles(&candidate, &original)
|
||||||
@@ -173,11 +171,11 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
|
|||||||
Err(outcome) => return Ok((original, Err(outcome))),
|
Err(outcome) => return Ok((original, Err(outcome))),
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
save_profiles(&candidate).await?;
|
candidate.save_file().await?;
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
let current = candidate.current.clone();
|
let current = candidate.current.clone();
|
||||||
cleanup_profile_files(plan.files).await;
|
plan.cleanup().await;
|
||||||
Ok((candidate, Ok((should_update, current, guard))))
|
Ok((candidate, Ok((should_update, current, guard))))
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
@@ -212,11 +210,15 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn restore_previous_profile(prev_profile: &String) -> CmdResult<()> {
|
async fn restore_previous_profile(prev_profile: &str) -> CmdResult<()> {
|
||||||
logging!(info, Type::Cmd, "尝试恢复到之前的配置: {}", prev_profile);
|
logging!(info, Type::Cmd, "尝试恢复到之前的配置: {}", prev_profile);
|
||||||
|
let restore_profiles = IProfiles {
|
||||||
|
current: Some(prev_profile.into()),
|
||||||
|
items: None,
|
||||||
|
};
|
||||||
Config::profiles()
|
Config::profiles()
|
||||||
.await
|
.await
|
||||||
.edit_draft(|d| d.patch_current(Some(prev_profile)));
|
.edit_draft(|d| d.patch_config(&restore_profiles));
|
||||||
Config::profiles().await.apply();
|
Config::profiles().await.apply();
|
||||||
crate::process::AsyncHandler::spawn(|| async move {
|
crate::process::AsyncHandler::spawn(|| async move {
|
||||||
if let Err(e) = profiles_save_file_safe().await {
|
if let Err(e) = profiles_save_file_safe().await {
|
||||||
@@ -234,7 +236,10 @@ async fn commit_current_profile(profiles: &Draft<IProfiles>, current: Option<Str
|
|||||||
|
|
||||||
profiles
|
profiles
|
||||||
.with_data_modify(|mut committed| async move {
|
.with_data_modify(|mut committed| async move {
|
||||||
committed.patch_current(Some(¤t));
|
committed.patch_config(&IProfiles {
|
||||||
|
current: Some(current),
|
||||||
|
items: None,
|
||||||
|
});
|
||||||
Ok((committed, ()))
|
Ok((committed, ()))
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
@@ -392,12 +397,16 @@ pub async fn patch_profiles_config(profiles: ProfileSelection) -> CmdResult<Vali
|
|||||||
});
|
});
|
||||||
let _profile_write_guard = PROFILE_WRITE_LOCK.lock().await;
|
let _profile_write_guard = PROFILE_WRITE_LOCK.lock().await;
|
||||||
|
|
||||||
|
let profiles = IProfiles {
|
||||||
|
current: profiles.current,
|
||||||
|
items: None,
|
||||||
|
};
|
||||||
let target_profile = profiles.current.as_ref();
|
let target_profile = profiles.current.as_ref();
|
||||||
|
|
||||||
let previous_profile = Config::profiles().await.data_arc().current.clone();
|
let previous_profile = Config::profiles().await.data_arc().current.clone();
|
||||||
|
|
||||||
Config::profiles().await.edit_draft(|d| {
|
Config::profiles().await.edit_draft(|d| {
|
||||||
d.patch_current(target_profile);
|
d.patch_config(&profiles);
|
||||||
});
|
});
|
||||||
|
|
||||||
perform_config_update(target_profile, previous_profile.as_ref())
|
perform_config_update(target_profile, previous_profile.as_ref())
|
||||||
@@ -483,17 +492,20 @@ pub async fn view_profile(index: std::string::String) -> CmdResult {
|
|||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub async fn read_profile_file(index: std::string::String) -> CmdResult<std::string::String> {
|
pub async fn read_profile_file(index: std::string::String) -> CmdResult<std::string::String> {
|
||||||
let file = {
|
let item = {
|
||||||
let profiles = Config::profiles().await;
|
let profiles = Config::profiles().await;
|
||||||
let profiles_ref = profiles.latest_arc();
|
let profiles_ref = profiles.latest_arc();
|
||||||
profiles_ref
|
PrfItem {
|
||||||
.get_item(&index)
|
file: profiles_ref
|
||||||
.with_error_code("PROFILE_READ_FAILED")?
|
.get_item(&index)
|
||||||
.file
|
.with_error_code("PROFILE_READ_FAILED")?
|
||||||
.clone()
|
.file
|
||||||
|
.to_owned(),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if let Some(file) = file.as_ref() {
|
if let Some(file) = item.file.as_ref() {
|
||||||
let path = dirs::app_profiles_dir()
|
let path = dirs::app_profiles_dir()
|
||||||
.with_error_code("PROFILE_READ_FAILED")?
|
.with_error_code("PROFILE_READ_FAILED")?
|
||||||
.join(file.as_str());
|
.join(file.as_str());
|
||||||
@@ -509,9 +521,7 @@ pub async fn read_profile_file(index: std::string::String) -> CmdResult<std::str
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let data = read_profile_item_file(file.as_deref())
|
let data = item.read_file().await.with_error_code("PROFILE_READ_FAILED")?;
|
||||||
.await
|
|
||||||
.with_error_code("PROFILE_READ_FAILED")?;
|
|
||||||
Ok(data.into())
|
Ok(data.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -565,11 +575,16 @@ mod tests {
|
|||||||
current: Some("a".into()),
|
current: Some("a".into()),
|
||||||
items: Some(vec![profile("a"), profile("b")]),
|
items: Some(vec![profile("a"), profile("b")]),
|
||||||
});
|
});
|
||||||
profiles.edit_draft(|draft| draft.patch_current(Some(&"b".into())));
|
profiles.edit_draft(|draft| {
|
||||||
|
draft.patch_config(&IProfiles {
|
||||||
|
current: Some("b".into()),
|
||||||
|
items: None,
|
||||||
|
});
|
||||||
|
});
|
||||||
profiles
|
profiles
|
||||||
.with_data_modify(|mut committed| async move {
|
.with_data_modify(|mut committed| async move {
|
||||||
committed.items.get_or_insert_with(Vec::new).push(profile("new"));
|
committed.items.get_or_insert_with(Vec::new).push(profile("new"));
|
||||||
Ok::<_, clash_verge_draft::DraftConflict>((committed, ()))
|
Ok((committed, ()))
|
||||||
})
|
})
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
|
|||||||
+92
-10
@@ -1,6 +1,14 @@
|
|||||||
use super::CmdResult;
|
use super::CmdResult;
|
||||||
use crate::{cmd::StringifyErr as _, config::Config, core::handle::Handle};
|
use crate::{
|
||||||
use clash_verge_proxy_view::ProxyViewV1;
|
cmd::StringifyErr as _,
|
||||||
|
config::Config,
|
||||||
|
core::{
|
||||||
|
handle::Handle,
|
||||||
|
proxy_view::{GroupScope, ProxyViewBuilder, ProxyViewInput, ProxyViewV1},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
use serde_yaml_ng::Mapping;
|
||||||
|
use std::collections::{BTreeMap, HashSet};
|
||||||
|
|
||||||
/// Merges one selection pair into fresh backend state to avoid stale-list overwrites.
|
/// Merges one selection pair into fresh backend state to avoid stale-list overwrites.
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
@@ -19,16 +27,90 @@ pub async fn switch_proxy_node(group_name: String, proxy_name: String, unfix: bo
|
|||||||
.stringify_err()
|
.stringify_err()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn runtime_group_order(config: Option<&Mapping>) -> Vec<String> {
|
||||||
|
let mut seen = HashSet::new();
|
||||||
|
|
||||||
|
config
|
||||||
|
.and_then(|config| config.get("proxy-groups"))
|
||||||
|
.and_then(|groups| groups.as_sequence())
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.filter_map(|group| group.get("name"))
|
||||||
|
.filter_map(|name| name.as_str())
|
||||||
|
.filter(|name| !name.is_empty() && *name != "GLOBAL")
|
||||||
|
.filter(|name| seen.insert(*name))
|
||||||
|
.map(str::to_owned)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mirrors Mihomo: `include-all`/`include-all-providers` replace `use` with every provider, sorted.
|
||||||
|
fn runtime_group_scopes(config: Option<&Mapping>) -> BTreeMap<String, GroupScope> {
|
||||||
|
let Some(config) = config else {
|
||||||
|
return BTreeMap::new();
|
||||||
|
};
|
||||||
|
let mut all_providers = config
|
||||||
|
.get("proxy-providers")
|
||||||
|
.and_then(|providers| providers.as_mapping())
|
||||||
|
.into_iter()
|
||||||
|
.flat_map(|providers| providers.keys())
|
||||||
|
.filter_map(|name| name.as_str())
|
||||||
|
.map(str::to_owned)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
all_providers.sort();
|
||||||
|
let flag = |group: &Mapping, key: &str| group.get(key).and_then(|value| value.as_bool()) == Some(true);
|
||||||
|
|
||||||
|
config
|
||||||
|
.get("proxy-groups")
|
||||||
|
.and_then(|groups| groups.as_sequence())
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.filter_map(|group| group.as_mapping())
|
||||||
|
.filter_map(|group| {
|
||||||
|
let name = group.get("name")?.as_str()?.to_owned();
|
||||||
|
let providers = if flag(group, "include-all") || flag(group, "include-all-providers") {
|
||||||
|
all_providers.clone()
|
||||||
|
} else {
|
||||||
|
group
|
||||||
|
.get("use")
|
||||||
|
.and_then(|providers| providers.as_sequence())
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.filter_map(|provider| provider.as_str())
|
||||||
|
.map(str::to_owned)
|
||||||
|
.collect()
|
||||||
|
};
|
||||||
|
let exclude_types = group
|
||||||
|
.get("exclude-type")
|
||||||
|
.and_then(|types| types.as_str())
|
||||||
|
.filter(|types| !types.is_empty())
|
||||||
|
.map_or_default(|types| types.split('|').map(str::to_owned).collect());
|
||||||
|
Some((
|
||||||
|
name,
|
||||||
|
GroupScope {
|
||||||
|
providers,
|
||||||
|
exclude_types,
|
||||||
|
},
|
||||||
|
))
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub async fn get_proxy_view() -> CmdResult<ProxyViewV1> {
|
pub async fn get_proxy_view() -> CmdResult<ProxyViewV1> {
|
||||||
let runtime = Config::runtime().await.latest_arc();
|
let runtime = Config::runtime().await;
|
||||||
|
let latest_runtime = runtime.latest_arc();
|
||||||
|
let runtime_group_order = runtime_group_order(latest_runtime.config.as_ref());
|
||||||
|
let group_scopes = runtime_group_scopes(latest_runtime.config.as_ref());
|
||||||
|
|
||||||
let mihomo = Handle::mihomo();
|
let mihomo = Handle::mihomo();
|
||||||
crate::feat::proxy_view::load_proxy_view(
|
let (proxies, providers) = tokio::join!(mihomo.get_proxies(), mihomo.get_proxy_providers(),);
|
||||||
runtime.config.as_ref(),
|
let proxies = proxies.stringify_err()?;
|
||||||
mihomo.get_proxies(),
|
|
||||||
mihomo.get_proxy_providers(),
|
Ok(ProxyViewBuilder::build(ProxyViewInput {
|
||||||
)
|
runtime_group_order,
|
||||||
.await
|
group_scopes,
|
||||||
.stringify_err()
|
proxies,
|
||||||
|
providers: providers.ok(),
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,5 @@
|
|||||||
use super::CmdResult;
|
use super::CmdResult;
|
||||||
use crate::{
|
use crate::{cmd::StringifyErr as _, config::Config, core::CoreManager, utils::yaml_emitter};
|
||||||
cmd::StringifyErr as _,
|
|
||||||
config::{Config, mihomo_yaml},
|
|
||||||
core::CoreManager,
|
|
||||||
};
|
|
||||||
use anyhow::{Context as _, anyhow};
|
use anyhow::{Context as _, anyhow};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use tristr::alias::String;
|
use tristr::alias::String;
|
||||||
@@ -28,7 +24,7 @@ pub async fn get_runtime_yaml() -> CmdResult<std::string::String> {
|
|||||||
let config = runtime.config.as_ref();
|
let config = runtime.config.as_ref();
|
||||||
config
|
config
|
||||||
.ok_or_else(|| anyhow!("failed to parse config to yaml file"))
|
.ok_or_else(|| anyhow!("failed to parse config to yaml file"))
|
||||||
.and_then(|config| mihomo_yaml::serialize_for_export(config).context("failed to convert config to yaml"))
|
.and_then(|config| yaml_emitter::to_mihomo_config_string(config).context("failed to convert config to yaml"))
|
||||||
.stringify_err()
|
.stringify_err()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -91,7 +87,7 @@ pub async fn get_runtime_proxy_chain_config(
|
|||||||
|
|
||||||
config.insert("proxies".into(), proxies_chain);
|
config.insert("proxies".into(), proxies_chain);
|
||||||
|
|
||||||
mihomo_yaml::serialize_for_export(&config)
|
yaml_emitter::to_mihomo_config_string(&config)
|
||||||
.context("YAML generation failed")
|
.context("YAML generation failed")
|
||||||
.stringify_err()
|
.stringify_err()
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ use super::CmdResult;
|
|||||||
use crate::{
|
use crate::{
|
||||||
cmd::StringifyErr as _,
|
cmd::StringifyErr as _,
|
||||||
cmd::validate::{ValidationNoticeTarget, handle_validation_notice},
|
cmd::validate::{ValidationNoticeTarget, handle_validation_notice},
|
||||||
config::{Config, IProfiles, read_profile_item_file},
|
config::{Config, IProfiles, PrfItem},
|
||||||
core::auto_backup::{self, AutoBackupTrigger},
|
core::auto_backup::{self, AutoBackupTrigger},
|
||||||
core::{
|
core::{
|
||||||
CoreManager, handle,
|
CoreManager, handle,
|
||||||
@@ -58,7 +58,13 @@ pub async fn save_profile_file(
|
|||||||
))
|
))
|
||||||
})?;
|
})?;
|
||||||
let original_content = if original_existed {
|
let original_content = if original_existed {
|
||||||
read_profile_item_file(Some(rel_path.as_str())).await.stringify_err()?
|
PrfItem {
|
||||||
|
file: Some(rel_path.clone()),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
.read_file()
|
||||||
|
.await
|
||||||
|
.stringify_err()?
|
||||||
} else {
|
} else {
|
||||||
String::new()
|
String::new()
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
use super::mihomo_yaml;
|
|
||||||
use crate::constants::{network, tun as tun_const};
|
use crate::constants::{network, tun as tun_const};
|
||||||
use crate::utils::dirs::{path_to_str, sidecar_ipc_path};
|
use crate::utils::dirs::{path_to_str, sidecar_ipc_path};
|
||||||
use crate::utils::{dirs, help};
|
use crate::utils::{dirs, help};
|
||||||
@@ -151,9 +150,7 @@ impl IClashTemp {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn save_config(&self) -> Result<()> {
|
pub async fn save_config(&self) -> Result<()> {
|
||||||
let path = dirs::clash_path()?;
|
help::save_yaml(&dirs::clash_path()?, &self.0, Some("# Generated by Clash Verge")).await
|
||||||
let yaml = mihomo_yaml::serialize(&self.0)?;
|
|
||||||
help::save_yaml_str(&path, &yaml, Some("# Generated by Clash Verge")).await
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_mixed_port(&self) -> u16 {
|
pub fn get_mixed_port(&self) -> u16 {
|
||||||
|
|||||||
@@ -1,16 +1,13 @@
|
|||||||
use super::{IClashTemp, IProfiles, IVerge, MixedPort, mihomo_yaml};
|
use super::{IClashTemp, IProfiles, IVerge, MixedPort};
|
||||||
use crate::core::notify::NoticeStatus;
|
use crate::core::notify::NoticeStatus;
|
||||||
use crate::{
|
use crate::{
|
||||||
config::{
|
config::{PrfItem, profiles_append_item_to_safe, runtime::IRuntime},
|
||||||
prfitem::{build_merge_profile, build_script_profile},
|
|
||||||
profiles::{load_profiles, profiles_append_item_to_safe, save_profiles},
|
|
||||||
runtime::IRuntime,
|
|
||||||
},
|
|
||||||
constants::{files, timing},
|
constants::{files, timing},
|
||||||
core::{
|
core::{
|
||||||
CoreManager,
|
CoreManager,
|
||||||
handle::{self, Handle},
|
handle::{self, Handle},
|
||||||
listener::MIXED_PORT_KEY,
|
listener::MIXED_PORT_KEY,
|
||||||
|
runtime_bundle::resolve_provider_path_conflicts,
|
||||||
tray,
|
tray,
|
||||||
validate::CoreConfigValidator,
|
validate::CoreConfigValidator,
|
||||||
},
|
},
|
||||||
@@ -22,7 +19,6 @@ use anyhow::{Result, anyhow};
|
|||||||
use backon::{ExponentialBuilder, Retryable as _};
|
use backon::{ExponentialBuilder, Retryable as _};
|
||||||
use clash_verge_draft::Draft;
|
use clash_verge_draft::Draft;
|
||||||
use clash_verge_logging::{Type, logging, logging_error};
|
use clash_verge_logging::{Type, logging, logging_error};
|
||||||
use clash_verge_runtime_bundle::resolve_provider_path_conflicts;
|
|
||||||
use serde_yaml_ng::{Mapping, Value};
|
use serde_yaml_ng::{Mapping, Value};
|
||||||
use std::{collections::HashSet, path::PathBuf};
|
use std::{collections::HashSet, path::PathBuf};
|
||||||
use tokio::sync::{Mutex, MutexGuard, OnceCell};
|
use tokio::sync::{Mutex, MutexGuard, OnceCell};
|
||||||
@@ -49,7 +45,7 @@ impl Config {
|
|||||||
Self {
|
Self {
|
||||||
clash_config: Draft::new(IClashTemp::new().await),
|
clash_config: Draft::new(IClashTemp::new().await),
|
||||||
verge_config: Draft::new(IVerge::new().await),
|
verge_config: Draft::new(IVerge::new().await),
|
||||||
profiles_config: Draft::new(load_profiles().await),
|
profiles_config: Draft::new(IProfiles::new().await),
|
||||||
runtime_config: Draft::new(IRuntime::default()),
|
runtime_config: Draft::new(IRuntime::default()),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -141,11 +137,11 @@ impl Config {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if profiles.latest_arc().get_item("Merge").is_err() {
|
if profiles.latest_arc().get_item("Merge").is_err() {
|
||||||
let merge_item = &mut build_merge_profile(Some("Merge".into()));
|
let merge_item = &mut PrfItem::from_merge(Some("Merge".into()));
|
||||||
profiles_append_item_to_safe(&profiles, merge_item).await?;
|
profiles_append_item_to_safe(&profiles, merge_item).await?;
|
||||||
}
|
}
|
||||||
if profiles.latest_arc().get_item("Script").is_err() {
|
if profiles.latest_arc().get_item("Script").is_err() {
|
||||||
let script_item = &mut build_script_profile(Some("Script".into()));
|
let script_item = &mut PrfItem::from_script(Some("Script".into()));
|
||||||
profiles_append_item_to_safe(&profiles, script_item).await?;
|
profiles_append_item_to_safe(&profiles, script_item).await?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -230,7 +226,7 @@ impl Config {
|
|||||||
{
|
{
|
||||||
return Ok(std::sync::Arc::clone(cached));
|
return Ok(std::sync::Arc::clone(cached));
|
||||||
}
|
}
|
||||||
let yaml_str = std::sync::Arc::new(mihomo_yaml::serialize(config)?);
|
let yaml_str = std::sync::Arc::new(serde_yaml_ng::to_string(config)?);
|
||||||
*RUNTIME_YAML_CACHE.lock() = Some((key, std::sync::Arc::clone(&yaml_str)));
|
*RUNTIME_YAML_CACHE.lock() = Some((key, std::sync::Arc::clone(&yaml_str)));
|
||||||
Ok(yaml_str)
|
Ok(yaml_str)
|
||||||
})
|
})
|
||||||
@@ -314,7 +310,7 @@ impl Config {
|
|||||||
let _profile_write = super::profiles::PROFILE_WRITE_LOCK.lock().await;
|
let _profile_write = super::profiles::PROFILE_WRITE_LOCK.lock().await;
|
||||||
let profiles = Self::profiles().await;
|
let profiles = Self::profiles().await;
|
||||||
profiles.apply();
|
profiles.apply();
|
||||||
logging_error!(Type::Config, save_profiles(&profiles.data_arc()).await);
|
logging_error!(Type::Config, profiles.data_arc().save_file().await);
|
||||||
});
|
});
|
||||||
|
|
||||||
let _ = tokio::join!(save_clash_task, save_verge_task, save_profiles_task);
|
let _ = tokio::join!(save_clash_task, save_verge_task, save_profiles_task);
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ mod clash;
|
|||||||
mod config;
|
mod config;
|
||||||
pub(crate) mod dns;
|
pub(crate) mod dns;
|
||||||
mod encrypt;
|
mod encrypt;
|
||||||
pub(crate) mod mihomo_yaml;
|
|
||||||
mod mixed_port;
|
mod mixed_port;
|
||||||
mod port;
|
mod port;
|
||||||
mod prfitem;
|
mod prfitem;
|
||||||
@@ -13,11 +12,7 @@ pub(crate) mod snapshot;
|
|||||||
mod verge;
|
mod verge;
|
||||||
|
|
||||||
pub(crate) use self::config::Config;
|
pub(crate) use self::config::Config;
|
||||||
pub(crate) use self::prfitem::{
|
pub use self::{clash::*, encrypt::*, mixed_port::*, prfitem::*, profiles::*, verge::*};
|
||||||
build_remote_profile, download_subscription, prepare_remote_refresh, read_profile_item_file,
|
|
||||||
};
|
|
||||||
pub use self::{clash::*, encrypt::*, mixed_port::*, profiles::*, verge::*};
|
|
||||||
pub use clash_verge_profile::{PrfExtra, PrfItem, PrfOption, PrfSelected};
|
|
||||||
|
|
||||||
macro_rules! patch_opt_field {
|
macro_rules! patch_opt_field {
|
||||||
($lv:expr, $rv:expr, $key:tt) => {
|
($lv:expr, $rv:expr, $key:tt) => {
|
||||||
|
|||||||
+460
-386
@@ -1,4 +1,4 @@
|
|||||||
use super::{PrfExtra, PrfItem, PrfOption};
|
use super::patch_opt_field;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
config::profiles,
|
config::profiles,
|
||||||
@@ -9,7 +9,8 @@ use crate::{
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
use anyhow::{Context as _, Result, bail};
|
use anyhow::{Context as _, Result, bail};
|
||||||
use clash_verge_subscription::decode_subscription;
|
use serde::{Deserialize, Serialize};
|
||||||
|
use serde_yaml_ng::Mapping;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use tokio::fs;
|
use tokio::fs;
|
||||||
use tristr::alias::String;
|
use tristr::alias::String;
|
||||||
@@ -17,318 +18,472 @@ use tristr::alias::String;
|
|||||||
use reqwest_dav::re_exports::url::form_urlencoded;
|
use reqwest_dav::re_exports::url::form_urlencoded;
|
||||||
use tauri::Url;
|
use tauri::Url;
|
||||||
|
|
||||||
/// Builds an item from a partial value that must include `itype`.
|
pub(super) fn normalize_profile_home_url(raw: &str) -> Option<String> {
|
||||||
pub(super) async fn build_profile(item: &PrfItem, file_data: Option<String>) -> Result<PrfItem> {
|
let url = Url::parse(raw.trim()).ok()?;
|
||||||
let itype = item
|
|
||||||
.itype
|
if !matches!(url.scheme(), "http" | "https") {
|
||||||
.as_ref()
|
return None;
|
||||||
.ok_or_else(|| anyhow::anyhow!("type should not be null"))?;
|
}
|
||||||
match itype.as_str() {
|
|
||||||
"remote" => {
|
url.host_str()?;
|
||||||
let url = item
|
Some(url.as_str().into())
|
||||||
.url
|
}
|
||||||
.as_ref()
|
|
||||||
.ok_or_else(|| anyhow::anyhow!("url should not be null"))?;
|
#[derive(Debug, Clone, Deserialize, Serialize, Default, specta::Type)]
|
||||||
let name = item.name.as_ref();
|
#[serde(default)]
|
||||||
let desc = item.desc.as_ref();
|
pub struct PrfItem {
|
||||||
let option = item.option.as_ref();
|
pub uid: Option<String>,
|
||||||
build_remote_profile(url, name, desc, option).await
|
|
||||||
|
/// enum value: remote | local | script | merge
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
pub itype: Option<String>,
|
||||||
|
pub name: Option<String>,
|
||||||
|
pub file: Option<String>,
|
||||||
|
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub desc: Option<String>,
|
||||||
|
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub url: Option<String>,
|
||||||
|
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub selected: Option<Vec<PrfSelected>>,
|
||||||
|
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub extra: Option<PrfExtra>,
|
||||||
|
|
||||||
|
pub updated: Option<usize>,
|
||||||
|
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub option: Option<PrfOption>,
|
||||||
|
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub home: Option<String>,
|
||||||
|
|
||||||
|
#[serde(skip)]
|
||||||
|
pub file_data: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)]
|
||||||
|
#[serde(default)]
|
||||||
|
pub struct PrfSelected {
|
||||||
|
pub name: Option<String>,
|
||||||
|
pub now: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Debug, Clone, Copy, Deserialize, Serialize, specta::Type)]
|
||||||
|
pub struct PrfExtra {
|
||||||
|
pub upload: u64,
|
||||||
|
pub download: u64,
|
||||||
|
pub total: u64,
|
||||||
|
pub expire: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)]
|
||||||
|
#[serde(default)]
|
||||||
|
pub struct PrfOption {
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub user_agent: Option<String>,
|
||||||
|
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub with_proxy: Option<bool>,
|
||||||
|
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub self_proxy: Option<bool>,
|
||||||
|
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub update_interval: Option<u64>,
|
||||||
|
|
||||||
|
/// HTTP request timeout in seconds
|
||||||
|
/// default is 60 seconds
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub timeout_seconds: Option<u64>,
|
||||||
|
|
||||||
|
/// default is `false`
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub danger_accept_invalid_certs: Option<bool>,
|
||||||
|
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub allow_auto_update: Option<bool>,
|
||||||
|
pub merge: Option<String>,
|
||||||
|
pub script: Option<String>,
|
||||||
|
pub rules: Option<String>,
|
||||||
|
pub proxies: Option<String>,
|
||||||
|
pub groups: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PrfOption {
|
||||||
|
pub(crate) fn merge(one: Option<&Self>, other: Option<&Self>) -> Option<Self> {
|
||||||
|
match (one, other) {
|
||||||
|
(Some(a_ref), Some(b_ref)) => {
|
||||||
|
let mut result = a_ref.clone();
|
||||||
|
patch_opt_field!(result, b_ref, user_agent);
|
||||||
|
patch_opt_field!(result, b_ref, with_proxy);
|
||||||
|
patch_opt_field!(result, b_ref, self_proxy);
|
||||||
|
patch_opt_field!(result, b_ref, danger_accept_invalid_certs);
|
||||||
|
patch_opt_field!(result, b_ref, allow_auto_update);
|
||||||
|
patch_opt_field!(result, b_ref, update_interval);
|
||||||
|
patch_opt_field!(result, b_ref, merge);
|
||||||
|
patch_opt_field!(result, b_ref, script);
|
||||||
|
patch_opt_field!(result, b_ref, rules);
|
||||||
|
patch_opt_field!(result, b_ref, proxies);
|
||||||
|
patch_opt_field!(result, b_ref, groups);
|
||||||
|
patch_opt_field!(result, b_ref, timeout_seconds);
|
||||||
|
Some(result)
|
||||||
|
}
|
||||||
|
(Some(a_ref), None) => Some(a_ref.clone()),
|
||||||
|
(None, Some(b_ref)) => Some(b_ref.clone()),
|
||||||
|
(None, None) => None,
|
||||||
}
|
}
|
||||||
"local" => {
|
}
|
||||||
let name = item.name.clone().unwrap_or_else(|| "Local File".into());
|
}
|
||||||
let desc = item.desc.clone().unwrap_or_else(|| "".into());
|
|
||||||
let option = item.option.as_ref();
|
impl PrfItem {
|
||||||
from_local(name, desc, file_data, option).await
|
/// Builds an item from a partial value that must include `itype`.
|
||||||
|
pub(super) async fn from(item: &Self, file_data: Option<String>) -> Result<Self> {
|
||||||
|
let itype = item
|
||||||
|
.itype
|
||||||
|
.as_ref()
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("type should not be null"))?;
|
||||||
|
match itype.as_str() {
|
||||||
|
"remote" => {
|
||||||
|
let url = item
|
||||||
|
.url
|
||||||
|
.as_ref()
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("url should not be null"))?;
|
||||||
|
let name = item.name.as_ref();
|
||||||
|
let desc = item.desc.as_ref();
|
||||||
|
let option = item.option.as_ref();
|
||||||
|
Self::from_url(url, name, desc, option).await
|
||||||
|
}
|
||||||
|
"local" => {
|
||||||
|
let name = item.name.clone().unwrap_or_else(|| "Local File".into());
|
||||||
|
let desc = item.desc.clone().unwrap_or_else(|| "".into());
|
||||||
|
let option = item.option.as_ref();
|
||||||
|
Self::from_local(name, desc, file_data, option).await
|
||||||
|
}
|
||||||
|
typ => bail!("invalid profile item type \"{typ}\""),
|
||||||
}
|
}
|
||||||
typ => bail!("invalid profile item type \"{typ}\""),
|
}
|
||||||
|
|
||||||
|
async fn append_companion_item(item: &mut Self) -> Result<String> {
|
||||||
|
profiles::profiles_append_item_safe(item).await?;
|
||||||
|
item.uid
|
||||||
|
.clone()
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("appended companion item has no uid"))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn ensure_companion_items(
|
||||||
|
merge: &mut Option<String>,
|
||||||
|
script: &mut Option<String>,
|
||||||
|
rules: &mut Option<String>,
|
||||||
|
proxies: &mut Option<String>,
|
||||||
|
groups: &mut Option<String>,
|
||||||
|
) -> Result<()> {
|
||||||
|
if merge.is_none() {
|
||||||
|
*merge = Some(Self::append_companion_item(&mut Self::from_merge(None)).await?);
|
||||||
|
}
|
||||||
|
if script.is_none() {
|
||||||
|
*script = Some(Self::append_companion_item(&mut Self::from_script(None)).await?);
|
||||||
|
}
|
||||||
|
if rules.is_none() {
|
||||||
|
*rules = Some(Self::append_companion_item(&mut Self::from_rules()).await?);
|
||||||
|
}
|
||||||
|
if proxies.is_none() {
|
||||||
|
*proxies = Some(Self::append_companion_item(&mut Self::from_proxies()).await?);
|
||||||
|
}
|
||||||
|
if groups.is_none() {
|
||||||
|
*groups = Some(Self::append_companion_item(&mut Self::from_groups()).await?);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn from_local(
|
||||||
|
name: String,
|
||||||
|
desc: String,
|
||||||
|
file_data: Option<String>,
|
||||||
|
option: Option<&PrfOption>,
|
||||||
|
) -> Result<Self> {
|
||||||
|
let uid = help::get_uid("L").into();
|
||||||
|
let file = format!("{uid}.yaml").into();
|
||||||
|
let opt_ref = option.as_ref();
|
||||||
|
let update_interval = opt_ref.and_then(|o| o.update_interval);
|
||||||
|
let mut merge = opt_ref.and_then(|o| o.merge.clone());
|
||||||
|
let mut script = opt_ref.and_then(|o| o.script.clone());
|
||||||
|
let mut rules = opt_ref.and_then(|o| o.rules.clone());
|
||||||
|
let mut proxies = opt_ref.and_then(|o| o.proxies.clone());
|
||||||
|
let mut groups = opt_ref.and_then(|o| o.groups.clone());
|
||||||
|
|
||||||
|
Self::ensure_companion_items(&mut merge, &mut script, &mut rules, &mut proxies, &mut groups).await?;
|
||||||
|
Ok(Self {
|
||||||
|
uid: Some(uid),
|
||||||
|
itype: Some("local".into()),
|
||||||
|
name: Some(name),
|
||||||
|
desc: Some(desc),
|
||||||
|
file: Some(file),
|
||||||
|
url: None,
|
||||||
|
selected: None,
|
||||||
|
extra: None,
|
||||||
|
option: Some(PrfOption {
|
||||||
|
update_interval,
|
||||||
|
merge,
|
||||||
|
script,
|
||||||
|
rules,
|
||||||
|
proxies,
|
||||||
|
groups,
|
||||||
|
..PrfOption::default()
|
||||||
|
}),
|
||||||
|
home: None,
|
||||||
|
updated: Some(chrono::Local::now().timestamp() as usize),
|
||||||
|
file_data: Some(file_data.unwrap_or_else(|| tmpl::ITEM_LOCAL.into())),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn from_url(
|
||||||
|
url: &str,
|
||||||
|
name: Option<&String>,
|
||||||
|
desc: Option<&String>,
|
||||||
|
option: Option<&PrfOption>,
|
||||||
|
) -> Result<Self> {
|
||||||
|
let with_proxy = option.is_some_and(|o| o.with_proxy.unwrap_or(false));
|
||||||
|
let self_proxy = option.is_some_and(|o| o.self_proxy.unwrap_or(false));
|
||||||
|
let accept_invalid_certs = option.is_some_and(|o| o.danger_accept_invalid_certs.unwrap_or(false));
|
||||||
|
let allow_auto_update = Some(allow_auto_update_enabled(option));
|
||||||
|
let user_agent = option.and_then(|o| o.user_agent.clone());
|
||||||
|
let update_interval = option.and_then(|o| o.update_interval);
|
||||||
|
let timeout = option.and_then(|o| o.timeout_seconds).unwrap_or(20);
|
||||||
|
let mut merge = option.and_then(|o| o.merge.clone());
|
||||||
|
let mut script = option.and_then(|o| o.script.clone());
|
||||||
|
let mut rules = option.and_then(|o| o.rules.clone());
|
||||||
|
let mut proxies = option.and_then(|o| o.proxies.clone());
|
||||||
|
let mut groups = option.and_then(|o| o.groups.clone());
|
||||||
|
|
||||||
|
let proxy_type = if self_proxy {
|
||||||
|
ProxyType::Localhost
|
||||||
|
} else if with_proxy {
|
||||||
|
ProxyType::System
|
||||||
|
} else {
|
||||||
|
ProxyType::None
|
||||||
|
};
|
||||||
|
|
||||||
|
let url = fix_dirty_url(url)?;
|
||||||
|
|
||||||
|
let resp = match NetworkManager::new()
|
||||||
|
.get(
|
||||||
|
url.as_str(),
|
||||||
|
proxy_type,
|
||||||
|
Some(timeout),
|
||||||
|
user_agent.clone(),
|
||||||
|
accept_invalid_certs,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(r) => r,
|
||||||
|
Err(e) => {
|
||||||
|
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||||
|
return Err(e).context("failed to fetch remote profile");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let status_code = resp.status();
|
||||||
|
if !status_code.is_success() {
|
||||||
|
bail!("failed to fetch remote profile with status {status_code}")
|
||||||
|
}
|
||||||
|
|
||||||
|
let header = resp.headers();
|
||||||
|
|
||||||
|
let extra;
|
||||||
|
'extra: {
|
||||||
|
for (k, v) in header.iter() {
|
||||||
|
let key_lower = k.as_str().to_ascii_lowercase();
|
||||||
|
// Accept standard custom-metadata prefixes (x-amz-meta-, x-obs-meta-, x-cos-meta-, etc.).
|
||||||
|
if key_lower
|
||||||
|
.strip_suffix("subscription-userinfo")
|
||||||
|
.is_some_and(|prefix| prefix.is_empty() || prefix.ends_with('-'))
|
||||||
|
{
|
||||||
|
let sub_info = v.to_str().unwrap_or("");
|
||||||
|
extra = Some(PrfExtra {
|
||||||
|
upload: help::parse_str(sub_info, "upload").unwrap_or(0),
|
||||||
|
download: help::parse_str(sub_info, "download").unwrap_or(0),
|
||||||
|
total: help::parse_str(sub_info, "total").unwrap_or(0),
|
||||||
|
expire: help::parse_str(sub_info, "expire").unwrap_or(0),
|
||||||
|
});
|
||||||
|
break 'extra;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
extra = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let filename = match header.get("Content-Disposition") {
|
||||||
|
Some(value) => {
|
||||||
|
let filename = format!("{value:?}");
|
||||||
|
let filename = filename.trim_matches('"');
|
||||||
|
match help::parse_str::<String>(filename, "filename*") {
|
||||||
|
Some(filename) => {
|
||||||
|
let iter = percent_encoding::percent_decode(filename.as_bytes());
|
||||||
|
let filename = iter.decode_utf8().unwrap_or_default();
|
||||||
|
filename.split("''").last().map(|s| s.into())
|
||||||
|
}
|
||||||
|
None => match help::parse_str::<String>(filename, "filename") {
|
||||||
|
Some(filename) => {
|
||||||
|
let filename = filename.trim_matches('"');
|
||||||
|
Some(filename.into())
|
||||||
|
}
|
||||||
|
None => None,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
Some(crate::utils::help::get_last_part_and_decode(url.as_str()).unwrap_or_else(|| "Remote File".into()))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let update_interval = match update_interval {
|
||||||
|
Some(val) => Some(val),
|
||||||
|
None => match header.get("profile-update-interval") {
|
||||||
|
Some(value) => match value.to_str().unwrap_or("").parse::<u64>() {
|
||||||
|
Ok(val) => Some(val * 60), // hour -> min
|
||||||
|
Err(_) => None,
|
||||||
|
},
|
||||||
|
None => None,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
let home = header
|
||||||
|
.get("profile-web-page-url")
|
||||||
|
.and_then(|value| value.to_str().ok())
|
||||||
|
.and_then(normalize_profile_home_url);
|
||||||
|
|
||||||
|
let uid = help::get_uid("R").into();
|
||||||
|
let file = format!("{uid}.yaml").into();
|
||||||
|
let name = name.map_or_else(
|
||||||
|
|| filename.map_or_else(|| "Remote File".into(), |s| s.into()),
|
||||||
|
|s| s.to_owned(),
|
||||||
|
);
|
||||||
|
let data = resp.text();
|
||||||
|
|
||||||
|
let data = data.trim_start_matches('\u{feff}');
|
||||||
|
|
||||||
|
let yaml = serde_yaml_ng::from_str::<Mapping>(data).context("the remote profile data is invalid yaml")?;
|
||||||
|
|
||||||
|
if !yaml.contains_key("proxies") && !yaml.contains_key("proxy-providers") {
|
||||||
|
bail!("profile does not contain `proxies` or `proxy-providers`");
|
||||||
|
}
|
||||||
|
|
||||||
|
Self::ensure_companion_items(&mut merge, &mut script, &mut rules, &mut proxies, &mut groups).await?;
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
uid: Some(uid),
|
||||||
|
itype: Some("remote".into()),
|
||||||
|
name: Some(name),
|
||||||
|
desc: desc.cloned(),
|
||||||
|
file: Some(file),
|
||||||
|
url: Some(url.as_str().into()),
|
||||||
|
selected: None,
|
||||||
|
extra,
|
||||||
|
option: Some(PrfOption {
|
||||||
|
update_interval,
|
||||||
|
merge,
|
||||||
|
script,
|
||||||
|
rules,
|
||||||
|
proxies,
|
||||||
|
groups,
|
||||||
|
allow_auto_update,
|
||||||
|
..PrfOption::default()
|
||||||
|
}),
|
||||||
|
home,
|
||||||
|
updated: Some(chrono::Local::now().timestamp() as usize),
|
||||||
|
file_data: Some(data.into()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn from_merge(uid: Option<String>) -> Self {
|
||||||
|
let (id, template) = if let Some(uid) = uid {
|
||||||
|
(uid, tmpl::ITEM_MERGE.into())
|
||||||
|
} else {
|
||||||
|
(help::get_uid("m").into(), tmpl::ITEM_MERGE_EMPTY.into())
|
||||||
|
};
|
||||||
|
let file = format!("{id}.yaml").into();
|
||||||
|
|
||||||
|
Self {
|
||||||
|
uid: Some(id),
|
||||||
|
itype: Some("merge".into()),
|
||||||
|
file: Some(file),
|
||||||
|
updated: Some(chrono::Local::now().timestamp() as usize),
|
||||||
|
file_data: Some(template),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn from_script(uid: Option<String>) -> Self {
|
||||||
|
let id = if let Some(uid) = uid {
|
||||||
|
uid
|
||||||
|
} else {
|
||||||
|
help::get_uid("s").into()
|
||||||
|
};
|
||||||
|
let file = format!("{id}.js").into(); // js ext
|
||||||
|
Self {
|
||||||
|
uid: Some(id),
|
||||||
|
itype: Some("script".into()),
|
||||||
|
file: Some(file),
|
||||||
|
updated: Some(chrono::Local::now().timestamp() as usize),
|
||||||
|
file_data: Some(tmpl::ITEM_SCRIPT.into()),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn new_seq_item(prefix: &str, itype: &str, template: &str) -> Self {
|
||||||
|
let uid = help::get_uid(prefix).into();
|
||||||
|
let file = format!("{uid}.yaml").into(); // yaml ext
|
||||||
|
|
||||||
|
Self {
|
||||||
|
uid: Some(uid),
|
||||||
|
itype: Some(itype.into()),
|
||||||
|
file: Some(file),
|
||||||
|
updated: Some(chrono::Local::now().timestamp() as usize),
|
||||||
|
file_data: Some(template.into()),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_rules() -> Self {
|
||||||
|
Self::new_seq_item("r", "rules", tmpl::ITEM_RULES)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_proxies() -> Self {
|
||||||
|
Self::new_seq_item("p", "proxies", tmpl::ITEM_PROXIES)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_groups() -> Self {
|
||||||
|
Self::new_seq_item("g", "groups", tmpl::ITEM_GROUPS)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn read_file(&self) -> Result<String> {
|
||||||
|
let file = self
|
||||||
|
.file
|
||||||
|
.as_ref()
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("could not find the file"))?;
|
||||||
|
let path = dirs::app_profiles_dir()?.join(file.as_str());
|
||||||
|
let content = fs::read_to_string(&path)
|
||||||
|
.await
|
||||||
|
.with_context(|| format!("failed to read the file \"{}\"", path.display()))?;
|
||||||
|
Ok(content.into())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn append_companion_item(item: &mut PrfItem) -> Result<String> {
|
macro_rules! current_field {
|
||||||
profiles::profiles_append_item_safe(item).await?;
|
($name:ident, $field:ident) => {
|
||||||
item.uid
|
pub(crate) fn $name(&self) -> Option<&String> {
|
||||||
.clone()
|
self.option.as_ref().and_then(|o| o.$field.as_ref())
|
||||||
.ok_or_else(|| anyhow::anyhow!("appended companion item has no uid"))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn ensure_companion_items(
|
|
||||||
merge: &mut Option<String>,
|
|
||||||
script: &mut Option<String>,
|
|
||||||
rules: &mut Option<String>,
|
|
||||||
proxies: &mut Option<String>,
|
|
||||||
groups: &mut Option<String>,
|
|
||||||
) -> Result<()> {
|
|
||||||
if merge.is_none() {
|
|
||||||
*merge = Some(append_companion_item(&mut build_merge_profile(None)).await?);
|
|
||||||
}
|
|
||||||
if script.is_none() {
|
|
||||||
*script = Some(append_companion_item(&mut build_script_profile(None)).await?);
|
|
||||||
}
|
|
||||||
if rules.is_none() {
|
|
||||||
*rules = Some(append_companion_item(&mut from_rules()).await?);
|
|
||||||
}
|
|
||||||
if proxies.is_none() {
|
|
||||||
*proxies = Some(append_companion_item(&mut from_proxies()).await?);
|
|
||||||
}
|
|
||||||
if groups.is_none() {
|
|
||||||
*groups = Some(append_companion_item(&mut from_groups()).await?);
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn from_local(
|
|
||||||
name: String,
|
|
||||||
desc: String,
|
|
||||||
file_data: Option<String>,
|
|
||||||
option: Option<&PrfOption>,
|
|
||||||
) -> Result<PrfItem> {
|
|
||||||
let uid = help::get_uid("L").into();
|
|
||||||
let file = format!("{uid}.yaml").into();
|
|
||||||
let opt_ref = option.as_ref();
|
|
||||||
let update_interval = opt_ref.and_then(|o| o.update_interval);
|
|
||||||
let mut merge = opt_ref.and_then(|o| o.merge.clone());
|
|
||||||
let mut script = opt_ref.and_then(|o| o.script.clone());
|
|
||||||
let mut rules = opt_ref.and_then(|o| o.rules.clone());
|
|
||||||
let mut proxies = opt_ref.and_then(|o| o.proxies.clone());
|
|
||||||
let mut groups = opt_ref.and_then(|o| o.groups.clone());
|
|
||||||
|
|
||||||
ensure_companion_items(&mut merge, &mut script, &mut rules, &mut proxies, &mut groups).await?;
|
|
||||||
Ok(PrfItem {
|
|
||||||
uid: Some(uid),
|
|
||||||
itype: Some("local".into()),
|
|
||||||
name: Some(name),
|
|
||||||
desc: Some(desc),
|
|
||||||
file: Some(file),
|
|
||||||
url: None,
|
|
||||||
selected: None,
|
|
||||||
extra: None,
|
|
||||||
option: Some(PrfOption {
|
|
||||||
update_interval,
|
|
||||||
merge,
|
|
||||||
script,
|
|
||||||
rules,
|
|
||||||
proxies,
|
|
||||||
groups,
|
|
||||||
..PrfOption::default()
|
|
||||||
}),
|
|
||||||
home: None,
|
|
||||||
updated: Some(chrono::Local::now().timestamp() as usize),
|
|
||||||
file_data: Some(file_data.unwrap_or_else(|| tmpl::ITEM_LOCAL.into())),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) struct DownloadedSubscription {
|
|
||||||
url: Url,
|
|
||||||
suggested_name: Option<std::string::String>,
|
|
||||||
extra: Option<PrfExtra>,
|
|
||||||
update_interval_minutes: Option<u64>,
|
|
||||||
home: Option<String>,
|
|
||||||
body: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) struct RemoteProfileRefresh {
|
|
||||||
pub(super) extra: Option<PrfExtra>,
|
|
||||||
pub(super) home: Option<String>,
|
|
||||||
pub(super) updated: usize,
|
|
||||||
pub(super) option: PrfOption,
|
|
||||||
pub(super) body: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn build_remote_profile(
|
|
||||||
url: &str,
|
|
||||||
name: Option<&String>,
|
|
||||||
desc: Option<&String>,
|
|
||||||
option: Option<&PrfOption>,
|
|
||||||
) -> Result<PrfItem> {
|
|
||||||
let mut downloaded = download_subscription(url, option).await?;
|
|
||||||
let uid: String = help::get_uid("R").into();
|
|
||||||
let file = format!("{uid}.yaml").into();
|
|
||||||
let name = name
|
|
||||||
.cloned()
|
|
||||||
.or_else(|| downloaded.suggested_name.take().map(Into::into))
|
|
||||||
.unwrap_or_else(|| "Remote File".into());
|
|
||||||
let url = downloaded.url.as_str().into();
|
|
||||||
let RemoteProfileRefresh {
|
|
||||||
extra,
|
|
||||||
home,
|
|
||||||
updated,
|
|
||||||
option,
|
|
||||||
body,
|
|
||||||
} = prepare_remote_refresh(downloaded, option).await?;
|
|
||||||
|
|
||||||
Ok(PrfItem {
|
|
||||||
uid: Some(uid),
|
|
||||||
itype: Some("remote".into()),
|
|
||||||
name: Some(name),
|
|
||||||
desc: desc.cloned(),
|
|
||||||
file: Some(file),
|
|
||||||
url: Some(url),
|
|
||||||
selected: None,
|
|
||||||
extra,
|
|
||||||
option: Some(option),
|
|
||||||
home,
|
|
||||||
updated: Some(updated),
|
|
||||||
file_data: Some(body),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn download_subscription(url: &str, option: Option<&PrfOption>) -> Result<DownloadedSubscription> {
|
|
||||||
let with_proxy = option.is_some_and(|o| o.with_proxy.unwrap_or(false));
|
|
||||||
let self_proxy = option.is_some_and(|o| o.self_proxy.unwrap_or(false));
|
|
||||||
let accept_invalid_certs = option.is_some_and(|o| o.danger_accept_invalid_certs.unwrap_or(false));
|
|
||||||
let user_agent = option.and_then(|o| o.user_agent.clone());
|
|
||||||
let timeout = option.and_then(|o| o.timeout_seconds).unwrap_or(20);
|
|
||||||
|
|
||||||
let proxy_type = if self_proxy {
|
|
||||||
ProxyType::Localhost
|
|
||||||
} else if with_proxy {
|
|
||||||
ProxyType::System
|
|
||||||
} else {
|
|
||||||
ProxyType::None
|
|
||||||
};
|
|
||||||
|
|
||||||
let url = fix_dirty_url(url)?;
|
|
||||||
|
|
||||||
let resp = match NetworkManager::new()
|
|
||||||
.get(
|
|
||||||
url.as_str(),
|
|
||||||
proxy_type,
|
|
||||||
Some(timeout),
|
|
||||||
user_agent,
|
|
||||||
accept_invalid_certs,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(r) => r,
|
|
||||||
Err(e) => {
|
|
||||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
|
||||||
return Err(e).context("failed to fetch remote profile");
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let status_code = resp.status();
|
|
||||||
if !status_code.is_success() {
|
|
||||||
bail!("failed to fetch remote profile with status {status_code}")
|
|
||||||
}
|
|
||||||
|
|
||||||
let document = decode_subscription(&url, resp.headers(), resp.text())?;
|
|
||||||
let extra = document.usage.map(|usage| PrfExtra {
|
|
||||||
upload: usage.upload,
|
|
||||||
download: usage.download,
|
|
||||||
total: usage.total,
|
|
||||||
expire: usage.expire,
|
|
||||||
});
|
|
||||||
Ok(DownloadedSubscription {
|
|
||||||
suggested_name: document.filename,
|
|
||||||
update_interval_minutes: document.update_interval_minutes,
|
|
||||||
home: document.home.map(Into::into),
|
|
||||||
body: document.body.into(),
|
|
||||||
url,
|
|
||||||
extra,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn prepare_remote_refresh(
|
impl PrfItem {
|
||||||
downloaded: DownloadedSubscription,
|
current_field!(current_merge, merge);
|
||||||
option: Option<&PrfOption>,
|
current_field!(current_script, script);
|
||||||
) -> Result<RemoteProfileRefresh> {
|
current_field!(current_rules, rules);
|
||||||
let mut resolved = PrfOption {
|
current_field!(current_proxies, proxies);
|
||||||
update_interval: option
|
current_field!(current_groups, groups);
|
||||||
.and_then(|o| o.update_interval)
|
|
||||||
.or(downloaded.update_interval_minutes),
|
|
||||||
merge: option.and_then(|o| o.merge.clone()),
|
|
||||||
script: option.and_then(|o| o.script.clone()),
|
|
||||||
rules: option.and_then(|o| o.rules.clone()),
|
|
||||||
proxies: option.and_then(|o| o.proxies.clone()),
|
|
||||||
groups: option.and_then(|o| o.groups.clone()),
|
|
||||||
allow_auto_update: Some(allow_auto_update_enabled(option)),
|
|
||||||
..PrfOption::default()
|
|
||||||
};
|
|
||||||
ensure_companion_items(
|
|
||||||
&mut resolved.merge,
|
|
||||||
&mut resolved.script,
|
|
||||||
&mut resolved.rules,
|
|
||||||
&mut resolved.proxies,
|
|
||||||
&mut resolved.groups,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
Ok(RemoteProfileRefresh {
|
|
||||||
extra: downloaded.extra,
|
|
||||||
home: downloaded.home,
|
|
||||||
updated: chrono::Local::now().timestamp() as usize,
|
|
||||||
option: resolved,
|
|
||||||
body: downloaded.body,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn build_merge_profile(uid: Option<String>) -> PrfItem {
|
|
||||||
let (id, template) = if let Some(uid) = uid {
|
|
||||||
(uid, tmpl::ITEM_MERGE.into())
|
|
||||||
} else {
|
|
||||||
(help::get_uid("m").into(), tmpl::ITEM_MERGE_EMPTY.into())
|
|
||||||
};
|
|
||||||
let file = format!("{id}.yaml").into();
|
|
||||||
|
|
||||||
PrfItem {
|
|
||||||
uid: Some(id),
|
|
||||||
itype: Some("merge".into()),
|
|
||||||
file: Some(file),
|
|
||||||
updated: Some(chrono::Local::now().timestamp() as usize),
|
|
||||||
file_data: Some(template),
|
|
||||||
..Default::default()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn build_script_profile(uid: Option<String>) -> PrfItem {
|
|
||||||
let id = if let Some(uid) = uid {
|
|
||||||
uid
|
|
||||||
} else {
|
|
||||||
help::get_uid("s").into()
|
|
||||||
};
|
|
||||||
let file = format!("{id}.js").into(); // js ext
|
|
||||||
PrfItem {
|
|
||||||
uid: Some(id),
|
|
||||||
itype: Some("script".into()),
|
|
||||||
file: Some(file),
|
|
||||||
updated: Some(chrono::Local::now().timestamp() as usize),
|
|
||||||
file_data: Some(tmpl::ITEM_SCRIPT.into()),
|
|
||||||
..Default::default()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn new_seq_item(prefix: &str, itype: &str, template: &str) -> PrfItem {
|
|
||||||
let uid = help::get_uid(prefix).into();
|
|
||||||
let file = format!("{uid}.yaml").into(); // yaml ext
|
|
||||||
|
|
||||||
PrfItem {
|
|
||||||
uid: Some(uid),
|
|
||||||
itype: Some(itype.into()),
|
|
||||||
file: Some(file),
|
|
||||||
updated: Some(chrono::Local::now().timestamp() as usize),
|
|
||||||
file_data: Some(template.into()),
|
|
||||||
..Default::default()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn from_rules() -> PrfItem {
|
|
||||||
new_seq_item("r", "rules", tmpl::ITEM_RULES)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn from_proxies() -> PrfItem {
|
|
||||||
new_seq_item("p", "proxies", tmpl::ITEM_PROXIES)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn from_groups() -> PrfItem {
|
|
||||||
new_seq_item("g", "groups", tmpl::ITEM_GROUPS)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn read_profile_item_file(file: Option<&str>) -> Result<String> {
|
|
||||||
let file = file.ok_or_else(|| anyhow::anyhow!("could not find the file"))?;
|
|
||||||
let path = dirs::app_profiles_dir()?.join(file);
|
|
||||||
let content = fs::read_to_string(&path)
|
|
||||||
.await
|
|
||||||
.with_context(|| format!("failed to read the file \"{}\"", path.display()))?;
|
|
||||||
Ok(content.into())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn allow_auto_update_enabled(option: Option<&PrfOption>) -> bool {
|
fn allow_auto_update_enabled(option: Option<&PrfOption>) -> bool {
|
||||||
@@ -363,84 +518,3 @@ fn fix_dirty_url(input: &str) -> Result<Url> {
|
|||||||
|
|
||||||
Ok(url)
|
Ok(url)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use tokio::{
|
|
||||||
io::{AsyncBufReadExt as _, AsyncWriteExt as _, BufReader},
|
|
||||||
net::TcpListener,
|
|
||||||
};
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn import_and_refresh_share_subscription_decoding() -> Result<()> {
|
|
||||||
const BODY: &str = "# keep this comment\nproxies: []\n";
|
|
||||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
|
||||||
let url = format!("http://{}/subscription", listener.local_addr()?);
|
|
||||||
let server = tokio::spawn(async move {
|
|
||||||
let response = format!(
|
|
||||||
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\
|
|
||||||
Content-Disposition: attachment; filename=remote.yaml\r\n\
|
|
||||||
Profile-Update-Interval: 2\r\n\
|
|
||||||
Profile-Web-Page-Url: https://example.invalid/\r\n\
|
|
||||||
Subscription-Userinfo: upload=1; download=2; total=3; expire=4\r\n\r\n{BODY}",
|
|
||||||
BODY.len()
|
|
||||||
);
|
|
||||||
for _ in 0..2 {
|
|
||||||
let (socket, _) = listener.accept().await?;
|
|
||||||
let mut socket = BufReader::new(socket);
|
|
||||||
let mut line = std::string::String::new();
|
|
||||||
loop {
|
|
||||||
line.clear();
|
|
||||||
if socket.read_line(&mut line).await? == 0 || line == "\r\n" {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
socket.get_mut().write_all(response.as_bytes()).await?;
|
|
||||||
}
|
|
||||||
Ok::<_, std::io::Error>(())
|
|
||||||
});
|
|
||||||
let option = PrfOption {
|
|
||||||
update_interval: Some(0),
|
|
||||||
allow_auto_update: Some(false),
|
|
||||||
timeout_seconds: Some(5),
|
|
||||||
merge: Some("test-merge".into()),
|
|
||||||
script: Some("test-script".into()),
|
|
||||||
rules: Some("test-rules".into()),
|
|
||||||
proxies: Some("test-proxies".into()),
|
|
||||||
groups: Some("test-groups".into()),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
let item: clash_verge_profile::PrfItem = build_remote_profile(&url, None, None, Some(&option)).await?;
|
|
||||||
let refresh_option = PrfOption {
|
|
||||||
update_interval: None,
|
|
||||||
..option
|
|
||||||
};
|
|
||||||
let downloaded = download_subscription(&url, Some(&refresh_option)).await?;
|
|
||||||
let refresh = prepare_remote_refresh(downloaded, Some(&refresh_option)).await?;
|
|
||||||
server.await??;
|
|
||||||
assert_eq!(item.itype.as_deref(), Some("remote"));
|
|
||||||
assert_eq!(item.name.as_deref(), Some("remote.yaml"));
|
|
||||||
assert_eq!(item.home.as_deref(), Some("https://example.invalid/"));
|
|
||||||
assert_eq!(item.file_data.as_deref(), Some(BODY));
|
|
||||||
assert_eq!(item.current_merge().map(String::as_str), Some("test-merge"));
|
|
||||||
let usage = item.extra.context("expected decoded usage")?;
|
|
||||||
assert_eq!((usage.upload, usage.download, usage.total, usage.expire), (1, 2, 3, 4));
|
|
||||||
let fetched_option = item.option.context("expected profile options")?;
|
|
||||||
assert_eq!(fetched_option.update_interval, Some(0));
|
|
||||||
assert_eq!(fetched_option.allow_auto_update, Some(false));
|
|
||||||
|
|
||||||
assert_eq!(refresh.body.as_str(), BODY);
|
|
||||||
assert_eq!(refresh.home, item.home);
|
|
||||||
let usage = refresh.extra.context("expected refresh usage")?;
|
|
||||||
assert_eq!((usage.upload, usage.download, usage.total, usage.expire), (1, 2, 3, 4));
|
|
||||||
assert_eq!(
|
|
||||||
refresh.option,
|
|
||||||
PrfOption {
|
|
||||||
update_interval: Some(120),
|
|
||||||
..fetched_option
|
|
||||||
}
|
|
||||||
);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
+582
-278
File diff suppressed because it is too large
Load Diff
@@ -2,7 +2,7 @@ use serde_yaml_ng::{Mapping, Value};
|
|||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::{HashMap, HashSet};
|
||||||
use tristr::alias::String;
|
use tristr::alias::String;
|
||||||
|
|
||||||
use clash_verge_config_render::use_keys;
|
use crate::enhance::field::use_keys;
|
||||||
|
|
||||||
const PATCH_CONFIG_INNER: [&str; 5] = ["allow-lan", "ipv6", "log-level", "unified-delay", "tunnels"];
|
const PATCH_CONFIG_INNER: [&str; 5] = ["allow-lan", "ipv6", "log-level", "unified-delay", "tunnels"];
|
||||||
|
|
||||||
|
|||||||
@@ -64,5 +64,22 @@ pub mod files {
|
|||||||
pub mod tun {
|
pub mod tun {
|
||||||
pub const DEFAULT_STACK: &str = "mips";
|
pub const DEFAULT_STACK: &str = "mips";
|
||||||
|
|
||||||
|
pub const DEFAULT_MTU: u16 = 1500;
|
||||||
|
|
||||||
pub const DNS_HIJACK: &[&str] = &["any:53"];
|
pub const DNS_HIJACK: &[&str] = &["any:53"];
|
||||||
|
|
||||||
|
/// Saved dialog fields; `enable` belongs to the verge switch.
|
||||||
|
pub const GUI_KEYS: &[&str] = &[
|
||||||
|
"stack",
|
||||||
|
"device",
|
||||||
|
"auto-route",
|
||||||
|
"route-exclude-address",
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
"auto-redirect",
|
||||||
|
"auto-detect-interface",
|
||||||
|
"dns-hijack",
|
||||||
|
"dns-mode",
|
||||||
|
"strict-route",
|
||||||
|
"mtu",
|
||||||
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ use crate::{config::Config, process::AsyncHandler, utils::dirs};
|
|||||||
use anyhow::Error;
|
use anyhow::Error;
|
||||||
use arc_swap::{ArcSwap, ArcSwapOption};
|
use arc_swap::{ArcSwap, ArcSwapOption};
|
||||||
use backon::{ConstantBuilder, Retryable as _};
|
use backon::{ConstantBuilder, Retryable as _};
|
||||||
use clash_verge_backup_archive::BackupWriter;
|
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use reqwest_dav::list_cmd::{ListEntity, ListFile, ListMultiStatus};
|
use reqwest_dav::list_cmd::{ListEntity, ListFile, ListMultiStatus};
|
||||||
use std::{
|
use std::{
|
||||||
@@ -16,6 +15,7 @@ use std::{
|
|||||||
};
|
};
|
||||||
use tokio::{fs, time::timeout};
|
use tokio::{fs, time::timeout};
|
||||||
use tristr::alias::String;
|
use tristr::alias::String;
|
||||||
|
use zip::write::SimpleFileOptions;
|
||||||
|
|
||||||
const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
|
const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||||
|
|
||||||
@@ -275,7 +275,9 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> {
|
|||||||
|
|
||||||
let value = zip_path.clone();
|
let value = zip_path.clone();
|
||||||
let file = AsyncHandler::spawn_blocking(move || std::fs::File::create(&value)).await??;
|
let file = AsyncHandler::spawn_blocking(move || std::fs::File::create(&value)).await??;
|
||||||
let mut archive = BackupWriter::new(file)?;
|
let mut zip = zip::ZipWriter::new(file);
|
||||||
|
zip.add_directory("profiles/", SimpleFileOptions::default())?;
|
||||||
|
let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
|
||||||
|
|
||||||
if let Ok(mut entries) = fs::read_dir(dirs::app_profiles_dir()?).await {
|
if let Ok(mut entries) = fs::read_dir(dirs::app_profiles_dir()?).await {
|
||||||
while let Some(entry) = entries.next_entry().await? {
|
while let Some(entry) = entries.next_entry().await? {
|
||||||
@@ -285,16 +287,15 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> {
|
|||||||
let file_name = file_name_os
|
let file_name = file_name_os
|
||||||
.to_str()
|
.to_str()
|
||||||
.ok_or_else(|| anyhow::Error::msg("Invalid file name encoding"))?;
|
.ok_or_else(|| anyhow::Error::msg("Invalid file name encoding"))?;
|
||||||
let mut entry = archive.start_profile(file_name)?;
|
let backup_path = format!("profiles/{}", file_name);
|
||||||
|
zip.start_file(backup_path, options)?;
|
||||||
let file_content = fs::read(&path).await?;
|
let file_content = fs::read(&path).await?;
|
||||||
entry.write_all(&file_content)?;
|
zip.write_all(&file_content)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
zip.start_file(dirs::CLASH_CONFIG, options)?;
|
||||||
archive
|
zip.write_all(fs::read(dirs::clash_path()?).await?.as_slice())?;
|
||||||
.start_file(dirs::CLASH_CONFIG)?
|
|
||||||
.write_all(&fs::read(dirs::clash_path()?).await?)?;
|
|
||||||
|
|
||||||
let verge_text = fs::read_to_string(dirs::verge_path()?).await?;
|
let verge_text = fs::read_to_string(dirs::verge_path()?).await?;
|
||||||
let mut verge_config: serde_json::Value = serde_yaml_ng::from_str(&verge_text)?;
|
let mut verge_config: serde_json::Value = serde_yaml_ng::from_str(&verge_text)?;
|
||||||
@@ -303,20 +304,17 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> {
|
|||||||
obj.remove("webdav_password");
|
obj.remove("webdav_password");
|
||||||
obj.remove("webdav_url");
|
obj.remove("webdav_url");
|
||||||
}
|
}
|
||||||
archive
|
zip.start_file(dirs::VERGE_CONFIG, options)?;
|
||||||
.start_file(dirs::VERGE_CONFIG)?
|
zip.write_all(serde_yaml_ng::to_string(&verge_config)?.as_bytes())?;
|
||||||
.write_all(serde_yaml_ng::to_string(&verge_config)?.as_bytes())?;
|
|
||||||
|
|
||||||
let dns_config_path = dirs::app_home_dir()?.join(DNS_CONFIG);
|
let dns_config_path = dirs::app_home_dir()?.join(DNS_CONFIG);
|
||||||
if dns_config_path.exists() {
|
if dns_config_path.exists() {
|
||||||
archive
|
zip.start_file(DNS_CONFIG, options)?;
|
||||||
.start_file(DNS_CONFIG)?
|
zip.write_all(fs::read(&dns_config_path).await?.as_slice())?;
|
||||||
.write_all(&fs::read(&dns_config_path).await?)?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
archive
|
zip.start_file(dirs::PROFILE_YAML, options)?;
|
||||||
.start_file(dirs::PROFILE_YAML)?
|
zip.write_all(fs::read(dirs::profiles_path()?).await?.as_slice())?;
|
||||||
.write_all(&fs::read(dirs::profiles_path()?).await?)?;
|
zip.finish()?;
|
||||||
archive.finish()?;
|
|
||||||
Ok((zip_file_name, zip_path))
|
Ok((zip_file_name, zip_path))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode};
|
|||||||
use crate::core::notify::NoticeStatus;
|
use crate::core::notify::NoticeStatus;
|
||||||
use crate::core::service::StageRequest;
|
use crate::core::service::StageRequest;
|
||||||
use crate::{
|
use crate::{
|
||||||
config::{Config, IProfiles, mihomo_yaml, profiles::save_profiles, runtime::IRuntime},
|
config::{Config, IProfiles, runtime::IRuntime},
|
||||||
constants::timing,
|
constants::timing,
|
||||||
core::{
|
core::{
|
||||||
handle,
|
handle,
|
||||||
@@ -170,8 +170,7 @@ impl CoreManager {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
let yaml = mihomo_yaml::serialize(clash_config)?;
|
help::save_yaml(&runtime_path, &clash_config, Some("# Clash Verge Runtime")).await?;
|
||||||
help::save_yaml_str(&runtime_path, &yaml, Some("# Clash Verge Runtime")).await?;
|
|
||||||
handle::Handle::notice(status, message);
|
handle::Handle::notice(status, message);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -244,7 +243,7 @@ impl CoreManager {
|
|||||||
crate::config::profiles::restore_selected_nodes().await;
|
crate::config::profiles::restore_selected_nodes().await;
|
||||||
return Ok(Err(outcome));
|
return Ok(Err(outcome));
|
||||||
}
|
}
|
||||||
match save_profiles(candidate).await {
|
match candidate.save_file().await {
|
||||||
Ok(()) => {
|
Ok(()) => {
|
||||||
tracing::Span::current().record("outcome", "committed");
|
tracing::Span::current().record("outcome", "committed");
|
||||||
Ok(Ok(guard))
|
Ok(Ok(guard))
|
||||||
|
|||||||
@@ -235,7 +235,7 @@ impl CoreManager {
|
|||||||
anyhow::bail!("core startup blocked after mixed proxy port fallback failure: {reason}");
|
anyhow::bail!("core startup blocked after mixed proxy port fallback failure: {reason}");
|
||||||
}
|
}
|
||||||
|
|
||||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
|
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||||
retry(
|
retry(
|
||||||
RetryPolicy::fixed(
|
RetryPolicy::fixed(
|
||||||
std::num::NonZeroUsize::MIN.saturating_add(MAX_PORT_FALLBACK_RETRIES),
|
std::num::NonZeroUsize::MIN.saturating_add(MAX_PORT_FALLBACK_RETRIES),
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
use super::claim_core_readiness_generation;
|
use super::claim_core_readiness_generation;
|
||||||
use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode};
|
use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode};
|
||||||
|
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||||
use crate::{
|
use crate::{
|
||||||
AsyncHandler,
|
AsyncHandler,
|
||||||
config::Config,
|
config::Config,
|
||||||
@@ -10,7 +11,6 @@ use crate::{
|
|||||||
};
|
};
|
||||||
use anyhow::{Context as _, Result};
|
use anyhow::{Context as _, Result};
|
||||||
use clash_verge_logging::Type;
|
use clash_verge_logging::Type;
|
||||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
|
|
||||||
use futures::{
|
use futures::{
|
||||||
FutureExt as _,
|
FutureExt as _,
|
||||||
future::{Map, Shared},
|
future::{Map, Shared},
|
||||||
@@ -35,7 +35,6 @@ pub(super) fn explain_core_occupancy(error: anyhow::Error) -> anyhow::Error {
|
|||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
fn sidecar_config_without_tun(yaml: &str) -> Result<std::string::String> {
|
fn sidecar_config_without_tun(yaml: &str) -> Result<std::string::String> {
|
||||||
use crate::config::mihomo_yaml;
|
|
||||||
use serde_yaml_ng::{Mapping, Value};
|
use serde_yaml_ng::{Mapping, Value};
|
||||||
|
|
||||||
let mut config: Mapping = serde_yaml_ng::from_str(yaml)?;
|
let mut config: Mapping = serde_yaml_ng::from_str(yaml)?;
|
||||||
@@ -48,7 +47,7 @@ fn sidecar_config_without_tun(yaml: &str) -> Result<std::string::String> {
|
|||||||
tun.as_mapping_mut()
|
tun.as_mapping_mut()
|
||||||
.context("invalid Sidecar TUN configuration")?
|
.context("invalid Sidecar TUN configuration")?
|
||||||
.insert(Value::from("enable"), Value::Bool(false));
|
.insert(Value::from("enable"), Value::Bool(false));
|
||||||
Ok(mihomo_yaml::serialize(&config)?)
|
Ok(serde_yaml_ng::to_string(&config)?)
|
||||||
}
|
}
|
||||||
|
|
||||||
const SIDECAR_READINESS_ATTEMPTS: usize = 30;
|
const SIDECAR_READINESS_ATTEMPTS: usize = 30;
|
||||||
|
|||||||
@@ -11,7 +11,9 @@ pub mod network_watch;
|
|||||||
pub mod notify;
|
pub mod notify;
|
||||||
pub(crate) mod owner_identity;
|
pub(crate) mod owner_identity;
|
||||||
pub mod proxy_control;
|
pub mod proxy_control;
|
||||||
|
pub mod proxy_view;
|
||||||
pub mod runstate;
|
pub mod runstate;
|
||||||
|
pub(crate) mod runtime_bundle;
|
||||||
pub mod service;
|
pub mod service;
|
||||||
pub mod sysopt;
|
pub mod sysopt;
|
||||||
pub mod timer;
|
pub mod timer;
|
||||||
|
|||||||
@@ -555,7 +555,7 @@ pub async fn clear() -> Result<()> {
|
|||||||
|
|
||||||
/// A failed system call is usually a transient RPC hiccup, so give it a few tries.
|
/// A failed system call is usually a transient RPC hiccup, so give it a few tries.
|
||||||
async fn clear_with_retry() -> Result<()> {
|
async fn clear_with_retry() -> Result<()> {
|
||||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
|
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||||
retry(
|
retry(
|
||||||
RetryPolicy::fixed(
|
RetryPolicy::fixed(
|
||||||
std::num::NonZeroUsize::MIN.saturating_add((CLEAR_ATTEMPTS - 1) as usize),
|
std::num::NonZeroUsize::MIN.saturating_add((CLEAR_ATTEMPTS - 1) as usize),
|
||||||
|
|||||||
@@ -1,40 +1,15 @@
|
|||||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use tristr::alias::String;
|
use tauri_plugin_mihomo::models::{
|
||||||
|
DelayHistory, Proxies, Proxy, ProxyProvider, ProxyProviders, ProxyType, VehicleType,
|
||||||
|
};
|
||||||
|
|
||||||
pub struct ProxyViewInput {
|
pub struct ProxyViewInput {
|
||||||
pub runtime_group_order: Vec<String>,
|
pub runtime_group_order: Vec<String>,
|
||||||
pub group_scopes: BTreeMap<String, GroupScope>,
|
pub group_scopes: BTreeMap<String, GroupScope>,
|
||||||
pub proxies: HashMap<String, ProxySnapshot>,
|
pub proxies: Proxies,
|
||||||
pub providers: Option<HashMap<String, ProviderSnapshot>>,
|
pub providers: Option<ProxyProviders>,
|
||||||
}
|
|
||||||
|
|
||||||
pub struct ProxySnapshot {
|
|
||||||
pub name: String,
|
|
||||||
pub proxy_type: String,
|
|
||||||
pub all: Option<Vec<String>>,
|
|
||||||
pub fixed: Option<String>,
|
|
||||||
pub hidden: Option<bool>,
|
|
||||||
pub icon: Option<String>,
|
|
||||||
pub now: Option<String>,
|
|
||||||
pub test_url: Option<String>,
|
|
||||||
pub id: Option<String>,
|
|
||||||
pub history: Vec<DelayHistory>,
|
|
||||||
pub capabilities: ProxyCapabilities,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct ProviderSnapshot {
|
|
||||||
pub vehicle_type: ProxyProviderVehicleType,
|
|
||||||
pub proxies: Vec<ProxySnapshot>,
|
|
||||||
pub updated_at: Option<String>,
|
|
||||||
pub subscription_info: Option<ProxySubscriptionInfo>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)]
|
|
||||||
pub struct DelayHistory {
|
|
||||||
pub time: String,
|
|
||||||
pub delay: u16,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The providers a group draws from (Mihomo order) and its `exclude-type` entries.
|
/// The providers a group draws from (Mihomo order) and its `exclude-type` entries.
|
||||||
@@ -87,7 +62,8 @@ pub struct ProxyCapabilities {
|
|||||||
pub struct ProxyGroupView {
|
pub struct ProxyGroupView {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
#[serde(rename = "type")]
|
#[serde(rename = "type")]
|
||||||
pub proxy_type: String,
|
#[specta(type = String)]
|
||||||
|
pub proxy_type: ProxyType,
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub now: Option<String>,
|
pub now: Option<String>,
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
@@ -98,6 +74,7 @@ pub struct ProxyGroupView {
|
|||||||
pub icon: Option<String>,
|
pub icon: Option<String>,
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub test_url: Option<String>,
|
pub test_url: Option<String>,
|
||||||
|
#[specta(type = Vec<crate::ipc::DelayHistory>)]
|
||||||
pub history: Vec<DelayHistory>,
|
pub history: Vec<DelayHistory>,
|
||||||
#[serde(flatten)]
|
#[serde(flatten)]
|
||||||
pub capabilities: ProxyCapabilities,
|
pub capabilities: ProxyCapabilities,
|
||||||
@@ -110,7 +87,9 @@ pub struct ProxyNodeView {
|
|||||||
pub record_id: String,
|
pub record_id: String,
|
||||||
pub name: String,
|
pub name: String,
|
||||||
#[serde(rename = "type")]
|
#[serde(rename = "type")]
|
||||||
pub proxy_type: String,
|
#[specta(type = String)]
|
||||||
|
pub proxy_type: ProxyType,
|
||||||
|
#[specta(type = Vec<crate::ipc::DelayHistory>)]
|
||||||
pub history: Vec<DelayHistory>,
|
pub history: Vec<DelayHistory>,
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub id: Option<String>,
|
pub id: Option<String>,
|
||||||
@@ -221,13 +200,12 @@ impl<'a> MemberResolver<'a> {
|
|||||||
.flat_map(|provider| candidates.iter().filter(move |(owner, _)| owner == provider))
|
.flat_map(|provider| candidates.iter().filter(move |(owner, _)| owner == provider))
|
||||||
.map(|(_, record_id)| record_id)
|
.map(|(_, record_id)| record_id)
|
||||||
.filter(|record_id| {
|
.filter(|record_id| {
|
||||||
scope.exclude_types.is_empty()
|
!self.records.get(*record_id).is_some_and(|node| {
|
||||||
|| !self.records.get(*record_id).is_some_and(|node| {
|
scope
|
||||||
scope
|
.exclude_types
|
||||||
.exclude_types
|
.iter()
|
||||||
.iter()
|
.any(|excluded| excluded.eq_ignore_ascii_case(node.proxy_type.as_str()))
|
||||||
.any(|excluded| excluded.eq_ignore_ascii_case(node.proxy_type.as_str()))
|
})
|
||||||
})
|
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
@@ -292,7 +270,7 @@ impl ProxyViewBuilder {
|
|||||||
|
|
||||||
let global = core_groups
|
let global = core_groups
|
||||||
.remove("GLOBAL")
|
.remove("GLOBAL")
|
||||||
.map(|proxy| build_group("GLOBAL".into(), proxy, &resolver));
|
.map(|proxy| build_group("GLOBAL".to_owned(), proxy, &resolver));
|
||||||
let (groups, order_source) = build_ordered_groups(core_groups, runtime_group_order, &resolver);
|
let (groups, order_source) = build_ordered_groups(core_groups, runtime_group_order, &resolver);
|
||||||
let direct = core_node_ids.get("DIRECT").cloned();
|
let direct = core_node_ids.get("DIRECT").cloned();
|
||||||
let standalone = build_standalone(&core_node_ids);
|
let standalone = build_standalone(&core_node_ids);
|
||||||
@@ -311,13 +289,11 @@ impl ProxyViewBuilder {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn partition_core(
|
fn partition_core(proxies: Proxies) -> (BTreeMap<String, Proxy>, BTreeMap<String, Proxy>) {
|
||||||
proxies: HashMap<String, ProxySnapshot>,
|
|
||||||
) -> (BTreeMap<String, ProxySnapshot>, BTreeMap<String, ProxySnapshot>) {
|
|
||||||
let mut groups = BTreeMap::new();
|
let mut groups = BTreeMap::new();
|
||||||
let mut nodes = BTreeMap::new();
|
let mut nodes = BTreeMap::new();
|
||||||
|
|
||||||
for (name, proxy) in proxies {
|
for (name, proxy) in proxies.proxies {
|
||||||
if proxy.all.is_some() {
|
if proxy.all.is_some() {
|
||||||
groups.insert(name, proxy);
|
groups.insert(name, proxy);
|
||||||
} else {
|
} else {
|
||||||
@@ -329,13 +305,13 @@ fn partition_core(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn build_core_records(
|
fn build_core_records(
|
||||||
core_nodes: BTreeMap<String, ProxySnapshot>,
|
core_nodes: BTreeMap<String, Proxy>,
|
||||||
) -> (BTreeMap<String, ProxyNodeView>, BTreeMap<String, String>) {
|
) -> (BTreeMap<String, ProxyNodeView>, BTreeMap<String, String>) {
|
||||||
let mut records = BTreeMap::new();
|
let mut records = BTreeMap::new();
|
||||||
let mut ids = BTreeMap::new();
|
let mut ids = BTreeMap::new();
|
||||||
|
|
||||||
for (index, (name, proxy)) in core_nodes.into_iter().enumerate() {
|
for (index, (name, proxy)) in core_nodes.into_iter().enumerate() {
|
||||||
let record_id: String = format!("c:{index}").into();
|
let record_id = format!("c:{index}");
|
||||||
ids.insert(name.clone(), record_id.clone());
|
ids.insert(name.clone(), record_id.clone());
|
||||||
records.insert(
|
records.insert(
|
||||||
record_id.clone(),
|
record_id.clone(),
|
||||||
@@ -352,25 +328,32 @@ fn build_core_records(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn build_provider_records(
|
fn build_provider_records(
|
||||||
providers: Option<HashMap<String, ProviderSnapshot>>,
|
providers: Option<ProxyProviders>,
|
||||||
records: &mut BTreeMap<String, ProxyNodeView>,
|
records: &mut BTreeMap<String, ProxyNodeView>,
|
||||||
) -> (Vec<ProxyProviderView>, ProviderCandidates) {
|
) -> (Vec<ProxyProviderView>, ProviderCandidates) {
|
||||||
let providers = providers.map_or_default(|providers| providers.into_iter().collect::<BTreeMap<_, _>>());
|
let providers = providers.map_or_default(|providers| providers.providers.into_iter().collect::<BTreeMap<_, _>>());
|
||||||
let mut views = Vec::new();
|
let mut views = Vec::new();
|
||||||
let mut candidates = BTreeMap::new();
|
let mut candidates = BTreeMap::new();
|
||||||
|
|
||||||
for (provider_name, provider) in providers {
|
for (provider_name, provider) in providers {
|
||||||
let ProviderSnapshot {
|
let ProxyProvider {
|
||||||
vehicle_type,
|
vehicle_type,
|
||||||
proxies,
|
proxies,
|
||||||
updated_at,
|
updated_at,
|
||||||
subscription_info,
|
subscription_info,
|
||||||
|
..
|
||||||
} = provider;
|
} = provider;
|
||||||
|
let vehicle_type = match vehicle_type {
|
||||||
|
VehicleType::HTTP => ProxyProviderVehicleType::Http,
|
||||||
|
VehicleType::File => ProxyProviderVehicleType::File,
|
||||||
|
VehicleType::Inline => ProxyProviderVehicleType::Inline,
|
||||||
|
_ => continue,
|
||||||
|
};
|
||||||
let provider_index = views.len();
|
let provider_index = views.len();
|
||||||
let mut proxy_record_ids = Vec::new();
|
let mut proxy_record_ids = Vec::new();
|
||||||
|
|
||||||
for (member_index, proxy) in proxies.into_iter().enumerate() {
|
for (member_index, proxy) in proxies.into_iter().enumerate() {
|
||||||
let record_id: String = format!("p:{provider_index}:{member_index}").into();
|
let record_id = format!("p:{provider_index}:{member_index}");
|
||||||
let proxy_name = proxy.name.clone();
|
let proxy_name = proxy.name.clone();
|
||||||
let node_name = proxy.name.clone();
|
let node_name = proxy.name.clone();
|
||||||
candidates
|
candidates
|
||||||
@@ -396,7 +379,12 @@ fn build_provider_records(
|
|||||||
name: provider_name,
|
name: provider_name,
|
||||||
vehicle_type,
|
vehicle_type,
|
||||||
updated_at,
|
updated_at,
|
||||||
subscription_info,
|
subscription_info: subscription_info.map(|subscription_info| ProxySubscriptionInfo {
|
||||||
|
upload: subscription_info.upload,
|
||||||
|
download: subscription_info.download,
|
||||||
|
total: subscription_info.total,
|
||||||
|
expire: subscription_info.expire,
|
||||||
|
}),
|
||||||
proxy_record_ids,
|
proxy_record_ids,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -404,8 +392,8 @@ fn build_provider_records(
|
|||||||
(views, candidates)
|
(views, candidates)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn build_group(name: String, proxy: ProxySnapshot, resolver: &MemberResolver<'_>) -> ProxyGroupView {
|
fn build_group(name: String, proxy: Proxy, resolver: &MemberResolver<'_>) -> ProxyGroupView {
|
||||||
let ProxySnapshot {
|
let Proxy {
|
||||||
all,
|
all,
|
||||||
fixed,
|
fixed,
|
||||||
hidden,
|
hidden,
|
||||||
@@ -413,7 +401,11 @@ fn build_group(name: String, proxy: ProxySnapshot, resolver: &MemberResolver<'_>
|
|||||||
now,
|
now,
|
||||||
test_url,
|
test_url,
|
||||||
history,
|
history,
|
||||||
capabilities,
|
udp,
|
||||||
|
xudp,
|
||||||
|
tfo,
|
||||||
|
mptcp,
|
||||||
|
smux,
|
||||||
proxy_type,
|
proxy_type,
|
||||||
..
|
..
|
||||||
} = proxy;
|
} = proxy;
|
||||||
@@ -441,19 +433,29 @@ fn build_group(name: String, proxy: ProxySnapshot, resolver: &MemberResolver<'_>
|
|||||||
icon,
|
icon,
|
||||||
test_url,
|
test_url,
|
||||||
history,
|
history,
|
||||||
capabilities,
|
capabilities: ProxyCapabilities {
|
||||||
|
udp,
|
||||||
|
xudp,
|
||||||
|
tfo,
|
||||||
|
mptcp,
|
||||||
|
smux,
|
||||||
|
},
|
||||||
members,
|
members,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn build_node(record_id: String, name: String, proxy: ProxySnapshot, source: ProxyNodeSource) -> ProxyNodeView {
|
fn build_node(record_id: String, name: String, proxy: Proxy, source: ProxyNodeSource) -> ProxyNodeView {
|
||||||
let ProxySnapshot {
|
let Proxy {
|
||||||
id,
|
id,
|
||||||
hidden,
|
hidden,
|
||||||
icon,
|
icon,
|
||||||
test_url,
|
test_url,
|
||||||
history,
|
history,
|
||||||
capabilities,
|
udp,
|
||||||
|
xudp,
|
||||||
|
tfo,
|
||||||
|
mptcp,
|
||||||
|
smux,
|
||||||
proxy_type,
|
proxy_type,
|
||||||
..
|
..
|
||||||
} = proxy;
|
} = proxy;
|
||||||
@@ -467,13 +469,19 @@ fn build_node(record_id: String, name: String, proxy: ProxySnapshot, source: Pro
|
|||||||
hidden,
|
hidden,
|
||||||
icon,
|
icon,
|
||||||
test_url,
|
test_url,
|
||||||
capabilities,
|
capabilities: ProxyCapabilities {
|
||||||
|
udp,
|
||||||
|
xudp,
|
||||||
|
tfo,
|
||||||
|
mptcp,
|
||||||
|
smux,
|
||||||
|
},
|
||||||
source,
|
source,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn build_ordered_groups(
|
fn build_ordered_groups(
|
||||||
mut core_groups: BTreeMap<String, ProxySnapshot>,
|
mut core_groups: BTreeMap<String, Proxy>,
|
||||||
runtime_group_order: Vec<String>,
|
runtime_group_order: Vec<String>,
|
||||||
resolver: &MemberResolver<'_>,
|
resolver: &MemberResolver<'_>,
|
||||||
) -> (Vec<ProxyGroupView>, ProxyViewOrderSource) {
|
) -> (Vec<ProxyGroupView>, ProxyViewOrderSource) {
|
||||||
@@ -135,7 +135,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
|||||||
|
|
||||||
/// Retries transport failures but stops at the first readable reply, including a rejection.
|
/// Retries transport failures but stops at the first readable reply, including a rejection.
|
||||||
pub async fn await_ready(&self, attempts: usize, interval: Duration) -> Result<RunState, ReadyWaitError> {
|
pub async fn await_ready(&self, attempts: usize, interval: Duration) -> Result<RunState, ReadyWaitError> {
|
||||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
|
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||||
let attempts = std::num::NonZeroUsize::new(attempts).ok_or_else(|| {
|
let attempts = std::num::NonZeroUsize::new(attempts).ok_or_else(|| {
|
||||||
ReadyWaitError::Unreachable(anyhow::anyhow!(
|
ReadyWaitError::Unreachable(anyhow::anyhow!(
|
||||||
"service readiness wait was configured with no attempts"
|
"service readiness wait was configured with no attempts"
|
||||||
|
|||||||
+141
-186
@@ -1,15 +1,12 @@
|
|||||||
mod error;
|
use anyhow::{Context as _, Result, bail};
|
||||||
|
|
||||||
pub use error::RuntimeBundleError;
|
|
||||||
|
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
|
use clash_verge_service_ipc::{RemoteProvider, RuntimeAsset, RuntimeBundle};
|
||||||
use serde_yaml_ng::{Mapping, Value};
|
use serde_yaml_ng::{Mapping, Value};
|
||||||
use sha2::{Digest as _, Sha256};
|
use sha2::{Digest as _, Sha256};
|
||||||
use std::collections::{BTreeMap, HashSet};
|
use std::collections::{BTreeMap, HashSet};
|
||||||
use std::path::{Component, Path, PathBuf, Prefix};
|
use std::path::{Component, Path, PathBuf, Prefix};
|
||||||
use tristr::TriStr;
|
|
||||||
|
|
||||||
pub const GEO_ASSETS: &[&str] = &[
|
pub(crate) const GEO_ASSETS: &[&str] = &[
|
||||||
"Country.mmdb",
|
"Country.mmdb",
|
||||||
"ASN.mmdb",
|
"ASN.mmdb",
|
||||||
"geoip.dat",
|
"geoip.dat",
|
||||||
@@ -20,62 +17,42 @@ pub const GEO_ASSETS: &[&str] = &[
|
|||||||
|
|
||||||
/// Provider identity used by the runtime config and core API.
|
/// Provider identity used by the runtime config and core API.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct RemoteProviderRef {
|
pub(crate) struct RemoteProviderRef {
|
||||||
pub section: &'static str,
|
pub section: &'static str,
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub destination: TriStr,
|
pub provider: RemoteProvider,
|
||||||
pub url: String,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct RuntimeAsset {
|
struct RuntimeParts {
|
||||||
pub source: String,
|
config: Value,
|
||||||
pub destination: TriStr,
|
assets: Vec<RuntimeAsset>,
|
||||||
|
remote_providers: Vec<RemoteProviderRef>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct RuntimeBundlePlan {
|
pub(crate) async fn collect_runtime_bundle(config_file: &Path, core_path: &Path) -> Result<RuntimeBundle> {
|
||||||
pub config: Value,
|
|
||||||
pub assets: Vec<RuntimeAsset>,
|
|
||||||
pub remote_providers: Vec<RemoteProviderRef>,
|
|
||||||
}
|
|
||||||
|
|
||||||
type Result<T> = std::result::Result<T, RuntimeBundleError>;
|
|
||||||
|
|
||||||
pub async fn collect_runtime_bundle(config_file: &Path) -> Result<RuntimeBundlePlan> {
|
|
||||||
let yaml = tokio::fs::read_to_string(config_file)
|
let yaml = tokio::fs::read_to_string(config_file)
|
||||||
.await
|
.await
|
||||||
.map_err(|source| RuntimeBundleError::ReadConfig {
|
.with_context(|| format!("failed to read runtime config {config_file:?}"))?;
|
||||||
path: config_file.to_owned(),
|
let config: Value =
|
||||||
source,
|
serde_yaml_ng::from_str(&yaml).with_context(|| format!("failed to parse runtime config {config_file:?}"))?;
|
||||||
})?;
|
let config_root = config_file
|
||||||
let config: Value = serde_yaml_ng::from_str(&yaml).map_err(|source| RuntimeBundleError::ParseConfig {
|
.parent()
|
||||||
path: config_file.to_owned(),
|
.ok_or_else(|| anyhow::anyhow!("runtime config has no parent directory"))?;
|
||||||
source,
|
let parts = collect_runtime_parts(config, config_root)?;
|
||||||
})?;
|
Ok(RuntimeBundle {
|
||||||
let config_root = config_file.parent().ok_or(RuntimeBundleError::MissingConfigDirectory)?;
|
yaml: serde_yaml_ng::to_string(&parts.config).context("failed to serialize service runtime config")?,
|
||||||
collect_runtime_parts(config, config_root)
|
assets: parts.assets,
|
||||||
|
remote_providers: parts
|
||||||
|
.remote_providers
|
||||||
|
.into_iter()
|
||||||
|
.map(|declared| declared.provider)
|
||||||
|
.collect(),
|
||||||
|
core_path: core_path.to_string_lossy().into_owned(),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn remote_providers_of(config: &Mapping, config_root: &Path) -> Result<Vec<RemoteProviderRef>> {
|
pub(crate) fn remote_providers_of(config: &Mapping, config_root: &Path) -> Result<Vec<RemoteProviderRef>> {
|
||||||
let config_root = std::fs::canonicalize(config_root)?;
|
Ok(collect_runtime_parts(Value::Mapping(config.clone()), config_root)?.remote_providers)
|
||||||
let mut destinations = HashSet::new();
|
|
||||||
let mut remote_providers = Vec::new();
|
|
||||||
for section in ["proxy-providers", "rule-providers"] {
|
|
||||||
let Some(providers) = config.get(section).and_then(Value::as_mapping) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
for (name, provider) in providers {
|
|
||||||
plan_provider(
|
|
||||||
section,
|
|
||||||
name,
|
|
||||||
provider,
|
|
||||||
&config_root,
|
|
||||||
&mut destinations,
|
|
||||||
None,
|
|
||||||
&mut remote_providers,
|
|
||||||
)?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(remote_providers)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
@@ -84,10 +61,10 @@ struct ProviderPathOwners {
|
|||||||
local: bool,
|
local: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn resolve_provider_path_conflicts(config: &mut Mapping, config_root: &Path) -> Result<()> {
|
pub(crate) fn resolve_provider_path_conflicts(config: &mut Mapping, config_root: &Path) -> Result<()> {
|
||||||
let config_root = std::fs::canonicalize(config_root)?;
|
let config_root = std::fs::canonicalize(config_root)?;
|
||||||
let mut paths = BTreeMap::<TriStr, ProviderPathOwners>::new();
|
let mut paths = BTreeMap::<String, ProviderPathOwners>::new();
|
||||||
let mut reserved: HashSet<TriStr> = GEO_ASSETS.iter().copied().map(TriStr::from).collect();
|
let mut reserved: HashSet<String> = GEO_ASSETS.iter().map(|name| (*name).to_owned()).collect();
|
||||||
for section in ["proxy-providers", "rule-providers"] {
|
for section in ["proxy-providers", "rule-providers"] {
|
||||||
let Some(providers) = config.get(section).and_then(Value::as_mapping) else {
|
let Some(providers) = config.get(section).and_then(Value::as_mapping) else {
|
||||||
continue;
|
continue;
|
||||||
@@ -107,7 +84,6 @@ pub fn resolve_provider_path_conflicts(config: &mut Mapping, config_root: &Path)
|
|||||||
let Ok(destination) = destination else {
|
let Ok(destination) = destination else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
let destination = TriStr::from(destination.as_str());
|
|
||||||
reserved.insert(destination.clone());
|
reserved.insert(destination.clone());
|
||||||
let owners = paths.entry(destination).or_default();
|
let owners = paths.entry(destination).or_default();
|
||||||
match (is_remote, provider.get("url").and_then(Value::as_str)) {
|
match (is_remote, provider.get("url").and_then(Value::as_str)) {
|
||||||
@@ -141,12 +117,12 @@ pub fn resolve_provider_path_conflicts(config: &mut Mapping, config_root: &Path)
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut HashSet<TriStr>) -> String {
|
fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut HashSet<String>) -> String {
|
||||||
let mut digest = Sha256::new();
|
let mut digest = Sha256::new();
|
||||||
digest.update(destination.as_bytes());
|
digest.update(destination.as_bytes());
|
||||||
digest.update([0]);
|
digest.update([0]);
|
||||||
digest.update(url.as_bytes());
|
digest.update(url.as_bytes());
|
||||||
let digest = hex::encode(digest.finalize());
|
let digest: String = crate::utils::help::hex_encode(&digest.finalize());
|
||||||
let path = Path::new(destination);
|
let path = Path::new(destination);
|
||||||
let extension = path
|
let extension = path
|
||||||
.extension()
|
.extension()
|
||||||
@@ -158,7 +134,7 @@ fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut Ha
|
|||||||
.with_file_name(format!("cvr-{digest}{suffix}{extension}"))
|
.with_file_name(format!("cvr-{digest}{suffix}{extension}"))
|
||||||
.to_string_lossy()
|
.to_string_lossy()
|
||||||
.replace('\\', "/");
|
.replace('\\', "/");
|
||||||
if reserved.insert(TriStr::from(candidate.as_str())) {
|
if reserved.insert(candidate.clone()) {
|
||||||
return candidate;
|
return candidate;
|
||||||
}
|
}
|
||||||
sequence += 1;
|
sequence += 1;
|
||||||
@@ -166,7 +142,7 @@ fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut Ha
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn collect_runtime_parts(mut config: Value, config_root: &Path) -> Result<RuntimeBundlePlan> {
|
fn collect_runtime_parts(mut config: Value, config_root: &Path) -> Result<RuntimeParts> {
|
||||||
let config_root = std::fs::canonicalize(config_root)?;
|
let config_root = std::fs::canonicalize(config_root)?;
|
||||||
let mut assets = Vec::new();
|
let mut assets = Vec::new();
|
||||||
let mut destinations = HashSet::new();
|
let mut destinations = HashSet::new();
|
||||||
@@ -191,15 +167,15 @@ fn collect_runtime_parts(mut config: Value, config_root: &Path) -> Result<Runtim
|
|||||||
collect_ssh_private_keys(&mut config, &config_root, &mut destinations, &mut assets);
|
collect_ssh_private_keys(&mut config, &config_root, &mut destinations, &mut assets);
|
||||||
for filename in GEO_ASSETS {
|
for filename in GEO_ASSETS {
|
||||||
let source = config_root.join(filename);
|
let source = config_root.join(filename);
|
||||||
if source.is_file() && destinations.insert(TriStr::from(*filename)) {
|
if source.is_file() && destinations.insert((*filename).to_string()) {
|
||||||
assets.push(RuntimeAsset {
|
assets.push(RuntimeAsset {
|
||||||
source: std::fs::canonicalize(&source)?.to_string_lossy().into_owned(),
|
source: std::fs::canonicalize(&source)?.to_string_lossy().into_owned(),
|
||||||
destination: (*filename).into(),
|
destination: (*filename).to_string(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(RuntimeBundlePlan {
|
Ok(RuntimeParts {
|
||||||
config,
|
config,
|
||||||
assets,
|
assets,
|
||||||
remote_providers,
|
remote_providers,
|
||||||
@@ -212,7 +188,7 @@ fn collect_provider_assets(
|
|||||||
config: &mut Value,
|
config: &mut Value,
|
||||||
section: &'static str,
|
section: &'static str,
|
||||||
config_root: &Path,
|
config_root: &Path,
|
||||||
destinations: &mut HashSet<TriStr>,
|
destinations: &mut HashSet<String>,
|
||||||
assets: &mut Vec<RuntimeAsset>,
|
assets: &mut Vec<RuntimeAsset>,
|
||||||
remote_providers: &mut Vec<RemoteProviderRef>,
|
remote_providers: &mut Vec<RemoteProviderRef>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
@@ -225,103 +201,80 @@ fn collect_provider_assets(
|
|||||||
};
|
};
|
||||||
|
|
||||||
for (name, provider) in providers.iter_mut() {
|
for (name, provider) in providers.iter_mut() {
|
||||||
if let Some(destination) = plan_provider(
|
let Some(provider) = provider.as_mapping_mut() else {
|
||||||
section,
|
continue;
|
||||||
name,
|
};
|
||||||
provider,
|
let Some(raw_path) = provider.get("path").and_then(Value::as_str) else {
|
||||||
config_root,
|
continue;
|
||||||
destinations,
|
};
|
||||||
Some(assets),
|
// Match mihomo's `type` classification and leave malformed-but-accepted providers untouched.
|
||||||
remote_providers,
|
let is_remote = provider.get("type").and_then(Value::as_str) == Some("http");
|
||||||
)? && let Some(provider) = provider.as_mapping_mut()
|
let url = provider.get("url").and_then(Value::as_str).map(str::to_owned);
|
||||||
{
|
let destination = match (is_remote, url) {
|
||||||
provider.insert(Value::String("path".to_owned()), Value::String(destination));
|
(true, Some(url)) => {
|
||||||
}
|
let destination = provider_destination(config_root, raw_path)?;
|
||||||
}
|
// Reserve remote destinations too; copied and downloaded files must not collide.
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn plan_provider(
|
|
||||||
section: &'static str,
|
|
||||||
name: &Value,
|
|
||||||
provider: &Value,
|
|
||||||
config_root: &Path,
|
|
||||||
destinations: &mut HashSet<TriStr>,
|
|
||||||
assets: Option<&mut Vec<RuntimeAsset>>,
|
|
||||||
remote_providers: &mut Vec<RemoteProviderRef>,
|
|
||||||
) -> Result<Option<String>> {
|
|
||||||
let Some(raw_path) = provider
|
|
||||||
.as_mapping()
|
|
||||||
.and_then(|provider| provider.get("path"))
|
|
||||||
.and_then(Value::as_str)
|
|
||||||
else {
|
|
||||||
return Ok(None);
|
|
||||||
};
|
|
||||||
// Match mihomo's `type` classification and leave malformed-but-accepted providers untouched.
|
|
||||||
let is_remote = provider.get("type").and_then(Value::as_str) == Some("http");
|
|
||||||
let url = provider.get("url").and_then(Value::as_str);
|
|
||||||
let destination = match (is_remote, url) {
|
|
||||||
(true, Some(url)) => {
|
|
||||||
let destination = provider_destination(config_root, raw_path)?;
|
|
||||||
// Reserve remote destinations too; copied and downloaded files must not collide.
|
|
||||||
let reserved = TriStr::from(destination.as_str());
|
|
||||||
if destinations.insert(reserved.clone()) {
|
|
||||||
remote_providers.push(RemoteProviderRef {
|
|
||||||
section,
|
|
||||||
name: name.as_str().unwrap_or_default().to_owned(),
|
|
||||||
destination: reserved,
|
|
||||||
url: url.to_owned(),
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
match remote_providers
|
match remote_providers
|
||||||
.iter()
|
.iter()
|
||||||
.find(|declared| declared.destination == destination)
|
.find(|declared| declared.provider.destination == destination)
|
||||||
{
|
{
|
||||||
Some(declared) if declared.url == url => {}
|
Some(declared) if declared.provider.url == url => {}
|
||||||
Some(_) => return Err(RuntimeBundleError::DifferentSources(destination)),
|
Some(_) => {
|
||||||
None => return Err(RuntimeBundleError::DuplicateDestination(destination)),
|
bail!("runtime provider destination {destination:?} is declared for two different sources")
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
if !destinations.insert(destination.clone()) {
|
||||||
|
bail!("runtime provider destination {destination:?} is claimed more than once");
|
||||||
|
}
|
||||||
|
remote_providers.push(RemoteProviderRef {
|
||||||
|
section,
|
||||||
|
name: name.as_str().unwrap_or_default().to_owned(),
|
||||||
|
provider: RemoteProvider {
|
||||||
|
destination: destination.clone(),
|
||||||
|
url,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
destination
|
||||||
}
|
}
|
||||||
destination
|
(true, None) => {
|
||||||
}
|
|
||||||
(true, None) => {
|
|
||||||
logging!(
|
|
||||||
warn,
|
|
||||||
Type::Config,
|
|
||||||
"remote provider {name:?} declares no url; leaving its path to the core"
|
|
||||||
);
|
|
||||||
return Ok(None);
|
|
||||||
}
|
|
||||||
(false, _) => {
|
|
||||||
let Ok(source) = local_provider_source(config_root, raw_path) else {
|
|
||||||
logging!(
|
logging!(
|
||||||
warn,
|
warn,
|
||||||
Type::Config,
|
Type::Config,
|
||||||
"local provider {name:?} is unavailable at {raw_path:?}; leaving its path to the core"
|
"remote provider {name:?} declares no url; leaving its path to the core"
|
||||||
);
|
);
|
||||||
return Ok(None);
|
continue;
|
||||||
};
|
|
||||||
let destination = destination_below_root(config_root, &source)?;
|
|
||||||
let reserved = TriStr::from(destination.as_str());
|
|
||||||
if destinations.insert(reserved.clone())
|
|
||||||
&& let Some(assets) = assets
|
|
||||||
{
|
|
||||||
assets.push(RuntimeAsset {
|
|
||||||
source: source.to_string_lossy().into_owned(),
|
|
||||||
destination: reserved,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
destination
|
(false, _) => {
|
||||||
}
|
let Ok(source) = local_provider_source(config_root, raw_path) else {
|
||||||
};
|
logging!(
|
||||||
Ok(Some(destination))
|
warn,
|
||||||
|
Type::Config,
|
||||||
|
"local provider {name:?} is unavailable at {raw_path:?}; leaving its path to the core"
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let destination = destination_below_root(config_root, &source)?;
|
||||||
|
if destinations.insert(destination.clone()) {
|
||||||
|
assets.push(RuntimeAsset {
|
||||||
|
source: source.to_string_lossy().into_owned(),
|
||||||
|
destination: destination.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
destination
|
||||||
|
}
|
||||||
|
};
|
||||||
|
provider.insert(Value::String("path".to_owned()), Value::String(destination));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Stages file-based ssh keys, which mihomo resolves against the core home directory.
|
/// Stages file-based ssh keys, which mihomo resolves against the core home directory.
|
||||||
fn collect_ssh_private_keys(
|
fn collect_ssh_private_keys(
|
||||||
config: &mut Value,
|
config: &mut Value,
|
||||||
config_root: &Path,
|
config_root: &Path,
|
||||||
destinations: &mut HashSet<TriStr>,
|
destinations: &mut HashSet<String>,
|
||||||
assets: &mut Vec<RuntimeAsset>,
|
assets: &mut Vec<RuntimeAsset>,
|
||||||
) {
|
) {
|
||||||
let Some(config) = config.as_mapping_mut() else {
|
let Some(config) = config.as_mapping_mut() else {
|
||||||
@@ -372,7 +325,7 @@ fn collect_ssh_private_keys(
|
|||||||
let destination = allocate_provider_destination("ssh-private-key", &source, destinations);
|
let destination = allocate_provider_destination("ssh-private-key", &source, destinations);
|
||||||
assets.push(RuntimeAsset {
|
assets.push(RuntimeAsset {
|
||||||
source,
|
source,
|
||||||
destination: TriStr::from(destination.as_str()),
|
destination: destination.clone(),
|
||||||
});
|
});
|
||||||
proxy.insert(Value::String("private-key".to_owned()), Value::String(destination));
|
proxy.insert(Value::String("private-key".to_owned()), Value::String(destination));
|
||||||
}
|
}
|
||||||
@@ -394,13 +347,10 @@ fn local_provider_source(config_root: &Path, raw_path: &str) -> Result<PathBuf>
|
|||||||
config_root.join(path)
|
config_root.join(path)
|
||||||
};
|
};
|
||||||
let canonical_source =
|
let canonical_source =
|
||||||
std::fs::canonicalize(&source).map_err(|error| RuntimeBundleError::LocalProviderUnavailable {
|
std::fs::canonicalize(&source).with_context(|| format!("local runtime provider is unavailable: {source:?}"))?;
|
||||||
path: source,
|
|
||||||
source: error,
|
|
||||||
})?;
|
|
||||||
canonical_source
|
canonical_source
|
||||||
.strip_prefix(config_root)
|
.strip_prefix(config_root)
|
||||||
.map_err(|_| RuntimeBundleError::LocalProviderOutsideRoot(canonical_source.clone()))?;
|
.map_err(|_| anyhow::anyhow!("local runtime provider is outside the config root: {canonical_source:?}"))?;
|
||||||
Ok(canonical_source)
|
Ok(canonical_source)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -410,7 +360,7 @@ fn provider_destination(config_root: &Path, raw_path: &str) -> Result<String> {
|
|||||||
.components()
|
.components()
|
||||||
.any(|component| matches!(component, Component::ParentDir))
|
.any(|component| matches!(component, Component::ParentDir))
|
||||||
{
|
{
|
||||||
return Err(RuntimeBundleError::DestinationOutsideRuntime);
|
bail!("runtime provider destination traverses outside the runtime");
|
||||||
}
|
}
|
||||||
if path.is_absolute() {
|
if path.is_absolute() {
|
||||||
let normalized = canonicalize_with_missing_tail(path)?;
|
let normalized = canonicalize_with_missing_tail(path)?;
|
||||||
@@ -426,11 +376,11 @@ fn canonicalize_with_missing_tail(path: &Path) -> Result<PathBuf> {
|
|||||||
while !ancestor.exists() {
|
while !ancestor.exists() {
|
||||||
let name = ancestor
|
let name = ancestor
|
||||||
.file_name()
|
.file_name()
|
||||||
.ok_or_else(|| RuntimeBundleError::MissingAncestor(path.to_owned()))?;
|
.ok_or_else(|| anyhow::anyhow!("runtime provider path has no existing ancestor: {path:?}"))?;
|
||||||
tail.push(name.to_owned());
|
tail.push(name.to_owned());
|
||||||
ancestor = ancestor
|
ancestor = ancestor
|
||||||
.parent()
|
.parent()
|
||||||
.ok_or_else(|| RuntimeBundleError::MissingAncestor(path.to_owned()))?;
|
.ok_or_else(|| anyhow::anyhow!("runtime provider path has no existing ancestor: {path:?}"))?;
|
||||||
}
|
}
|
||||||
let mut normalized = std::fs::canonicalize(ancestor)?;
|
let mut normalized = std::fs::canonicalize(ancestor)?;
|
||||||
for component in tail.iter().rev() {
|
for component in tail.iter().rev() {
|
||||||
@@ -442,7 +392,7 @@ fn canonicalize_with_missing_tail(path: &Path) -> Result<PathBuf> {
|
|||||||
fn destination_below_root(config_root: &Path, path: &Path) -> Result<String> {
|
fn destination_below_root(config_root: &Path, path: &Path) -> Result<String> {
|
||||||
let relative = path
|
let relative = path
|
||||||
.strip_prefix(config_root)
|
.strip_prefix(config_root)
|
||||||
.map_err(|_| RuntimeBundleError::ProviderOutsideRoot(path.to_owned()))?;
|
.map_err(|_| anyhow::anyhow!("runtime provider path is outside the config root: {path:?}"))?;
|
||||||
normalized_destination(relative)
|
normalized_destination(relative)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -452,11 +402,11 @@ fn normalized_destination(relative: &Path) -> Result<String> {
|
|||||||
match component {
|
match component {
|
||||||
Component::Normal(component) => destination.push(component),
|
Component::Normal(component) => destination.push(component),
|
||||||
Component::CurDir => {}
|
Component::CurDir => {}
|
||||||
_ => return Err(RuntimeBundleError::LocalDestinationOutsideRuntime),
|
_ => bail!("local runtime provider destination traverses outside the runtime"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if destination.as_os_str().is_empty() {
|
if destination.as_os_str().is_empty() {
|
||||||
return Err(RuntimeBundleError::EmptyDestination);
|
bail!("local runtime provider destination is empty");
|
||||||
}
|
}
|
||||||
Ok(destination.to_string_lossy().replace('\\', "/"))
|
Ok(destination.to_string_lossy().replace('\\', "/"))
|
||||||
}
|
}
|
||||||
@@ -466,8 +416,7 @@ mod tests {
|
|||||||
use super::{collect_runtime_bundle, remote_providers_of, resolve_provider_path_conflicts};
|
use super::{collect_runtime_bundle, remote_providers_of, resolve_provider_path_conflicts};
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn conflicting_sources_get_separate_paths_in_config_bundle_and_readback()
|
async fn conflicting_sources_get_separate_paths_in_config_bundle_and_readback() -> anyhow::Result<()> {
|
||||||
-> std::result::Result<(), Box<dyn std::error::Error>> {
|
|
||||||
let root = std::env::temp_dir().join(format!("clash-verge-provider-paths-{}", std::process::id()));
|
let root = std::env::temp_dir().join(format!("clash-verge-provider-paths-{}", std::process::id()));
|
||||||
std::fs::create_dir_all(&root)?;
|
std::fs::create_dir_all(&root)?;
|
||||||
let mut config: serde_yaml_ng::Mapping = serde_yaml_ng::from_str(
|
let mut config: serde_yaml_ng::Mapping = serde_yaml_ng::from_str(
|
||||||
@@ -484,7 +433,7 @@ mod tests {
|
|||||||
resolve_provider_path_conflicts(&mut config, &root)?;
|
resolve_provider_path_conflicts(&mut config, &root)?;
|
||||||
let config_file = root.join("config.yaml");
|
let config_file = root.join("config.yaml");
|
||||||
std::fs::write(&config_file, serde_yaml_ng::to_string(&config)?)?;
|
std::fs::write(&config_file, serde_yaml_ng::to_string(&config)?)?;
|
||||||
let bundle = collect_runtime_bundle(&config_file).await?;
|
let bundle = collect_runtime_bundle(&config_file, &root.join("mihomo")).await?;
|
||||||
let paths = &config["rule-providers"];
|
let paths = &config["rule-providers"];
|
||||||
assert_ne!(paths["AppleDev"]["path"], paths["mirror"]["path"]);
|
assert_ne!(paths["AppleDev"]["path"], paths["mirror"]["path"]);
|
||||||
resolve_provider_path_conflicts(&mut reordered, &root)?;
|
resolve_provider_path_conflicts(&mut reordered, &root)?;
|
||||||
@@ -499,14 +448,14 @@ mod tests {
|
|||||||
"resolving an already generated config must be idempotent"
|
"resolving an already generated config must be idempotent"
|
||||||
);
|
);
|
||||||
|
|
||||||
assert_eq!(bundle.config.as_mapping(), Some(&config));
|
assert_eq!(serde_yaml_ng::from_str::<serde_yaml_ng::Mapping>(&bundle.yaml)?, config);
|
||||||
let readback = remote_providers_of(&config, &root)?;
|
let readback = remote_providers_of(&config, &root)?;
|
||||||
assert_eq!(bundle.remote_providers.len(), 2);
|
assert_eq!(bundle.remote_providers.len(), 2);
|
||||||
for declared in readback {
|
for declared in readback {
|
||||||
assert!(bundle.remote_providers.contains(&declared));
|
assert!(bundle.remote_providers.contains(&declared.provider));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
config[declared.section][&declared.name]["path"],
|
config[declared.section][&declared.name]["path"],
|
||||||
declared.destination.as_str()
|
declared.provider.destination
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
config[declared.section][&declared.name]["url"],
|
config[declared.section][&declared.name]["url"],
|
||||||
@@ -518,8 +467,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn allocated_provider_paths_do_not_claim_another_declared_path()
|
fn allocated_provider_paths_do_not_claim_another_declared_path() -> anyhow::Result<()> {
|
||||||
-> std::result::Result<(), Box<dyn std::error::Error>> {
|
|
||||||
let root = std::env::temp_dir();
|
let root = std::env::temp_dir();
|
||||||
let original: serde_yaml_ng::Mapping = serde_yaml_ng::from_str(
|
let original: serde_yaml_ng::Mapping = serde_yaml_ng::from_str(
|
||||||
"proxy-providers:\n a:\n type: http\n url: https://one.example/p.yaml\n path: ./providers/shared.yaml\nrule-providers:\n b:\n type: http\n url: https://two.example/r.yaml\n path: ./providers/shared.yaml\n",
|
"proxy-providers:\n a:\n type: http\n url: https://one.example/p.yaml\n path: ./providers/shared.yaml\nrule-providers:\n b:\n type: http\n url: https://two.example/r.yaml\n path: ./providers/shared.yaml\n",
|
||||||
@@ -541,8 +489,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn provider_path_resolution_leaves_shared_sources_and_local_files_unchanged()
|
fn provider_path_resolution_leaves_shared_sources_and_local_files_unchanged() -> anyhow::Result<()> {
|
||||||
-> std::result::Result<(), Box<dyn std::error::Error>> {
|
|
||||||
let mut config: serde_yaml_ng::Mapping = serde_yaml_ng::from_str(
|
let mut config: serde_yaml_ng::Mapping = serde_yaml_ng::from_str(
|
||||||
"rule-providers:\n a:\n type: http\n url: https://one.example/r.yaml\n path: ./rules/shared.yaml\n b:\n type: http\n url: https://one.example/r.yaml\n path: ./rules/shared.yaml\n local:\n type: file\n path: ./rules/local.yaml\n remote:\n type: http\n url: https://two.example/r.yaml\n path: ./rules/local.yaml\n mirror:\n type: http\n url: https://three.example/r.yaml\n path: ./rules/local.yaml\n",
|
"rule-providers:\n a:\n type: http\n url: https://one.example/r.yaml\n path: ./rules/shared.yaml\n b:\n type: http\n url: https://one.example/r.yaml\n path: ./rules/shared.yaml\n local:\n type: file\n path: ./rules/local.yaml\n remote:\n type: http\n url: https://two.example/r.yaml\n path: ./rules/local.yaml\n mirror:\n type: http\n url: https://three.example/r.yaml\n path: ./rules/local.yaml\n",
|
||||||
)?;
|
)?;
|
||||||
@@ -553,8 +500,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn collects_only_local_providers_and_existing_geo_assets()
|
async fn collects_only_local_providers_and_existing_geo_assets() -> anyhow::Result<()> {
|
||||||
-> std::result::Result<(), Box<dyn std::error::Error>> {
|
|
||||||
let root = std::env::temp_dir().join(format!("clash-verge-runtime-bundle-{}", std::process::id()));
|
let root = std::env::temp_dir().join(format!("clash-verge-runtime-bundle-{}", std::process::id()));
|
||||||
std::fs::create_dir_all(root.join("providers"))?;
|
std::fs::create_dir_all(root.join("providers"))?;
|
||||||
std::fs::write(root.join("providers/local.yaml"), b"proxies: []\n")?;
|
std::fs::write(root.join("providers/local.yaml"), b"proxies: []\n")?;
|
||||||
@@ -570,10 +516,12 @@ mod tests {
|
|||||||
absolute_remote.display()
|
absolute_remote.display()
|
||||||
),
|
),
|
||||||
)?;
|
)?;
|
||||||
|
let core = root.join("mihomo");
|
||||||
|
std::fs::write(&core, b"core")?;
|
||||||
|
|
||||||
let bundle = collect_runtime_bundle(&config).await?;
|
let bundle = collect_runtime_bundle(&config, &core).await?;
|
||||||
|
|
||||||
let bundled_config = &bundle.config;
|
let bundled_config: serde_yaml_ng::Value = serde_yaml_ng::from_str(&bundle.yaml)?;
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
bundled_config["proxy-providers"]["local"]["path"].as_str(),
|
bundled_config["proxy-providers"]["local"]["path"].as_str(),
|
||||||
Some("providers/local.yaml")
|
Some("providers/local.yaml")
|
||||||
@@ -582,7 +530,7 @@ mod tests {
|
|||||||
bundled_config["proxy-providers"]["remote"]["path"].as_str(),
|
bundled_config["proxy-providers"]["remote"]["path"].as_str(),
|
||||||
Some("providers/remote.yaml")
|
Some("providers/remote.yaml")
|
||||||
);
|
);
|
||||||
assert!(!serde_yaml_ng::to_string(bundled_config)?.contains(root.to_string_lossy().as_ref()));
|
assert!(!bundle.yaml.contains(&root.to_string_lossy().into_owned()));
|
||||||
assert!(
|
assert!(
|
||||||
bundle
|
bundle
|
||||||
.assets
|
.assets
|
||||||
@@ -612,8 +560,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn two_names_for_one_remote_file_are_folded_rather_than_refused()
|
async fn two_names_for_one_remote_file_are_folded_rather_than_refused() -> anyhow::Result<()> {
|
||||||
-> std::result::Result<(), Box<dyn std::error::Error>> {
|
|
||||||
// Identical repeats are one service-side file and are safe to fold.
|
// Identical repeats are one service-side file and are safe to fold.
|
||||||
let root = std::env::temp_dir().join(format!("clash-verge-bundle-dup-{}", std::process::id()));
|
let root = std::env::temp_dir().join(format!("clash-verge-bundle-dup-{}", std::process::id()));
|
||||||
let _ = std::fs::remove_dir_all(&root);
|
let _ = std::fs::remove_dir_all(&root);
|
||||||
@@ -623,8 +570,10 @@ mod tests {
|
|||||||
&config,
|
&config,
|
||||||
"rule-providers:\n a:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n b:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n",
|
"rule-providers:\n a:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n b:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n",
|
||||||
)?;
|
)?;
|
||||||
|
let core = root.join("mihomo");
|
||||||
|
std::fs::write(&core, b"core")?;
|
||||||
|
|
||||||
let bundle = collect_runtime_bundle(&config).await?;
|
let bundle = collect_runtime_bundle(&config, &core).await?;
|
||||||
|
|
||||||
assert_eq!(bundle.remote_providers.len(), 1, "one file, declared twice");
|
assert_eq!(bundle.remote_providers.len(), 1, "one file, declared twice");
|
||||||
assert_eq!(bundle.remote_providers[0].destination, "rules/x.yaml");
|
assert_eq!(bundle.remote_providers[0].destination, "rules/x.yaml");
|
||||||
@@ -633,7 +582,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn two_sources_for_one_remote_file_are_refused() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
async fn two_sources_for_one_remote_file_are_refused() -> anyhow::Result<()> {
|
||||||
let root = std::env::temp_dir().join(format!("clash-verge-bundle-conflict-{}", std::process::id()));
|
let root = std::env::temp_dir().join(format!("clash-verge-bundle-conflict-{}", std::process::id()));
|
||||||
let _ = std::fs::remove_dir_all(&root);
|
let _ = std::fs::remove_dir_all(&root);
|
||||||
std::fs::create_dir_all(&root)?;
|
std::fs::create_dir_all(&root)?;
|
||||||
@@ -642,9 +591,11 @@ mod tests {
|
|||||||
&config,
|
&config,
|
||||||
"rule-providers:\n a:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n b:\n type: http\n url: https://two.example/x.yaml\n path: ./rules/x.yaml\n",
|
"rule-providers:\n a:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n b:\n type: http\n url: https://two.example/x.yaml\n path: ./rules/x.yaml\n",
|
||||||
)?;
|
)?;
|
||||||
|
let core = root.join("mihomo");
|
||||||
|
std::fs::write(&core, b"core")?;
|
||||||
|
|
||||||
let Err(error) = collect_runtime_bundle(&config).await else {
|
let Err(error) = collect_runtime_bundle(&config, &core).await else {
|
||||||
return Err("two sources cannot own one file".into());
|
anyhow::bail!("two sources cannot own one file");
|
||||||
};
|
};
|
||||||
|
|
||||||
assert!(error.to_string().contains("two different sources"), "{error}");
|
assert!(error.to_string().contains("two different sources"), "{error}");
|
||||||
@@ -653,8 +604,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn an_odd_provider_is_left_alone_instead_of_failing_the_whole_bundle()
|
async fn an_odd_provider_is_left_alone_instead_of_failing_the_whole_bundle() -> anyhow::Result<()> {
|
||||||
-> std::result::Result<(), Box<dyn std::error::Error>> {
|
|
||||||
// Odd providers accepted by mihomo must not block the rest of the bundle.
|
// Odd providers accepted by mihomo must not block the rest of the bundle.
|
||||||
let root = std::env::temp_dir().join(format!("clash-verge-bundle-odd-{}", std::process::id()));
|
let root = std::env::temp_dir().join(format!("clash-verge-bundle-odd-{}", std::process::id()));
|
||||||
let _ = std::fs::remove_dir_all(&root);
|
let _ = std::fs::remove_dir_all(&root);
|
||||||
@@ -664,8 +614,10 @@ mod tests {
|
|||||||
&config,
|
&config,
|
||||||
"rule-providers:\n nourl:\n type: http\n path: ./rules/nourl.yaml\n missing:\n type: inline\n url: https://one.example/i.yaml\n path: ./rules/missing.yaml\n good:\n type: http\n url: https://one.example/g.yaml\n path: ./rules/g.yaml\n",
|
"rule-providers:\n nourl:\n type: http\n path: ./rules/nourl.yaml\n missing:\n type: inline\n url: https://one.example/i.yaml\n path: ./rules/missing.yaml\n good:\n type: http\n url: https://one.example/g.yaml\n path: ./rules/g.yaml\n",
|
||||||
)?;
|
)?;
|
||||||
|
let core = root.join("mihomo");
|
||||||
|
std::fs::write(&core, b"core")?;
|
||||||
|
|
||||||
let bundle = collect_runtime_bundle(&config).await?;
|
let bundle = collect_runtime_bundle(&config, &core).await?;
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
bundle.remote_providers.len(),
|
bundle.remote_providers.len(),
|
||||||
@@ -673,8 +625,9 @@ mod tests {
|
|||||||
"only the provider that could be classified is declared"
|
"only the provider that could be classified is declared"
|
||||||
);
|
);
|
||||||
assert_eq!(bundle.remote_providers[0].destination, "rules/g.yaml");
|
assert_eq!(bundle.remote_providers[0].destination, "rules/g.yaml");
|
||||||
|
let reserialized: serde_yaml_ng::Value = serde_yaml_ng::from_str(&bundle.yaml)?;
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
bundle.config["rule-providers"]["nourl"]["path"].as_str(),
|
reserialized["rule-providers"]["nourl"]["path"].as_str(),
|
||||||
Some("./rules/nourl.yaml"),
|
Some("./rules/nourl.yaml"),
|
||||||
"an unclassifiable provider keeps the path the core was given"
|
"an unclassifiable provider keeps the path the core was given"
|
||||||
);
|
);
|
||||||
@@ -683,13 +636,13 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn rejects_provider_paths_outside_the_config_root() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
async fn rejects_provider_paths_outside_the_config_root() -> anyhow::Result<()> {
|
||||||
let root = std::env::temp_dir().join(format!("clash-verge-runtime-bundle-outside-{}", std::process::id()));
|
let root = std::env::temp_dir().join(format!("clash-verge-runtime-bundle-outside-{}", std::process::id()));
|
||||||
std::fs::create_dir_all(&root)?;
|
std::fs::create_dir_all(&root)?;
|
||||||
let config = root.join("config.yaml");
|
let config = root.join("config.yaml");
|
||||||
let outside = root
|
let outside = root
|
||||||
.parent()
|
.parent()
|
||||||
.ok_or("test root has no parent")?
|
.ok_or_else(|| anyhow::anyhow!("test root has no parent"))?
|
||||||
.join(format!("outside-{}.yaml", std::process::id()));
|
.join(format!("outside-{}.yaml", std::process::id()));
|
||||||
std::fs::write(
|
std::fs::write(
|
||||||
&config,
|
&config,
|
||||||
@@ -698,9 +651,11 @@ mod tests {
|
|||||||
outside.display()
|
outside.display()
|
||||||
),
|
),
|
||||||
)?;
|
)?;
|
||||||
|
let core = root.join("mihomo");
|
||||||
|
std::fs::write(&core, b"core")?;
|
||||||
|
|
||||||
let Err(error) = collect_runtime_bundle(&config).await else {
|
let Err(error) = collect_runtime_bundle(&config, &core).await else {
|
||||||
return Err("outside provider path must be rejected".into());
|
anyhow::bail!("outside provider path must be rejected");
|
||||||
};
|
};
|
||||||
|
|
||||||
assert!(error.to_string().contains("outside the config root"));
|
assert!(error.to_string().contains("outside the config root"));
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
use crate::core::notify::NoticeStatus;
|
use crate::core::notify::NoticeStatus;
|
||||||
use crate::utils::dirs;
|
use crate::utils::dirs;
|
||||||
use crate::{
|
use crate::{
|
||||||
config::{Config, mihomo_yaml, runtime::IRuntime},
|
config::{Config, runtime::IRuntime},
|
||||||
constants,
|
constants,
|
||||||
core::{
|
core::{
|
||||||
CoreManager,
|
CoreManager,
|
||||||
@@ -13,6 +13,7 @@ use crate::{
|
|||||||
CORE_REJECTED_PREFIX, OwnerRecoveryReason, OwnerSample, OwnerStep, OwnerWatch, PendingAction, RUN_STATE,
|
CORE_REJECTED_PREFIX, OwnerRecoveryReason, OwnerSample, OwnerStep, OwnerWatch, PendingAction, RUN_STATE,
|
||||||
ReadyWaitError, RunState, RunStateEnv, RunStateStore, ServiceHealth,
|
ReadyWaitError, RunState, RunStateEnv, RunStateStore, ServiceHealth,
|
||||||
},
|
},
|
||||||
|
runtime_bundle::{GEO_ASSETS, RemoteProviderRef, collect_runtime_bundle, remote_providers_of},
|
||||||
tray::Tray,
|
tray::Tray,
|
||||||
},
|
},
|
||||||
process::AsyncHandler,
|
process::AsyncHandler,
|
||||||
@@ -20,11 +21,10 @@ use crate::{
|
|||||||
use anyhow::{Context as _, Result, anyhow, bail};
|
use anyhow::{Context as _, Result, anyhow, bail};
|
||||||
use clash_verge_draft::Draft;
|
use clash_verge_draft::Draft;
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use clash_verge_runtime_bundle::{GEO_ASSETS, RemoteProviderRef, collect_runtime_bundle, remote_providers_of};
|
|
||||||
use clash_verge_service_ipc::{
|
use clash_verge_service_ipc::{
|
||||||
MacosProxyConfig, OwnerCredentials, OwnerIdentity, OwnerSessionProof, ProtocolInfo, ProxyApplyOutcome,
|
MacosProxyConfig, OwnerCredentials, OwnerIdentity, OwnerSessionProof, ProtocolInfo, ProxyApplyOutcome,
|
||||||
RemoteProvider, RuntimeAsset, RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode,
|
RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode, ServiceStatusSnapshot,
|
||||||
ServiceStatusSnapshot, StageRuntimeOutcome, StartClashRequest, WriterConfig,
|
StageRuntimeOutcome, StartClashRequest, WriterConfig,
|
||||||
};
|
};
|
||||||
use clash_verge_task::scheduled_task::{self, Mailbox, Next, ScheduledTask};
|
use clash_verge_task::scheduled_task::{self, Mailbox, Next, ScheduledTask};
|
||||||
use clash_verge_task::watch_task;
|
use clash_verge_task::watch_task;
|
||||||
@@ -611,27 +611,7 @@ async fn collect_service_runtime_bundle(config_file: &Path) -> Result<RuntimeBun
|
|||||||
|
|
||||||
let bin_ext = if cfg!(windows) { ".exe" } else { "" };
|
let bin_ext = if cfg!(windows) { ".exe" } else { "" };
|
||||||
let bin_path = service_core_path(&clash_core, bin_ext)?;
|
let bin_path = service_core_path(&clash_core, bin_ext)?;
|
||||||
let plan = collect_runtime_bundle(config_file).await?;
|
collect_runtime_bundle(config_file, &bin_path).await
|
||||||
Ok(RuntimeBundle {
|
|
||||||
yaml: mihomo_yaml::serialize(&plan.config).context("failed to serialize service runtime config")?,
|
|
||||||
assets: plan
|
|
||||||
.assets
|
|
||||||
.into_iter()
|
|
||||||
.map(|asset| RuntimeAsset {
|
|
||||||
source: asset.source,
|
|
||||||
destination: asset.destination.into(),
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
remote_providers: plan
|
|
||||||
.remote_providers
|
|
||||||
.into_iter()
|
|
||||||
.map(|provider| RemoteProvider {
|
|
||||||
destination: provider.destination.into(),
|
|
||||||
url: provider.url,
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
core_path: bin_path.to_string_lossy().into_owned(),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A staging response whose refusal code tells callers whether a fresh start can help.
|
/// A staging response whose refusal code tells callers whether a fresh start can help.
|
||||||
@@ -968,7 +948,7 @@ async fn sync_runtime_providers_by_service() -> Result<ProviderSync> {
|
|||||||
let loaded_before = provider_load_times().await;
|
let loaded_before = provider_load_times().await;
|
||||||
let mut fetched = Vec::new();
|
let mut fetched = Vec::new();
|
||||||
for declared in applied_remote_providers(&runtime, &app_dir)? {
|
for declared in applied_remote_providers(&runtime, &app_dir)? {
|
||||||
let (temp, file) = match create_sync_temp(&app_dir.join(declared.destination.as_str())).await {
|
let (temp, file) = match create_sync_temp(&app_dir.join(&declared.provider.destination)).await {
|
||||||
Ok(created) => created,
|
Ok(created) => created,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
logging!(warn, Type::Service, "{error:#}");
|
logging!(warn, Type::Service, "{error:#}");
|
||||||
@@ -976,7 +956,7 @@ async fn sync_runtime_providers_by_service() -> Result<ProviderSync> {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
match fetch_runtime_file(&credentials, &session, &declared.destination, file).await {
|
match fetch_runtime_file(&credentials, &session, &declared.provider.destination, file).await {
|
||||||
Ok(Fetch::Complete { len, mtime_ns }) => fetched.push(FetchedCache {
|
Ok(Fetch::Complete { len, mtime_ns }) => fetched.push(FetchedCache {
|
||||||
declared,
|
declared,
|
||||||
temp,
|
temp,
|
||||||
@@ -997,7 +977,7 @@ async fn sync_runtime_providers_by_service() -> Result<ProviderSync> {
|
|||||||
warn,
|
warn,
|
||||||
Type::Service,
|
Type::Service,
|
||||||
"failed to read provider cache {} into {}: {error:#}",
|
"failed to read provider cache {} into {}: {error:#}",
|
||||||
declared.destination,
|
declared.provider.destination,
|
||||||
temp.display()
|
temp.display()
|
||||||
);
|
);
|
||||||
outcome.pending += 1;
|
outcome.pending += 1;
|
||||||
@@ -1108,7 +1088,7 @@ async fn sync_runtime_geo(
|
|||||||
fn applied_remote_providers(runtime: &Draft<IRuntime>, app_dir: &Path) -> Result<Vec<RemoteProviderRef>> {
|
fn applied_remote_providers(runtime: &Draft<IRuntime>, app_dir: &Path) -> Result<Vec<RemoteProviderRef>> {
|
||||||
let applied = runtime.data_arc();
|
let applied = runtime.data_arc();
|
||||||
match applied.config.as_ref() {
|
match applied.config.as_ref() {
|
||||||
Some(config) => remote_providers_of(config, app_dir).map_err(Into::into),
|
Some(config) => remote_providers_of(config, app_dir),
|
||||||
None => Ok(Vec::new()),
|
None => Ok(Vec::new()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1137,7 +1117,7 @@ async fn publish_fetched(
|
|||||||
};
|
};
|
||||||
let mut synced = 0;
|
let mut synced = 0;
|
||||||
for cache in fetched {
|
for cache in fetched {
|
||||||
let target = app_dir.join(cache.declared.destination.as_str());
|
let target = app_dir.join(&cache.declared.provider.destination);
|
||||||
if !declared.contains(&cache.declared) || same_contents(&cache.temp, &target).await {
|
if !declared.contains(&cache.declared) || same_contents(&cache.temp, &target).await {
|
||||||
remove_temp(&cache.temp).await;
|
remove_temp(&cache.temp).await;
|
||||||
continue;
|
continue;
|
||||||
@@ -1214,7 +1194,7 @@ async fn recheck_identity(
|
|||||||
cache: &FetchedCache,
|
cache: &FetchedCache,
|
||||||
) -> Result<Fetch> {
|
) -> Result<Fetch> {
|
||||||
let request = RuntimeFileRequest {
|
let request = RuntimeFileRequest {
|
||||||
destination: cache.declared.destination.as_str().to_owned(),
|
destination: cache.declared.provider.destination.to_owned(),
|
||||||
offset: cache.len,
|
offset: cache.len,
|
||||||
};
|
};
|
||||||
Ok(match read_chunk(credentials, session, &request).await? {
|
Ok(match read_chunk(credentials, session, &request).await? {
|
||||||
@@ -1302,7 +1282,7 @@ async fn create_sync_temp(target: &Path) -> Result<(PathBuf, tokio::fs::File)> {
|
|||||||
.with_context(|| format!("failed to create provider cache directory {}", parent.display()))?;
|
.with_context(|| format!("failed to create provider cache directory {}", parent.display()))?;
|
||||||
}
|
}
|
||||||
let name = target.file_name().map_or_default(|name| name.to_string_lossy());
|
let name = target.file_name().map_or_default(|name| name.to_string_lossy());
|
||||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
|
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||||
retry(
|
retry(
|
||||||
RetryPolicy::fixed(std::num::NonZeroUsize::MIN.saturating_add(7), std::time::Duration::ZERO),
|
RetryPolicy::fixed(std::num::NonZeroUsize::MIN.saturating_add(7), std::time::Duration::ZERO),
|
||||||
|_| async {
|
|_| async {
|
||||||
@@ -1719,7 +1699,7 @@ async fn recover_after_owner_loss_while_locked(reason: OwnerRecoveryReason) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn clear_proxy_after_owner_loss() {
|
async fn clear_proxy_after_owner_loss() {
|
||||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
|
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||||
let result = retry(
|
let result = retry(
|
||||||
RetryPolicy::fixed(
|
RetryPolicy::fixed(
|
||||||
std::num::NonZeroUsize::MIN.saturating_add(2),
|
std::num::NonZeroUsize::MIN.saturating_add(2),
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ use crate::{
|
|||||||
use anyhow::{Context as _, Result};
|
use anyhow::{Context as _, Result};
|
||||||
use clash_verge_draft::Draft;
|
use clash_verge_draft::Draft;
|
||||||
use clash_verge_logging::{Type, logging, logging_error};
|
use clash_verge_logging::{Type, logging, logging_error};
|
||||||
use clash_verge_profile::SubscriptionSchedule as TaskSchedule;
|
|
||||||
use futures::{FutureExt as _, StreamExt as _};
|
use futures::{FutureExt as _, StreamExt as _};
|
||||||
use std::{collections::HashMap, panic::AssertUnwindSafe, time::Duration};
|
use std::{collections::HashMap, panic::AssertUnwindSafe, time::Duration};
|
||||||
use tokio::{
|
use tokio::{
|
||||||
@@ -25,6 +24,28 @@ enum TimerCommand {
|
|||||||
TaskFinished(String),
|
TaskFinished(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Next update is due at `updated + interval`, but the queue only takes a delay from now.
|
||||||
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
|
struct TaskSchedule {
|
||||||
|
interval_minutes: u64,
|
||||||
|
first_delay: Duration,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TaskSchedule {
|
||||||
|
/// No recorded `updated` -> full interval. Deadline already past -> `ZERO`, fires at once.
|
||||||
|
fn new(interval_minutes: u64, updated: Option<usize>, now: i64) -> Self {
|
||||||
|
let full = Timer::interval_duration(interval_minutes);
|
||||||
|
let elapsed = updated
|
||||||
|
.filter(|updated| *updated > 0)
|
||||||
|
.map_or(0, |updated| now.saturating_sub(updated as i64).max(0) as u64);
|
||||||
|
|
||||||
|
Self {
|
||||||
|
interval_minutes,
|
||||||
|
first_delay: full.saturating_sub(Duration::from_secs(elapsed)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
struct TaskState {
|
struct TaskState {
|
||||||
key: Option<Key>,
|
key: Option<Key>,
|
||||||
interval_minutes: u64,
|
interval_minutes: u64,
|
||||||
@@ -101,9 +122,16 @@ impl Timer {
|
|||||||
let mut new_map = HashMap::new();
|
let mut new_map = HashMap::new();
|
||||||
|
|
||||||
for item in items {
|
for item in items {
|
||||||
if let Some(uid) = &item.uid
|
if let Some(option) = item.option.as_ref()
|
||||||
&& let Some(schedule) = TaskSchedule::for_profile(item, initializing, now)
|
&& let (Some(interval), Some(uid)) = (option.update_interval, &item.uid)
|
||||||
|
&& option.allow_auto_update.unwrap_or(true)
|
||||||
|
&& interval > 0
|
||||||
{
|
{
|
||||||
|
let mut schedule = TaskSchedule::new(interval, item.updated, now);
|
||||||
|
// Startup historically treats an explicit zero timestamp as overdue.
|
||||||
|
if initializing && item.updated == Some(0) {
|
||||||
|
schedule.first_delay = Duration::ZERO;
|
||||||
|
}
|
||||||
new_map.insert(uid.clone(), schedule);
|
new_map.insert(uid.clone(), schedule);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -289,7 +317,7 @@ impl Timer {
|
|||||||
|
|
||||||
// Full interval, not from `updated`: a failed run leaves `updated` in the past, so
|
// Full interval, not from `updated`: a failed run leaves `updated` in the past, so
|
||||||
// counting from it would retry at zero delay and spin.
|
// counting from it would retry at zero delay and spin.
|
||||||
let key = Self::schedule_task(queue, &uid, TaskSchedule::interval_duration(state.interval_minutes));
|
let key = Self::schedule_task(queue, &uid, Self::interval_duration(state.interval_minutes));
|
||||||
state.key = Some(key);
|
state.key = Some(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -302,6 +330,10 @@ impl Timer {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const fn interval_duration(interval_minutes: u64) -> Duration {
|
||||||
|
Duration::from_secs(interval_minutes.saturating_mul(60))
|
||||||
|
}
|
||||||
|
|
||||||
fn schedule_task(queue: &mut DelayQueue<String>, uid: &str, delay: Duration) -> Key {
|
fn schedule_task(queue: &mut DelayQueue<String>, uid: &str, delay: Duration) -> Key {
|
||||||
queue.insert(String::from(uid), delay)
|
queue.insert(String::from(uid), delay)
|
||||||
}
|
}
|
||||||
@@ -316,8 +348,10 @@ impl Timer {
|
|||||||
|
|
||||||
fn next_update_time(tasks: &HashMap<String, TaskState>, profiles: &IProfiles, uid: &str) -> Option<i64> {
|
fn next_update_time(tasks: &HashMap<String, TaskState>, profiles: &IProfiles, uid: &str) -> Option<i64> {
|
||||||
let task = tasks.get(uid).filter(|task| !task.retired)?;
|
let task = tasks.get(uid).filter(|task| !task.retired)?;
|
||||||
let updated = profiles.get_item(uid).ok()?.updated;
|
let updated = profiles.get_item(uid).ok()?.updated.filter(|updated| *updated > 0)?;
|
||||||
TaskSchedule::reported_deadline(task.interval_minutes, updated)
|
let updated = i64::try_from(updated).ok()?;
|
||||||
|
let interval = i64::try_from(task.interval_minutes).ok()?.checked_mul(60)?;
|
||||||
|
updated.checked_add(interval)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn emit_update_event(uid: &str, is_start: bool) {
|
fn emit_update_event(uid: &str, is_start: bool) {
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ use crate::core::handle;
|
|||||||
use crate::singleton;
|
use crate::singleton;
|
||||||
use crate::utils::{dirs, help};
|
use crate::utils::{dirs, help};
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use clash_verge_profile_script::MainDeclaration;
|
|
||||||
|
|
||||||
const SYNTAX_CHECK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
|
const SYNTAX_CHECK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
|
||||||
|
|
||||||
@@ -32,7 +31,7 @@ async fn validation_fingerprint(yaml: &str) -> u64 {
|
|||||||
.map(|exe| exe.with_file_name(format!("{}{}", core.as_str(), std::env::consts::EXE_SUFFIX)));
|
.map(|exe| exe.with_file_name(format!("{}{}", core.as_str(), std::env::consts::EXE_SUFFIX)));
|
||||||
// The test run reads geo databases from the app dir; a geo update must revalidate.
|
// The test run reads geo databases from the app dir; a geo update must revalidate.
|
||||||
let geo = dirs::app_home_dir().into_iter().flat_map(|dir| {
|
let geo = dirs::app_home_dir().into_iter().flat_map(|dir| {
|
||||||
clash_verge_runtime_bundle::GEO_ASSETS
|
super::runtime_bundle::GEO_ASSETS
|
||||||
.iter()
|
.iter()
|
||||||
.map(move |asset| dir.join(asset))
|
.map(move |asset| dir.join(asset))
|
||||||
});
|
});
|
||||||
@@ -256,8 +255,22 @@ impl CoreConfigValidator {
|
|||||||
};
|
};
|
||||||
|
|
||||||
logging!(debug, Type::Validate, "验证脚本文件: {}", path);
|
logging!(debug, Type::Validate, "验证脚本文件: {}", path);
|
||||||
let syntax =
|
let has_main =
|
||||||
crate::process::AsyncHandler::spawn_blocking(move || clash_verge_profile_script::validate(&content));
|
content.contains("function main") || content.contains("const main") || content.contains("let main");
|
||||||
|
|
||||||
|
// Boa parsing is pure CPU; keep it off the async worker, with a timeout.
|
||||||
|
let syntax = crate::process::AsyncHandler::spawn_blocking(move || {
|
||||||
|
use boa_engine::{Context, Source};
|
||||||
|
|
||||||
|
let mut context = Context::default();
|
||||||
|
let _ = context.eval(Source::from_bytes(
|
||||||
|
"var console = Object.freeze({log(...data){},info(...data){},error(...data){},debug(...data){}});",
|
||||||
|
));
|
||||||
|
context
|
||||||
|
.eval(Source::from_bytes(&content))
|
||||||
|
.map(|_| ())
|
||||||
|
.map_err(|err| err.to_string())
|
||||||
|
});
|
||||||
let result = match tokio::time::timeout(SYNTAX_CHECK_TIMEOUT, syntax).await {
|
let result = match tokio::time::timeout(SYNTAX_CHECK_TIMEOUT, syntax).await {
|
||||||
Ok(Ok(evaluated)) => evaluated,
|
Ok(Ok(evaluated)) => evaluated,
|
||||||
Ok(Err(join_err)) => Err(format!("syntax check task failed: {join_err}")),
|
Ok(Err(join_err)) => Err(format!("syntax check task failed: {join_err}")),
|
||||||
@@ -265,10 +278,10 @@ impl CoreConfigValidator {
|
|||||||
};
|
};
|
||||||
|
|
||||||
match result {
|
match result {
|
||||||
Ok(main) => {
|
Ok(()) => {
|
||||||
logging!(debug, Type::Validate, "脚本语法验证通过: {}", path);
|
logging!(debug, Type::Validate, "脚本语法验证通过: {}", path);
|
||||||
|
|
||||||
if main == MainDeclaration::Missing {
|
if !has_main {
|
||||||
let error_msg = "Script must contain a main function";
|
let error_msg = "Script must contain a main function";
|
||||||
logging!(warn, Type::Validate, "脚本缺少main函数: {}", path);
|
logging!(warn, Type::Validate, "脚本缺少main函数: {}", path);
|
||||||
return Ok(ValidationOutcome::invalid_from_message(error_msg));
|
return Ok(ValidationOutcome::invalid_from_message(error_msg));
|
||||||
|
|||||||
@@ -1,14 +1,31 @@
|
|||||||
|
use super::SeqMap;
|
||||||
use crate::{
|
use crate::{
|
||||||
config::PrfItem,
|
config::PrfItem,
|
||||||
utils::{dirs, help},
|
utils::{dirs, help},
|
||||||
};
|
};
|
||||||
use clash_verge_config_render::{ChainItem, ChainType, SeqMap};
|
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
|
use serde_yaml_ng::Mapping;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::sync::{Arc, LazyLock};
|
use std::sync::{Arc, LazyLock};
|
||||||
use std::time::SystemTime;
|
use std::time::SystemTime;
|
||||||
use tokio::fs;
|
use tokio::fs;
|
||||||
|
use tristr::alias::String;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct ChainItem {
|
||||||
|
pub uid: String,
|
||||||
|
pub data: ChainType,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum ChainType {
|
||||||
|
Merge(Mapping),
|
||||||
|
Script(String),
|
||||||
|
Rules(SeqMap),
|
||||||
|
Proxies(SeqMap),
|
||||||
|
Groups(SeqMap),
|
||||||
|
}
|
||||||
|
|
||||||
struct CachedChain {
|
struct CachedChain {
|
||||||
mtime: SystemTime,
|
mtime: SystemTime,
|
||||||
|
|||||||
@@ -18,21 +18,19 @@ pub const HANDLE_FIELDS: [&str; 12] = [
|
|||||||
|
|
||||||
pub const DEFAULT_FIELDS: [&str; 5] = ["proxies", "proxy-providers", "proxy-groups", "rule-providers", "rules"];
|
pub const DEFAULT_FIELDS: [&str; 5] = ["proxies", "proxy-providers", "proxy-groups", "rule-providers", "rules"];
|
||||||
|
|
||||||
|
fn lowercase_key(key: &str) -> Value {
|
||||||
|
let mut key = String::from(key);
|
||||||
|
key.make_ascii_lowercase();
|
||||||
|
Value::from(key.as_str())
|
||||||
|
}
|
||||||
|
|
||||||
pub fn use_lowercase(config: Mapping) -> Mapping {
|
pub fn use_lowercase(config: Mapping) -> Mapping {
|
||||||
let mut lowercased = Mapping::new();
|
let mut lowercased = Mapping::new();
|
||||||
|
|
||||||
for (key, value) in config {
|
for (key, value) in config {
|
||||||
let mut key = match key {
|
if let Some(key_str) = key.as_str() {
|
||||||
Value::String(key) => key,
|
lowercased.insert(lowercase_key(key_str), value);
|
||||||
key => {
|
}
|
||||||
let Some(key) = key.as_str() else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
key.to_owned()
|
|
||||||
}
|
|
||||||
};
|
|
||||||
key.make_ascii_lowercase();
|
|
||||||
lowercased.insert(Value::String(key), value);
|
|
||||||
}
|
}
|
||||||
lowercased
|
lowercased
|
||||||
}
|
}
|
||||||
@@ -32,7 +32,7 @@ pub fn use_merge(merge: Mapping, mut config: Mapping) -> Mapping {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_merge() -> Result<(), serde_yaml_ng::Error> {
|
fn test_merge() -> anyhow::Result<()> {
|
||||||
let merge = r"
|
let merge = r"
|
||||||
prepend-rules:
|
prepend-rules:
|
||||||
- prepend
|
- prepend
|
||||||
+1702
-80
File diff suppressed because it is too large
Load Diff
@@ -1,3 +1,7 @@
|
|||||||
|
use crate::{process::AsyncHandler, utils::tmpl};
|
||||||
|
|
||||||
|
use super::field::use_lowercase;
|
||||||
|
use anyhow::Result;
|
||||||
use boa_engine::{Context, JsString, JsValue, Source, js_string, native_function::NativeFunction, property::Attribute};
|
use boa_engine::{Context, JsString, JsValue, Source, js_string, native_function::NativeFunction, property::Attribute};
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
@@ -11,50 +15,65 @@ const MAX_JSON_SIZE: usize = 10 * 1024 * 1024; // 10MB
|
|||||||
const MAX_LOOP_ITERATIONS: u64 = 10_000_000;
|
const MAX_LOOP_ITERATIONS: u64 = 10_000_000;
|
||||||
const SCRIPT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
|
const SCRIPT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
|
||||||
|
|
||||||
/// Script logs are retained when evaluation or result conversion fails.
|
type ScriptResult = (Mapping, Vec<String>, Vec<(String, String)>);
|
||||||
pub type ScriptLogs = Vec<(String, String)>;
|
type EvalOutcome = (Result<Mapping, std::string::String>, Vec<(String, String)>);
|
||||||
|
|
||||||
type EvalOutcome = (Result<Mapping, std::string::String>, ScriptLogs);
|
/// Never fails: exceptions are logged and the input config is returned unchanged.
|
||||||
|
pub(super) async fn use_script(script: String, config: Mapping, name: String) -> ScriptResult {
|
||||||
#[derive(Debug, PartialEq, Eq)]
|
// The template is identity-plus-lowercasing; skip the Boa round-trip.
|
||||||
pub enum MainDeclaration {
|
if script == tmpl::ITEM_SCRIPT {
|
||||||
Present,
|
return (use_lowercase(config), vec![], vec![]);
|
||||||
Missing,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Preserves the editor's evaluation and main-declaration check.
|
|
||||||
pub fn validate(source: &str) -> Result<MainDeclaration, std::string::String> {
|
|
||||||
let mut context = Context::default();
|
|
||||||
let _ = context.eval(Source::from_bytes(
|
|
||||||
"var console = Object.freeze({log(...data){},info(...data){},error(...data){},debug(...data){}});",
|
|
||||||
));
|
|
||||||
context
|
|
||||||
.eval(Source::from_bytes(source))
|
|
||||||
.map_err(|err| err.to_string())?;
|
|
||||||
let has_main = source.contains("function main") || source.contains("const main") || source.contains("let main");
|
|
||||||
Ok(if has_main {
|
|
||||||
MainDeclaration::Present
|
|
||||||
} else {
|
|
||||||
MainDeclaration::Missing
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Runs one script on the blocking pool. The timeout bounds waiting for its result.
|
|
||||||
pub async fn execute(script: String, config: serde_json::Value, name: String) -> EvalOutcome {
|
|
||||||
if json_approx_size(&config) > MAX_JSON_SIZE {
|
|
||||||
return (
|
|
||||||
Err("Configuration size exceeds maximum allowed size".to_owned()),
|
|
||||||
vec![],
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
let evaluated = tokio::task::spawn_blocking(move || eval_script(&script, &config, &name));
|
|
||||||
match tokio::time::timeout(SCRIPT_TIMEOUT, evaluated).await {
|
let json = match serde_json::to_value(&config) {
|
||||||
|
Ok(mut json) => {
|
||||||
|
if let Some(map) = json.as_object_mut() {
|
||||||
|
let mut lowered = serde_json::Map::with_capacity(map.len());
|
||||||
|
for (key, value) in std::mem::take(map) {
|
||||||
|
let mut key = key;
|
||||||
|
key.make_ascii_lowercase();
|
||||||
|
lowered.insert(key, value);
|
||||||
|
}
|
||||||
|
*map = lowered;
|
||||||
|
}
|
||||||
|
if json_approx_size(&json) <= MAX_JSON_SIZE {
|
||||||
|
json
|
||||||
|
} else {
|
||||||
|
let message = "Configuration size exceeds maximum allowed size";
|
||||||
|
return (config, vec![], vec![("exception".into(), message.into())]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(err) => return (config, vec![], vec![("exception".into(), err.to_string().into())]),
|
||||||
|
};
|
||||||
|
|
||||||
|
let evaluated = AsyncHandler::spawn_blocking(move || eval_script(&script, &json, &name));
|
||||||
|
let (outcome, mut logs) = match tokio::time::timeout(SCRIPT_TIMEOUT, evaluated).await {
|
||||||
Ok(Ok(evaluated)) => evaluated,
|
Ok(Ok(evaluated)) => evaluated,
|
||||||
Ok(Err(join_err)) => (Err(format!("script task panicked: {join_err}")), vec![]),
|
Ok(Err(join_err)) => (Err(format!("script task panicked: {join_err}")), vec![]),
|
||||||
Err(_) => (
|
Err(_elapsed) => (
|
||||||
Err(format!("script execution timed out after {SCRIPT_TIMEOUT:?}")),
|
Err(format!("script execution timed out after {SCRIPT_TIMEOUT:?}")),
|
||||||
vec![],
|
vec![],
|
||||||
),
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
match outcome {
|
||||||
|
Ok(result) => {
|
||||||
|
// Compared against the config as handed in, not the lowercased copy the script saw.
|
||||||
|
let changed_keys = result
|
||||||
|
.iter()
|
||||||
|
.filter(|(key, value)| config.get(key) != Some(value))
|
||||||
|
.filter_map(|(key, _)| {
|
||||||
|
let mut key: String = key.as_str()?.into();
|
||||||
|
key.make_ascii_lowercase();
|
||||||
|
Some(key)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
(result, changed_keys, logs)
|
||||||
|
}
|
||||||
|
Err(reason) => {
|
||||||
|
logs.push(("exception".into(), reason.into()));
|
||||||
|
(config, vec![], logs)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,8 +91,7 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) ->
|
|||||||
let outputs_clone = Arc::clone(&outputs);
|
let outputs_clone = Arc::clone(&outputs);
|
||||||
let total_size_clone = Arc::clone(&total_size);
|
let total_size_clone = Arc::clone(&total_size);
|
||||||
|
|
||||||
let take_logs = || std::mem::take(&mut *outputs.lock());
|
let bail = |reason: std::string::String| (Err(reason), outputs.lock().to_vec());
|
||||||
let bail = |reason: std::string::String| (Err(reason), take_logs());
|
|
||||||
|
|
||||||
let _ = context.register_global_builtin_callable("__verge_log__".into(), 2, unsafe {
|
let _ = context.register_global_builtin_callable("__verge_log__".into(), 2, unsafe {
|
||||||
NativeFunction::from_closure(move |_: &JsValue, args: &[JsValue], context: &mut Context| {
|
NativeFunction::from_closure(move |_: &JsValue, args: &[JsValue], context: &mut Context| {
|
||||||
@@ -93,6 +111,7 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) ->
|
|||||||
boa_engine::JsError::from_opaque(JsString::from("Failed to convert data to string").into())
|
boa_engine::JsError::from_opaque(JsString::from("Failed to convert data to string").into())
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
|
// 检查输出限制
|
||||||
if outputs_clone.lock().len() >= MAX_OUTPUTS {
|
if outputs_clone.lock().len() >= MAX_OUTPUTS {
|
||||||
return Err(boa_engine::JsError::from_opaque(
|
return Err(boa_engine::JsError::from_opaque(
|
||||||
JsString::from("Maximum number of log outputs exceeded").into(),
|
JsString::from("Maximum number of log outputs exceeded").into(),
|
||||||
@@ -132,6 +151,7 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) ->
|
|||||||
return bail(format!("failed to bind config for script: {err}"));
|
return bail(format!("failed to bind config for script: {err}"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 仅处理 name 参数中的特殊字符
|
||||||
let safe_name = escape_js_string_for_single_quote(name);
|
let safe_name = escape_js_string_for_single_quote(name);
|
||||||
if safe_name.len() > 1024 {
|
if safe_name.len() > 1024 {
|
||||||
return bail("Name parameter too long".to_owned());
|
return bail("Name parameter too long".to_owned());
|
||||||
@@ -194,7 +214,7 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) ->
|
|||||||
}
|
}
|
||||||
|
|
||||||
match serde_json::from_value::<Mapping>(result) {
|
match serde_json::from_value::<Mapping>(result) {
|
||||||
Ok(config) => (Ok(config), take_logs()),
|
Ok(config) => (Ok(use_lowercase(config)), outputs.lock().to_vec()),
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
logging!(
|
logging!(
|
||||||
error,
|
error,
|
||||||
@@ -220,29 +240,16 @@ fn json_approx_size(value: &serde_json::Value) -> usize {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 安全地转义字符串
|
||||||
fn escape_js_string_for_single_quote(s: &str) -> String {
|
fn escape_js_string_for_single_quote(s: &str) -> String {
|
||||||
|
// 限制处理的字符串长度
|
||||||
if s.len() > 10240 {
|
if s.len() > 10240 {
|
||||||
return s[..10240].replace('\\', "\\\\").replace('\'', "\\'").into();
|
return s[..10240].replace('\\', "\\\\").replace('\'', "\\'").into();
|
||||||
}
|
}
|
||||||
|
|
||||||
s.replace('\\', "\\\\")
|
s.replace('\\', "\\\\")
|
||||||
.replace('\'', "\\'")
|
.replace('\'', "\\'")
|
||||||
.replace('\n', "\\n")
|
.replace('\n', "\\n") // 添加换行符转义
|
||||||
.replace('\r', "\\r")
|
.replace('\r', "\\r") // 添加回车转义
|
||||||
.into()
|
.into()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::{MainDeclaration, validate};
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn validation_distinguishes_missing_main_from_evaluation_failure() {
|
|
||||||
assert_eq!(
|
|
||||||
validate("console.log('setup'); const main = config => config;"),
|
|
||||||
Ok(MainDeclaration::Present)
|
|
||||||
);
|
|
||||||
assert_eq!(validate("console.log('setup');"), Ok(MainDeclaration::Missing));
|
|
||||||
assert!(validate("throw new Error('setup failed'); function main(config) { return config; }").is_err());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_yaml_ng::{Mapping, Sequence, Value};
|
use serde_yaml_ng::{Mapping, Sequence, Value};
|
||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
use tristr::TriStr;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||||
pub struct SeqMap {
|
pub struct SeqMap {
|
||||||
@@ -10,11 +9,11 @@ pub struct SeqMap {
|
|||||||
pub delete: Vec<String>,
|
pub delete: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn collect_proxy_names(seq: &Sequence) -> Vec<TriStr> {
|
fn collect_proxy_names(seq: &Sequence) -> Vec<String> {
|
||||||
seq.iter()
|
seq.iter()
|
||||||
.filter_map(|item| match item {
|
.filter_map(|item| match item {
|
||||||
Value::Mapping(map) => map.get("name").and_then(Value::as_str).map(TriStr::from),
|
Value::Mapping(map) => map.get("name").and_then(Value::as_str).map(str::to_owned),
|
||||||
Value::String(name) => Some(TriStr::from(name.as_str())),
|
Value::String(name) => Some(name.to_owned()),
|
||||||
_ => None,
|
_ => None,
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
@@ -41,7 +40,7 @@ pub fn use_seq(seq: SeqMap, mut config: Mapping, field: &str) -> Mapping {
|
|||||||
names
|
names
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter(|name| seen.insert(name.clone()))
|
.filter(|name| seen.insert(name.clone()))
|
||||||
.collect::<Vec<TriStr>>()
|
.collect::<Vec<String>>()
|
||||||
} else {
|
} else {
|
||||||
Vec::new()
|
Vec::new()
|
||||||
};
|
};
|
||||||
@@ -89,56 +88,56 @@ pub fn use_seq(seq: SeqMap, mut config: Mapping, field: &str) -> Mapping {
|
|||||||
let mut updated_groups = Sequence::new();
|
let mut updated_groups = Sequence::new();
|
||||||
let mut appended_to_selector = false;
|
let mut appended_to_selector = false;
|
||||||
for group in proxy_groups {
|
for group in proxy_groups {
|
||||||
let Value::Mapping(mut group_map) = group else {
|
if let Value::Mapping(mut group_map) = group {
|
||||||
|
let mut group_proxies = match group_map.remove("proxies") {
|
||||||
|
Some(Value::Sequence(proxies)) => Some(
|
||||||
|
proxies
|
||||||
|
.into_iter()
|
||||||
|
.filter(|p| {
|
||||||
|
if let Value::String(name) = p {
|
||||||
|
!delete.contains(name)
|
||||||
|
} else {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect::<Sequence>(),
|
||||||
|
),
|
||||||
|
Some(value) => {
|
||||||
|
group_map.insert(Value::String("proxies".into()), value);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
if !appended_to_selector && !added_proxy_names.is_empty() && is_selector_group(&group_map) {
|
||||||
|
let base_group_proxies = group_proxies.unwrap_or_else(Sequence::new);
|
||||||
|
let mut merged_proxies = Sequence::new();
|
||||||
|
let mut seen_proxy_names = HashSet::new();
|
||||||
|
for name in &added_proxy_names {
|
||||||
|
if seen_proxy_names.insert(name.clone()) {
|
||||||
|
merged_proxies.push(Value::String(name.clone()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for value in base_group_proxies {
|
||||||
|
if let Value::String(name) = &value
|
||||||
|
&& !seen_proxy_names.insert(name.to_owned())
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
merged_proxies.push(value);
|
||||||
|
}
|
||||||
|
group_proxies = Some(merged_proxies);
|
||||||
|
appended_to_selector = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(group_proxies) = group_proxies {
|
||||||
|
group_map.insert(Value::String("proxies".into()), Value::Sequence(group_proxies));
|
||||||
|
}
|
||||||
|
updated_groups.push(Value::Mapping(group_map));
|
||||||
|
} else {
|
||||||
updated_groups.push(group);
|
updated_groups.push(group);
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let mut group_proxies = match group_map.remove("proxies") {
|
|
||||||
Some(Value::Sequence(proxies)) => Some(
|
|
||||||
proxies
|
|
||||||
.into_iter()
|
|
||||||
.filter(|p| {
|
|
||||||
if let Value::String(name) = p {
|
|
||||||
!delete.contains(name)
|
|
||||||
} else {
|
|
||||||
true
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect::<Sequence>(),
|
|
||||||
),
|
|
||||||
Some(value) => {
|
|
||||||
group_map.insert(Value::String("proxies".into()), value);
|
|
||||||
None
|
|
||||||
}
|
|
||||||
None => None,
|
|
||||||
};
|
|
||||||
|
|
||||||
if !appended_to_selector && !added_proxy_names.is_empty() && is_selector_group(&group_map) {
|
|
||||||
let base_group_proxies = group_proxies.unwrap_or_else(Sequence::new);
|
|
||||||
let mut merged_proxies = Sequence::new();
|
|
||||||
let mut seen_proxy_names = HashSet::new();
|
|
||||||
for name in &added_proxy_names {
|
|
||||||
if seen_proxy_names.insert(name.clone()) {
|
|
||||||
merged_proxies.push(Value::String(name.as_str().to_owned()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for value in base_group_proxies {
|
|
||||||
if let Value::String(name) = &value
|
|
||||||
&& !seen_proxy_names.insert(TriStr::from(name.as_str()))
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
merged_proxies.push(value);
|
|
||||||
}
|
|
||||||
group_proxies = Some(merged_proxies);
|
|
||||||
appended_to_selector = true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(group_proxies) = group_proxies {
|
|
||||||
group_map.insert(Value::String("proxies".into()), Value::Sequence(group_proxies));
|
|
||||||
}
|
|
||||||
updated_groups.push(Value::Mapping(group_map));
|
|
||||||
}
|
}
|
||||||
config.insert(Value::String("proxy-groups".into()), Value::Sequence(updated_groups));
|
config.insert(Value::String("proxy-groups".into()), Value::Sequence(updated_groups));
|
||||||
|
|
||||||
@@ -45,20 +45,3 @@ pub fn use_tun(mut config: Mapping, enable: bool) -> Mapping {
|
|||||||
|
|
||||||
config
|
config
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) const DEFAULT_MTU: u16 = 1500;
|
|
||||||
|
|
||||||
/// Saved dialog fields; `enable` belongs to the verge switch.
|
|
||||||
pub(super) const GUI_KEYS: &[&str] = &[
|
|
||||||
"stack",
|
|
||||||
"device",
|
|
||||||
"auto-route",
|
|
||||||
"route-exclude-address",
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
"auto-redirect",
|
|
||||||
"auto-detect-interface",
|
|
||||||
"dns-hijack",
|
|
||||||
"dns-mode",
|
|
||||||
"strict-route",
|
|
||||||
"mtu",
|
|
||||||
];
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
config::{Config, IClashTemp, IVerge, profiles::load_profiles},
|
config::{Config, IClashTemp, IProfiles, IVerge},
|
||||||
core::{CoreManager, auto_backup, backup, proxy_control, proxy_control::SystemProxyStateUnknown},
|
core::{CoreManager, auto_backup, backup, proxy_control, proxy_control::SystemProxyStateUnknown},
|
||||||
process::AsyncHandler,
|
process::AsyncHandler,
|
||||||
utils::{
|
utils::{
|
||||||
@@ -46,7 +46,7 @@ async fn finalize_restored_verge_config(
|
|||||||
});
|
});
|
||||||
clash_draft.apply();
|
clash_draft.apply();
|
||||||
|
|
||||||
let restored_profiles = load_profiles().await;
|
let restored_profiles = IProfiles::new().await;
|
||||||
let profiles_draft = Config::profiles().await;
|
let profiles_draft = Config::profiles().await;
|
||||||
profiles_draft.edit_draft(|d| {
|
profiles_draft.edit_draft(|d| {
|
||||||
*d = restored_profiles;
|
*d = restored_profiles;
|
||||||
|
|||||||
@@ -349,7 +349,7 @@ fn stage_core(target: &Path, package: &[u8], version: &str) -> Result<StagedCore
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn create_staging_file(directory: &Path, core_name: &OsStr) -> Result<(PathBuf, File)> {
|
fn create_staging_file(directory: &Path, core_name: &OsStr) -> Result<(PathBuf, File)> {
|
||||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry_sync};
|
use crate::utils::retry::{RetryError, RetryPolicy, retry_sync};
|
||||||
retry_sync(
|
retry_sync(
|
||||||
RetryPolicy::fixed(
|
RetryPolicy::fixed(
|
||||||
std::num::NonZeroUsize::MIN.saturating_add(31),
|
std::num::NonZeroUsize::MIN.saturating_add(31),
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ use crate::{
|
|||||||
config::{
|
config::{
|
||||||
Config,
|
Config,
|
||||||
dns::{ProfileDnsSettings, dns_override_source},
|
dns::{ProfileDnsSettings, dns_override_source},
|
||||||
profiles::{PROFILE_WRITE_LOCK, current_mapping},
|
profiles::PROFILE_WRITE_LOCK,
|
||||||
},
|
},
|
||||||
constants::files::DNS_CONFIG,
|
constants::files::DNS_CONFIG,
|
||||||
core::CoreManager,
|
core::CoreManager,
|
||||||
@@ -36,7 +36,7 @@ pub async fn set_dns_override(
|
|||||||
);
|
);
|
||||||
let source = dns_override_source(
|
let source = dns_override_source(
|
||||||
profiles.current.as_deref().unwrap_or_default(),
|
profiles.current.as_deref().unwrap_or_default(),
|
||||||
¤t_mapping(&profiles).await?,
|
&profiles.current_mapping().await?,
|
||||||
)?;
|
)?;
|
||||||
if enabled && let Some(source) = source.as_ref().filter(|source| Some(*source) != confirmation.as_ref()) {
|
if enabled && let Some(source) = source.as_ref().filter(|source| Some(*source) != confirmation.as_ref()) {
|
||||||
return Ok(DnsOverrideOutcome::ConfirmationRequired { source: source.clone() });
|
return Ok(DnsOverrideOutcome::ConfirmationRequired { source: source.clone() });
|
||||||
|
|||||||
@@ -9,8 +9,6 @@ mod icon;
|
|||||||
mod listener;
|
mod listener;
|
||||||
mod profile;
|
mod profile;
|
||||||
mod proxy;
|
mod proxy;
|
||||||
pub(crate) mod proxy_view;
|
|
||||||
mod subscription;
|
|
||||||
mod tun;
|
mod tun;
|
||||||
mod window;
|
mod window;
|
||||||
|
|
||||||
@@ -24,6 +22,5 @@ pub use icon::*;
|
|||||||
pub use listener::*;
|
pub use listener::*;
|
||||||
pub use profile::*;
|
pub use profile::*;
|
||||||
pub use proxy::*;
|
pub use proxy::*;
|
||||||
pub use subscription::update_profile;
|
|
||||||
pub use tun::*;
|
pub use tun::*;
|
||||||
pub use window::*;
|
pub use window::*;
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
|
use crate::core::notify::NoticeStatus;
|
||||||
use crate::core::notify::{Refresh, announce};
|
use crate::core::notify::{Refresh, announce};
|
||||||
use crate::{
|
use crate::{
|
||||||
cmd,
|
cmd,
|
||||||
config::Config,
|
config::{Config, PrfItem, PrfOption, profiles::profiles_update_item_safe},
|
||||||
core::{CoreManager, handle, tray, validate::ValidationOutcome},
|
core::{CoreManager, handle, tray, validate::ValidationOutcome},
|
||||||
process::AsyncHandler,
|
process::AsyncHandler,
|
||||||
|
utils::help::{mask_err, mask_url},
|
||||||
};
|
};
|
||||||
use anyhow::Result;
|
use anyhow::{Result, bail};
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::{HashMap, HashSet};
|
||||||
use tauri_plugin_mihomo::models::{Proxy, ProxyType, Rule};
|
use tauri_plugin_mihomo::models::{Proxy, ProxyType, Rule};
|
||||||
@@ -199,6 +201,179 @@ async fn finish_proxy_switch(stale_proxies: Vec<std::string::String>) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result<Option<(String, Option<PrfOption>)>> {
|
||||||
|
let profiles = Config::profiles().await;
|
||||||
|
let profiles = profiles.latest_arc();
|
||||||
|
let item = profiles.get_item(uid)?;
|
||||||
|
let is_remote = item.itype.as_ref().is_some_and(|s| s == "remote");
|
||||||
|
|
||||||
|
if !is_remote {
|
||||||
|
logging!(info, Type::Config, "[订阅更新] 不是远程订阅,跳过更新");
|
||||||
|
Ok(None)
|
||||||
|
} else if item.url.is_none() {
|
||||||
|
logging!(warn, Type::Config, "[订阅更新] 缺少URL,无法更新");
|
||||||
|
bail!("failed to get the profile item url");
|
||||||
|
} else if !ignore_auto_update && !item.option.as_ref().and_then(|o| o.allow_auto_update).unwrap_or(true) {
|
||||||
|
logging!(info, Type::Config, "[订阅更新] 禁止自动更新,跳过更新");
|
||||||
|
Ok(None)
|
||||||
|
} else {
|
||||||
|
logging!(
|
||||||
|
info,
|
||||||
|
Type::Config,
|
||||||
|
"[订阅更新] 远程订阅,URL: {}",
|
||||||
|
mask_url(
|
||||||
|
item.url
|
||||||
|
.as_ref()
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("Profile URL is None"))?
|
||||||
|
)
|
||||||
|
);
|
||||||
|
Ok(Some((
|
||||||
|
item.url.clone().ok_or_else(|| anyhow::anyhow!("Profile URL is None"))?,
|
||||||
|
item.option.clone(),
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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,
|
||||||
|
opt: Option<&PrfOption>,
|
||||||
|
option: Option<&PrfOption>,
|
||||||
|
is_mannual_trigger: bool,
|
||||||
|
) -> Result<()> {
|
||||||
|
let merged_opt = PrfOption::merge(opt, option);
|
||||||
|
let profiles = Config::profiles().await;
|
||||||
|
let profiles_arc = profiles.latest_arc();
|
||||||
|
let profile_name = profiles_arc
|
||||||
|
.get_item(uid)
|
||||||
|
.ok()
|
||||||
|
.and_then(|item| item.name.clone())
|
||||||
|
.unwrap_or_else(|| String::from("UnKnown Profile"));
|
||||||
|
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
enum Strategy {
|
||||||
|
Configured,
|
||||||
|
Clash,
|
||||||
|
System,
|
||||||
|
}
|
||||||
|
|
||||||
|
let result =
|
||||||
|
crate::utils::retry::try_strategies(Strategy::Configured, [Strategy::Clash, Strategy::System], |strategy| {
|
||||||
|
let mut options = merged_opt.clone();
|
||||||
|
async move {
|
||||||
|
let (name, success, failure) = match strategy {
|
||||||
|
Strategy::Configured => (
|
||||||
|
"configured",
|
||||||
|
"[订阅更新] 更新订阅配置成功",
|
||||||
|
"[订阅更新] 直接更新失败: {},尝试使用Clash代理更新",
|
||||||
|
),
|
||||||
|
Strategy::Clash => (
|
||||||
|
"clash",
|
||||||
|
"[订阅更新] 使用 Clash代理 更新订阅配置成功",
|
||||||
|
"[订阅更新] Clash代理更新失败: {},尝试使用系统代理更新",
|
||||||
|
),
|
||||||
|
Strategy::System => (
|
||||||
|
"system",
|
||||||
|
"[订阅更新] 使用 系统代理 更新订阅配置成功",
|
||||||
|
"[订阅更新] 系统代理更新失败: {},所有重试均已失败",
|
||||||
|
),
|
||||||
|
};
|
||||||
|
match strategy {
|
||||||
|
Strategy::Configured => {}
|
||||||
|
Strategy::Clash | Strategy::System => {
|
||||||
|
let option = options.get_or_insert_with(PrfOption::default);
|
||||||
|
option.self_proxy = Some(matches!(strategy, Strategy::Clash));
|
||||||
|
option.with_proxy = Some(matches!(strategy, Strategy::System));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tracing::Span::current().record("strategy", name);
|
||||||
|
let started = std::time::Instant::now();
|
||||||
|
let result = PrfItem::from_url(url, None, None, options.as_ref()).await;
|
||||||
|
let elapsed_field = match strategy {
|
||||||
|
Strategy::Configured => "configured_elapsed",
|
||||||
|
Strategy::Clash => "clash_elapsed",
|
||||||
|
Strategy::System => "system_elapsed",
|
||||||
|
};
|
||||||
|
tracing::Span::current().record(elapsed_field, tracing::field::debug(started.elapsed()));
|
||||||
|
match &result {
|
||||||
|
Ok(_) => logging!(info, Type::Config, "{success}"),
|
||||||
|
Err(error) => logging!(
|
||||||
|
warn,
|
||||||
|
Type::Config,
|
||||||
|
"{}",
|
||||||
|
failure.replace("{}", &mask_err(&format!("{error:#}")))
|
||||||
|
),
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let last_err = match result {
|
||||||
|
Ok((strategy, mut item)) => {
|
||||||
|
// A persistence error must not replay a successful download with another transport.
|
||||||
|
profiles_update_item_safe(uid, &mut item).await?;
|
||||||
|
if !matches!(strategy, Strategy::Configured) {
|
||||||
|
handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name.as_str());
|
||||||
|
}
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
Err(error) => error,
|
||||||
|
};
|
||||||
|
|
||||||
|
let last_err = mask_err(&last_err.to_string());
|
||||||
|
if is_mannual_trigger {
|
||||||
|
handle::Handle::notice(
|
||||||
|
NoticeStatus::UpdateFailedEvenWithClash,
|
||||||
|
format!("{profile_name} - {last_err}"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
bail!(last_err)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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<()> {
|
||||||
|
let url_opt = should_update_profile(uid, is_mannual_trigger).await?;
|
||||||
|
|
||||||
|
let profile_persisted = match url_opt {
|
||||||
|
Some((url, opt)) => {
|
||||||
|
perform_profile_update(uid, &url, opt.as_ref(), option, is_mannual_trigger).await?;
|
||||||
|
true
|
||||||
|
}
|
||||||
|
None => false,
|
||||||
|
};
|
||||||
|
let profiles = Config::profiles().await;
|
||||||
|
let is_current = profiles.latest_arc().current.as_deref() == Some(uid);
|
||||||
|
let should_refresh = is_current || (!profile_persisted && is_mannual_trigger);
|
||||||
|
|
||||||
|
if should_refresh {
|
||||||
|
logging!(debug, Type::Config, "[订阅更新] 更新内核配置");
|
||||||
|
match CoreManager::global().update_config_with_force(is_mannual_trigger).await {
|
||||||
|
Ok(outcome) if outcome.is_valid() => announce(Refresh::Clash),
|
||||||
|
Ok(outcome @ (ValidationOutcome::Skipped { .. } | ValidationOutcome::Busy)) if !is_mannual_trigger => {
|
||||||
|
logging!(info, Type::Config, "[订阅更新] 本次配置刷新已跳过: {}", outcome);
|
||||||
|
}
|
||||||
|
result => {
|
||||||
|
let message = match result {
|
||||||
|
Ok(outcome) => outcome.to_string(),
|
||||||
|
Err(err) => err.to_string(),
|
||||||
|
};
|
||||||
|
let message = mask_err(&message);
|
||||||
|
let message = if profile_persisted {
|
||||||
|
format!("订阅已保存,但未能确认已应用到内核: {message}")
|
||||||
|
} else {
|
||||||
|
message
|
||||||
|
};
|
||||||
|
logging!(error, Type::Config, "[订阅更新] 更新失败: {}", message);
|
||||||
|
handle::Handle::notice(NoticeStatus::UpdateFailed, message.as_str());
|
||||||
|
bail!(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// 增强配置
|
/// 增强配置
|
||||||
pub async fn enhance_profiles() -> Result<ValidationOutcome> {
|
pub async fn enhance_profiles() -> Result<ValidationOutcome> {
|
||||||
CoreManager::global().update_config_forced().await
|
CoreManager::global().update_config_forced().await
|
||||||
|
|||||||
@@ -1,165 +0,0 @@
|
|||||||
mod groups;
|
|
||||||
|
|
||||||
use clash_verge_proxy_view::{
|
|
||||||
DelayHistory, ProviderSnapshot, ProxyCapabilities, ProxyProviderVehicleType, ProxySnapshot, ProxySubscriptionInfo,
|
|
||||||
ProxyViewBuilder, ProxyViewInput, ProxyViewV1,
|
|
||||||
};
|
|
||||||
use serde_yaml_ng::Mapping;
|
|
||||||
use std::future::Future;
|
|
||||||
use tauri_plugin_mihomo::{
|
|
||||||
Result,
|
|
||||||
models::{Proxies, Proxy, ProxyProvider, ProxyProviders, ProxyType, VehicleType},
|
|
||||||
};
|
|
||||||
|
|
||||||
pub(crate) async fn load_proxy_view(
|
|
||||||
config: Option<&Mapping>,
|
|
||||||
proxies: impl Future<Output = Result<Proxies>>,
|
|
||||||
providers: impl Future<Output = Result<ProxyProviders>>,
|
|
||||||
) -> Result<ProxyViewV1> {
|
|
||||||
let (runtime_group_order, group_scopes) = groups::runtime_groups(config);
|
|
||||||
let (proxies, providers) = tokio::join!(proxies, providers);
|
|
||||||
let proxies = proxies?;
|
|
||||||
|
|
||||||
Ok(ProxyViewBuilder::build(ProxyViewInput {
|
|
||||||
runtime_group_order,
|
|
||||||
group_scopes,
|
|
||||||
proxies: proxies
|
|
||||||
.proxies
|
|
||||||
.into_iter()
|
|
||||||
.map(|(name, proxy)| (name.into(), proxy_snapshot(proxy)))
|
|
||||||
.collect(),
|
|
||||||
providers: providers.ok().map(|providers| {
|
|
||||||
providers
|
|
||||||
.providers
|
|
||||||
.into_iter()
|
|
||||||
.filter_map(|(name, provider)| provider_snapshot(provider).map(|snapshot| (name.into(), snapshot)))
|
|
||||||
.collect()
|
|
||||||
}),
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn proxy_snapshot(proxy: Proxy) -> ProxySnapshot {
|
|
||||||
ProxySnapshot {
|
|
||||||
name: proxy.name.into(),
|
|
||||||
proxy_type: match proxy.proxy_type {
|
|
||||||
ProxyType::Unknown(value) => value.into(),
|
|
||||||
proxy_type => proxy_type.as_str().into(),
|
|
||||||
},
|
|
||||||
all: proxy.all.map(|all| all.into_iter().map(Into::into).collect()),
|
|
||||||
fixed: proxy.fixed.map(Into::into),
|
|
||||||
hidden: proxy.hidden,
|
|
||||||
icon: proxy.icon.map(Into::into),
|
|
||||||
now: proxy.now.map(Into::into),
|
|
||||||
test_url: proxy.test_url.map(Into::into),
|
|
||||||
id: proxy.id.map(Into::into),
|
|
||||||
history: proxy
|
|
||||||
.history
|
|
||||||
.into_iter()
|
|
||||||
.map(|entry| DelayHistory {
|
|
||||||
time: entry.time.into(),
|
|
||||||
delay: entry.delay,
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
capabilities: ProxyCapabilities {
|
|
||||||
udp: proxy.udp,
|
|
||||||
xudp: proxy.xudp,
|
|
||||||
tfo: proxy.tfo,
|
|
||||||
mptcp: proxy.mptcp,
|
|
||||||
smux: proxy.smux,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn provider_snapshot(provider: ProxyProvider) -> Option<ProviderSnapshot> {
|
|
||||||
let vehicle_type = match provider.vehicle_type {
|
|
||||||
VehicleType::HTTP => ProxyProviderVehicleType::Http,
|
|
||||||
VehicleType::File => ProxyProviderVehicleType::File,
|
|
||||||
VehicleType::Inline => ProxyProviderVehicleType::Inline,
|
|
||||||
_ => return None,
|
|
||||||
};
|
|
||||||
|
|
||||||
Some(ProviderSnapshot {
|
|
||||||
vehicle_type,
|
|
||||||
proxies: provider.proxies.into_iter().map(proxy_snapshot).collect(),
|
|
||||||
updated_at: provider.updated_at.map(Into::into),
|
|
||||||
subscription_info: provider.subscription_info.map(|info| ProxySubscriptionInfo {
|
|
||||||
upload: info.upload,
|
|
||||||
download: info.download,
|
|
||||||
total: info.total,
|
|
||||||
expire: info.expire,
|
|
||||||
}),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use clash_verge_proxy_view::{
|
|
||||||
ProxyMemberRef, ProxyMemberUnresolvedReason, ProxyNodeSource, ProxyViewProviderState,
|
|
||||||
};
|
|
||||||
use std::future::ready;
|
|
||||||
use tauri_plugin_mihomo::Error;
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn preserves_scoped_members_and_global_when_providers_are_unavailable() -> anyhow::Result<()> {
|
|
||||||
let config = serde_yaml_ng::from_str(
|
|
||||||
"proxy-providers: {z: {}, a: {}}\n\
|
|
||||||
proxy-groups:\n\
|
|
||||||
- {name: GLOBAL}\n\
|
|
||||||
- {name: Select, use: [a], include-all-providers: true, exclude-type: Direct}",
|
|
||||||
)?;
|
|
||||||
let proxies = r#"{"proxies":{
|
|
||||||
"GLOBAL":{"type":"Selector","all":["Select"]},
|
|
||||||
"Select":{"type":"Selector","all":["shared"]}
|
|
||||||
}}"#;
|
|
||||||
let providers = serde_json::from_str(
|
|
||||||
r#"{"providers":{
|
|
||||||
"a":{"vehicleType":"HTTP","proxies":[{"name":"shared","type":"Direct"}]},
|
|
||||||
"z":{"vehicleType":"File","proxies":[{"name":"shared","type":"Shadowsocks"}]}
|
|
||||||
}}"#,
|
|
||||||
)?;
|
|
||||||
|
|
||||||
let available = load_proxy_view(
|
|
||||||
Some(&config),
|
|
||||||
ready(Ok(serde_json::from_str(proxies)?)),
|
|
||||||
ready(Ok(providers)),
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
let unavailable = load_proxy_view(
|
|
||||||
Some(&config),
|
|
||||||
ready(Ok(serde_json::from_str(proxies)?)),
|
|
||||||
ready(Err(Error::FailedResponse("providers unavailable".into()))),
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
for view in [&available, &unavailable] {
|
|
||||||
assert_eq!(
|
|
||||||
view.global.as_ref().map(|global| global.members.as_slice()),
|
|
||||||
Some([ProxyMemberRef::Group { name: "Select".into() }].as_slice())
|
|
||||||
);
|
|
||||||
assert_eq!(view.groups.len(), 1);
|
|
||||||
assert_eq!(view.groups[0].name.as_str(), "Select");
|
|
||||||
}
|
|
||||||
|
|
||||||
assert_eq!(available.provider_state, ProxyViewProviderState::Ready);
|
|
||||||
let [ProxyMemberRef::Node { record_id, .. }] = available.groups[0].members.as_slice() else {
|
|
||||||
anyhow::bail!("expected the scoped provider member");
|
|
||||||
};
|
|
||||||
assert_eq!(
|
|
||||||
available.records.get(record_id).map(|record| &record.source),
|
|
||||||
Some(&ProxyNodeSource::Provider {
|
|
||||||
provider_name: "z".into(),
|
|
||||||
proxy_name: "shared".into(),
|
|
||||||
})
|
|
||||||
);
|
|
||||||
assert_eq!(unavailable.provider_state, ProxyViewProviderState::Unavailable);
|
|
||||||
assert_eq!(
|
|
||||||
unavailable.groups[0].members,
|
|
||||||
[ProxyMemberRef::Unresolved {
|
|
||||||
name: "shared".into(),
|
|
||||||
reason: ProxyMemberUnresolvedReason::ProviderUnavailable,
|
|
||||||
}]
|
|
||||||
);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
use clash_verge_proxy_view::GroupScope;
|
|
||||||
use serde_yaml_ng::Mapping;
|
|
||||||
use std::collections::{BTreeMap, HashSet};
|
|
||||||
use tristr::alias::String as ViewString;
|
|
||||||
|
|
||||||
fn runtime_group_order(config: Option<&Mapping>) -> Vec<ViewString> {
|
|
||||||
let mut seen = HashSet::new();
|
|
||||||
|
|
||||||
config
|
|
||||||
.and_then(|config| config.get("proxy-groups"))
|
|
||||||
.and_then(|groups| groups.as_sequence())
|
|
||||||
.into_iter()
|
|
||||||
.flatten()
|
|
||||||
.filter_map(|group| group.get("name"))
|
|
||||||
.filter_map(|name| name.as_str())
|
|
||||||
.filter(|name| !name.is_empty() && *name != "GLOBAL")
|
|
||||||
.filter(|name| seen.insert(*name))
|
|
||||||
.map(ViewString::from)
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Mirrors Mihomo: `include-all`/`include-all-providers` replace `use` with every provider, sorted.
|
|
||||||
fn runtime_group_scopes(config: Option<&Mapping>) -> BTreeMap<ViewString, GroupScope> {
|
|
||||||
let Some(config) = config else {
|
|
||||||
return BTreeMap::new();
|
|
||||||
};
|
|
||||||
let mut all_providers = None;
|
|
||||||
let flag = |group: &Mapping, key: &str| group.get(key).and_then(|value| value.as_bool()) == Some(true);
|
|
||||||
|
|
||||||
config
|
|
||||||
.get("proxy-groups")
|
|
||||||
.and_then(|groups| groups.as_sequence())
|
|
||||||
.into_iter()
|
|
||||||
.flatten()
|
|
||||||
.filter_map(|group| group.as_mapping())
|
|
||||||
.filter_map(|group| {
|
|
||||||
let name = ViewString::from(group.get("name")?.as_str()?);
|
|
||||||
let providers = if flag(group, "include-all") || flag(group, "include-all-providers") {
|
|
||||||
all_providers
|
|
||||||
.get_or_insert_with(|| {
|
|
||||||
let mut names = config
|
|
||||||
.get("proxy-providers")
|
|
||||||
.and_then(|providers| providers.as_mapping())
|
|
||||||
.into_iter()
|
|
||||||
.flat_map(|providers| providers.keys())
|
|
||||||
.filter_map(|name| name.as_str())
|
|
||||||
.map(ViewString::from)
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
names.sort();
|
|
||||||
names
|
|
||||||
})
|
|
||||||
.clone()
|
|
||||||
} else {
|
|
||||||
group
|
|
||||||
.get("use")
|
|
||||||
.and_then(|providers| providers.as_sequence())
|
|
||||||
.into_iter()
|
|
||||||
.flatten()
|
|
||||||
.filter_map(|provider| provider.as_str())
|
|
||||||
.map(ViewString::from)
|
|
||||||
.collect()
|
|
||||||
};
|
|
||||||
let exclude_types = group
|
|
||||||
.get("exclude-type")
|
|
||||||
.and_then(|types| types.as_str())
|
|
||||||
.filter(|types| !types.is_empty())
|
|
||||||
.map_or_default(|types| types.split('|').map(ViewString::from).collect());
|
|
||||||
Some((
|
|
||||||
name,
|
|
||||||
GroupScope {
|
|
||||||
providers,
|
|
||||||
exclude_types,
|
|
||||||
},
|
|
||||||
))
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn runtime_groups(config: Option<&Mapping>) -> (Vec<ViewString>, BTreeMap<ViewString, GroupScope>) {
|
|
||||||
(runtime_group_order(config), runtime_group_scopes(config))
|
|
||||||
}
|
|
||||||
@@ -1,196 +0,0 @@
|
|||||||
use crate::{
|
|
||||||
config::{Config, PrfOption, download_subscription, prepare_remote_refresh, profiles::apply_remote_refresh_safe},
|
|
||||||
core::{
|
|
||||||
CoreManager, handle,
|
|
||||||
notify::{NoticeStatus, Refresh, announce},
|
|
||||||
validate::ValidationOutcome,
|
|
||||||
},
|
|
||||||
utils::help::{mask_err, mask_url},
|
|
||||||
};
|
|
||||||
use anyhow::{Result, bail};
|
|
||||||
use clash_verge_logging::{Type, logging};
|
|
||||||
use tristr::alias::String;
|
|
||||||
|
|
||||||
async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result<Option<(String, Option<PrfOption>)>> {
|
|
||||||
let profiles = Config::profiles().await;
|
|
||||||
let profiles = profiles.latest_arc();
|
|
||||||
let item = profiles.get_item(uid)?;
|
|
||||||
let is_remote = item.itype.as_ref().is_some_and(|s| s == "remote");
|
|
||||||
|
|
||||||
if !is_remote {
|
|
||||||
logging!(info, Type::Config, "[订阅更新] 不是远程订阅,跳过更新");
|
|
||||||
Ok(None)
|
|
||||||
} else if item.url.is_none() {
|
|
||||||
logging!(warn, Type::Config, "[订阅更新] 缺少URL,无法更新");
|
|
||||||
bail!("failed to get the profile item url");
|
|
||||||
} else if !ignore_auto_update && !item.option.as_ref().and_then(|o| o.allow_auto_update).unwrap_or(true) {
|
|
||||||
logging!(info, Type::Config, "[订阅更新] 禁止自动更新,跳过更新");
|
|
||||||
Ok(None)
|
|
||||||
} else {
|
|
||||||
logging!(
|
|
||||||
info,
|
|
||||||
Type::Config,
|
|
||||||
"[订阅更新] 远程订阅,URL: {}",
|
|
||||||
mask_url(
|
|
||||||
item.url
|
|
||||||
.as_ref()
|
|
||||||
.ok_or_else(|| anyhow::anyhow!("Profile URL is None"))?
|
|
||||||
)
|
|
||||||
);
|
|
||||||
Ok(Some((
|
|
||||||
item.url.clone().ok_or_else(|| anyhow::anyhow!("Profile URL is None"))?,
|
|
||||||
item.option.clone(),
|
|
||||||
)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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,
|
|
||||||
opt: Option<&PrfOption>,
|
|
||||||
option: Option<&PrfOption>,
|
|
||||||
is_manual_trigger: bool,
|
|
||||||
) -> Result<()> {
|
|
||||||
let merged_opt = PrfOption::merge(opt, option);
|
|
||||||
let profiles = Config::profiles().await;
|
|
||||||
let profiles_arc = profiles.latest_arc();
|
|
||||||
let profile_name = profiles_arc
|
|
||||||
.get_item(uid)
|
|
||||||
.ok()
|
|
||||||
.and_then(|item| item.name.clone())
|
|
||||||
.unwrap_or_else(|| String::from("UnKnown Profile"));
|
|
||||||
|
|
||||||
#[derive(Clone, Copy)]
|
|
||||||
enum Strategy {
|
|
||||||
Configured,
|
|
||||||
Clash,
|
|
||||||
System,
|
|
||||||
}
|
|
||||||
|
|
||||||
let result = clash_verge_task::retry::try_strategies(
|
|
||||||
Strategy::Configured,
|
|
||||||
[Strategy::Clash, Strategy::System],
|
|
||||||
|strategy| {
|
|
||||||
let mut options = merged_opt.clone();
|
|
||||||
async move {
|
|
||||||
let (name, success, failure) = match strategy {
|
|
||||||
Strategy::Configured => (
|
|
||||||
"configured",
|
|
||||||
"[订阅更新] 更新订阅配置成功",
|
|
||||||
"[订阅更新] 直接更新失败: {},尝试使用Clash代理更新",
|
|
||||||
),
|
|
||||||
Strategy::Clash => (
|
|
||||||
"clash",
|
|
||||||
"[订阅更新] 使用 Clash代理 更新订阅配置成功",
|
|
||||||
"[订阅更新] Clash代理更新失败: {},尝试使用系统代理更新",
|
|
||||||
),
|
|
||||||
Strategy::System => (
|
|
||||||
"system",
|
|
||||||
"[订阅更新] 使用 系统代理 更新订阅配置成功",
|
|
||||||
"[订阅更新] 系统代理更新失败: {},所有重试均已失败",
|
|
||||||
),
|
|
||||||
};
|
|
||||||
match strategy {
|
|
||||||
Strategy::Configured => {}
|
|
||||||
Strategy::Clash | Strategy::System => {
|
|
||||||
let option = options.get_or_insert_with(PrfOption::default);
|
|
||||||
option.self_proxy = Some(matches!(strategy, Strategy::Clash));
|
|
||||||
option.with_proxy = Some(matches!(strategy, Strategy::System));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
tracing::Span::current().record("strategy", name);
|
|
||||||
let started = std::time::Instant::now();
|
|
||||||
let result = download_subscription(url, options.as_ref()).await;
|
|
||||||
let elapsed_field = match strategy {
|
|
||||||
Strategy::Configured => "configured_elapsed",
|
|
||||||
Strategy::Clash => "clash_elapsed",
|
|
||||||
Strategy::System => "system_elapsed",
|
|
||||||
};
|
|
||||||
tracing::Span::current().record(elapsed_field, tracing::field::debug(started.elapsed()));
|
|
||||||
match &result {
|
|
||||||
Ok(_) => logging!(info, Type::Config, "{success}"),
|
|
||||||
Err(error) => logging!(
|
|
||||||
warn,
|
|
||||||
Type::Config,
|
|
||||||
"{}",
|
|
||||||
failure.replace("{}", &mask_err(&format!("{error:#}")))
|
|
||||||
),
|
|
||||||
}
|
|
||||||
result
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
let last_err = match result {
|
|
||||||
Ok((strategy, downloaded)) => {
|
|
||||||
// A persistence error must not replay a successful download with another transport.
|
|
||||||
let profiles = Config::profiles().await;
|
|
||||||
let snapshot = profiles.latest_arc();
|
|
||||||
let current = snapshot.get_item(uid)?;
|
|
||||||
anyhow::ensure!(
|
|
||||||
current.itype.as_deref() == Some("remote") && current.url.as_deref() == Some(url),
|
|
||||||
"profile source changed during refresh"
|
|
||||||
);
|
|
||||||
let refresh = prepare_remote_refresh(downloaded, merged_opt.as_ref()).await?;
|
|
||||||
apply_remote_refresh_safe(uid, url, refresh).await?;
|
|
||||||
if !matches!(strategy, Strategy::Configured) {
|
|
||||||
handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name.as_str());
|
|
||||||
}
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
Err(error) => error,
|
|
||||||
};
|
|
||||||
|
|
||||||
let last_err = mask_err(&last_err.to_string());
|
|
||||||
if is_manual_trigger {
|
|
||||||
handle::Handle::notice(
|
|
||||||
NoticeStatus::UpdateFailedEvenWithClash,
|
|
||||||
format!("{profile_name} - {last_err}"),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
bail!(last_err)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, manual = is_manual_trigger))]
|
|
||||||
pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_manual_trigger: bool) -> Result<()> {
|
|
||||||
let url_opt = should_update_profile(uid, is_manual_trigger).await?;
|
|
||||||
|
|
||||||
let profile_persisted = match url_opt {
|
|
||||||
Some((url, opt)) => {
|
|
||||||
perform_profile_update(uid, &url, opt.as_ref(), option, is_manual_trigger).await?;
|
|
||||||
true
|
|
||||||
}
|
|
||||||
None => false,
|
|
||||||
};
|
|
||||||
let profiles = Config::profiles().await;
|
|
||||||
let is_current = profiles.latest_arc().current.as_deref() == Some(uid);
|
|
||||||
let should_refresh = is_current || (!profile_persisted && is_manual_trigger);
|
|
||||||
|
|
||||||
if should_refresh {
|
|
||||||
logging!(debug, Type::Config, "[订阅更新] 更新内核配置");
|
|
||||||
match CoreManager::global().update_config_with_force(is_manual_trigger).await {
|
|
||||||
Ok(outcome) if outcome.is_valid() => announce(Refresh::Clash),
|
|
||||||
Ok(outcome @ (ValidationOutcome::Skipped { .. } | ValidationOutcome::Busy)) if !is_manual_trigger => {
|
|
||||||
logging!(info, Type::Config, "[订阅更新] 本次配置刷新已跳过: {}", outcome);
|
|
||||||
}
|
|
||||||
result => {
|
|
||||||
let message = match result {
|
|
||||||
Ok(outcome) => outcome.to_string(),
|
|
||||||
Err(err) => err.to_string(),
|
|
||||||
};
|
|
||||||
let message = mask_err(&message);
|
|
||||||
let message = if profile_persisted {
|
|
||||||
format!("订阅已保存,但未能确认已应用到内核: {message}")
|
|
||||||
} else {
|
|
||||||
message
|
|
||||||
};
|
|
||||||
logging!(error, Type::Config, "[订阅更新] 更新失败: {}", message);
|
|
||||||
handle::Handle::notice(NoticeStatus::UpdateFailed, message.as_str());
|
|
||||||
bail!(message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
@@ -165,6 +165,12 @@ impl From<network_interface::NetworkInterface> for NetworkInterfaceView {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, specta::Type)]
|
||||||
|
pub struct DelayHistory {
|
||||||
|
pub time: String,
|
||||||
|
pub delay: u16,
|
||||||
|
}
|
||||||
|
|
||||||
fn platform_types() -> specta::Types {
|
fn platform_types() -> specta::Types {
|
||||||
use specta::datatype::{DataType, Fields};
|
use specta::datatype::{DataType, Fields};
|
||||||
let mut types = specta::Types::default().register::<crate::config::IVerge>();
|
let mut types = specta::Types::default().register::<crate::config::IVerge>();
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
#![allow(non_snake_case)]
|
#![allow(non_snake_case)]
|
||||||
#![deny(clippy::expect_used, clippy::unwrap_used)]
|
|
||||||
#![recursion_limit = "512"]
|
#![recursion_limit = "512"]
|
||||||
|
|
||||||
mod cmd;
|
mod cmd;
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||||
#![deny(clippy::expect_used, clippy::unwrap_used)]
|
|
||||||
|
|
||||||
use std::process::ExitCode;
|
use std::process::ExitCode;
|
||||||
#[cfg(not(all(feature = "perf-harness", target_os = "macos")))]
|
#[cfg(not(all(feature = "perf-harness", target_os = "macos")))]
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ use serde_yaml_ng::{Mapping, Value};
|
|||||||
use std::{
|
use std::{
|
||||||
mem::DropGuard,
|
mem::DropGuard,
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
|
str::FromStr,
|
||||||
};
|
};
|
||||||
use tokio::io::AsyncWriteExt as _;
|
use tokio::io::AsyncWriteExt as _;
|
||||||
|
|
||||||
@@ -211,6 +212,16 @@ pub fn get_uid(prefix: &str) -> String {
|
|||||||
format!("{prefix}{id}")
|
format!("{prefix}{id}")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn parse_str<T: FromStr>(target: &str, key: &str) -> Option<T> {
|
||||||
|
target.split(';').map(str::trim).find_map(|s| {
|
||||||
|
let mut parts = s.splitn(2, '=');
|
||||||
|
match (parts.next(), parts.next()) {
|
||||||
|
(Some(k), Some(v)) if k == key => v.parse::<T>().ok(),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
pub fn hex_encode(bytes: &[u8]) -> String {
|
pub fn hex_encode(bytes: &[u8]) -> String {
|
||||||
const HEX: &[u8; 16] = b"0123456789abcdef";
|
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||||
let mut out = String::with_capacity(bytes.len() * 2);
|
let mut out = String::with_capacity(bytes.len() * 2);
|
||||||
@@ -296,6 +307,18 @@ pub fn mask_err(err: &str) -> String {
|
|||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn get_last_part_and_decode(url: &str) -> Option<String> {
|
||||||
|
let path = url.split('?').next().unwrap_or("");
|
||||||
|
let segments: Vec<&str> = path.split('/').collect();
|
||||||
|
let last_segment = segments.last()?;
|
||||||
|
|
||||||
|
Some(
|
||||||
|
percent_encoding::percent_decode_str(last_segment)
|
||||||
|
.decode_utf8_lossy()
|
||||||
|
.to_string(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn open_file(path: PathBuf) -> Result<()> {
|
pub fn open_file(path: PathBuf) -> Result<()> {
|
||||||
open::that_detached(path.as_os_str())?;
|
open::that_detached(path.as_os_str())?;
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -1,8 +1,5 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
config::{
|
config::{Config, IClashTemp, IProfiles, IVerge},
|
||||||
Config, IClashTemp, IProfiles, IVerge,
|
|
||||||
profiles::{raise_short_update_intervals, save_profiles},
|
|
||||||
},
|
|
||||||
constants,
|
constants,
|
||||||
core::handle,
|
core::handle,
|
||||||
logging,
|
logging,
|
||||||
@@ -269,9 +266,9 @@ pub async fn migrate_short_update_intervals() -> Result<()> {
|
|||||||
if profiles.items.is_none() {
|
if profiles.items.is_none() {
|
||||||
anyhow::bail!("profiles.yaml was not loaded; refusing to record the migration as done");
|
anyhow::bail!("profiles.yaml was not loaded; refusing to record the migration as done");
|
||||||
}
|
}
|
||||||
let raised = raise_short_update_intervals(&mut profiles, min);
|
let raised = profiles.raise_short_update_intervals(min);
|
||||||
if raised > 0 {
|
if raised > 0 {
|
||||||
save_profiles(&profiles).await?;
|
profiles.save_file().await?;
|
||||||
}
|
}
|
||||||
Ok((profiles, raised))
|
Ok((profiles, raised))
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -109,7 +109,7 @@ fn current_user_home() -> anyhow::Result<PathBuf> {
|
|||||||
}
|
}
|
||||||
.max(1024);
|
.max(1024);
|
||||||
|
|
||||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry_sync};
|
use crate::utils::retry::{RetryError, RetryPolicy, retry_sync};
|
||||||
retry_sync(
|
retry_sync(
|
||||||
RetryPolicy::fixed(
|
RetryPolicy::fixed(
|
||||||
std::num::NonZeroUsize::MIN.saturating_add(11),
|
std::num::NonZeroUsize::MIN.saturating_add(11),
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ pub(crate) mod network;
|
|||||||
pub use crate::core::notify::desktop as notification;
|
pub use crate::core::notify::desktop as notification;
|
||||||
pub mod port;
|
pub mod port;
|
||||||
pub mod resolve;
|
pub mod resolve;
|
||||||
|
pub mod retry;
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
pub mod schtasks;
|
pub mod schtasks;
|
||||||
pub mod server;
|
pub mod server;
|
||||||
@@ -21,3 +22,4 @@ pub mod tmpl;
|
|||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
pub mod tray_speed;
|
pub mod tray_speed;
|
||||||
pub mod window_manager;
|
pub mod window_manager;
|
||||||
|
pub mod yaml_emitter;
|
||||||
|
|||||||
@@ -1,15 +1,15 @@
|
|||||||
use crate::core::notify::NoticeStatus;
|
use crate::core::notify::NoticeStatus;
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
|
use percent_encoding::percent_decode_str;
|
||||||
use tauri::Url;
|
use tauri::Url;
|
||||||
use tristr::alias::String;
|
use tristr::alias::String;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
config::{Config, PrfItem, build_remote_profile, profiles},
|
config::{Config, PrfItem, profiles},
|
||||||
core::{CoreManager, handle, timer::Timer},
|
core::{CoreManager, handle, timer::Timer},
|
||||||
utils::help,
|
utils::help,
|
||||||
};
|
};
|
||||||
use clash_verge_logging::{Type, logging, logging_error};
|
use clash_verge_logging::{Type, logging, logging_error};
|
||||||
use clash_verge_subscription::decode_subscription_link;
|
|
||||||
|
|
||||||
pub(super) async fn resolve_scheme(param: &str) -> Result<()> {
|
pub(super) async fn resolve_scheme(param: &str) -> Result<()> {
|
||||||
let param_str = if param.starts_with("[") && param.len() > 4 {
|
let param_str = if param.starts_with("[") && param.len() > 4 {
|
||||||
@@ -26,7 +26,7 @@ pub(super) async fn resolve_scheme(param: &str) -> Result<()> {
|
|||||||
let link_parsed = Url::parse(param_str)
|
let link_parsed = Url::parse(param_str)
|
||||||
.map_err(|e| anyhow::anyhow!("failed to parse deep link: {e:?}, param: {masked_deep_link}"))?;
|
.map_err(|e| anyhow::anyhow!("failed to parse deep link: {e:?}, param: {masked_deep_link}"))?;
|
||||||
|
|
||||||
let Some(link) = decode_subscription_link(&link_parsed) else {
|
let Some((url, name)) = extract_subscription_info(&link_parsed) else {
|
||||||
logging!(
|
logging!(
|
||||||
warn,
|
warn,
|
||||||
Type::Config,
|
Type::Config,
|
||||||
@@ -35,11 +35,51 @@ pub(super) async fn resolve_scheme(param: &str) -> Result<()> {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
};
|
};
|
||||||
|
|
||||||
let name = link.name.map(String::from);
|
import_subscription(&url, name.as_ref()).await;
|
||||||
import_subscription(&link.url, name.as_ref()).await;
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn extract_subscription_info(link_parsed: &Url) -> Option<(std::string::String, Option<String>)> {
|
||||||
|
if !matches!(link_parsed.scheme(), "clash" | "clash-verge") {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let name = link_parsed
|
||||||
|
.query_pairs()
|
||||||
|
.find(|(key, _)| key == "name")
|
||||||
|
.map(|(_, value)| value.into());
|
||||||
|
let url = extract_subscription_url(link_parsed)?;
|
||||||
|
Some((url, name))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn extract_subscription_url(link_parsed: &Url) -> Option<std::string::String> {
|
||||||
|
let query = link_parsed.query()?;
|
||||||
|
let prefix = "url=";
|
||||||
|
let pos = query.find(prefix)?;
|
||||||
|
let raw_url = query[pos + prefix.len()..].trim();
|
||||||
|
Some(decode_subscription_url(raw_url))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decode_subscription_url(raw_url: &str) -> std::string::String {
|
||||||
|
// Avoid double-decoding nested subscription URLs; decode only when needed.
|
||||||
|
if Url::parse(raw_url).is_ok() {
|
||||||
|
return raw_url.to_string();
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut candidate = raw_url.to_string();
|
||||||
|
for _ in 0..2 {
|
||||||
|
let next = percent_decode_str(&candidate).decode_utf8_lossy().to_string();
|
||||||
|
if next == candidate {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
candidate = next;
|
||||||
|
if Url::parse(&candidate).is_ok() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
candidate
|
||||||
|
}
|
||||||
|
|
||||||
async fn import_subscription(url: &str, name: Option<&String>) {
|
async fn import_subscription(url: &str, name: Option<&String>) {
|
||||||
let had_current_profile = {
|
let had_current_profile = {
|
||||||
let profiles = Config::profiles().await;
|
let profiles = Config::profiles().await;
|
||||||
@@ -73,7 +113,7 @@ async fn import_subscription(url: &str, name: Option<&String>) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn fetch_profile_item(url: &str, name: Option<&String>) -> Option<PrfItem> {
|
async fn fetch_profile_item(url: &str, name: Option<&String>) -> Option<PrfItem> {
|
||||||
match build_remote_profile(url, name, None, None).await {
|
match PrfItem::from_url(url, name, None, None).await {
|
||||||
Ok(item) => Some(item),
|
Ok(item) => Some(item),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
logging!(error, Type::Config, "failed to parse profile from url: {:?}", e);
|
logging!(error, Type::Config, "failed to parse profile from url: {:?}", e);
|
||||||
|
|||||||
@@ -21,29 +21,25 @@ pub enum RetryError<E> {
|
|||||||
Stop(E),
|
Stop(E),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<E> RetryError<E> {
|
|
||||||
fn into_inner(self) -> E {
|
|
||||||
match self {
|
|
||||||
Self::Retry(error) | Self::Stop(error) => error,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn retry<T: Send, E: Send, Fut: Future<Output = Result<T, RetryError<E>>> + Send>(
|
pub async fn retry<T: Send, E: Send, Fut: Future<Output = Result<T, RetryError<E>>> + Send>(
|
||||||
policy: RetryPolicy,
|
policy: RetryPolicy,
|
||||||
mut operation: impl FnMut(usize) -> Fut + Send,
|
mut operation: impl FnMut(usize) -> Fut + Send,
|
||||||
) -> Result<T, E> {
|
) -> Result<T, E> {
|
||||||
let mut result = operation(0).await;
|
let mut result = operation(0).await;
|
||||||
for (index, delay) in policy.delays().enumerate() {
|
for (index, delay) in policy.delays().enumerate() {
|
||||||
if !matches!(result, Err(RetryError::Retry(_))) {
|
match result {
|
||||||
break;
|
Ok(_) | Err(RetryError::Stop(_)) => break,
|
||||||
}
|
Err(RetryError::Retry(_)) => {
|
||||||
if !delay.is_zero() {
|
if !delay.is_zero() {
|
||||||
tokio::time::sleep(delay).await;
|
tokio::time::sleep(delay).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
result = operation(index + 1).await;
|
result = operation(index + 1).await;
|
||||||
}
|
}
|
||||||
result.map_err(RetryError::into_inner)
|
result.map_err(|error| match error {
|
||||||
|
RetryError::Retry(error) | RetryError::Stop(error) => error,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn try_strategies<
|
pub async fn try_strategies<
|
||||||
@@ -57,14 +53,15 @@ pub async fn try_strategies<
|
|||||||
rest: [S; N],
|
rest: [S; N],
|
||||||
mut operation: impl FnMut(S) -> Fut + Send,
|
mut operation: impl FnMut(S) -> Fut + Send,
|
||||||
) -> Result<(S, T), E> {
|
) -> Result<(S, T), E> {
|
||||||
let mut result = operation(first).await.map(|value| (first, value));
|
retry(
|
||||||
for strategy in rest {
|
RetryPolicy::fixed(NonZeroUsize::MIN.saturating_add(N), Duration::ZERO),
|
||||||
if result.is_ok() {
|
move |attempt| {
|
||||||
break;
|
let strategy = if attempt == 0 { first } else { rest[attempt - 1] };
|
||||||
}
|
let future = operation(strategy);
|
||||||
result = operation(strategy).await.map(|value| (strategy, value));
|
async move { future.await.map(|value| (strategy, value)).map_err(RetryError::Retry) }
|
||||||
}
|
},
|
||||||
result
|
)
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn retry_with_state<S: Send, T: Send, E: Send>(
|
pub async fn retry_with_state<S: Send, T: Send, E: Send>(
|
||||||
@@ -74,15 +71,19 @@ pub async fn retry_with_state<S: Send, T: Send, E: Send>(
|
|||||||
) -> Result<T, E> {
|
) -> Result<T, E> {
|
||||||
let mut result = operation(&mut state, 0).await;
|
let mut result = operation(&mut state, 0).await;
|
||||||
for (index, delay) in policy.delays().enumerate() {
|
for (index, delay) in policy.delays().enumerate() {
|
||||||
if !matches!(result, Err(RetryError::Retry(_))) {
|
match result {
|
||||||
break;
|
Ok(_) | Err(RetryError::Stop(_)) => break,
|
||||||
}
|
Err(RetryError::Retry(_)) => {
|
||||||
if !delay.is_zero() {
|
if !delay.is_zero() {
|
||||||
tokio::time::sleep(delay).await;
|
tokio::time::sleep(delay).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
result = operation(&mut state, index + 1).await;
|
result = operation(&mut state, index + 1).await;
|
||||||
}
|
}
|
||||||
result.map_err(RetryError::into_inner)
|
result.map_err(|error| match error {
|
||||||
|
RetryError::Retry(error) | RetryError::Stop(error) => error,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn retry_sync<T, E>(
|
pub fn retry_sync<T, E>(
|
||||||
@@ -91,39 +92,41 @@ pub fn retry_sync<T, E>(
|
|||||||
) -> Result<T, E> {
|
) -> Result<T, E> {
|
||||||
let mut result = operation(0);
|
let mut result = operation(0);
|
||||||
for (index, delay) in policy.delays().enumerate() {
|
for (index, delay) in policy.delays().enumerate() {
|
||||||
if !matches!(result, Err(RetryError::Retry(_))) {
|
match result {
|
||||||
break;
|
Ok(_) | Err(RetryError::Stop(_)) => break,
|
||||||
}
|
Err(RetryError::Retry(_)) => {
|
||||||
if !delay.is_zero() {
|
if !delay.is_zero() {
|
||||||
std::thread::sleep(delay);
|
std::thread::sleep(delay);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
result = operation(index + 1);
|
result = operation(index + 1);
|
||||||
}
|
}
|
||||||
result.map_err(RetryError::into_inner)
|
result.map_err(|error| match error {
|
||||||
|
RetryError::Retry(error) | RetryError::Stop(error) => error,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use std::future::ready;
|
|
||||||
|
|
||||||
#[tokio::test(start_paused = true)]
|
#[tokio::test]
|
||||||
async fn retries_stop_at_success_terminal_error_or_attempt_limit() {
|
async fn retries_stop_at_success_terminal_error_or_attempt_limit() {
|
||||||
let delay = Duration::from_millis(50);
|
let policy = RetryPolicy::fixed(NonZeroUsize::MIN.saturating_add(2), Duration::ZERO);
|
||||||
let policy = RetryPolicy::fixed(NonZeroUsize::MIN.saturating_add(2), delay);
|
|
||||||
let started = tokio::time::Instant::now();
|
|
||||||
let mut calls = 0;
|
let mut calls = 0;
|
||||||
let success = retry(policy, |attempt| {
|
let success = retry(policy, |attempt| {
|
||||||
calls += 1;
|
calls += 1;
|
||||||
ready(if attempt == 1 {
|
async move {
|
||||||
Ok(7)
|
if attempt == 1 {
|
||||||
} else {
|
Ok(7)
|
||||||
Err(RetryError::Retry(attempt))
|
} else {
|
||||||
})
|
Err(RetryError::Retry(attempt))
|
||||||
|
}
|
||||||
|
}
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
assert_eq!((success, calls), (Ok(7), 2));
|
assert_eq!((success, calls), (Ok(7), 2));
|
||||||
assert_eq!(started.elapsed(), delay);
|
|
||||||
calls = 0;
|
calls = 0;
|
||||||
let stopped = retry(policy, |_| {
|
let stopped = retry(policy, |_| {
|
||||||
calls += 1;
|
calls += 1;
|
||||||
@@ -131,7 +134,6 @@ mod tests {
|
|||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
assert_eq!((stopped, calls), (Err("terminal"), 1));
|
assert_eq!((stopped, calls), (Err("terminal"), 1));
|
||||||
assert_eq!(started.elapsed(), delay);
|
|
||||||
calls = 0;
|
calls = 0;
|
||||||
let exhausted = retry(policy, |attempt| {
|
let exhausted = retry(policy, |attempt| {
|
||||||
calls += 1;
|
calls += 1;
|
||||||
@@ -139,7 +141,6 @@ mod tests {
|
|||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
assert_eq!((exhausted, calls), (Err(2), 3));
|
assert_eq!((exhausted, calls), (Err(2), 3));
|
||||||
assert_eq!(started.elapsed(), delay * 3);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
@@ -160,9 +161,11 @@ mod tests {
|
|||||||
let result = retry_with_state(policy, Vec::new(), |visited, attempt| {
|
let result = retry_with_state(policy, Vec::new(), |visited, attempt| {
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
visited.push(attempt);
|
visited.push(attempt);
|
||||||
(visited.len() == 3)
|
if visited.len() == 3 {
|
||||||
.then(|| visited.clone())
|
Ok(visited.clone())
|
||||||
.ok_or(RetryError::Retry(()))
|
} else {
|
||||||
|
Err(RetryError::Retry(()))
|
||||||
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
@@ -52,7 +52,7 @@ pub async fn check_singleton() -> Result<SingletonDisposition> {
|
|||||||
.context("failed to initialize singleton lock")?;
|
.context("failed to initialize singleton lock")?;
|
||||||
if !try_lock_instance(&lock).context("failed to acquire singleton lock")? {
|
if !try_lock_instance(&lock).context("failed to acquire singleton lock")? {
|
||||||
let deadline = std::time::Instant::now() + Duration::from_secs(20);
|
let deadline = std::time::Instant::now() + Duration::from_secs(20);
|
||||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
|
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||||
let secondary = retry(
|
let secondary = retry(
|
||||||
RetryPolicy::fixed(
|
RetryPolicy::fixed(
|
||||||
std::num::NonZeroUsize::MIN.saturating_add(400),
|
std::num::NonZeroUsize::MIN.saturating_add(400),
|
||||||
|
|||||||
@@ -17,7 +17,12 @@ pub const ITEM_MERGE_EMPTY: &str = "# Profile Enhancement Merge Template for Cla
|
|||||||
|
|
||||||
";
|
";
|
||||||
|
|
||||||
pub use clash_verge_config_render::ITEM_SCRIPT;
|
pub const ITEM_SCRIPT: &str = "// Define main function (script entry)
|
||||||
|
|
||||||
|
function main(config, profileName) {
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
";
|
||||||
|
|
||||||
pub const ITEM_RULES: &str = "# Profile Enhancement Rules Template for Clash Verge
|
pub const ITEM_RULES: &str = "# Profile Enhancement Rules Template for Clash Verge
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use serde_yaml_ng::Result;
|
use serde_yaml_ng::Result;
|
||||||
|
|
||||||
pub(crate) use serde_yaml_ng::to_string as serialize;
|
pub fn to_mihomo_config_string<T: Serialize>(data: &T) -> Result<String> {
|
||||||
|
let yaml = serde_yaml_ng::to_string(data)?;
|
||||||
pub(crate) fn serialize_for_export<T: Serialize>(data: &T) -> Result<String> {
|
Ok(quote_fake_ip_filter_wildcards(&yaml))
|
||||||
Ok(quote_fake_ip_filter_wildcards(&serialize(data)?))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn quote_fake_ip_filter_wildcards(yaml: &str) -> String {
|
fn quote_fake_ip_filter_wildcards(yaml: &str) -> String {
|
||||||
@@ -13,7 +12,7 @@ fn quote_fake_ip_filter_wildcards(yaml: &str) -> String {
|
|||||||
let mut fake_ip_filter_indent = 0;
|
let mut fake_ip_filter_indent = 0;
|
||||||
|
|
||||||
for line in yaml.lines() {
|
for line in yaml.lines() {
|
||||||
let indent = line.len() - line.trim_start_matches(' ').len();
|
let indent = leading_spaces(line);
|
||||||
let trimmed = &line[indent..];
|
let trimmed = &line[indent..];
|
||||||
|
|
||||||
if in_fake_ip_filter && indent <= fake_ip_filter_indent && !trimmed.starts_with("- ") {
|
if in_fake_ip_filter && indent <= fake_ip_filter_indent && !trimmed.starts_with("- ") {
|
||||||
@@ -23,47 +22,54 @@ fn quote_fake_ip_filter_wildcards(yaml: &str) -> String {
|
|||||||
if !in_fake_ip_filter && trimmed == "fake-ip-filter:" {
|
if !in_fake_ip_filter && trimmed == "fake-ip-filter:" {
|
||||||
in_fake_ip_filter = true;
|
in_fake_ip_filter = true;
|
||||||
fake_ip_filter_indent = indent;
|
fake_ip_filter_indent = indent;
|
||||||
|
result.push_str(line);
|
||||||
|
result.push('\n');
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if in_fake_ip_filter
|
if in_fake_ip_filter && indent >= fake_ip_filter_indent && trimmed.starts_with("- ") {
|
||||||
&& indent >= fake_ip_filter_indent
|
result.push_str(&line[..indent]);
|
||||||
&& let Some(item) = trimmed.strip_prefix("- ")
|
result.push_str("- ");
|
||||||
&& needs_quotes(item)
|
result.push_str("e_wildcard_item(&trimmed[2..]));
|
||||||
{
|
result.push('\n');
|
||||||
result.push_str(&line[..indent + 2]);
|
continue;
|
||||||
push_quoted(&mut result, item);
|
|
||||||
} else {
|
|
||||||
result.push_str(line);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
result.push_str(line);
|
||||||
result.push('\n');
|
result.push('\n');
|
||||||
}
|
}
|
||||||
|
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
fn needs_quotes(item: &str) -> bool {
|
fn leading_spaces(line: &str) -> usize {
|
||||||
!item.starts_with(['"', '\'']) && (item.contains('*') || item.starts_with(['+', '.']))
|
line.len() - line.trim_start_matches(' ').len()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn push_quoted(output: &mut String, item: &str) {
|
fn quote_wildcard_item(item: &str) -> String {
|
||||||
output.push('\'');
|
if !item.starts_with('\"') && !item.starts_with('\'') && contains_wildcard(item) {
|
||||||
for (index, part) in item.split('\'').enumerate() {
|
quote_string(item)
|
||||||
if index != 0 {
|
} else {
|
||||||
output.push_str("''");
|
item.to_string()
|
||||||
}
|
|
||||||
output.push_str(part);
|
|
||||||
}
|
}
|
||||||
output.push('\'');
|
}
|
||||||
|
|
||||||
|
fn quote_string(s: &str) -> String {
|
||||||
|
"\'".to_string() + s.replace('\'', "''").as_str() + "\'"
|
||||||
|
}
|
||||||
|
|
||||||
|
fn contains_wildcard(value: &str) -> bool {
|
||||||
|
value.contains('*') || value.starts_with('+') || value.starts_with('.')
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
#[allow(clippy::expect_used)]
|
#[allow(clippy::expect_used)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::serialize_for_export;
|
use super::to_mihomo_config_string;
|
||||||
|
|
||||||
fn roundtrip(input: &str) {
|
fn roundtrip(input: &str) {
|
||||||
let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(input).expect("input yaml should parse");
|
let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(input).expect("input yaml should parse");
|
||||||
let output = serialize_for_export(&value).expect("yaml should serialize");
|
let output = to_mihomo_config_string(&value).expect("yaml should serialize");
|
||||||
let reparsed: serde_yaml_ng::Value = serde_yaml_ng::from_str(&output).expect("serialized yaml should parse");
|
let reparsed: serde_yaml_ng::Value = serde_yaml_ng::from_str(&output).expect("serialized yaml should parse");
|
||||||
|
|
||||||
assert_eq!(reparsed, value);
|
assert_eq!(reparsed, value);
|
||||||
@@ -84,7 +90,7 @@ dns:
|
|||||||
roundtrip(input);
|
roundtrip(input);
|
||||||
|
|
||||||
let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(input).expect("input yaml should parse");
|
let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(input).expect("input yaml should parse");
|
||||||
let output = serialize_for_export(&value).expect("yaml should serialize");
|
let output = to_mihomo_config_string(&value).expect("yaml should serialize");
|
||||||
|
|
||||||
assert!(output.contains("- '*.lan'"));
|
assert!(output.contains("- '*.lan'"));
|
||||||
assert!(output.contains("- '+.market.xiaomi.com'"));
|
assert!(output.contains("- '+.market.xiaomi.com'"));
|
||||||
Reference in New Issue
Block a user